diff --git a/.dockerignore b/.dockerignore index cf5dc200..da968ce5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -4,14 +4,14 @@ models/ captures/ logs/ control-plane/target/ -engine/* -!engine/strata/ -engine/strata/* -!engine/strata/LICENSE -# prompt.rs embeds the pinned chat template at compile time -!engine/strata/serve/ -engine/strata/serve/* -!engine/strata/serve/chat_template.jinja +third_party/* +!third_party/strata/ +third_party/strata/* +!third_party/strata/LICENSE +# prompt.rs and server_api.rs embed the pinned chat template at compile time +!third_party/strata/serve/ +third_party/strata/serve/* +!third_party/strata/serve/chat_template.jinja benchmarks/ target/ dist/ diff --git a/.gitattributes b/.gitattributes index 61da554d..414736db 100644 --- a/.gitattributes +++ b/.gitattributes @@ -27,3 +27,6 @@ scripts/check-ci-coverage.py text eol=lf scripts/install-pinned-rustup.sh text eol=lf scripts/test-cuda-fixed-ptx.sh text eol=lf .github/workflows/*.yml text eol=lf + +# Strata files kept for the shipped product and the Rust tests (third_party/strata/UPSTREAM.md): embedded and hashed byte for byte, never converted. +third_party/strata/** -text diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8113053b..9fea4adb 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -6,23 +6,6 @@ on: tags: ['v*'] pull_request: workflow_dispatch: - inputs: - keyless_gpu: - description: Run synthetic Keyless CUDA tests on the private GPU runner - type: boolean - default: false - hosted_cuda_package: - description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact) - type: boolean - default: false - hosted_cuda_ple: - description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default) - type: boolean - default: false - static_cuda_package: - description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference) - type: boolean - default: false permissions: contents: read @@ -41,296 +24,6 @@ jobs: - name: GPU-hidden fixed PTX assembly run: scripts/test-cuda-fixed-ptx.sh - keyless-cuda-gate: - if: gitea.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - outputs: - enabled: ${{ steps.select.outputs.enabled }} - steps: - - id: select - env: - KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }} - run: | - case "${KEYLESS_GPU:-false}" in - true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;; - false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;; - *) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;; - esac - - keyless-cuda: - needs: [verify, keyless-cuda-gate] - if: needs.keyless-cuda-gate.outputs.enabled == 'true' - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Query-routing, streaming and snapshot GPU tests - run: scripts/check-keyless-gpu.sh - - name: Bounded KAR expert component GPU tests - run: scripts/check-kar-expert-gpu.sh - - static-cuda-package: - permissions: - contents: read - releases: write - if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private - needs: verify - runs-on: [self-hosted, linux, x64, strata-gpu] - steps: - - uses: actions/checkout@v4 - - name: Build and audit engine without GPU inference - env: - CUDA_VISIBLE_DEVICES: '' - BUILD_JOBS: '2' - STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }} - run: nice -n 10 scripts/build-static-cuda.sh - - name: Install pinned Rust and musl target - run: | - scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - command -v musl-gcc - - name: Assemble combined private package - run: | - engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata" - python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \ - --cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \ - --output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Build compatible private runtime image without GPU inference - run: | - package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json" - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS) - - name: Publish exact six-file static CUDA preview through Gitea - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ - --repository "$GITHUB_REPOSITORY" --profile static-cuda \ - --tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ - --title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ - --notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \ - --directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove uploaded package copy - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}" - - name: Remove owned runtime image - if: always() - run: | - receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - rm "$receipt" - fi - - name: Remove private build intermediates - if: always() - run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" - - hosted-cuda-package: - permissions: - contents: read - releases: write - if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private - needs: verify - runs-on: ubuntu-latest - timeout-minutes: 150 - env: - CUDA_VISIBLE_DEVICES: '' - NVIDIA_VISIBLE_DEVICES: void - BUILD_JOBS: '1' - CARGO_BUILD_JOBS: '2' - CUDA_ARCHITECTURES: '120' - STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} - steps: - - uses: actions/checkout@v4 - - name: Install compatible host tools (no drivers) - run: | - echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV" - echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV" - echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV" - apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time - - name: Actual runtime-image loader boundary without GPU - run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py - - name: Assemble pinned build-only CUDA components - run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT" - - name: Build pinned GPU-hidden compiler image - env: - CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - run: | - context="$RUNNER_TEMP/strata-cuda-builder-context" - mkdir -p "$context" - cp deploy/Dockerfile.cuda-builder "$context/Dockerfile" - cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt" - docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \ - --tag "$CUDA_BUILDER_IMAGE" "$context" - docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" - - name: Record actual toolchain - env: - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b - run: | - "$CUDACXX" --version - docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version - df -h "$RUNNER_TEMP" - free -h - python3 - <<'PYTOOL' - import json, os, platform, subprocess - from pathlib import Path - info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text()) - packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', - os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10), - 'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines() - gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none', - os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True) - info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(), - builder_base=os.environ['CUDA_BUILDER_BASE'], - builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(), - builder_packages=packages, - gcc=gcc, - nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True), - cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False) - (Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n') - PYTOOL - - name: Build actual static CUDA engine and audit without GPU - env: - CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }} - STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }} - run: | - mkdir -p "$STRATA_BUILD_DIR" - container="leleka-cuda-build-${GITHUB_RUN_ID}" - volume="leleka-cuda-build-${GITHUB_RUN_ID}" - source_archive="$RUNNER_TEMP/strata-cuda-source.tar" - cleanup() { - docker rm -f "$container" >/dev/null 2>&1 || true - docker volume rm "$volume" >/dev/null 2>&1 || true - rm -f -- "$source_archive" - } - trap cleanup EXIT - git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive" - docker volume create "$volume" >/dev/null - docker create --name "$container" --platform linux/amd64 --network bridge --read-only \ - --cap-drop ALL --security-opt no-new-privileges \ - --tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \ - -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ - "$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null - docker start "$container" >/dev/null - docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build - docker exec "$container" chmod 0777 /work/build - # Stage tracked source only. docker cp streams the archive from the - # runner container; bind mounts cannot use its path on the daemon host. - docker cp "$source_archive" "$container:/work/source.tar" - docker exec "$container" tar -xf /work/source.tar -C /work/workspace - docker exec "$container" rm /work/source.tar - docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/" - docker exec --user "$(id -u):$(id -g)" \ - -e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \ - -e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \ - -e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \ - -e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \ - -e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \ - -e SOURCE_REVISION="$GITHUB_SHA" \ - "$container" /bin/bash -euo pipefail -c ' - if compgen -G "/dev/nvidia*" >/dev/null; then - echo "NVIDIA devices unexpectedly visible in build container" >&2 - exit 1 - fi - cd /work/workspace - scripts/build-static-cuda.sh - ' - docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata" - docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json" - - name: Bind compile capability to CUDA toolchain provenance - run: | - python3 - <<'PYFEATURES' - import hashlib, json, os - from pathlib import Path - features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json' - features=json.loads(features_path.read_text()) - toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' - info=json.loads(toolchain_path.read_text()) - info['build_features']=features['features'] - info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest() - toolchain_path.write_text(json.dumps(info,indent=2)+'\n') - PYFEATURES - - name: Install pinned Rust and musl target - run: | - scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl - - name: Assemble actual combined executable and runtime image - run: | - # Keep resource evidence even if the hosted runner terminates this job. - (while sleep 20; do - date -u - free -m - df -m "$RUNNER_TEMP" - test ! -r /sys/fs/cgroup/memory.events || cat /sys/fs/cgroup/memory.events - done) & - resource_sampler=$! - trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT - engine="$STRATA_BUILD_DIR/strata" - package="$RUNNER_TEMP/strata-hosted-cuda-package" - /usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \ - --sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \ - --build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \ - --cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package" - python3 scripts/build-runtime-image.py --package "$package" \ - --receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \ - > "$RUNNER_TEMP/strata-hosted-image.json" - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")" - docker save --output "$package/runtime-image.tar" "$image" - cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json" - python3 - <<'PYBIND' - import hashlib, json, os - from pathlib import Path - package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package' - receipt=json.loads((package/'PROVENANCE.json').read_text()) - image=json.loads((package/'IMAGE-PROVENANCE.json').read_text()) - path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json' - toolchain=json.loads(path.read_text()) - with (package/'runtime-image.tar').open('rb') as archive: - archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest() - toolchain['docker_builder']={ - 'source_commit': os.environ['GITHUB_SHA'], - 'image_id': toolchain['builder_image_id'], - 'engine_sha256': receipt['engine']['sha256'], - 'build_features_sha256': receipt['build_features_sha256'], - 'runtime_image_id': image['image'], - 'runtime_archive_sha256': archive_sha} - path.write_text(json.dumps(toolchain,indent=2)+'\n') - PYBIND - cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json" - tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses - (cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS) - - name: Publish exact eight-file hosted CUDA preview through Gitea - env: - GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} - run: | - python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \ - --repository "$GITHUB_REPOSITORY" --profile cuda \ - --tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \ - --title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \ - --notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \ - --directory "$RUNNER_TEMP/strata-hosted-cuda-package" - - name: Remove uploaded package copy - if: always() - run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package" - - name: Remove owned intermediate image and build files - if: always() - run: | - receipt="$RUNNER_TEMP/strata-hosted-image.json" - if test -s "$receipt"; then - image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")" - docker image rm "$image" - fi - rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build" - docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true - rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID" - linux-static-cli: permissions: contents: read @@ -387,12 +80,8 @@ jobs: run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Atomic pinned assets before native serving run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - - name: Native GGUF pack preparation against upstream oracle - run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native fetch prepare serve and verified offline reuse run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - - name: Pinned MTP structural preflight and native bootstrap - run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native runtime profile metadata admission run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api - name: Native systemd unit syntax and path safety diff --git a/.github/workflows/port.yml b/.github/workflows/port.yml index 278bf5b2..2fc73abc 100644 --- a/.github/workflows/port.yml +++ b/.github/workflows/port.yml @@ -4,7 +4,8 @@ name: Rust port # weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates: # port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast) # port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run -# port-oracles CPU oracle differentials against the unmodified Python tools (needs pip and a pinned llama.cpp gguf-py) +# port-oracles the sampler host shim over the checked-in oracle fixtures (the live Python differentials and the oracle +# generators needed the vendored Strata tree, removed in STRA-406) # port-linux-tests Docker Linux harness (scripts/linux-tests/run.sh); optional until branch claude/port-linux-tests merges # Type-checking is not execution: nothing here runs the Linux-gated tests or any GPU smoke. @@ -54,45 +55,18 @@ jobs: cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings port-oracles: - # CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the - # sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by - # port-fast regardless. + # The sampler host shim over the checked-in oracle fixtures. Optional until it has run green on the hosted runner; + # the committed goldens are replayed by port-fast regardless. runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v4 - name: Install build tools - run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 python3-venv + run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 - name: Install pinned Rust run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy - - name: Oracle Python environment (no model data) - # numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the - # interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below). - # The oracle differentials compare against recorded goldens with tolerances, not against a numpy build. - run: | - python3 -m venv "$RUNNER_TEMP/oracle-venv" - cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF' - numpy==2.5.4; python_version >= "3.12" - numpy==2.4.6; python_version == "3.11" - numpy==2.2.6; python_version < "3.11" - PyYAML==6.0.3 - tqdm==4.70.1 - Jinja2==3.1.6 - regex==2026.9.10 - EOF - "$RUNNER_TEMP/oracle-venv/bin/python" --version - "$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt" - - name: Fetch the pinned llama.cpp gguf-py - run: | - commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)" - test -n "$commit" - git init -q "$RUNNER_TEMP/llama.cpp" - git -C "$RUNNER_TEMP/llama.cpp" fetch --depth 1 https://github.com/ggml-org/llama.cpp "$commit" - git -C "$RUNNER_TEMP/llama.cpp" checkout -q FETCH_HEAD - - name: Port oracles (sampler shim and live Python differentials) + - name: Port oracles (sampler host shim over the checked-in fixtures) env: - OFFLINE_ORACLE_PYTHON: ${{ runner.temp }}/oracle-venv/bin/python - STRATA_GGUF_PY: ${{ runner.temp }}/llama.cpp/gguf-py SKIP_LINUX_TYPECHECK: '1' run: scripts/check-local.sh --port diff --git a/PORT-GAPS-MODE17.md b/PORT-GAPS-MODE17.md index 3a7c141e..749294f9 100644 --- a/PORT-GAPS-MODE17.md +++ b/PORT-GAPS-MODE17.md @@ -2,7 +2,7 @@ Read-only snapshot, 2026-10-12. Audit artifact only; no builds, tests, GPU, Strata, model or daemon execution. Paths below are relative to this source-port -tree or to the imported `engine/strata/`. Root integration remains mutable. +tree or to the Strata tree that was imported (removed, see `third_party/strata/UPSTREAM.md`). Root integration remains mutable. This is a bounded core-path ledger, not a whole-project completion certificate. ## Actionable remaining boundaries diff --git a/README.md b/README.md index 0adac84c..cba5eba0 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs. -It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at -upstream `41cf05a0`, see `engine/upstream.md`). Serving needs no Python and no CUDA toolkit on the host. +It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (pinned at upstream `41cf05a0`; the vendored copy was removed, see +`third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host. **Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers"). It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`; @@ -76,7 +76,7 @@ What the service is doing, and why a request was slow or failed, is in its logs; - `crates/` — the runtime: `engine-qwen35-cuda` (the engine; `leleka-runtime` is its facade), `engine-core` (pure engine domain), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels. - `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes. -- `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka). +- `third_party/strata/` — the Strata MIT licence texts, the pinned chat template and golden, and `UPSTREAM.md` (pin `41cf05a0`, local patches, where the removed vendored tree is in history). The Strata source tree itself is not in the repository. - `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving). - `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`. @@ -92,4 +92,4 @@ scripts/release/package-5090.sh check # the release gates; `package` buil ## Licence -MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`). +MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`third_party/strata/LICENSE`, printed by `leleka engine license`). diff --git a/control-plane/src/cli/operations.rs b/control-plane/src/cli/operations.rs index 154ff2c1..33573a77 100644 --- a/control-plane/src/cli/operations.rs +++ b/control-plane/src/cli/operations.rs @@ -201,7 +201,7 @@ fn engine_info() -> Result<(), BoxError> { } fn engine_license() -> Result<(), BoxError> { - print!("{}", include_str!("../../../engine/strata/LICENSE")); + print!("{}", include_str!("../../../third_party/strata/LICENSE")); Ok(()) } diff --git a/control-plane/src/hardware_view.rs b/control-plane/src/hardware_view.rs index c2f04dc2..8405408f 100644 --- a/control-plane/src/hardware_view.rs +++ b/control-plane/src/hardware_view.rs @@ -1,5 +1,5 @@ //! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`, -//! `hardware_static`, `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document +//! `hardware_static`, `history`; `Strata 41cf05a0, serve/telemetry.py`), built from the engine's telemetry document //! (`leleka-memory`'s `telemetry.rs`, copied here by the worker on its health tick). //! //! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in diff --git a/control-plane/src/mcp.rs b/control-plane/src/mcp.rs index 6e18f304..aded0adc 100644 --- a/control-plane/src/mcp.rs +++ b/control-plane/src/mcp.rs @@ -1,5 +1,5 @@ //! MCP (Model Context Protocol) hub: tools from MCP servers, namespaced `__`, called -//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`. +//! on behalf of an agent. Port of `Strata 41cf05a0, serve/mcp.py`. //! //! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers` //! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`, diff --git a/control-plane/src/mtp_pack.rs b/control-plane/src/mtp_pack.rs index fcd3cfbe..c5d85cf2 100644 --- a/control-plane/src/mtp_pack.rs +++ b/control-plane/src/mtp_pack.rs @@ -8,10 +8,10 @@ use std::{ }; const INDEX_LIMIT: u64 = 64 * 1024; -// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB. +// Strata 41cf05a0, include/strata/kernels/cpu/expert.hpp: NE * BLOB. const EXPERT_BYTES: u64 = 512 * 1_382_400; // Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py. -// Consumer: engine/strata/src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256). +// Consumer: Strata 41cf05a0, src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256). const REQUIRED: &[(&str, &str, u64, u64)] = &[ ("fc_embedding.weight", "q8_0", 2560, 2560), ("fc_hidden.weight", "q8_0", 2560, 2560), diff --git a/control-plane/src/native_pack/tests.rs b/control-plane/src/native_pack/tests.rs index 1afc9dd5..4653f606 100644 --- a/control-plane/src/native_pack/tests.rs +++ b/control-plane/src/native_pack/tests.rs @@ -236,12 +236,12 @@ fn shards_for(golden: &Golden) -> Vec { #[test] fn real_golden_expert_tables_are_reproduced() { let goldens = [ - include_str!("../../../engine/strata/tests/data/native_experts/iq3_s.txt"), - include_str!("../../../engine/strata/tests/data/native_experts/iq3_xxs.txt"), - include_str!("../../../engine/strata/tests/data/native_experts/iq2_xs.txt"), - include_str!("../../../engine/strata/tests/data/native_experts/q2_0.txt"), - include_str!("../../../engine/strata/tests/data/native_experts/coder-iq1_m.txt"), - include_str!("../../../engine/strata/tests/data/native_experts/swift-iq2_xs.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/iq3_s.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/iq3_xxs.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/iq2_xs.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/q2_0.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/coder-iq1_m.txt"), + include_str!("../../../third_party/strata/tests/data/native_experts/swift-iq2_xs.txt"), ]; for text in goldens { let golden = parse_golden(text); diff --git a/control-plane/src/request_monitor.rs b/control-plane/src/request_monitor.rs index 0e1e2c16..5fd68621 100644 --- a/control-plane/src/request_monitor.rs +++ b/control-plane/src/request_monitor.rs @@ -1,5 +1,5 @@ //! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the -//! Python service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`, +//! Python service (`api_monitor` in its config; `Strata 41cf05a0, serve/server.py` `begin_request` / `request_records`, //! tests in `serve/test_monitor.py`). //! //! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`, diff --git a/control-plane/src/server_api.rs b/control-plane/src/server_api.rs index 06a1b4f5..cb74c61c 100644 --- a/control-plane/src/server_api.rs +++ b/control-plane/src/server_api.rs @@ -1,4 +1,4 @@ -//! The operational HTTP surface of the Original's Python server (`engine/strata/serve/server.py`) +//! The operational HTTP surface of the Original's Python server (`Strata 41cf05a0, serve/server.py`) //! that is not an inference API: `GET /props`, `GET /slots`, `GET /v1/status`, `GET /api/health`, //! `GET|POST /settings`, `POST /load`, `POST /unload`, `POST /v1/load`, `POST /v1/unload`, CORS and //! the own-page guard. Behaviour is checked against the real Python handlers in @@ -32,7 +32,7 @@ use crate::{ }; /// The chat template the Original serves in `/props` when the model ships none. -pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../engine/strata/serve/chat_template.jinja"); +pub const DEFAULT_CHAT_TEMPLATE: &str = include_str!("../../third_party/strata/serve/chat_template.jinja"); mod engine_lifecycle; pub use engine_lifecycle::*; diff --git a/control-plane/tests/gguf_header_differential.rs b/control-plane/tests/gguf_header_differential.rs index ad505ffd..ad63fb8a 100644 --- a/control-plane/tests/gguf_header_differential.rs +++ b/control-plane/tests/gguf_header_differential.rs @@ -1,4 +1,4 @@ -//! GGUF header reader versus `engine/strata/tools/gguf_reader.py`. +//! GGUF header reader versus `Strata 41cf05a0, tools/gguf_reader.py`. //! //! `tests/fixtures/offline/gguf_headers.json` is generated by `scripts/offline/gen_goldens.py` from the unmodified //! Python reader: random GGUF v3 headers (all 13 metadata value types, arrays, unicode, alignment, split keys, diff --git a/control-plane/tests/golden/gen_goldens.py b/control-plane/tests/golden/gen_goldens.py deleted file mode 100644 index 330b670f..00000000 --- a/control-plane/tests/golden/gen_goldens.py +++ /dev/null @@ -1,617 +0,0 @@ -"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only). - -Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables -of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of -`crates/serving-policy` compare against these files. - - python3 -I control-plane/tests/golden/gen_goldens.py [section ...] - -Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them. -Sections: gen_lines, shared, props_slots, cors, ... -""" -import json -import os -import queue -import sys -import threading - -HERE = os.path.dirname(os.path.abspath(__file__)) -REPO = os.path.normpath(os.path.join(HERE, "..", "..", "..")) -ENGINE = os.path.join(REPO, "engine", "strata") -sys.path.insert(0, ENGINE) -sys.path.insert(0, os.path.join(ENGINE, "tools")) - -OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden") -OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures") - - -def write(name, obj, dest="control"): - out = OUT_POLICY if dest == "policy" else OUT_CONTROL - os.makedirs(out, exist_ok=True) - path = os.path.join(out, name + ".json") - with open(path, "w", encoding="utf-8") as f: - json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False) - f.write("\n") - print("wrote", os.path.relpath(path, REPO), file=sys.stderr) - - -# ------------------------------------------------------------------------------------------------ gen_lines -def gen_lines(): - from serve.server import StrataEngine - - class Pipe: - def __init__(self): - self.sent = [] - - def write(self, text): - self.sent.append(text) - - def flush(self): - pass - - def capture(ids, max_new, sampling, embeddings=None): - eng = object.__new__(StrataEngine) - eng.proc = type("P", (), {"stdin": Pipe()})() - eng.lines = queue.Queue() - eng.lines.put("DONE 1 1 1.0 1.0 stop\n") - eng.can_stop = False - eng.progress = None - eng.prefill_tok_s_mean = None - eng.last = {} - list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings)) - return "".join(eng.proc.stdin.sent) - - cases = [] - sampling_tables = [ - {}, - {"temperature": 0.0}, - {"temperature": 0.7}, - {"temperature": 0.7, "top_p": 0.9}, - {"temperature": 1, "top_p": 1.0}, - {"temperature": 0.8, "top_k": 40, "min_p": 0.05}, - {"temperature": 0.8, "top_k": 0}, - {"temperature": 0.8, "top_k": 1000}, - {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0}, - {"repetition_penalty": 1.1}, - {"repetition_penalty": 1.1, "penalty_last_n": 256}, - {"presence_penalty": 0.5, "frequency_penalty": 0.25}, - {"presence_penalty": -0.5}, - {"frequency_penalty": 1.5, "penalty_last_n": 0}, - {"temperature": 0.7, "seed": 42}, - {"temperature": 0.7, "seed": 0}, - {"temperature": 0.7, "seed": 18446744073709551615}, - {"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05, - "presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7}, - {"strata_tune": {"pcie_frac": 0.0}}, - {"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}}, - {"strata_tune": {"spec_min_p": 1.0}}, - {"experimental_speed_projection": True}, - {"experimental_speed_projection": False}, - {"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False}, - ] - for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None), - ([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")): - for sampling in sampling_tables: - cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling, - "line": capture(ids, max_new, sampling, emb)}) - write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases}) - - -# ------------------------------------------------------------------------------------------------ shared -def shared(): - from serve.server import clean_shared_defaults, sampling_defaults_from_config - - clean_cases = [ - None, {}, [], "x", 5, - {"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5}, - {"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"}, - {"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False}, - {"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"}, - {"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615}, - {"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"}, - {"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, - {"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3}, - {"experimental_speed_projection": True}, {"experimental_speed_projection": False}, - {"experimental_speed_projection": 1}, - {"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1}, - {"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100, - "reasoning_effort": "medium", "experimental_speed_projection": False}, - ] - clean = [] - for case in clean_cases: - try: - clean.append({"input": case, "ok": clean_shared_defaults(case)}) - except ValueError as e: - clean.append({"input": case, "error": str(e)}) - - config_cases = [ - None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True}, - {"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2}, - {"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5}, - {"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25}, - {"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0}, - {"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5}, - {"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"}, - {"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"}, - {"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3}, - {"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1, - "frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9}, - ] - import contextlib - import io - config = [] - for case in config_cases: - out = io.StringIO() - try: - with contextlib.redirect_stdout(out): - ok = sampling_defaults_from_config({"sampling": case} if case is not None else {}) - config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines() - if "unknown key" in ln]}) - except SystemExit as e: - config.append({"input": case, "error": str(e)}) - write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)", - "clean": clean, "config": config}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ reasoning -def reasoning(): - import random - from serve.frontend import OutputParser - from serve.server import Detokenizer, Service, ByteTokenizer - - class BytesTok: - """Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer.""" - def __init__(self, table): - self.table = table - - def token_bytes(self, t): - return self.table[t] - - pieces = [b"a", b"b", b" so ", b"think", b"", b"", b"", b"<", b"/", b"\n", - b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"", b"x"] - rng = random.Random(1234) - seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0], - [3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] - for _ in range(120): - seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))]) - cases = [] - for seq in seqs: - row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}} - for budget in (1, 2, 3, 5, 8): - parser = OutputParser(thinking=True, tools=None, stream_tools=True) - detok = Detokenizer(BytesTok(pieces)) - thought, wrap_at = 0, None - for i, t in enumerate(seq): - parser.feed(detok.push(t)) - if parser.state == "reasoning": - thought += 1 - if thought >= budget and not parser.buf and not detok.pending(): - wrap_at = i - break - row["wrap_at"][str(budget)] = wrap_at - cases.append(row) - - parse = [] - svc = Service.__new__(Service) - for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0), - ({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50), - ({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0), - ({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0), - ({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]: - svc.reasoning_budget_tokens = default - try: - parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)}) - except ValueError as e: - parse.append({"request": req, "default": default, "error": str(e)}) - from serve.server import REASONING_WRAP_UP - write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real " - "Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases, - "parse": parse}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ http -def http_surface(): - """The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine).""" - import http.client - from pathlib import Path - from serve.frontend import ChatTemplate - from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve - - class Resident(StrataEngine): - def __init__(self, tok, loaded, max_context): - self.reply = MockEngine(tok, "Hello.", max_context=max_context) - self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {} - self.loaded, self.unloaded, self.progress = loaded, not loaded, None - - def alive(self): - return self.loaded - - def exit_code(self): - return None - - def restart(self): - self.loaded, self.unloaded = True, False - - def close(self): - self.loaded = False - - def unload(self): - self.close() - self.unloaded = True - - def generate(self, *args, **kwargs): - yield from self.reply.generate(*args, **kwargs) - - def run(setup, steps): - tok = ByteTokenizer() - engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096)) - svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), - model_name=setup.get("model", "strata-test"), - sampling_defaults=setup.get("config_sampling") or {}) - svc.set_aliases(setup.get("aliases")) - svc.api_key = setup.get("api_key", "") - svc.cors_origins = setup.get("cors_origins", []) - svc.trusted_origins = setup.get("trusted_origins", []) - if setup.get("shared"): - svc.shared = dict(setup["shared"]) - svc.idle_unload_s = setup.get("idle_unload_s", 0) - for key, value in (setup.get("status") or {}).items(): - svc.status[key] = value - httpd = serve(svc, port=0) - port = httpd.server_address[1] - out = [] - try: - for step in steps: - conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) - headers = dict(step.get("headers") or {}) - body = step.get("body") - if body is not None and not isinstance(body, str): - body = json.dumps(body) - headers.setdefault("Content-Type", "application/json") - if body is not None: - headers.setdefault("Content-Length", str(len(body.encode()))) - conn.request(step["method"], step["path"], body=body.encode() if body is not None else None, - headers=headers) - response = conn.getresponse() - raw = response.read().decode() - selected = {k.lower(): v for k, v in response.getheaders() - if k.lower().startswith("access-control-") or k.lower() == "vary"} - try: - parsed = json.loads(raw) if raw else None - except ValueError: - parsed = raw - out.append({"request": {"method": step["method"], "path": step["path"], - "headers": step.get("headers") or {}, "body": step.get("body")}, - "status": response.status, "headers": selected, "body": parsed, - "state": {"loaded": engine.loaded, "shared": svc.shared}}) - conn.close() - finally: - httpd.shutdown() - httpd.server_close() - return {"setup": setup, "steps": out} - - scenarios = {} - # ---- CORS - cors_steps = [ - {"method": "OPTIONS", "path": "/v1/chat/completions", - "headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}}, - {"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, - {"method": "OPTIONS", "path": "/v1/models"}, - {"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}}, - {"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}}, - {"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}}, - {"method": "GET", "path": "/v1/models"}, - {"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}}, - {"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}}, - ] - for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])): - scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps) - # (an unknown path answers 404 before authentication in the Python server; the Rust server - # authenticates every path first, so that one step is left out here) - scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1]) - # ---- own page - page = {"defaults": {"temperature": 0.5}} - own = [ - {"method": "POST", "path": "/settings", "body": page}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com", - "Host": "proxy.internal"}}, - {"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example", - "X-Forwarded-Host": "evil.example", - "CF-Ray": "1"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), - "headers": {"Content-Type": "application/x-www-form-urlencoded"}}, - {"method": "POST", "path": "/settings", "body": json.dumps(page), - "headers": {"Content-Type": "application/json; charset=utf-8"}}, - {"method": "GET", "path": "/settings"}, - ] - scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own) - # ---- settings - settings = [ - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low", - "experimental_speed_projection": True}}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": [1, 2]}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}}, - {"method": "POST", "path": "/settings", "body": {}}, - {"method": "GET", "path": "/settings"}, - {"method": "POST", "path": "/settings", "body": {"defaults": 5}}, - ] - scenarios["settings"] = run({}, settings) - scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "GET", "path": "/settings"}, - {"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}}, - {"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}, - "headers": {"Authorization": "Bearer " + "k" * 40}}, - ]) - # ---- props, slots, health, status - reads = [ - {"method": "GET", "path": "/props"}, - {"method": "GET", "path": "/props?model=strata-test"}, - {"method": "GET", "path": "/props?model=alias-one"}, - {"method": "GET", "path": "/props?model=nope"}, - {"method": "GET", "path": "/props?model="}, - {"method": "GET", "path": "/slots"}, - {"method": "GET", "path": "/api/health"}, - {"method": "GET", "path": "/v1/status"}, - ] - scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads) - scenarios["reads_loaded_with_defaults"] = run( - {"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2, - "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8}, - "shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads) - scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads) - scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [ - {"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}]) - scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"}, - {"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"}, - {"method": "GET", "path": "/health"}]) - # ---- load / unload - lifecycle = [ - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/unload"}, - {"method": "GET", "path": "/slots"}, - {"method": "POST", "path": "/load"}, - {"method": "POST", "path": "/load"}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}}, - {"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}}, - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}}, - {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}}, - {"method": "POST", "path": "/v1/unload", "body": [1]}, - {"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}}, - {"method": "POST", "path": "/v1/unload", "body": {"model": None}}, - {"method": "GET", "path": "/props"}, - ] - scenarios["lifecycle"] = run({}, lifecycle) - scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [ - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/load"}, - ]) - scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [ - {"method": "POST", "path": "/v1/load", "body": {}}, - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/load"}, - ]) - scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [ - {"method": "POST", "path": "/unload"}, - {"method": "POST", "path": "/v1/unload", "body": {}}, - {"method": "POST", "path": "/v1/unload", "body": {}, - "headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}}, - {"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}}, - {"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}}, - ]) - write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)", - "scenarios": scenarios}) - - -# ------------------------------------------------------------------------------------------------ timings -def timings(): - from serve.server import ByteTokenizer, MockEngine, Service, request_timings - from serve.frontend import ChatTemplate - from pathlib import Path - - cases = [] - lasts = [ - {"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60}, - {"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0}, - {"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None}, - {"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3}, - {"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15}, - {"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200}, - {"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0}, - {"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1}, - ] - for last in lasts: - for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)): - cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated, - "timings": request_timings(prompt_tokens, generated, last)}) - cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})}) - aliases = [] - tok = ByteTokenizer() - for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]): - svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"), - model_name="m") - try: - svc.set_aliases(value) - aliases.append({"input": value, "ok": svc.aliases}) - except ValueError as e: - aliases.append({"input": value, "error": str(e)}) - write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)", - "timings": cases, "aliases": aliases}, dest="policy") - - -# ------------------------------------------------------------------------------------------------ vision -def vision(): - import base64 - import tempfile - from pathlib import Path - from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages - from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision - - # base64 as Vision.load decodes data: URLs - b64 = [] - for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==", - "Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]: - try: - b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()}) - except Exception as e: # binascii.Error and friends - b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)}) - - sources = [ - {"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"}, - {"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}}, - {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}}, - {"type": "image", "source": {"type": "base64", "data": "QQ=="}}, - {"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}}, - {"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None}, - ] - src = [{"part": part, "source": _image_source(part)} for part in sources] - - tok = ByteTokenizer() - - class FakeVision: - def __init__(self, counts): - self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-")) - - def encode(self, source): - path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve") - path.write_bytes(source.encode()) - return path, self.counts[source] - - template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") - prepared = [] - cases = [ - ([{"role": "user", "content": "hello"}], {}), - ([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}], - {"A": 3}), - ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}, - {"type": "image_url", "image_url": {"url": "B"}}, - {"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}), - ([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]}, - {"role": "assistant", "content": "ok"}, - {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}], - {"A": 1, "C": 4}), - ([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"}, - {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), - ([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}), - ([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"}, - {"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}), - ] - for messages, counts in cases: - req = {"messages": messages} - norm, tools, kw = openai_to_messages(req) - prompt = template.render(norm, tools=tools, **kw) - ids_before = tok.encode(prompt, parse_special=True) - svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None) - entry = {"messages": messages, "counts": counts, "ids_before": ids_before, - "images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0], - "start": tok.encode(VISION_START, parse_special=True)[0], - "literal": tok.encode(IMAGE_PAD, parse_special=False)} - try: - ids, thinking, max_new = svc.prepare(norm, tools, kw, 10) - entry["ids_after"] = ids - entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None - except ValueError as e: - entry["error"] = str(e) - prepared.append(entry) - write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)", - "base64": b64, "sources": src, "prepare": prepared}, dest="policy") - - -def vision_dialects(): - """Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages` - and the real chat template: the prompt text and the picture sources in prompt order.""" - import base64 - from pathlib import Path - from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages - - template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja") - counter = iter(range(1, 250)) - - def url(): - # a PNG signature and one tag byte: the tests find the picture again by its last byte - return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode() - - def chat(messages): - return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}} - - def claude(messages, system=None): - request = {"messages": messages, "thinking": {"type": "disabled"}} - if system: - request["system"] = system - return {"dialect": "messages", "request": request} - - def b64(media="image/png"): - data = url().split(",", 1)[1] - return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}} - - cases = [ - chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"}, - {"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]), - chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}}, - {"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()}, - {"type": "text", "text": "c"}]}]), - chat([{"role": "system", "content": "be brief"}, - {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]), - chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"}, - {"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]), - chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}, - {"role": "assistant", "content": "a cat"}, - {"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]), - chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"}, - {"type": "image_url", "image_url": {"url": url()}}]}]), - claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]), - claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"), - claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]), - claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]), - claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]), - claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]}, - {"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]), - ] - out = [] - for case in cases: - req = case["request"] - if case["dialect"] == "chat": - messages, tools, kw = openai_to_messages(req) - else: - messages, tools, kw = anthropic_to_messages(req) - out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)}) - write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja", - "cases": out}) - - -SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface, - "timings": timings, "vision": vision, "vision_dialects": vision_dialects} - - -def main(argv): - names = argv or list(SECTIONS) - for name in names: - SECTIONS[name]() - - -if __name__ == "__main__": - main(sys.argv[1:]) diff --git a/control-plane/tests/http_surface.rs b/control-plane/tests/http_surface.rs index 93ff5509..c2bc0d50 100644 --- a/control-plane/tests/http_surface.rs +++ b/control-plane/tests/http_surface.rs @@ -2,7 +2,7 @@ //! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`, //! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python //! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from -//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here +//! `Strata 41cf05a0, serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here //! against the Rust router with a real worker supervisor and the mock engine. //! //! Deliberate differences, skipped in the comparison: the chat template text, the build/version diff --git a/control-plane/tests/mcp_hub/harness.rs b/control-plane/tests/mcp_hub/harness.rs index 46cb3d9a..e546faa2 100644 --- a/control-plane/tests/mcp_hub/harness.rs +++ b/control-plane/tests/mcp_hub/harness.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; use std::process::{Command, Stdio}; pub(super) fn fake_path() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py") + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/mcp_hub/mcp_fake_server.py") } pub(super) fn python() -> Option<&'static str> { diff --git a/control-plane/tests/mcp_hub/main.rs b/control-plane/tests/mcp_hub/main.rs index fce9d816..0b04b8e5 100644 --- a/control-plane/tests/mcp_hub/main.rs +++ b/control-plane/tests/mcp_hub/main.rs @@ -1,6 +1,6 @@ -//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`, -//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients, -//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation. +//! The MCP hub against the Python fake server of the Original (`mcp_fake_server.py` next to this test, from +//! Strata 41cf05a0 `serve/`, standard library only; a test double, not part of serving): stdio and Streamable +//! HTTP clients, paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation. //! The tests are skipped (with a message) when `python3` is not installed. mod harness; diff --git a/engine/strata/serve/mcp_fake_server.py b/control-plane/tests/mcp_hub/mcp_fake_server.py similarity index 100% rename from engine/strata/serve/mcp_fake_server.py rename to control-plane/tests/mcp_hub/mcp_fake_server.py diff --git a/control-plane/tests/mtp_fetch.rs b/control-plane/tests/mtp_fetch.rs index fb1e7413..e5e1e349 100644 --- a/control-plane/tests/mtp_fetch.rs +++ b/control-plane/tests/mtp_fetch.rs @@ -1,5 +1,5 @@ //! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is -//! `engine/strata/tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine. +//! `Strata 41cf05a0, tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine. use std::{ collections::BTreeMap, fs, diff --git a/control-plane/third_party/ggml/UPSTREAM.md b/control-plane/third_party/ggml/UPSTREAM.md index d7bc7ed9..85ac63dd 100644 --- a/control-plane/third_party/ggml/UPSTREAM.md +++ b/control-plane/third_party/ggml/UPSTREAM.md @@ -2,7 +2,7 @@ These unmodified source and header files come from `ggml-org/llama.cpp` commit `3cf03257f219afbe7334045ff7c6a06ac68c627d`, the same commit pinned by -the imported Strata engine in `engine/strata/third_party/ggml/VERSION.txt`. +the Strata engine pinned in `third_party/strata/UPSTREAM.md` (its `third_party/ggml/VERSION.txt`). Their original repository paths are under `ggml/src/` or `ggml/include/`; `ggml-cpu-impl.h` came from `ggml/src/ggml-cpu/`. `SHA256SUMS` records every vendored file. The upstream MIT license is in `LICENSE`. diff --git a/crates/context/src/rope_scaling.rs b/crates/context/src/rope_scaling.rs index acc69f35..f80d23a9 100644 --- a/crates/context/src/rope_scaling.rs +++ b/crates/context/src/rope_scaling.rs @@ -1,6 +1,6 @@ //! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder. //! -//! Literal port of the Original (pinned Strata under `engine/strata/`): +//! Literal port of the Original (pinned Strata, upstream commit 41cf05a0): //! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`, //! `rope_scaling_invalid`, `RopeKernelArgs`), //! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads), diff --git a/crates/context/src/setup_policy.rs b/crates/context/src/setup_policy.rs index 0b20819d..84ee2294 100644 --- a/crates/context/src/setup_policy.rs +++ b/crates/context/src/setup_policy.rs @@ -1,4 +1,4 @@ -//! `engine/strata/setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function. +//! `Strata 41cf05a0, setup.py`'s pure RAM / VRAM / context sizing rules, ported function for function. //! //! The rope half of `setup.py` (`derived_factor`, `resolve_rope`) lives in [`crate::rope_scaling`] //! (`derived_factor`, `setup_resolve_rope`); this module holds the rest: which contexts the RAM allows diff --git a/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp b/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp deleted file mode 100644 index 40d4643b..00000000 --- a/crates/context/tests/rope_plan_golden/gen_kv_pool_golden.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// gen_kv_pool_golden.cpp - prints the Original's `kv_pool_bytes` (src/core/layer.cpp, extracted verbatim by -// gen_plan_golden.py into kv_pool_bytes.inc) for every KV format on several shapes. Output: JSON array. -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include - -using strata::kernels::QsaShapes; - -static bool g_without_key = false; // layer.cpp globals the extracted function reads -static bool g_kv_q4 = false; - -#include "kv_pool_bytes.inc" - -int main() { - struct Shape { int64_t kv, dim, page; }; - const Shape shapes[] = {{2, 256, 4}, {4, 128, 1}, {2, 256, 1}, {1, 64, 8}}; - const int64_t pages[] = {1, 7, 131072, 262144}; - struct Fmt { const char* name; bool without_key, q4, hybrid, int8; }; - // the flag combinations qsa_state_bytes passes: kv_pool_bytes(s, slots, g_kv_hybrid, g_kv_int8 || g_kv_hybrid) - const Fmt fmts[] = {{"fp16", false, false, false, false}, - {"int8", false, false, false, true}, - {"q4_0", false, true, false, false}, - {"k8v4", false, false, true, true}, - {"int8-keyless", true, false, false, true}}; - std::printf("["); - bool first = true; - for (const Shape& sh : shapes) { - QsaShapes s = strata::kernels::qsa_real_shapes(); - s.n_head_kv = sh.kv; - s.head_dim = sh.dim; - s.page_size = sh.page; - for (const Fmt& f : fmts) { - g_without_key = f.without_key; - g_kv_q4 = f.q4; - for (int64_t p : pages) { - std::printf("%s\n {\"n_head_kv\": %lld, \"head_dim\": %lld, \"page_size\": %lld, \"format\": \"%s\", " - "\"pages\": %lld, \"bytes\": %llu}", - first ? "" : ",", (long long) sh.kv, (long long) sh.dim, (long long) sh.page, f.name, - (long long) p, (unsigned long long) kv_pool_bytes(s, p, f.hybrid, f.int8)); - first = false; - } - } - } - std::printf("\n]\n"); - return 0; -} diff --git a/crates/context/tests/rope_plan_golden/gen_plan_golden.py b/crates/context/tests/rope_plan_golden/gen_plan_golden.py deleted file mode 100644 index 11b011ad..00000000 --- a/crates/context/tests/rope_plan_golden/gen_plan_golden.py +++ /dev/null @@ -1,62 +0,0 @@ -#!/usr/bin/env python3 -"""Offline fixture generator (Python is allowed for offline tooling, AGENTS.md): builds the Original's -`strata-plan` CLI (header-only) and the `kv_pool_bytes` harness, runs a table of configurations and writes -memory_plan_golden.json. Usage: gen_plan_golden.py .""" -import json, subprocess, sys, os, re - -out, strata, work = sys.argv[1:4] -cxx = os.environ.get("CXX", "clang++") -here = os.path.dirname(os.path.abspath(__file__)) -flags = ["-std=c++17", "-O2", "-I" + os.path.join(strata, "include"), "-I" + work] - -subprocess.check_call([cxx, *flags, os.path.join(strata, "src/plan/plan_main.cpp"), "-o", os.path.join(work, "strata-plan")]) -with open(os.path.join(strata, "src/core/layer.cpp")) as f: - src = f.read().split("\n") -start = next(i for i, l in enumerate(src) if l.startswith("uint64_t kv_pool_bytes(")) -end = next(i for i in range(start, len(src)) if src[i].startswith("}")) -with open(os.path.join(work, "kv_pool_bytes.inc"), "w") as f: - f.write("\n".join(src[start:end + 1]) + "\n") -subprocess.check_call([cxx, *flags, os.path.join(here, "gen_kv_pool_golden.cpp"), "-o", os.path.join(work, "kvgen")]) -kv_pool = json.loads(subprocess.check_output([os.path.join(work, "kvgen")])) - -G = 1000 ** 3 -GIB = 1024 ** 3 -state_default = 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4) -cases = [] -def add(*args): cases.append([str(a) for a in args]) - -for ctx in (20480, 65536, 131072, 262144, 393216, 524288): - for vram in (12 * G, 16 * G, 24 * G, 32 * G, 32 * GIB, 48 * G): - add("--max-context", ctx, "--vram", vram) -# charter profiles with their state (x2 slots for 2x256K), on 32 GiB with and without resident weights -for (ctx, slots) in ((524288, 1), (524288, 2), (262144, 1), (262144, 2)): - st = state_default * slots - for vram in (16 * G, 24 * G, 32 * GIB): - add("--max-context", ctx, "--vram", vram, "--state", st) - add("--max-context", ctx, "--vram", vram, "--state", st, "--dense", 4 * G, "--embd", 500_000_000, "--workspace", 300_000_000) -# small cards: the planner must refuse -for ctx in (262144, 524288): - for vram in (3 * G, 4 * G, 6 * G, 7 * G): - add("--max-context", ctx, "--vram", vram) -# resident weights larger than the card: derived pool 0 falls back to the default pool -add("--max-context", 4096, "--vram", 5 * G, "--dense", 6 * G) -add("--max-context", 20480) # CLI defaults -add("--pool", 5943000000, "--max-context", 20480) -add("--pool", 3 * G, "--max-context", 100000) -add("--pool", 20 * G, "--max-context", 100000, "--dense", 5 * G, "--embd", G) # --pool still subtracts dense/embd -add("--max-context", 1000, "--vram", 1_000_000) # does not close -add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_399) # no room for one slot (default state) -add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_400) # exactly one slot -add("--max-context", 100, "--vram", 10 * G, "--state", 0) -add("--max-context", 100, "--vram", 10 * G, "--workspace", 123456789) -add("--help") -add("--bogus") -add("--max-context") - -runs = [] -for args in cases: - p = subprocess.run([os.path.join(work, "strata-plan"), *args], capture_output=True, text=True) - runs.append({"args": args, "exit": p.returncode, "stdout": p.stdout, "stderr": p.stderr}) - -json.dump({"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes", - "state_bytes_default": state_default, "cli": runs, "kv_pool": kv_pool}, open(out, "w"), indent=1) diff --git a/crates/context/tests/rope_plan_golden/gen_plan_golden.sh b/crates/context/tests/rope_plan_golden/gen_plan_golden.sh deleted file mode 100755 index 65f76c9a..00000000 --- a/crates/context/tests/rope_plan_golden/gen_plan_golden.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# Regenerates memory_plan_golden.json from the Original (macOS or Linux, any C++17 compiler + python3). -set -eu -here=$(cd "$(dirname "$0")" && pwd) -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -python3 -I "$here/gen_plan_golden.py" "$here/memory_plan_golden.json" "$here/../../../../engine/strata" "$work" diff --git a/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp b/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp deleted file mode 100644 index c0de014b..00000000 --- a/crates/context/tests/rope_plan_golden/gen_rope_golden.cpp +++ /dev/null @@ -1,196 +0,0 @@ -// gen_rope_golden.cpp - golden-fixture generator for the Rust rope port (leleka-runtime::rope_scaling). -// -// It links the ORIGINAL host-side code: `include/strata/kernels/rope_scaling.hpp` is included unmodified, and the -// two `build_rope_table` definitions are extracted VERBATIM from `src/kernels/cuda/rope.cu` by `gen_rope_golden.sh` -// into a generated include (`rope_table_original.inc`). Nothing from the Original is re-typed here. -// -// Every double/float is printed as its IEEE bit pattern in hex so the fixture is exact (serde_json's default -// float parser is not guaranteed correctly rounded). Tables are summarised by FNV-1a 64 over the little-endian -// f32 bytes of the whole cos table and of the whole sin table, plus full rows at selected positions. -#include "strata/kernels/rope_scaling.hpp" - -#include -#include -#include -#include -#include - -namespace strata::kernels { -// the engine's other definitions live in the .cu next to the extracted functions; only the table builders are needed -void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab); -void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab); -} // namespace strata::kernels - -namespace strata::kernels { -#include "rope_table_original.inc" -} // namespace strata::kernels - -using namespace strata::kernels; - -static std::string hex64(double d) { - uint64_t u; - std::memcpy(&u, &d, 8); - char b[32]; - std::snprintf(b, sizeof b, "0x%016llx", (unsigned long long) u); - return b; -} -static std::string hex32(float f) { - uint32_t u; - std::memcpy(&u, &f, 4); - char b[32]; - std::snprintf(b, sizeof b, "0x%08x", u); - return b; -} -static uint64_t fnv(const float* p, size_t n) { - uint64_t h = 0xcbf29ce484222325ull; - for (size_t i = 0; i < n; ++i) { - uint32_t u; - std::memcpy(&u, p + i, 4); - for (int k = 0; k < 4; ++k) { - h ^= (uint8_t) (u >> (8 * k)); - h *= 0x100000001b3ull; - } - } - return h; -} - -struct Case { - const char* name; - const char* desc; - int n_rot; - RopeScaling sc; - bool tables; // build the 524288-position tables (skipped for invalid configs) -}; - -static RopeScaling mk(RopeScalingType t, double fb, double factor, double fsi, double orig, double ext, double attn, - double bf, double bs) { - RopeScaling s; - s.type = t; - s.freq_base = fb; - s.factor = factor; - s.freq_scale_in = fsi; - s.orig_ctx = orig; - s.ext_factor = ext; - s.attn_factor = attn; - s.beta_fast = bf; - s.beta_slow = bs; - return s; -} - -int main() { - using T = RopeScalingType; - const double B = 1e7, O = 262144; - std::vector cases = { - {"none_default", "default-constructed RopeScaling (today's engine)", 64, RopeScaling{}, true}, - {"none_junk_knobs", "type none with every scaling knob set: knobs must be inert", 64, - mk(T::None, B, 4.0, 0.25, 4096, 1.0, 0.5, 20, 2), true}, - {"linear_2", "linear factor 2 (512K over 262144)", 64, mk(T::Linear, B, 2.0, 0, O, 0, 1.0, 32, 1), true}, - {"linear_1_5", "linear factor 1.5 (393216 over 262144)", 64, mk(T::Linear, B, 1.5, 0, O, 0, 1.0, 32, 1), true}, - {"linear_freq_scale_in", "linear with the raw ggml freq_scale 0.25 overriding 1/factor", 64, - mk(T::Linear, B, 2.0, 0.25, O, 0, 1.0, 32, 1), true}, - {"linear_attn_factor", "linear with attn_factor 0.9 and no correction: mscale = attn_factor", 64, - mk(T::Linear, B, 2.0, 0, O, 0, 0.9, 32, 1), true}, - {"yarn_2", "yarn factor 2 (setup.py default for 512K), ext 1, betas 32/1", 64, - mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_1_5", "yarn factor 1.5 (setup.py default for 393216)", 64, - mk(T::YaRN, B, 1.5, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_1", "yarn factor 1 (inside trained range): ramp active, mscale 1", 64, - mk(T::YaRN, B, 1.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_4", "yarn factor 4 (1M context)", 64, mk(T::YaRN, B, 4.0, 0, O, 1.0, 1.0, 32, 1), true}, - {"yarn_2_betas", "yarn factor 2 with attn 1.1, betas 16/2", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.1, 16, 2), true}, - {"yarn_2_ext_half", "yarn factor 2 with ext_factor 0.5", 64, mk(T::YaRN, B, 2.0, 0, O, 0.5, 1.0, 32, 1), true}, - {"yarn_orig_131072", "yarn factor 4 against a 131072 trained context", 64, - mk(T::YaRN, B, 4.0, 0, 131072, 1.0, 1.0, 32, 1), true}, - {"yarn_ext0", "yarn type with ext_factor 0: correction off, behaves as linear", 64, - mk(T::YaRN, B, 2.0, 0, O, 0.0, 1.0, 32, 1), true}, - {"yarn_n_rot128", "yarn n_rot 128, base 1e6, orig 4096, factor 8", 128, - mk(T::YaRN, 1e6, 8.0, 0, 4096, 1.0, 1.0, 32, 1), true}, - {"yarn_n_rot4", "yarn n_rot 4: corr_dims clamps to n_rot-1", 4, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true}, - // invalid (finite) configurations: only the validity message and the scalar resolutions are recorded - {"bad_factor_below_1", "factor 0.5", 64, mk(T::Linear, B, 0.5, 0, O, 0, 1.0, 32, 1), false}, - {"bad_freq_base_1", "freq_base 1 (none)", 64, mk(T::None, 1.0, 1.0, 0, O, 0, 1.0, 32, 1), false}, - {"bad_orig_ctx_0", "orig_ctx 0", 64, mk(T::YaRN, B, 2.0, 0, 0.0, 1.0, 1.0, 32, 1), false}, - {"bad_ext_negative", "ext_factor -1", 64, mk(T::YaRN, B, 2.0, 0, O, -1.0, 1.0, 32, 1), false}, - {"bad_attn_0", "attn_factor 0", 64, mk(T::Linear, B, 2.0, 0, O, 0, 0.0, 32, 1), false}, - {"bad_beta_fast_0", "beta_fast 0", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 0, 1), false}, - {"bad_beta_slow_neg", "beta_slow -1", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, -1), false}, - {"bad_freq_scale_in_neg", "freq_scale_in -0.1", 64, mk(T::Linear, B, 2.0, -0.1, O, 0, 1.0, 32, 1), false}, - {"bad_mscale_negative", "freq_scale_in 1e6 with ext 1: the log term drives mscale negative", 64, - mk(T::YaRN, B, 2.0, 1e6, O, 1.0, 1.0, 32, 1), false}, - }; - - const int NMAX = 524288; - const int NS[2] = {262144, 524288}; - const int SAMPLE_POS[] = {0, 1, 2, 4095, 4096, 65535, 131071, 262143, 262144, 524287}; - const int AN_POS[] = {1, 4096, 262143, 524287}; - std::printf("{\n \"generator\": \"gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)\",\n"); - std::printf(" \"cases\": [\n"); - std::vector cs, sn; - for (size_t ci = 0; ci < cases.size(); ++ci) { - const Case& c = cases[ci]; - const RopeScaling& s = c.sc; - const int half = c.n_rot / 2; - std::printf(" {\n \"name\": \"%s\", \"desc\": \"%s\", \"n_rot\": %d,\n", c.name, c.desc, c.n_rot); - const char* tn = s.type == T::YaRN ? "yarn" : s.type == T::Linear ? "linear" : "none"; - std::printf(" \"type\": \"%s\",\n", tn); - std::printf(" \"freq_base\": \"%s\", \"factor\": \"%s\", \"freq_scale_in\": \"%s\", \"orig_ctx\": \"%s\",\n", - hex64(s.freq_base).c_str(), hex64(s.factor).c_str(), hex64(s.freq_scale_in).c_str(), - hex64(s.orig_ctx).c_str()); - std::printf(" \"ext_factor\": \"%s\", \"attn_factor\": \"%s\", \"beta_fast\": \"%s\", \"beta_slow\": \"%s\",\n", - hex64(s.ext_factor).c_str(), hex64(s.attn_factor).c_str(), hex64(s.beta_fast).c_str(), - hex64(s.beta_slow).c_str()); - const char* bad = rope_scaling_invalid(s); - if (bad) std::printf(" \"invalid\": \"%s\",\n", bad); - else std::printf(" \"invalid\": null,\n"); - std::printf(" \"freq_scale\": \"%s\", \"mscale\": \"%s\",\n", hex64(s.freq_scale()).c_str(), - hex64(s.mscale()).c_str()); - double cd[2]; - s.corr_dims(c.n_rot, cd); - std::printf(" \"corr_dims\": [\"%s\", \"%s\"],\n", hex64(cd[0]).c_str(), hex64(cd[1]).c_str()); - const RopeKernelArgs a = s.kernel_args(c.n_rot); - std::printf(" \"kernel_args\": {\"freq_scale\": \"%s\", \"corr_low\": \"%s\", \"corr_high\": \"%s\", " - "\"ext_factor\": \"%s\", \"attn_factor\": \"%s\"},\n", - hex32(a.freq_scale).c_str(), hex32(a.corr_low).c_str(), hex32(a.corr_high).c_str(), - hex32(a.ext_factor).c_str(), hex32(a.attn_factor).c_str()); - // analytic path (float32 rope_scaled_angle): theta_extrap = (float)(p * inv_i) - std::printf(" \"analytic\": ["); - bool first = true; - const int pairs[] = {0, 1, 7, 15, 16, 31}; - for (int pair : pairs) { - if (pair >= half) continue; - for (int p : AN_POS) { - const double inv = std::pow(s.freq_base, -2.0 * (double) pair / (double) c.n_rot); - const float te = (float) ((double) p * inv); - float co, si; - rope_scaled_angle(te, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si); - std::printf("%s\n {\"theta_extrap\": \"%s\", \"pair\": %d, \"cos\": \"%s\", \"sin\": \"%s\"}", - first ? "" : ",", hex32(te).c_str(), pair, hex32(co).c_str(), hex32(si).c_str()); - first = false; - } - } - std::printf("\n ]"); - if (c.tables) { - cs.assign((size_t) NMAX * half, 0.f); - sn.assign((size_t) NMAX * half, 0.f); - build_rope_table(c.n_rot, s, NMAX, cs.data(), sn.data()); - std::printf(",\n \"tables\": ["); - for (int k = 0; k < 2; ++k) - std::printf("%s\n {\"n_pos\": %d, \"cos_fnv1a64\": \"0x%016llx\", \"sin_fnv1a64\": \"0x%016llx\"}", - k ? "," : "", NS[k], (unsigned long long) fnv(cs.data(), (size_t) NS[k] * half), - (unsigned long long) fnv(sn.data(), (size_t) NS[k] * half)); - std::printf("\n ],\n \"rows\": ["); - for (size_t k = 0; k < sizeof SAMPLE_POS / sizeof *SAMPLE_POS; ++k) { - const int p = SAMPLE_POS[k]; - std::printf("%s\n {\"pos\": %d, \"cos\": [", k ? "," : "", p); - for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(cs[(size_t) p * half + i]).c_str()); - std::printf("], \"sin\": ["); - for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(sn[(size_t) p * half + i]).c_str()); - std::printf("]}"); - } - std::printf("\n ]"); - } - std::printf("\n }%s\n", ci + 1 < cases.size() ? "," : ""); - } - std::printf(" ]\n}\n"); - return 0; -} diff --git a/crates/context/tests/rope_plan_golden/gen_rope_golden.sh b/crates/context/tests/rope_plan_golden/gen_rope_golden.sh deleted file mode 100755 index 78b9b6d5..00000000 --- a/crates/context/tests/rope_plan_golden/gen_rope_golden.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# Regenerates rope_golden.json from the Original's host code (macOS or Linux, any C++17 compiler). -# usage: gen_rope_golden.sh [extra compiler flags] -# The committed fixture is built with -O2 -ffp-contract=off (Rust never fuses multiply-adds) and -# -fno-builtin-sinf/-cosf: Apple clang otherwise merges a sinf+cosf pair into __sincosf_stret, whose sinf -# differs from a separate sinf call by 1-2 ULP, and Rust (like the CUDA device code) calls them separately. -# Only the float32 analytic path is affected; the float64 tables are identical either way. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../../engine/strata" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# extract the two build_rope_table definitions from rope.cu verbatim (up to the next anonymous namespace) -awk '/^void build_rope_table\(int n_rot, double theta/ {on=1} on && /^namespace \{/ {exit} on {print}' \ - "$strata/src/kernels/cuda/rope.cu" > "$work/rope_table_original.inc" -test -s "$work/rope_table_original.inc" -${CXX:-clang++} -std=c++17 -O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf "$@" -I"$strata/include" -I"$work" \ - "$here/gen_rope_golden.cpp" -o "$work/gen_rope_golden" -"$work/gen_rope_golden" > "$here/rope_golden.json" diff --git a/crates/cuda-driver/oracle/check_cu_syntax.sh b/crates/cuda-driver/oracle/check_cu_syntax.sh deleted file mode 100755 index 00318600..00000000 --- a/crates/cuda-driver/oracle/check_cu_syntax.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -# Syntax-check ported .cu files without nvcc. Superseded by the unified stub set under scripts/cuda-stubs/ (clang's CUDA -# frontend against stub headers; covers every .cu, not only the ones the host shim can execute). The EXECUTING emulation -# (shim/cuda_host_shim.h, run_shim_oracles.sh) is a different tool and stays. -# usage: check_cu_syntax.sh [file.cu ...] (no argument: every crates/cuda-driver/src/*.cu) -here=$(cd "$(dirname "$0")" && pwd) -exec python3 "$here/../../../scripts/cuda-stubs/check-cu.py" "$@" diff --git a/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp b/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp deleted file mode 100644 index 47368295..00000000 --- a/crates/cuda-driver/oracle/drivers/prefill_ring_trace.cpp +++ /dev/null @@ -1,463 +0,0 @@ -// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp -// (sha256 1d18288208debcf1d26021ed8bdfc2633db6dcbd88d899c76d1f628b57838c91). The code between the VERBATIM markers is copied from that file (lines 1170-1228, 1279-1287, 1692-1743, 1806-1853); -// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer -// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule. -#include -#include -#include -#include -#include -#include -#include -#include -#include -using cudaStream_t = int; -using cudaEvent_t = int; -enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 }; -constexpr int STAGE = 8, RING_MAX = 512, DQ = 2; -static std::vector g_ops; -static void op(const std::string& s) { g_ops.push_back(s); } -static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; } -static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); } -static std::string src_of_host(const void* p) { - const uintptr_t v = (uintptr_t) p; - if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u); - return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u); -} -static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) { - op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src)); - return 0; -} -static std::string ev_name(cudaEvent_t e) { - if (e >= 4000) return "ple_copied " + std::to_string(e - 4000); - if (e >= 3000) return "dma " + std::to_string(e - 3000); - return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000)); -} -static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; } -static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; } -struct Clock { struct time_point {}; static time_point now() { return {}; } }; -static double ms_since(Clock::time_point) { return 0.0; } -struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } }; -namespace strata { namespace kernels { namespace cpu { -using ExpertLayout = ExpertLayoutStub; -inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; } -} } } -struct ModelGeom { int64_t n_expert; int64_t n_layers; }; -struct Scenario { - const char* name; - int n_layers, n_expert, lb, le, ring, stager_ring; - int64_t T; // rows of the chunk (stream_all needs T >= 1024) - std::vector> orders; // per layer in [lb, le): routed experts, ascending - int resident_mod, resident_rem; // cache-resident when e % mod == rem (mod 0: none) - bool cache_present; - int pinned_mod, transient_mod; // pinned: e % pinned_mod == 0; transient: (e+l) % transient_mod == 0 - int chunks; -}; -static const Scenario* g_sc = nullptr; -struct Src { - bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e % g_sc->pinned_mod == 0; } - bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) % g_sc->transient_mod == 0; } - const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); } -}; -struct Stager { - struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; }; - int kRing = 16; - void start(std::vector&& js) { - if (js.empty()) return; // Stager::start - std::string d = "H stager_start"; - for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U"; - op(d + " n=" + std::to_string(js.size())); - } - const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j % kRing) * 0x1000u); } - void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j % kRing, copy); } - void finish() { op("H stager_finish"); } -}; -struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } }; -struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; }; -constexpr int64_t N = 2560; -struct PT { void mark(int, cudaStream_t) {} }; -enum { kPfWaitCopy = 0, kPfDequant = 1 }; -inline int64_t stream_all_min() { return 1024; } -// ---- PLE read-ahead stubs -#include -static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); } -static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) { - (void) dst; - op("K upload ple_emb " + ple_buf_of(src, 0x60000000u)); - return 0; -} -static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; } -template static std::future shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); } -struct PleTable { - bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; } -}; -struct PleState { PleTable* table; }; -struct SessionStub { struct { PleTable* table; } ple; }; -struct Impl { - Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr; - int ring = STAGE; cudaStream_t cs = 2, copy = 1; - std::unique_ptr stager; - uint8_t* stage_dev[RING_MAX] = {}; - cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; - bool stage_live[RING_MAX] = {}; - float* ple_emb = nullptr; - float* ple_emb_host[2] = {}; - cudaEvent_t ple_copied[2] = {}; - std::vector ple_rows[2]; - int64_t T = 0; -}; - -static void run_scenario(const Scenario& sc) { - g_sc = ≻ - g_ops.clear(); - Impl m; - ModelGeom geom{sc.n_expert, sc.n_layers}; - const ModelGeom& g = geom; - Src src_obj; Cache cache_obj; - m.src = &src_obj; - m.g = &geom; - m.ring = sc.ring; - m.stager.reset(new Stager()); - m.stager->kRing = sc.stager_ring; - for (int i = 0; i < RING_MAX; ++i) { - m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u); - m.copied[i] = 1000 + i; m.used[i] = 2000 + i; - } - std::vector host_res_table((size_t) sc.n_layers * sc.n_expert, -1); - if (sc.cache_present) { - int next_slot = 0; - for (int l = 0; l < sc.n_layers; ++l) - for (int e = 0; e < sc.n_expert; ++e) - if (sc.resident_mod != 0 && e % sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++; - m.host_res = host_res_table.data(); - m.cache = &cache_obj; - } - Stats stats_; - PT pt; - cudaStream_t cs = m.cs; - const int64_t LB = sc.lb, LE = sc.le, T = sc.T; - std::string err; - for (int chunk = 0; chunk < sc.chunks; ++chunk) { - op("H chunk " + std::to_string(chunk)); - auto chunk_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (sequence, issue_until) ---- - const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout(); - const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr; - struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; }; - std::vector seq; - std::vector seq_start; - size_t issued = 0, consumed = 0; - if (stream_all) { - seq_start.assign((size_t) g.n_layers + 1, 0); - std::vector js; - for (int64_t l = LB; l < LE; ++l) { - seq_start[(size_t) l] = seq.size(); - for (int32_t e = 0; e < m.g->n_expert; ++e) { - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - int job = -1; - const uint8_t* b = nullptr; - if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer - job = (int) js.size(); - js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e}); - } else { - b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - if (!m.src->pinned(l, e)) { - job = (int) js.size(); - js.push_back({b, (size_t) lay0.blob_bytes(l)}); - } - } - seq.push_back({(int32_t) l, e, b, job}); - } - } - for (int64_t l = LE; l <= g.n_layers; ++l) seq_start[(size_t) l] = seq.size(); - m.stager->start(std::move(js)); - } - struct StagerDone { - Stager* st; - ~StagerDone() { if (st) st->finish(); } - } chunk_stager_done{stream_all ? m.stager.get() : nullptr}; - auto issue_until = [&](size_t limit) { - limit = std::min(limit, seq.size()); - while (issued < limit) { - const StreamEntry& en = seq[issued]; - const int sl = (int) (issued % (size_t) m.ring); - const auto th = Clock::now(); - const size_t bytes = (size_t) lay0.blob_bytes(en.l); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - if (en.job < 0) { - cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - const uint8_t* hb = m.stager->wait(en.job); - cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(en.job, m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - ++issued; - } - }; -// ---- end VERBATIM ---- - const bool threaded_issue = false; - std::atomic a_issued{0}, a_consumed{0}; -// ---- VERBATIM prefill.cpp (wait_issued, give_back) ---- - // the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back - auto wait_issued = [&](size_t k) { - if (!threaded_issue) return; - while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield(); - }; - auto give_back = [&](size_t upto) { - if (threaded_issue) a_consumed.store(upto, std::memory_order_release); - else issue_until(upto + (size_t) m.ring); - }; -// ---- end VERBATIM ---- - if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); } - for (int64_t l = LB; l < LE; ++l) { - const std::vector& order = sc.orders[(size_t) (l - LB)]; - op("H layer " + std::to_string(l)); - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); -// ---- VERBATIM prefill.cpp (staging setup, stage_one) ---- - // Stage ahead: the copy stream moves blobs host -> device while the compute stream works. - int stage_next = 0; - std::vector stage_of(order.size(), -1); - // the unpinned ones are copied to pinned buffers by the stager's threads, in this order - std::vector job_of(order.size(), -1); - if (!stream_all) { - std::vector js; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue; - if (m.src->pinned(l, e)) continue; - job_of[j] = (int) js.size(); - if (m.src->transient(l, e)) { // CS-T: copied by the source - js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e}); - continue; - } - const uint8_t* b = m.src->blob(l, e); - if (!b) { err = "prefill: expert source has no blob"; return false; } - js.push_back({b, (size_t) lay.blob_bytes(l)}); - } - m.stager->start(std::move(js)); - } - StagerDone stager_done{stream_all ? nullptr : m.stager.get()}; - auto stage_one = [&](size_t j) -> bool { - const int32_t e = order[j]; - const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0; - if (resident) return true; - const int sl = stage_next; - stage_next = (stage_next + 1) % STAGE; - const auto th = Clock::now(); - const bool pinned = m.src->pinned(l, e); // pinned: never transient - const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr; - if (pinned && !b) { err = "prefill: expert source has no blob"; return false; } - if (pinned) { - // DMA straight from the page-locked arena: the copy stream only waits for the slot - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - ++stats_.experts_dma; - } else { - // copied to a pinned buffer by the stager (waits only if it is behind), then DMA - const uint8_t* hb = m.stager->wait(job_of[j]); - if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0); - cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy); - m.stager->issued_one(job_of[j], m.copy); - } - cudaEventRecord(m.copied[sl], m.copy); - m.stage_live[sl] = true; - stage_of[j] = sl; - stats_.ms_experts_host += ms_since(th); - ++stats_.experts_streamed; - return true; - }; -// ---- end VERBATIM ---- - auto compute = [&](size_t j, const uint8_t*, int slot) -> bool { - op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-"))); - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob - return true; - }; -// ---- VERBATIM prefill.cpp (the walks) ---- - if (!stream_all) { - size_t staged = 0; - const size_t lookahead = STAGE - 1; - for (size_t j = 0; j < order.size(); ++j) { - while (staged < order.size() && staged <= j + lookahead) { - if (!stage_one(staged)) return false; - ++staged; - } - const int32_t e = order[j]; - if (stage_of[j] < 0) { - ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; - } else { - pt.mark(kPfWaitCopy, cs); - cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0); - if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false; - } - } - } else { - // the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not - // pick only gives its slot back - size_t k = seq_start[(size_t) l]; - const size_t kend = seq_start[(size_t) l + 1]; - auto release_to = [&](int32_t e_stop) { - while (k < kend && seq[k].e < e_stop) { - cudaEventRecord(m.used[k % (size_t) m.ring], m.cs); - consumed = ++k; - give_back(consumed); - } - }; - for (size_t j = 0; j < order.size(); ++j) { - const int32_t e = order[j]; - release_to(e); - if (k < kend && seq[k].e == e) { - const int sl = (int) (k % (size_t) m.ring); - pt.mark(kPfWaitCopy, cs); - wait_issued(k); - cudaStreamWaitEvent(m.cs, m.copied[sl], 0); - if (!compute(j, m.stage_dev[sl], sl)) return false; - consumed = ++k; - give_back(consumed); - } else { - ++stats_.experts_resident; - if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false; - } - } - release_to(m.g->n_expert); - } -// ---- end VERBATIM ---- - op("K combine"); - } - return true; - }; - if (!chunk_fn()) { std::fprintf(stderr, "scenario %s failed: %s\n", sc.name, err.c_str()); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"p\":{\"n_layers\":%d,\"n_expert\":%d,\"lb\":%d,\"le\":%d,\"ring\":%d,\"stager_ring\":%d,\"rows\":%lld," - "\"resident_mod\":%d,\"resident_rem\":%d,\"cache_present\":%d,\"pinned_mod\":%d,\"transient_mod\":%d,\"chunks\":%d,\"orders\":[", - sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem, - (int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks); - for (size_t li = 0; li < sc.orders.size(); ++li) { - std::printf("%s[", li ? "," : ""); - for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%s%d", k ? "," : "", sc.orders[li][k]); - std::printf("]"); - } - std::printf("]},\"stats\":[%lld,%lld,%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; }; -static void run_ple_scenario(const PleScenario& sc) { - g_ops.clear(); - Impl m; - m.T = sc.T; - PleTable table; - SessionStub ss; - ss.ple.table = &table; - for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); } - m.ple_emb = (float*) 0x70000000u; - Stats stats_; - std::string err; - const int64_t n = sc.n; - const bool ple_on = true, ple_gpu_cache = sc.gpu_cache; - std::string ple_next_err; - std::future ple_next; - int ple_buf = 0; - auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; }; - for (int64_t c0 = 0; c0 < n; c0 += m.T) { - const int64_t T = std::min(m.T, n - c0); - op("H ple_chunk " + std::to_string(c0)); - cudaStream_t cs = 2; (void) cs; - auto ple_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ---- - if (ple_on) { - const auto tp = Clock::now(); - if (ple_gpu_cache) { - if (!ple_gather(c0, 0, err) || - !ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T, - m.ple_emb, m.cs, err)) return false; - } else if (!ple_next.valid()) { - if (!ple_gather(c0, ple_buf, err)) return false; - } else if (!ple_next.get()) { - err = ple_next_err; - return false; - } - if (!ple_gpu_cache) { - cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs); - cudaEventRecord(m.ple_copied[ple_buf], m.cs); - if (c0 + m.T < n) { - cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done - ple_next = shim_async( [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] { - return ple_gather(c1, b, ple_next_err); - }); - } - ple_buf ^= 1; - } - stats_.ms_ple += ms_since(tp); - } -// ---- end VERBATIM ---- - return true; - }; - if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -// ---- the GR write fusion decision of one half -namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } } -static bool g_gr_unfused = false; -static bool gr_unfused() { return g_gr_unfused; } -static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) { - g_gr_unfused = unfused; - strata::kernels::cvec().cover = cvec_covers; - const int64_t nl = half == 0 ? l : l + 1; - const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) && - !(half == 1 && strata::kernels::cvec().covers(l)); - return fuse; -} - -static std::vector iota_vec(int n, int step = 1, int from = 0) { - std::vector v; - for (int i = from; i < n; i += step) v.push_back(i); - return v; -} -int main() { - std::vector sc; - // fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks - sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024, - {iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2}); - sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048, - {iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2}); - sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024, - {iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1}); - sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096, - {{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2}); - sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512, - {iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2}); - sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096, - {iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1}); - sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100, - {{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1}); - std::printf("{\"ring\":["); - for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); } - std::printf("],\n"); - std::vector ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false}, - {"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false}, - {"ple_exact_multiple", 2048, 1024, false}}; - std::printf("\"ple\":["); - for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); } - std::printf("],\n\"fuse\":["); - bool first = true; - for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused) - for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) { - if (l >= le) continue; - std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0)); - first = false; - } - std::printf("]}\n"); - return 0; -} diff --git a/crates/cuda-driver/oracle/gen_prefill_ring_trace.py b/crates/cuda-driver/oracle/gen_prefill_ring_trace.py deleted file mode 100644 index fe07b3da..00000000 --- a/crates/cuda-driver/oracle/gen_prefill_ring_trace.py +++ /dev/null @@ -1,321 +0,0 @@ -#!/usr/bin/env python3 -"""Builds drivers/prefill_ring_trace.cpp by EXTRACTING the expert-stream scheduling code of the Original -engine/strata/src/prefill/prefill.cpp (the sequence builder + issue_until, wait_issued / give_back, the staged -stage_one lambda, and the two per-layer expert walks) verbatim between textual markers, wrapped in a host harness whose -cuda* calls only append to a trace. usage: gen_prefill_ring_trace.py [prefill.cpp] > drivers/prefill_ring_trace.cpp -The trace line format is the golden-fixture format read by original_prefill_schedule.rs.""" -import hashlib, os, sys - -here = os.path.dirname(os.path.abspath(__file__)) -path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, '../../../engine/strata/src/prefill/prefill.cpp') -text = open(path).read() -lines = text.split('\n') - -def find(marker, start=0): - for i in range(start, len(lines)): - if marker in lines[i]: - return i - raise SystemExit('marker not found: ' + marker) - -def cut(first, last_exclusive, start=0): - a = find(first, start) - b = find(last_exclusive, a + 1) - return '\n'.join(lines[a:b]), a + 1, b - -seq_build, a1, b1 = cut('const strata::kernels::cpu::ExpertLayout& lay0', '// D-5: the stream is issued by its own host thread') -consumer, a2, b2 = cut("// the consumer's side:", 'host_setup_ms += ms_since(tsetup);') -staged, a3, b3 = cut('// Stage ahead: the copy stream moves blobs host -> device', "// one expert's products from its blob on the device") -w_first = find('auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {') -a4 = find('if (!stream_all) {', w_first) -b4 = find('pt.mark(kPfCombine, cs);', a4) -walks = '\n'.join(lines[a4:b4]) -ple_a = find('// ---- the PLE rows of the whole chunk') -ple_first = find('if (ple_on) {', ple_a) -ple_last = find('for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1];', ple_first) -ple_block = '\n'.join(lines[ple_first:ple_last]) -assert 'std::async(std::launch::async,' in ple_block -ple_block = ple_block.replace('std::async(std::launch::async,', 'shim_async(') # the one documented edit: deferred, logged -fuse_a = find('const int64_t nl = half == 0 ? l : l + 1;') -fuse_b = find('const core::WeightRef* wnn = nullptr;', fuse_a) -fuse_block = '\n'.join(lines[fuse_a:fuse_b]) -digest = hashlib.sha256(text.encode()).hexdigest() - -template = r'''// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp -// (sha256 __DIGEST__). The code between the VERBATIM markers is copied from that file (lines __R1__, __R2__, __R3__, __R4__); -// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer -// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule. -#include -#include -#include -#include -#include -#include -#include -#include -#include -using cudaStream_t = int; -using cudaEvent_t = int; -enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 }; -constexpr int STAGE = 8, RING_MAX = 512, DQ = 2; -static std::vector g_ops; -static void op(const std::string& s) { g_ops.push_back(s); } -static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; } -static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); } -static std::string src_of_host(const void* p) { - const uintptr_t v = (uintptr_t) p; - if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u); - return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u); -} -static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) { - op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src)); - return 0; -} -static std::string ev_name(cudaEvent_t e) { - if (e >= 4000) return "ple_copied " + std::to_string(e - 4000); - if (e >= 3000) return "dma " + std::to_string(e - 3000); - return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000)); -} -static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; } -static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; } -struct Clock { struct time_point {}; static time_point now() { return {}; } }; -static double ms_since(Clock::time_point) { return 0.0; } -struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } }; -namespace strata { namespace kernels { namespace cpu { -using ExpertLayout = ExpertLayoutStub; -inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; } -} } } -struct ModelGeom { int64_t n_expert; int64_t n_layers; }; -struct Scenario { - const char* name; - int n_layers, n_expert, lb, le, ring, stager_ring; - int64_t T; // rows of the chunk (stream_all needs T >= 1024) - std::vector> orders; // per layer in [lb, le): routed experts, ascending - int resident_mod, resident_rem; // cache-resident when e %% mod == rem (mod 0: none) - bool cache_present; - int pinned_mod, transient_mod; // pinned: e %% pinned_mod == 0; transient: (e+l) %% transient_mod == 0 - int chunks; -}; -static const Scenario* g_sc = nullptr; -struct Src { - bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e %% g_sc->pinned_mod == 0; } - bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) %% g_sc->transient_mod == 0; } - const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); } -}; -struct Stager { - struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; }; - int kRing = 16; - void start(std::vector&& js) { - if (js.empty()) return; // Stager::start - std::string d = "H stager_start"; - for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U"; - op(d + " n=" + std::to_string(js.size())); - } - const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j %% kRing) * 0x1000u); } - void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j %% kRing, copy); } - void finish() { op("H stager_finish"); } -}; -struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } }; -struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; }; -constexpr int64_t N = 2560; -struct PT { void mark(int, cudaStream_t) {} }; -enum { kPfWaitCopy = 0, kPfDequant = 1 }; -inline int64_t stream_all_min() { return 1024; } -// ---- PLE read-ahead stubs -#include -static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); } -static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) { - (void) dst; - op("K upload ple_emb " + ple_buf_of(src, 0x60000000u)); - return 0; -} -static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; } -template static std::future shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); } -struct PleTable { - bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; } -}; -struct PleState { PleTable* table; }; -struct SessionStub { struct { PleTable* table; } ple; }; -struct Impl { - Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr; - int ring = STAGE; cudaStream_t cs = 2, copy = 1; - std::unique_ptr stager; - uint8_t* stage_dev[RING_MAX] = {}; - cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {}; - bool stage_live[RING_MAX] = {}; - float* ple_emb = nullptr; - float* ple_emb_host[2] = {}; - cudaEvent_t ple_copied[2] = {}; - std::vector ple_rows[2]; - int64_t T = 0; -}; - -static void run_scenario(const Scenario& sc) { - g_sc = ≻ - g_ops.clear(); - Impl m; - ModelGeom geom{sc.n_expert, sc.n_layers}; - const ModelGeom& g = geom; - Src src_obj; Cache cache_obj; - m.src = &src_obj; - m.g = &geom; - m.ring = sc.ring; - m.stager.reset(new Stager()); - m.stager->kRing = sc.stager_ring; - for (int i = 0; i < RING_MAX; ++i) { - m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u); - m.copied[i] = 1000 + i; m.used[i] = 2000 + i; - } - std::vector host_res_table((size_t) sc.n_layers * sc.n_expert, -1); - if (sc.cache_present) { - int next_slot = 0; - for (int l = 0; l < sc.n_layers; ++l) - for (int e = 0; e < sc.n_expert; ++e) - if (sc.resident_mod != 0 && e %% sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++; - m.host_res = host_res_table.data(); - m.cache = &cache_obj; - } - Stats stats_; - PT pt; - cudaStream_t cs = m.cs; - const int64_t LB = sc.lb, LE = sc.le, T = sc.T; - std::string err; - for (int chunk = 0; chunk < sc.chunks; ++chunk) { - op("H chunk " + std::to_string(chunk)); - auto chunk_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (sequence, issue_until) ---- -__SEQ_BUILD__ -// ---- end VERBATIM ---- - const bool threaded_issue = false; - std::atomic a_issued{0}, a_consumed{0}; -// ---- VERBATIM prefill.cpp (wait_issued, give_back) ---- -__CONSUMER__ -// ---- end VERBATIM ---- - if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); } - for (int64_t l = LB; l < LE; ++l) { - const std::vector& order = sc.orders[(size_t) (l - LB)]; - op("H layer " + std::to_string(l)); - const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); -// ---- VERBATIM prefill.cpp (staging setup, stage_one) ---- -__STAGED__ -// ---- end VERBATIM ---- - auto compute = [&](size_t j, const uint8_t*, int slot) -> bool { - op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-"))); - if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob - return true; - }; -// ---- VERBATIM prefill.cpp (the walks) ---- -__WALKS__ -// ---- end VERBATIM ---- - op("K combine"); - } - return true; - }; - if (!chunk_fn()) { std::fprintf(stderr, "scenario %%s failed: %%s\n", sc.name, err.c_str()); std::exit(2); } - } - std::printf("{\"name\":\"%%s\",\"p\":{\"n_layers\":%%d,\"n_expert\":%%d,\"lb\":%%d,\"le\":%%d,\"ring\":%%d,\"stager_ring\":%%d,\"rows\":%%lld," - "\"resident_mod\":%%d,\"resident_rem\":%%d,\"cache_present\":%%d,\"pinned_mod\":%%d,\"transient_mod\":%%d,\"chunks\":%%d,\"orders\":[", - sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem, - (int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks); - for (size_t li = 0; li < sc.orders.size(); ++li) { - std::printf("%%s[", li ? "," : ""); - for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%%s%%d", k ? "," : "", sc.orders[li][k]); - std::printf("]"); - } - std::printf("]},\"stats\":[%%lld,%%lld,%%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%%s\"%%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; }; -static void run_ple_scenario(const PleScenario& sc) { - g_ops.clear(); - Impl m; - m.T = sc.T; - PleTable table; - SessionStub ss; - ss.ple.table = &table; - for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); } - m.ple_emb = (float*) 0x70000000u; - Stats stats_; - std::string err; - const int64_t n = sc.n; - const bool ple_on = true, ple_gpu_cache = sc.gpu_cache; - std::string ple_next_err; - std::future ple_next; - int ple_buf = 0; - auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; }; - for (int64_t c0 = 0; c0 < n; c0 += m.T) { - const int64_t T = std::min(m.T, n - c0); - op("H ple_chunk " + std::to_string(c0)); - cudaStream_t cs = 2; (void) cs; - auto ple_fn = [&]() -> bool { -// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ---- -__PLE__ -// ---- end VERBATIM ---- - return true; - }; - if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); } - } - std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache); - for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str()); - std::printf("]}"); -} - -// ---- the GR write fusion decision of one half -namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } } -static bool g_gr_unfused = false; -static bool gr_unfused() { return g_gr_unfused; } -static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) { - g_gr_unfused = unfused; - strata::kernels::cvec().cover = cvec_covers; -__FUSE__ - return fuse; -} - -static std::vector iota_vec(int n, int step = 1, int from = 0) { - std::vector v; - for (int i = from; i < n; i += step) v.push_back(i); - return v; -} -int main() { - std::vector sc; - // fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks - sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024, - {iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2}); - sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048, - {iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2}); - sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024, - {iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1}); - sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096, - {{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2}); - sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512, - {iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2}); - sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096, - {iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1}); - sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100, - {{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1}); - std::printf("{\"ring\":["); - for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); } - std::printf("],\n"); - std::vector ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false}, - {"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false}, - {"ple_exact_multiple", 2048, 1024, false}}; - std::printf("\"ple\":["); - for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); } - std::printf("],\n\"fuse\":["); - bool first = true; - for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused) - for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) { - if (l >= le) continue; - std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0)); - first = false; - } - std::printf("]}\n"); - return 0; -} -''' -out = (template.replace('__DIGEST__', digest) - .replace('__R1__', f'{a1}-{b1}').replace('__R2__', f'{a2}-{b2}').replace('__R3__', f'{a3}-{b3}').replace('__R4__', f'{a4+1}-{b4}') - .replace('__SEQ_BUILD__', seq_build).replace('__CONSUMER__', consumer).replace('__STAGED__', staged).replace('__WALKS__', walks).replace('__PLE__', ple_block).replace('__FUSE__', fuse_block)) -out = out.replace('%%', '%') -sys.stdout.write(out) diff --git a/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs b/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs index b241d9c7..a2f75343 100644 --- a/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs +++ b/crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/physical_layout.rs @@ -1,7 +1,7 @@ //! Physical `MtpDrafter::load` arena contract. //! //! The order below is the literal `Bump::take` order in -//! `engine/strata/src/core/mtp.cpp`. Keep this independent from the smaller +//! `Strata 41cf05a0, src/core/mtp.cpp`. Keep this independent from the smaller //! prefix and tail views: those views borrow spans of this one allocation. use super::{DeviceBuffer, Error, Result, Scratch}; use crate::ffi::BufferHandle; diff --git a/crates/cuda-driver/src/original_mtp_draft_vocab.rs b/crates/cuda-driver/src/original_mtp_draft_vocab.rs index 4a69047b..ba240b0b 100644 --- a/crates/cuda-driver/src/original_mtp_draft_vocab.rs +++ b/crates/cuda-driver/src/original_mtp_draft_vocab.rs @@ -2,7 +2,8 @@ //! //! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299 //! of the 248,320 rows, English, code and every CJK token). Upstream Strata ships three smaller or different subsets -//! built with the same tool (`engine/strata/tools/draft_vocab.py`) and selects one with `--draft-vocab en|cyrillic|fr` +//! built with the same tool (`Strata 41cf05a0, tools/draft_vocab.py`) and selects one with +//! `--draft-vocab en|cyrillic|fr` //! or //! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the //! draft: about 110 MiB less VRAM and a shorter draft LM-head GEMV, at the price that a token outside the subset can diff --git a/crates/cuda-driver/src/original_mtp_rt.rs b/crates/cuda-driver/src/original_mtp_rt.rs index d0ac9d04..4cb26875 100644 --- a/crates/cuda-driver/src/original_mtp_rt.rs +++ b/crates/cuda-driver/src/original_mtp_rt.rs @@ -1,7 +1,7 @@ //! Host half of Original `MtpDrafter::load` (core/mtp.cpp:143-205) and the file //! reads of `bind` (:380-415): the `tools/mtp_rt.py` runtime directory. //! -//! Directory layout (engine/strata/tools/mtp_rt.py): `dense.txt` one line per +//! Directory layout (Strata 41cf05a0, tools/mtp_rt.py): `dense.txt` one line per //! tensor `name kind rows cols offset bytes` (kind q8_0|bf16|f32), `dense.bin` //! every indexed tensor 256-aligned, `experts.bin` 512 routed expert blobs, //! optional `draft_vocab.bin` int32 token ids. diff --git a/crates/cuda-driver/src/original_verify/down.rs b/crates/cuda-driver/src/original_verify/down.rs index 1d9ec6ec..2e1bbd73 100644 --- a/crates/cuda-driver/src/original_verify/down.rs +++ b/crates/cuda-driver/src/original_verify/down.rs @@ -1,5 +1,5 @@ //! D1 `LELEKA_SM120_DOWN_SUB16`: the routed experts' down projection with upstream's group-strided sub8/sub16 kernel -//! (`native_down_multi_kernel`, `engine/strata/.../iq_kernels.cu:2130`), formats 20 and 42. +//! (`native_down_multi_kernel`, `Strata 41cf05a0, .../iq_kernels.cu:2130`), formats 20 and 42. //! //! `sm120_down_sub16.cu` computes the same floats as `window_moe_down_` of `original_verify_window_moe_experts.cu` //! (the model-free probe `tools/decode-sm120/sm120_probe.cpp down` compares them byte for byte), with 8 (IQ4_NL) or 16 diff --git a/crates/cuda-driver/src/original_verify/moe.rs b/crates/cuda-driver/src/original_verify/moe.rs index ba619f6c..967d0b40 100644 --- a/crates/cuda-driver/src/original_verify/moe.rs +++ b/crates/cuda-driver/src/original_verify/moe.rs @@ -1,5 +1,5 @@ //! MoE / FFN producers of the Verifier window (child of `original_verify`): the FFN half of -//! `pre` and `post` of `Verifier::record_window` (engine/strata/src/core/verify.cpp) as pure launch plans +//! `pre` and `post` of `Verifier::record_window` (Strata 41cf05a0, src/core/verify.cpp) as pure launch plans //! over sealed assets. //! //! ```text diff --git a/crates/cuda-driver/src/original_verify/sm120.rs b/crates/cuda-driver/src/original_verify/sm120.rs index 816d371d..231954d8 100644 --- a/crates/cuda-driver/src/original_verify/sm120.rs +++ b/crates/cuda-driver/src/original_verify/sm120.rs @@ -1,5 +1,5 @@ //! claude/decode-sm120-switches: the bitwise decode switches that Strata 0.2.6 turns on by default on a compute -//! capability 12.0 card (`engine/strata/include/strata/core/sm120_series.hpp`), as switches of the Original-literal +//! capability 12.0 card (`Strata 41cf05a0, include/strata/core/sm120_series.hpp`), as switches of the Original-literal //! verify window. //! //! Each switch replaces kernels of the window by upstream's faster kernels that compute every output byte as the diff --git a/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs b/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs index d2d39573..528bd936 100644 --- a/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs +++ b/crates/cuda-driver/src/qwen_dispatch/gdn_fused_t1.rs @@ -6,7 +6,7 @@ //! `fused_gdn_ab` (BF16 alpha/beta GEMV + softplus/sigmoid epilogues), //! `fused_gdn_step_norm` (state update, readout, per-head RMS norm, ssm_norm weight, sigmoid(z) gate; state in //! place). -//! The kernels are the verbatim text of `engine/strata/src/kernels/cuda/fused_gdn.cu` (see +//! The kernels are the verbatim text of `Strata 41cf05a0, src/kernels/cuda/fused_gdn.cu` (see //! `offline_gdn_fused_t1_kernel.cu`). The pinned decode/T1 asset of `offline_gdn_kernel.cu` (decomposed //! `native_gdn = true / fused_gdn = false`) is NOT touched and keeps serving the decomposed path and MTP //! verification. diff --git a/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs b/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs index a10555c2..36dc7e85 100644 --- a/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs +++ b/crates/cuda-driver/src/qwen_dispatch/gdn_native_batch.rs @@ -5,7 +5,7 @@ //! BF16 alpha / beta GEMMs -> `gdn_gates` -> `gdn_conv` (+history) -> `gdn_l2` //! -> `gdn_rec_cols_pipe` -> `gdn_out_norm` (f32 `y` and half `y16`) -> native //! Out GEMM from `y16`. The kernels are the verbatim text of -//! `engine/strata/src/prefill/kernels.cu` (see `offline_gdn_prefill_kernel.cu`); +//! `Strata 41cf05a0, src/prefill/kernels.cu` (see `offline_gdn_prefill_kernel.cu`); //! the dequantizers are those of `dequant_bf16.cu`; the GEMMs are cuBLAS calls //! made by a closed adapter behind [`GdnGemm`]. This is NOT the pinned decode //! T1 arithmetic of `offline_gdn_kernel.cu`, which stays untouched for decode diff --git a/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs b/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs index aab1ce61..f06cf7f6 100644 --- a/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs +++ b/crates/cuda-driver/src/qwen_dispatch/moe_prefill_batch.rs @@ -1,7 +1,7 @@ //! Closed batched MoE router + shared-expert program of the Strata PREFILL path //! (STRA-169, option B), whole micro-window of `T` rows per drain. //! -//! Original program (engine/strata/src/prefill/prefill.cpp, MoE half): +//! Original program (Strata 41cf05a0, src/prefill/prefill.cpp, MoE half): //! BF16 router GEMM over the whole window (`bf16_proj(wr, mixed_bf, logits)`, + lo pass when enabled) //! -> `route()` = `route_kernel<16>` (warp per token, plain `expf`) -> ids/weights //! -> shared expert: native gate / up (dequantized GGUF blocks -> FP16 GEMM from `mixed_h`), diff --git a/crates/cuda-model/src/original_prefill_schedule.rs b/crates/cuda-model/src/original_prefill_schedule.rs index 3fafe0e0..d25abe10 100644 --- a/crates/cuda-model/src/original_prefill_schedule.rs +++ b/crates/cuda-model/src/original_prefill_schedule.rs @@ -1,5 +1,5 @@ //! Pure, platform-independent port of the SCHEDULING half of the Original `Prefill::run` -//! (engine/strata/src/prefill/prefill.cpp, "bool Prefill::run"): the per-chunk expert-stream plan (sequence +//! (Strata 41cf05a0, src/prefill/prefill.cpp, "bool Prefill::run"): the per-chunk expert-stream plan (sequence //! builder, `issue_until`, `give_back`, the streamed and the staged per-layer walks), the PLE row read-ahead //! double buffer, the hyper-connection write fusion rule, the layer-split hand-off double buffer and `ring_slots`. //! diff --git a/crates/deploy/build.rs b/crates/deploy/build.rs index ef6aa65a..827613f5 100644 --- a/crates/deploy/build.rs +++ b/crates/deploy/build.rs @@ -1,10 +1,10 @@ //! Build identity for `leleka version`. //! //! Embeds the git commit of the tree the binary was built from, whether that tree had uncommitted changes, and the -//! Strata upstream pin recorded in `engine/upstream.md`. The release packager (`scripts/release/package-5090.sh`) -//! exports `LELEKA_GIT_COMMIT` and `LELEKA_GIT_DIRTY` so the values do not depend on `git` being callable from the -//! build script; an ordinary developer build asks git itself and falls back to `unknown` (an exported tree has -//! no `.git`). +//! Strata upstream pin recorded in `third_party/strata/UPSTREAM.md`. The release packager +//! (`scripts/release/package-5090.sh`) exports `LELEKA_GIT_COMMIT` and `LELEKA_GIT_DIRTY` so the values do not +//! depend on `git` being callable from the build script; an ordinary developer build asks git itself and falls +//! back to `unknown` (an exported tree has no `.git`). //! Nothing here reads the network or changes the generated code of the engine. use std::path::{Path, PathBuf}; @@ -22,7 +22,7 @@ fn git(repo: &Path, args: &[&str]) -> Option { Some(String::from_utf8_lossy(&output.stdout).trim().to_owned()) } -/// The 40-hex commit on the `Upstream commit SHA` row of the pin table in `engine/upstream.md`. +/// The 40-hex commit on the `Upstream commit SHA` row of the pin table in `third_party/strata/UPSTREAM.md`. fn upstream_pin(doc: &Path) -> Option { let text = std::fs::read_to_string(doc).ok()?; let line = text @@ -40,7 +40,7 @@ fn main() { std::env::var_os("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"), ); let repo = manifest.join("..").join(".."); - let doc = repo.join("engine").join("upstream.md"); + let doc = repo.join("third_party").join("strata").join("UPSTREAM.md"); emit_reruns(&repo, &doc); let commit = std::env::var("LELEKA_GIT_COMMIT") .ok() diff --git a/crates/deploy/src/app/entry.rs b/crates/deploy/src/app/entry.rs index 9a88fdd8..85c844f6 100644 --- a/crates/deploy/src/app/entry.rs +++ b/crates/deploy/src/app/entry.rs @@ -11,7 +11,7 @@ pub fn version_text() -> String { format!( "leleka {} commit {} ({}) -strata pin {} (upstream commit of engine/upstream.md at build time) +strata pin {} (upstream commit of third_party/strata/UPSTREAM.md at build time) built for {}, {} profile", env!("CARGO_PKG_VERSION"), env!("LELEKA_BUILD_COMMIT"), diff --git a/crates/deploy/src/app/version_tests.rs b/crates/deploy/src/app/version_tests.rs index f1dab41b..ba8a75de 100644 --- a/crates/deploy/src/app/version_tests.rs +++ b/crates/deploy/src/app/version_tests.rs @@ -11,7 +11,8 @@ fn the_version_names_the_commit_and_the_strata_pin_and_keeps_the_first_line() { Some(concat!("leleka ", env!("CARGO_PKG_VERSION"))) ); let pin = env!("LELEKA_BUILD_STRATA_PIN"); - // engine/upstream.md is in the repository this crate is built from; an exported tree without it reports `unknown`. + // third_party/strata/UPSTREAM.md is in the repository this crate is built from; an exported tree without it + // reports `unknown`. assert!( pin == "unknown" || (pin.len() == 40 && pin.bytes().all(|b| b.is_ascii_hexdigit())), "{pin}" diff --git a/crates/deploy/src/expert_profile.rs b/crates/deploy/src/expert_profile.rs index 91e3cb2c..f5bd17d9 100644 --- a/crates/deploy/src/expert_profile.rs +++ b/crates/deploy/src/expert_profile.rs @@ -6,7 +6,7 @@ //! It is Strata's `STRP` v1 table: all 48 x 512 = 24,576 (layer, expert) pairs of the Qwen3.8-Flash-Next model, ranked //! by how often a calibration workload routed to them, plus the inverse slot table (24 + 4 x 24,576 + 4 x 48 x 512 = //! 196,632 bytes). `--expert-cache auto` fills the VRAM expert slots in that order -//! (`engine/strata/tools/make_profile.py`, header comment). +//! (Strata 41cf05a0, `tools/make_profile.py`, header comment). //! //! * It cannot be derived from the model weights: it is a routing statistic. Producing one means running the model on //! calibration prompts with `--dump-routing` and ranking the routed experts (`make_profile.py`, Python, offline). The @@ -16,8 +16,8 @@ //! 43 argmax flips in 1,660 rows (2.59 %), VRAM share 48 % against 90 %. Any other table needs its own quality //! gate; none exists, so the product pins the upstream bytes. //! * Upstream publishes it at `data/expert-profile.bin` in https://github.com/Niko1221/Strata (MIT, -//! `engine/strata/LICENSE`), byte-identical at the pin `41cf05a0` and at the older pin `d9ab8435` -//! (`engine/upstream.md` lists it as left out of the import because `*.bin` is git-ignored). Commit-pinned raw +//! `third_party/strata/LICENSE`), byte-identical at the pin `41cf05a0` and at the older pin `d9ab8435` +//! (the removed vendored tree left it out because `*.bin` is git-ignored). Commit-pinned raw //! URLs are immutable content; the SHA-256 is what is trusted, not the URL. //! //! * The 192 KiB file is small, so the exact upstream bytes are committed (`crates/deploy/data/expert-profile.bin`, the @@ -47,7 +47,7 @@ pub static EMBEDDED: &[u8] = include_bytes!("../data/expert-profile.bin"); /// Nothing larger is hashed or accepted (the pinned file is 192 KiB). pub const MAX_BYTES: u64 = 1 << 20; -/// The Strata commit the sources below are pinned to (`engine/upstream.md`). +/// The Strata commit the sources below are pinned to (`third_party/strata/UPSTREAM.md`). pub const UPSTREAM_COMMIT: &str = "41cf05a06a25dd29103b7b27a2279a3f60c21876"; /// Download sources, tried in order. All serve the same bytes; each result is checked against [`PINNED_SHA256`]. pub const SOURCES: [&str; 3] = [ diff --git a/crates/engine-core/src/conversation/golden/gen.sh b/crates/engine-core/src/conversation/golden/gen.sh deleted file mode 100755 index fd2d4d14..00000000 --- a/crates/engine-core/src/conversation/golden/gen.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -# Rebuild the conversation golden fixtures from the pinned ORIGINAL C++ sources. -# Host-only: no CUDA, no model, no network. Needs clang++ or g++ with C++20. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../../../.." && pwd) -strata="$root/engine/strata" -cxx=${CXX:-c++} -tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT -stub="$here/stub" # minimal cuda_runtime.h so the CUDA-free state sources compile on a CUDA-less host -flags="-std=c++20 -O1 -I$strata/include -I$stub -I$strata/src/core" -$cxx $flags "$here/gen_cache_golden.cpp" "$strata/src/core/conversation_memory.cpp" -o "$tmp/gen_cache" -"$tmp/gen_cache" > "$here/cache_golden.json" -echo "wrote $here/cache_golden.json" -$cxx $flags "$here/gen_state_golden.cpp" "$strata/src/core/conversation_state.cpp" \ - "$strata/src/core/conversation_snapshot.cpp" -o "$tmp/gen_state" -"$tmp/gen_state" > "$here/state_golden.json" -echo "wrote $here/state_golden.json" -$cxx $flags "$here/gen_manager_golden.cpp" -o "$tmp/gen_manager" -"$tmp/gen_manager" > "$here/manager_golden.json" -echo "wrote $here/manager_golden.json" diff --git a/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp b/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp deleted file mode 100644 index d87f313c..00000000 --- a/crates/engine-core/src/conversation/golden/gen_cache_golden.cpp +++ /dev/null @@ -1,333 +0,0 @@ -// Golden-fixture generator for the Rust conversation cache port. -// -// Compiles the ORIGINAL host-side headers (conversation_buffer.hpp, -// conversation_cache.hpp, conversation_memory.cpp, program/conv_cache.hpp) -// unchanged and records deterministic operation traces together with every -// observable result. The Rust tests replay the same traces and compare. -// -// ./gen.sh # rebuilds cache_golden.json (no CUDA needed) -// -// No model data, prompts or captures are involved: token ids are synthetic. -#include "strata/core/conversation_cache.hpp" -#include "strata/core/conversation_memory.hpp" -#include "strata/program/conv_cache.hpp" - -#include -#include -#include -#include -#include - -using namespace strata::core; - -namespace { -struct Rng { - uint64_t s; - explicit Rng(uint64_t seed) : s(seed * 6364136223846793005ULL + 1442695040888963407ULL) {} - uint64_t next() { - s = s * 6364136223846793005ULL + 1442695040888963407ULL; - return s >> 33; - } - uint64_t below(uint64_t n) { return n ? next() % n : 0; } -}; - -template std::string arr(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) out += (i ? "," : "") + std::to_string(v[i]); - return out + "]"; -} - -std::string imgs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) - out += (i ? "," : "") + std::string("[") + std::to_string(v[i].start) + "," + std::to_string(v[i].hash) + "]"; - return out + "]"; -} - -// ---- buffer traces ------------------------------------------------------------------------------------------- -void buffer_cases(std::string& out) { - out += "\"buffer_cases\":["; - const size_t seg = ConversationBuffer::segment_bytes; - for (int c = 0; c < 14; ++c) { - Rng rng(1000 + c); - ConversationBuffer buf; - std::string ops = "[", states = "["; - const int steps = 12 + (int) rng.below(10); - for (int i = 0; i < steps; ++i) { - size_t n; - switch (rng.below(6)) { - case 0: n = rng.below(200); break; - case 1: n = buf.size() + rng.below(70000); break; - case 2: n = buf.size() + 1 + rng.below(40); break; - case 3: n = seg + rng.below(5000); break; - case 4: n = rng.below(buf.size() + 1); break; - default: n = seg * 2 + rng.below(100000); break; - } - if (n > 3 * seg + 100000) n = 3 * seg + 100000; - const uint8_t value = (uint8_t) (rng.below(250) + 1); - std::vector probes = {buf.size(), n, n + 17, buf.size() + 99, seg + 1, 3 * seg, SIZE_MAX}; - std::string peaks = "["; - for (size_t p = 0; p < probes.size(); ++p) - peaks += (p ? "," : "") + std::string("[") + std::to_string(probes[p]) + "," + std::to_string(buf.allocation_peak(probes[p])) + "]"; - peaks += "]"; - const size_t peak = buf.allocation_peak(n); - buf.resize(n, value); - ops += (i ? "," : "") + std::string("[") + std::to_string(n) + "," + std::to_string(value) + "]"; - // sparse content probes: first, last and boundary bytes - std::vector at; - for (size_t b : {size_t(0), seg - 1, seg, seg + 1}) if (b < buf.size()) at.push_back(b); - if (buf.size()) at.push_back(buf.size() - 1); - std::string bytes_at = "["; - for (size_t k = 0; k < at.size(); ++k) { - uint8_t byte = 0; - buf.read(&byte, at[k], 1); - bytes_at += (k ? "," : "") + std::string("[") + std::to_string(at[k]) + "," + std::to_string(byte) + "]"; - } - bytes_at += "]"; - size_t segments = 0; - buf.visit(0, buf.size(), [&](const uint8_t*, size_t, size_t) { ++segments; return true; }); - states += (i ? "," : "") + std::string("{\"size\":") + std::to_string(buf.size()) + ",\"bytes\":" + std::to_string(buf.bytes()) + - ",\"peak\":" + std::to_string(peak) + ",\"peaks_before\":" + peaks + ",\"segments\":" + std::to_string(segments) + - ",\"bytes_at\":" + bytes_at + "}"; - } - out += (c ? "," : "") + std::string("{\"ops\":") + ops + "],\"states\":" + states + "]}"; - } - out += "]"; -} - -// ---- eviction ------------------------------------------------------------------------------------------------ -void eviction_cases(std::string& out) { - out += "\"eviction\":["; - Rng rng(77); - bool first = true; - for (int c = 0; c < 300; ++c) { - std::vector stamps(rng.below(9)); - for (auto& s : stamps) s = rng.below(12); - const int64_t cap = (int64_t) rng.below(9) - 1; - if (stamps.empty()) { - // C++ reads stamps[0..n): n == 0 returns 0 before touching memory - } - const size_t v = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), cap); - out += (first ? "" : ",") + std::string("{\"stamps\":") + arr(stamps) + ",\"cap\":" + std::to_string(cap) + - ",\"victim\":" + std::to_string(v) + "}"; - first = false; - } - out += "]"; -} - -// ---- meminfo ------------------------------------------------------------------------------------------------- -std::string esc(const std::string& s) { - std::string out = "\""; - for (char ch : s) { - if (ch == '\n') out += "\\n"; - else if (ch == '\t') out += "\\t"; - else if (ch == '\r') out += "\\r"; - else if (ch == '"') out += "\\\""; - else if (ch == '\\') out += "\\\\"; - else out += ch; - } - return out + "\""; -} -void memory_cases(std::string& out) { - out += "\"meminfo\":["; - const std::vector texts = { - "", "MemFree: 100 kB\n", "MemAvailable: -1 kB\n", "MemAvailable: +1 kB\n", "MemAvailable: 1 MB\n", - "MemAvailable: 1\n", "MemAvailable: 1x kB\n", "MemAvailable: 18446744073709551615 kB\n", - "MemAvailable: 18446744073709551616 kB\n", "MemAvailable: 1 kB trailing\n", - "MemAvailable: 1 kB\nMemAvailable: 2 kB\n", "MemTotal: 999999 kB\nMemAvailable: 12345 kB\nSwapFree: 777 kB\n", - "MemAvailable: 0 kB", "MemAvailable:\t7\tkB\r\n", "MemAvailableX: 5 kB\n", "MemAvailable: 007 kB\n", - " MemAvailable: 9 kB\n", "MemAvailable: 9 kB", "MemAvailable:\n", "MemAvailable: 9 KB\n", - "MemAvailable: 18014398509481983 kB\n", "MemAvailable: 18014398509481984 kB\n", "x\nMemAvailable: 5 kB\ny\n", - "MemAvailable: 1 kB\n\n\nfoo: 1 kB\n"}; - for (size_t i = 0; i < texts.size(); ++i) { - std::istringstream in(texts[i]); - const auto r = conversation_mem_available(in); - out += (i ? "," : "") + std::string("{\"text\":") + esc(texts[i]) + ",\"value\":" + (r ? std::to_string(*r) : "null") + "}"; - } - out += "],\"admit\":["; - Rng rng(5); - bool first = true; - const uint64_t M = UINT64_MAX; - std::vector pool = {0, 1, 59, 60, 99, 100, M / 2, M - 1, M}; - for (int c = 0; c < 200; ++c) { - const bool known = rng.below(5) != 0; - const uint64_t avail = pool[rng.below(pool.size())], alloc = pool[rng.below(pool.size())], floor = pool[rng.below(pool.size())]; - const bool ok = conversation_memory_admit(known ? std::optional(avail) : std::nullopt, alloc, floor); - out += (first ? "" : ",") + std::string("{\"known\":") + (known ? "true" : "false") + ",\"avail\":" + std::to_string(avail) + - ",\"alloc\":" + std::to_string(alloc) + ",\"floor\":" + std::to_string(floor) + ",\"ok\":" + (ok ? "true" : "false") + "}"; - first = false; - } - out += "]"; -} - -// ---- cache traces -------------------------------------------------------------------------------------------- -struct Spec { - std::vector ids; - std::vector imgs; - std::vector> checkpoints; - std::vector> cp_imgs; - size_t gdn = 0; - bool cvec = true; -}; - -SavedConversation build(const Spec& s) { - SavedConversation img; - img.live.ids = std::vector(s.ids.begin(), s.ids.end()); - img.live.imgs = std::vector(s.imgs.begin(), s.imgs.end()); - img.live.gdn = std::vector(s.gdn, 7); - img.cvec = s.cvec; - img.checkpoints.reserve(s.checkpoints.size()); - for (size_t i = 0; i < s.checkpoints.size(); ++i) { - ConversationCheckpoint c; - c.ids = std::vector(s.checkpoints[i].begin(), s.checkpoints[i].end()); - c.imgs = std::vector(s.cp_imgs[i].begin(), s.cp_imgs[i].end()); - c.gdn = std::vector(s.gdn / 4, 3); - img.checkpoints.push_back(std::move(c)); - } - return img; -} - -std::string spec_json(const Spec& s) { - std::string cps = "["; - for (size_t i = 0; i < s.checkpoints.size(); ++i) - cps += (i ? "," : "") + std::string("{\"ids\":") + arr(s.checkpoints[i]) + ",\"imgs\":" + imgs_json(s.cp_imgs[i]) + "}"; - cps += "]"; - return std::string("{\"ids\":") + arr(s.ids) + ",\"imgs\":" + imgs_json(s.imgs) + ",\"checkpoints\":" + cps + - ",\"gdn\":" + std::to_string(s.gdn) + ",\"cvec\":" + (s.cvec ? "true" : "false") + "}"; -} - -// A few synthetic conversation "families" so prefixes genuinely overlap. -struct World { - std::vector> roots; - explicit World(Rng& rng) { - for (int r = 0; r < 3; ++r) { - std::vector root; - const int len = 3 + (int) rng.below(5); - for (int i = 0; i < len; ++i) root.push_back((int32_t) (r * 100 + i + 1)); - roots.push_back(root); - } - } - std::vector extend(Rng& rng, const std::vector& base, int more) { - auto v = base; - for (int i = 0; i < more; ++i) v.push_back((int32_t) (500 + rng.below(4))); - return v; - } - Spec spec(Rng& rng) { - Spec s; - const auto& root = roots[rng.below(roots.size())]; - auto mid = extend(rng, root, (int) rng.below(4)); - s.ids = extend(rng, mid, 1 + (int) rng.below(4)); - if (rng.below(3)) { s.checkpoints.push_back(root); s.cp_imgs.push_back({}); } - if (rng.below(2) && mid.size() > root.size()) { s.checkpoints.push_back(mid); s.cp_imgs.push_back({}); } - if (rng.below(6) == 0) s.imgs.push_back({(int64_t) rng.below(s.ids.size()), rng.below(3)}); - for (auto& c : s.cp_imgs) for (const auto& k : s.imgs) if (k.start < (int64_t) 0) c.push_back(k); - // checkpoint images: those below its length (chain consistency) - for (size_t i = 0; i < s.checkpoints.size(); ++i) - for (const auto& k : s.imgs) if (k.start < (int64_t) s.checkpoints[i].size()) s.cp_imgs[i].push_back(k); - s.gdn = 16 + rng.below(200); - s.cvec = rng.below(8) != 0; - return s; - } - std::vector prompt(Rng& rng) { - const auto& root = roots[rng.below(roots.size())]; - return extend(rng, extend(rng, root, (int) rng.below(4)), 1 + (int) rng.below(5)); - } -}; - -void cache_traces(std::string& out) { - out += "\"cache_traces\":["; - for (int t = 0; t < 24; ++t) { - Rng rng(9000 + t); - World world(rng); - const size_t slots = 1 + rng.below(5); - const size_t one = build(world.spec(rng)).bytes(); - const size_t budget = rng.below(8) == 0 ? 0 : one * (1 + rng.below(6)) + rng.below(400); - ConversationCache cache(budget, slots); - std::string ops = "["; - const int steps = 32; - for (int i = 0; i < steps; ++i) { - std::string op, res; - const uint64_t kind = rng.below(12); - if (kind <= 3) { - Spec s = world.spec(rng); - const size_t held = rng.below(5) == 0 ? rng.below(one * 2 + 1) : 0; - const bool ok = cache.put(build(s), held); - op = "{\"op\":\"put\",\"spec\":" + spec_json(s) + ",\"held\":" + std::to_string(held) + "}"; - res = std::string("\"ok\":") + (ok ? "true" : "false"); - } else if (kind <= 6) { - auto p = world.prompt(rng); - std::vector im; - if (rng.below(8) == 0) im.push_back({(int64_t) rng.below(p.size()), rng.below(3)}); - const bool cv = rng.below(8) != 0; - const auto m = cache.best(std::vector(p.begin(), p.end()), im, cv); - op = "{\"op\":\"best\",\"prompt\":" + arr(p) + ",\"imgs\":" + imgs_json(im) + ",\"cvec\":" + (cv ? "true" : "false") + "}"; - res = "\"index\":" + std::to_string(m.index) + ",\"tokens\":" + std::to_string(m.tokens) + ",\"live\":" + (m.live ? "true" : "false"); - } else if (kind == 7) { - size_t idx = cache.size() ? rng.below(cache.size() + 1) : rng.below(2); - std::string taken = "null"; - if (idx < cache.size()) { - auto img = cache.take(idx); - taken = std::to_string(img.bytes()) + ",\"ids\":" + arr(img.live.ids); - taken = "{\"bytes\":" + taken + "}"; - } - op = "{\"op\":\"take\",\"index\":" + std::to_string(idx) + "}"; - res = "\"taken\":" + taken; - } else if (kind == 8) { - const size_t incoming = rng.below(one * 2 + 1), held = rng.below(4) == 0 ? rng.below(one + 1) : 0; - const bool fit = cache.can_fit(incoming, held); - const bool ok = cache.make_room(incoming, held); - op = "{\"op\":\"room\",\"incoming\":" + std::to_string(incoming) + ",\"held\":" + std::to_string(held) + "}"; - res = std::string("\"fit\":") + (fit ? "true" : "false") + ",\"ok\":" + (ok ? "true" : "false"); - } else if (kind == 9) { - std::vector layers; - const size_t n = 1 + rng.below(3); - layers.reserve(n); - std::vector sizes; - for (size_t l = 0; l < n; ++l) { - ConversationKv kv; - sizes.push_back(1 + rng.below(300)); - kv.k.resize(sizes.back()); - layers.push_back(std::move(kv)); - } - const int64_t tokens = (int64_t) (1 + rng.below(40)); - cache.retain(std::move(layers), tokens); - op = "{\"op\":\"retain\",\"sizes\":" + arr(sizes) + ",\"tokens\":" + std::to_string(tokens) + "}"; - res = "\"retained\":" + std::to_string(cache.retained_bytes()); - } else if (kind == 10) { - const int64_t dirty = (int64_t) rng.below(45); - cache.limit_reuse(dirty); - op = "{\"op\":\"limit\",\"dirty\":" + std::to_string(dirty) + "}"; - res = "\"retained\":" + std::to_string(cache.retained_bytes()); - } else { - auto reuse = cache.take_reuse(); - op = "{\"op\":\"take_reuse\"}"; - res = "\"layers\":" + std::to_string(reuse.kv.size()) + ",\"unchanged\":" + std::to_string(reuse.unchanged_tokens) + - ",\"captured\":" + std::to_string(reuse.captured_tokens); - } - ops += (i ? "," : "") + std::string("{\"call\":") + op + ",\"res\":{" + res + "},\"state\":{\"bytes\":" + - std::to_string(cache.bytes()) + ",\"size\":" + std::to_string(cache.size()) + ",\"evictions\":" + - std::to_string(cache.evictions()) + ",\"superseded\":" + std::to_string(cache.superseded()) + - ",\"retained\":" + std::to_string(cache.retained_bytes()) + "}}"; - } - out += (t ? "," : "") + std::string("{\"budget\":") + std::to_string(budget) + ",\"slots\":" + std::to_string(slots) + - ",\"ops\":" + ops + "]}"; - } - out += "]"; -} -} // namespace - -int main() { - std::string out = "{"; - out += "\"sizes\":{\"checkpoint\":" + std::to_string(sizeof(ConversationCheckpoint)) + ",\"kv\":" + std::to_string(sizeof(ConversationKv)) + - ",\"image_key\":" + std::to_string(sizeof(ConversationImageKey)) + "},"; - buffer_cases(out); - out += ","; - eviction_cases(out); - out += ","; - memory_cases(out); - out += ","; - cache_traces(out); - out += "}\n"; - std::fputs(out.c_str(), stdout); - return 0; -} diff --git a/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp b/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp deleted file mode 100644 index 552716a8..00000000 --- a/crates/engine-core/src/conversation/golden/gen_manager_golden.cpp +++ /dev/null @@ -1,423 +0,0 @@ -// Golden-fixture generator for the Rust conversation manager. -// -// The conversation block of generate.cpp (park_current, the resume choice at -// the head of a request, checkpoint_at, the periodic prompt checkpoint, the -// turn/root segment loop and the end-of-request live update) lives inside a -// 6,600-line CUDA translation unit and cannot be compiled on its own. Its -// statements are transliterated here VERBATIM in structure (same order, same -// conditions, same clock/LRU updates) against the real, unmodified -// ConversationCache, eviction_victim and memory admission, with a synthetic -// "device": snapshots carry fixed-size payloads and no CUDA is touched. The -// resulting per-request decisions and cache state are the oracle that the -// Rust ConversationManager must reproduce. -#include "strata/core/conversation_cache.hpp" -#include "strata/core/conversation_memory.hpp" -#include "strata/program/conv_cache.hpp" - -#include -#include -#include -#include -#include -#include - -using namespace strata::core; -using ImgKey = ConversationImageKey; -using ConvCheckpoint = ConversationCheckpoint; - -namespace { -struct Rng { - uint64_t s; - explicit Rng(uint64_t seed) : s(seed * 6364136223846793005ULL + 1442695040888963407ULL) {} - uint64_t next() { s = s * 6364136223846793005ULL + 1442695040888963407ULL; return s >> 33; } - uint64_t below(uint64_t n) { return n ? next() % n : 0; } -}; - -template std::string arr(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) out += (i ? "," : "") + std::to_string(v[i]); - return out + "]"; -} -// Token arrays are mostly consecutive runs: [start, length] pairs keep the fixture small. -std::string runs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size();) { - size_t j = i + 1; - while (j < v.size() && v[j] == v[j - 1] + 1) ++j; - out += (i ? "," : "") + std::string("[") + std::to_string(v[i]) + "," + std::to_string(j - i) + "]"; - i = j; - } - return out + "]"; -} -std::string imgs_json(const std::vector& v) { - std::string out = "["; - for (size_t i = 0; i < v.size(); ++i) - out += (i ? "," : "") + std::string("[") + std::to_string(v[i].start) + "," + std::to_string(v[i].hash) + "]"; - return out + "]"; -} - -struct ConversationView { // the shape of conversation_snapshot.hpp's view, which needs CUDA headers - const std::vector& ids; - const std::vector& images; - const std::vector& checkpoints; - bool cvec; -}; - -constexpr size_t kPayload = 100; // synthetic running-state payload per checkpoint / live -constexpr int64_t kChunk = 256; // batched prompt chunk (request_capacity with an admitted capacity of 256) -constexpr int64_t kWindow = 4; // verify-window width (read_windows) -constexpr int64_t kShortRead = 64; // windows_ok: at most this many tokens go through the verify windows - -struct Options { - int prompt_cache = 6; - int64_t prompt_cache_every = 16384; - int64_t prompt_cache_root = 2048; - int turn_token = 7; - size_t cache_bytes = 0; - size_t cache_slots = 4; - uint64_t min_free = 0; - bool reread = false; - bool incremental = true; -}; - -// ---- the generate.cpp state ------------------------------------------------------------------------------------ -struct Serve { - Options o; - std::vector live; - std::vector live_imgs; - bool live_ok = false; - std::vector checks; - uint64_t check_clock = 0; - bool cvec_cached = true; - ConversationCache conversations; - int64_t pp_next_check = 0; - std::optional available; // injected telemetry - bool validate_fails = false; // injected: the next parked image is unusable - int parked_events = 0; - explicit Serve(const Options& opt) : o(opt), conversations(opt.prompt_cache > 0 ? opt.cache_bytes : 0, opt.cache_slots) {} - - // synthetic device --------------------------------------------------------------------------------------- - static SavedConversation image_of(const ConversationView& v) { - SavedConversation s; - s.live.ids = std::vector(v.ids.begin(), v.ids.end()); - s.live.imgs = std::vector(v.images.begin(), v.images.end()); - s.live.gdn = std::vector(kPayload, 1); - s.cvec = v.cvec; - s.checkpoints = v.checkpoints; - return s; - } - - // ---- park_current (generate.cpp:4415) --------------------------------------------------------------------- - void park_current(size_t held) { - if (!conversations.enabled() || !live_ok || live.empty()) return; - const ConversationView view{live, live_imgs, checks, cvec_cached}; - auto reuse = conversations.take_reuse(); - size_t estimate = image_of(view).bytes(); - const size_t fresh_estimate = estimate; - if (!reuse.kv.empty()) { reuse = {}; estimate = fresh_estimate; } // (the synthetic device never retains K/V) - conversations.drop_superseded(live, live_imgs, checks, cvec_cached); - if (!conversations.make_room(estimate, held)) return; - const uint64_t floor = o.min_free; - const size_t additional = estimate - reuse.bytes(); - if (!conversation_memory_admit(available, additional, floor)) return; - SavedConversation image = image_of(view); - if (!conversation_memory_admit(available, 0, floor)) return; - const bool stored = conversations.put(std::move(image), held); - if (stored) ++parked_events; - } - - static std::vector imgs_below(const std::vector& all, int64_t L) { - std::vector v; - for (const ImgKey& k : all) if (k.start < L) v.push_back(k); - return v; - } - - // ---- checkpoint_at (generate.cpp:4495) -------------------------------------------------------------------- - bool checkpoint_at(int64_t L, const std::vector& cur, const std::vector& req_imgs) { - if (o.prompt_cache <= 0 || L < 1) return true; - for (ConvCheckpoint& c : checks) - if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; } - ConvCheckpoint c; - c.ids.assign(cur.begin(), cur.begin() + L); - c.imgs = imgs_below(req_imgs, L); - c.gdn = std::vector(kPayload, 2); - c.used = ++check_clock; - checks.push_back(std::move(c)); - while ((int) checks.size() > o.prompt_cache) { - std::vector stamps; - for (const ConvCheckpoint& k : checks) stamps.push_back(k.used); - const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(), o.prompt_cache); - checks.erase(checks.begin() + (std::ptrdiff_t) victim); - } - return true; - } -}; - -struct Request { - std::vector ids; - std::vector imgs; - bool cvec = true; - int gen = 1; - int stop_after = -1; // cancel before this prompt action (-1: never) - int64_t available = -1; // -1: unknown - bool validate_fails = false; -}; - -struct Outcome { - int64_t resume = 0; - bool from_live = false; - bool restored = false; - int64_t restored_tokens = 0; - bool restored_live = false; - int64_t reread_to = -1; - int64_t read_from = 0; - std::vector consumed; -}; - -// The request path from `cur = ids` to `finish` (generate.cpp:5013-5640, conversation parts only). -Outcome run_request(Serve& S, const Request& r) { - Outcome out; - S.available = r.available < 0 ? std::nullopt : std::optional((uint64_t) r.available); - S.validate_fails = r.validate_fails; - const std::vector& ids = r.ids; - const std::vector& req_imgs = r.imgs; - const int64_t n = (int64_t) ids.size(); - auto starts_with = [&](const std::vector& pre, const std::vector& pre_imgs) -> bool { - const int64_t L = (int64_t) pre.size(); - if (L < 1 || L > n - 1) return false; - for (int64_t i = 0; i < L; ++i) - if ((int32_t) ids[(size_t) i] != pre[(size_t) i]) return false; - return Serve::imgs_below(req_imgs, L) == pre_imgs; - }; - const bool want_cvec = r.cvec; - int64_t resume = 0; - bool from_live = false; - if (S.o.prompt_cache > 0 && want_cvec == S.cvec_cached) { - if (S.live_ok && starts_with(S.live, S.live_imgs)) { resume = (int64_t) S.live.size(); from_live = true; } - for (const ConvCheckpoint& c : S.checks) - if ((int64_t) c.ids.size() > resume && starts_with(c.ids, c.imgs)) { - resume = (int64_t) c.ids.size(); - from_live = false; - } - } - const auto parked = S.conversations.best(ids, req_imgs, want_cvec); - std::optional incoming; - if (parked.tokens > resume) incoming.emplace(S.conversations.take(parked.index)); - if (incoming && S.validate_fails) incoming.reset(); - if ((!from_live || incoming)) S.park_current(incoming ? incoming->bytes() : 0); - if (incoming) { - S.live = std::move(incoming->live.ids); - S.live_imgs = std::move(incoming->live.imgs); - S.checks = std::move(incoming->checkpoints); - S.cvec_cached = incoming->cvec; - resume = parked.tokens; - from_live = parked.live; - if (S.o.incremental) S.conversations.retain(std::vector{}, int64_t(S.live.size())); - incoming.reset(); - out.restored = true; out.restored_tokens = resume; out.restored_live = from_live; - } - if (want_cvec != S.cvec_cached) { - S.live_ok = false; - S.checks.clear(); - S.cvec_cached = want_cvec; - } - S.checks.erase(std::remove_if(S.checks.begin(), S.checks.end(), [&](const ConvCheckpoint& c) { - return (int64_t) c.ids.size() > resume || !starts_with(c.ids, c.imgs); - }), S.checks.end()); - S.live_ok = false; - int64_t reread_to = -1; - if (resume == 0) { - S.checks.clear(); - } else if (!from_live) { - ConvCheckpoint* c = nullptr; - for (ConvCheckpoint& k : S.checks) if ((int64_t) k.ids.size() == resume) c = &k; - if (c != nullptr) c->used = ++S.check_clock; - if (S.o.reread && c != nullptr) reread_to = resume; - } - const int64_t read_from = reread_to > 0 ? 0 : resume; - S.conversations.limit_reuse(read_from); - S.pp_next_check = reread_to > 0 ? INT64_MAX : resume + S.o.prompt_cache_every; - out.resume = resume; out.from_live = from_live; out.reread_to = reread_to; out.read_from = read_from; - - // ---- the prompt: segments up to the root / the last turn boundary / the last token ------------------------ - int64_t turn_at = -1; - if (S.o.prompt_cache > 0 && S.o.turn_token >= 0) - for (int64_t i = n - 1; i > resume; --i) - if (ids[(size_t) i] == S.o.turn_token) { turn_at = i; break; } - int64_t root_at = -1; - if (S.o.prompt_cache > 0 && S.o.turn_token >= 0 && S.o.prompt_cache_root > 0 && read_from == 0) - for (int64_t i = 1; i < turn_at; ++i) - if (ids[(size_t) i] == S.o.turn_token) { - if (i >= S.o.prompt_cache_root) root_at = i; - break; - } - int64_t at = read_from; - int actions = 0; - bool cancelled = false; - for (const int64_t to : {reread_to, root_at, turn_at, n - 1}) { - if (to <= at) continue; - const bool win = (to - at) <= kShortRead; - const int64_t width = win ? kWindow : kChunk; - while (at < to) { - if (r.stop_after >= 0 && actions == r.stop_after) { cancelled = true; break; } - const int64_t count = std::min(width, to - at); - at += count; - ++actions; - if (!win) { // sp.run's chunk callback - if (S.o.prompt_cache_every > 0 && at >= S.pp_next_check) { - S.checkpoint_at(at, ids, req_imgs); - S.pp_next_check = at + S.o.prompt_cache_every; - } - } - } - if (cancelled) break; - if (to == turn_at || to == root_at) S.checkpoint_at(to, ids, req_imgs); - } - // ---- the decode: consumed = ids[0..n-1) + the last prompt token + all generated tokens but the last ------- - if (!cancelled) { - std::vector consumed(ids.begin(), ids.end()); - for (int i = 0; i + 1 < r.gen; ++i) consumed.push_back(200000 + (int32_t) ids.size() * 10 + i); - out.consumed = consumed; - S.live.swap(consumed); - S.live_imgs = Serve::imgs_below(req_imgs, (int64_t) S.live.size()); - S.live_ok = S.o.prompt_cache > 0; - } - return out; -} - -std::string state_json(const Serve& S) { - std::string cps = "["; - for (size_t i = 0; i < S.checks.size(); ++i) - cps += (i ? "," : "") + std::string("[") + std::to_string(S.checks[i].ids.size()) + "," + std::to_string(S.checks[i].used) + "]"; - cps += "]"; - return "{\"live\":" + std::to_string(S.live.size()) + ",\"live_ok\":" + (S.live_ok ? "true" : "false") + ",\"cvec\":" + (S.cvec_cached ? "true" : "false") + - ",\"checks\":" + cps + ",\"clock\":" + std::to_string(S.check_clock) + ",\"pp_next\":" + std::to_string(S.pp_next_check) + - ",\"cache\":{\"size\":" + std::to_string(S.conversations.size()) + ",\"bytes\":" + std::to_string(S.conversations.bytes()) + - ",\"evictions\":" + std::to_string(S.conversations.evictions()) + ",\"superseded\":" + std::to_string(S.conversations.superseded()) + - ",\"retained\":" + std::to_string(S.conversations.retained_bytes()) + "},\"parks\":" + std::to_string(S.parked_events) + "}"; -} -} // namespace - -std::string options_json(const Options& o) { - return std::string("{\"prompt_cache\":") + std::to_string(o.prompt_cache) + ",\"every\":" + std::to_string(o.prompt_cache_every) + - ",\"root\":" + std::to_string(o.prompt_cache_root) + ",\"turn\":" + std::to_string(o.turn_token) + ",\"cache_bytes\":" + - std::to_string(o.cache_bytes) + ",\"slots\":" + std::to_string(o.cache_slots) + ",\"min_free\":" + std::to_string(o.min_free) + - ",\"reread\":" + (o.reread ? "true" : "false") + ",\"incremental\":" + (o.incremental ? "true" : "false") + "}"; -} - -// Run one request and emit it together with everything the Rust port must reproduce. -Outcome emit_request(Serve& S, const Request& r, std::string& reqs, bool first) { - const Outcome res = run_request(S, r); - reqs += (first ? "" : ",") + std::string("{\"ids\":") + runs_json(r.ids) + ",\"imgs\":" + imgs_json(r.imgs) + ",\"cvec\":" + (r.cvec ? "true" : "false") + - ",\"gen\":" + std::to_string(r.gen) + ",\"stop_after\":" + std::to_string(r.stop_after) + ",\"available\":" + std::to_string(r.available) + - ",\"validate_fails\":" + (r.validate_fails ? "true" : "false") + ",\"expect\":{\"resume\":" + std::to_string(res.resume) + - ",\"from_live\":" + (res.from_live ? "true" : "false") + ",\"restored\":" + - (res.restored ? "[" + std::to_string(res.restored_tokens) + "," + (res.restored_live ? "true" : "false") + "]" : std::string("null")) + - ",\"reread_to\":" + std::to_string(res.reread_to) + ",\"read_from\":" + std::to_string(res.read_from) + - ",\"consumed\":" + std::to_string(res.consumed.size()) + ",\"state\":" + state_json(S) + "}}"; - return res; -} - -// #342: MAIN conversation parked, then a sub-agent whose every turn re-renders the previous reply (so no turn -// continues the live session and each one parks a stale-tail copy of the one before). -std::string subagent_trace(const char* sep, size_t slots, size_t budget, int turns, bool with_main_return) { - Options o; - o.prompt_cache = 6; o.prompt_cache_every = 100000; o.prompt_cache_root = 8; o.cache_bytes = budget; o.cache_slots = slots; - Serve S(o); - std::string reqs = "["; - bool first = true; - auto emit = [&](std::vector ids, int gen) { - Request r; r.ids = std::move(ids); r.gen = gen; r.available = 1000000; - return emit_request(S, r, reqs, std::exchange(first, false)); - }; - auto block = [](int32_t base, int n) { std::vector v; for (int i = 0; i < n; ++i) v.push_back(base + i); return v; }; - auto cat = [](std::vector a, const std::vector& b) { a.insert(a.end(), b.begin(), b.end()); return a; }; - std::vector main_ids = cat(cat(cat({7}, block(100, 30)), cat({7}, block(1000, 20))), cat({7}, block(2000, 20))); - const auto main_run = emit(main_ids, 6); - std::vector rendered = cat({7}, block(5000, 24)); // the sub-agent's system prompt, rendered history so far - for (int t = 1; t <= turns; ++t) { - const std::vector ids = cat(cat(cat(rendered, {7}), block(6000 + 100 * t, 6)), {8, 8}); - emit(ids, 5); - rendered = cat(ids, block(7000 + 10 * t, 3)); // the reply, as the client re-renders it - } - if (with_main_return) { - emit(cat(main_run.consumed, cat({7}, block(9000, 5))), 4); - } - reqs += "]"; - return std::string(sep) + "{\"options\":" + options_json(o) + ",\"requests\":" + reqs + "}"; -} - -int main() { - std::string out = "{\"traces\":["; - for (int t = 0; t < 28; ++t) { - Rng rng(31000 + t); - Options o; - o.prompt_cache = 1 + (int) rng.below(7); - o.prompt_cache_every = rng.below(3) == 0 ? 0 : (rng.below(2) ? 100 + (int64_t) rng.below(300) : 100000); - const int64_t roots[] = {8, 40, 120, 2048, 0}; - o.prompt_cache_root = roots[rng.below(5)]; - o.cache_bytes = rng.below(6) == 0 ? 0 : (size_t) (6000 + rng.below(60000)); - o.cache_slots = 1 + rng.below(5); - o.min_free = rng.below(3) == 0 ? 1000 + rng.below(5000) : 0; - o.reread = rng.below(8) == 0; - o.incremental = rng.below(4) != 0; - Serve S(o); - // conversation family - std::vector> histories; - std::string reqs = "["; - const int steps = 30; - for (int step = 0; step < steps; ++step) { - Request r; - auto fresh_chat = [&](int sys_salt) { - std::vector v = {7}; - const int sys = 10 + (int) rng.below(120); - for (int i = 0; i < sys; ++i) v.push_back(100 + sys_salt * 1000 + i); - const int turns = 1 + (int) rng.below(3); - for (int tn = 0; tn < turns; ++tn) { - v.push_back(7); - const int len = 3 + (int) rng.below(90); - for (int i = 0; i < len; ++i) v.push_back((int32_t) (50000 + rng.below(3) * 10 + i + tn * 500)); - } - return v; - }; - const uint64_t pick = rng.below(7); - if (histories.empty() || pick == 0) { - r.ids = fresh_chat(rng.below(2) ? 0 : (int) (1 + rng.below(3))); - } else { - auto base = rng.below(5) < 3 ? histories.back() : histories[rng.below(histories.size())]; - const uint64_t how = rng.below(3); - if (how == 0) { - base.push_back(7); - const int len = 2 + (int) rng.below(60); - for (int i = 0; i < len; ++i) base.push_back(70000 + i); - r.ids = base; - } else if (how == 1) { - const size_t cut = 1 + rng.below(base.size() - 1); - base.resize(cut); - const int len = 2 + (int) rng.below(40); - for (int i = 0; i < len; ++i) base.push_back(80000 + i + (int32_t) rng.below(2)); - r.ids = base; - } else { - r.ids = base; - } - } - if (rng.below(12) == 0) r.imgs.push_back({(int64_t) rng.below(r.ids.size()), rng.below(2)}); - r.cvec = rng.below(8) != 0; - r.gen = 1 + (int) rng.below(10); - r.stop_after = rng.below(8) == 0 ? (int) rng.below(4) : -1; - r.available = rng.below(6) == 0 ? -1 : (int64_t) (rng.below(3) ? 1000000 : 3000); - r.validate_fails = rng.below(10) == 0; - const Outcome res = emit_request(S, r, reqs, step == 0); - if (!res.consumed.empty()) histories.push_back(res.consumed); - } - reqs += "]"; - out += (t ? "," : "") + std::string("{\"options\":") + options_json(o) + ",\"requests\":" + reqs + "}"; - } - // scripted #342 sub-agent traffic, with and without the MAIN conversation coming back - out += subagent_trace(",", 4, 1 << 20, 9, true); - out += subagent_trace(",", 3, 1 << 20, 7, true); - out += subagent_trace(",", 2, 1 << 20, 6, true); - out += subagent_trace(",", 4, 12000, 8, false); - out += "]}\n"; - std::fputs(out.c_str(), stdout); -} diff --git a/crates/engine-core/src/conversation/golden/gen_state_golden.cpp b/crates/engine-core/src/conversation/golden/gen_state_golden.cpp deleted file mode 100644 index 980944b3..00000000 --- a/crates/engine-core/src/conversation/golden/gen_state_golden.cpp +++ /dev/null @@ -1,274 +0,0 @@ -// Golden-fixture generator for the Rust conversation snapshot port. -// -// Links the ORIGINAL conversation_state.cpp / conversation_snapshot.cpp -// unchanged, with CUDA replaced by plain host memory (a stub cuda_runtime.h -// and memcpy-backed cudaMemcpy), and records sizes, layouts and content -// hashes of whole-session snapshots. The pools hold synthetic bytes only. -#include "strata/core/conversation_snapshot.hpp" -#include "strata/kernels/kv_q4.hpp" - -#include -#include -#include -#include -#include -#include - -using namespace strata::core; -using namespace strata::kernels; - -// ---- host stand-ins for the device runtime --------------------------------------------------------------------- -extern "C" cudaError_t cudaMemcpy(void* dst, const void* src, size_t n, cudaMemcpyKind) { - std::memcpy(dst, src, n); - return cudaSuccess; -} -extern "C" cudaError_t cudaDeviceSynchronize() { return cudaSuccess; } -extern "C" cudaError_t cudaGetLastError() { return cudaSuccess; } -namespace strata::kernels { -void kv_stream_reset(const KvStreamMap&, void*) {} -void kv_ring_restore(const QsaAttnPools&, const KvHostPools&, int, int64_t, int64_t, int64_t, const QsaShapes&, void*) {} -} // namespace strata::kernels -namespace strata::core { -strata::kernels::QsaAttnPools qsa_attn_pools(const QsaState&) { return {}; } -} // namespace strata::core - -namespace { -std::string hash_hex(const std::vector& v) { - uint64_t h = 1469598103934665603ull; - for (uint8_t b : v) { h ^= b; h *= 1099511628211ull; } - char out[17]; - std::snprintf(out, sizeof out, "%016llx", (unsigned long long) h); - return out; -} -std::string hash_buf(const ConversationBuffer& b) { - std::vector v(b.size()); - if (!v.empty()) b.read(v.data(), 0, v.size()); - return hash_hex(v); -} -std::string q(const std::string& s) { return "\"" + s + "\""; } - -struct Storage { - std::deque> blocks; - template void alloc(T*& p, size_t n) { - if (!n) return; - blocks.emplace_back(n, 0); - p = reinterpret_cast(blocks.back().data()); - } -}; - -struct Fixture { - ModelGeometry g; - QsaState state; - Storage store; - std::array sources{}; - std::array sizes{}; - Fixture(int fmt, int mode) { - auto& st = state; - st.kv_mode = mode; st.without_key = fmt == kKvValueInt8; st.kv_int8 = fmt == kKvInt8 || st.without_key; - st.kv_q4 = fmt == kKvQ4; st.kv_hybrid = fmt == 3; - st.n_pages = 24; st.n_slots = mode ? 4 : st.n_pages; - st.max_cells = st.n_pages * 4; st.idx_pooled_rows = mode == 2 ? 2 : st.max_cells / 4 + 2; - const size_t per = fmt == kKvQ4 ? kv_q4_bytes_per_head((int) g.head_dim) : g.head_dim * ((st.kv_int8 || st.kv_hybrid) ? 1 : 2); - const size_t rows = st.max_cells * g.n_head_kv, slot_rows = st.n_slots * 4 * g.n_head_kv; - sizes = {rows * per, rows * per, (fmt == kKvInt8 || fmt == kKvValueInt8) ? rows * (g.head_dim / 64) * 2 : 0, - (fmt == kKvInt8 || fmt == kKvValueInt8) ? rows * (g.head_dim / 64) * 2 : 0, (size_t) st.idx_pooled_rows * g.idx_key_dim * 4}; - if (st.without_key) { sizes[0] = 0; sizes[2] = 0; } - if (fmt == 3) { - sizes = {rows * per, rows * kv_q4_bytes_per_head((int) g.head_dim), rows * (g.head_dim / 64) * 2, 0, - (size_t) st.idx_pooled_rows * g.idx_key_dim * 4}; - store.alloc(st.k_q, sizes[0]); store.alloc(st.v_q4, sizes[1]); store.alloc(st.k_scale, sizes[2]); - sources[0] = st.k_q; sources[1] = st.v_q4; sources[2] = st.k_scale; - } else if (fmt == kKvQ4) { - store.alloc(st.k_q4, slot_rows * per); store.alloc(st.v_q4, slot_rows * per); - if (mode) { store.alloc(st.host.k_q4, sizes[0]); store.alloc(st.host.v_q4, sizes[1]); } - sources[0] = mode ? st.host.k_q4 : st.k_q4; sources[1] = mode ? st.host.v_q4 : st.v_q4; - } else if (st.kv_int8) { - if (!st.without_key) store.alloc(st.k_q, slot_rows * per); - store.alloc(st.v_q, slot_rows * per); - if (!st.without_key) store.alloc(st.k_scale, slot_rows * (g.head_dim / 64) * 2); - store.alloc(st.v_scale, slot_rows * (g.head_dim / 64) * 2); - if (mode) { - store.alloc(st.host.k_q, sizes[0]); store.alloc(st.host.v_q, sizes[1]); - store.alloc(st.host.k_scale, sizes[2]); store.alloc(st.host.v_scale, sizes[3]); - } - sources[0] = mode ? st.host.k_q : st.k_q; sources[1] = mode ? st.host.v_q : st.v_q; - sources[2] = mode ? st.host.k_scale : st.k_scale; sources[3] = mode ? st.host.v_scale : st.v_scale; - } else { - store.alloc(st.k_pool, slot_rows * per); store.alloc(st.v_pool, slot_rows * per); - if (mode) { store.alloc(st.host.k_pool, sizes[0]); store.alloc(st.host.v_pool, sizes[1]); } - sources[0] = mode ? st.host.k_pool : st.k_pool; sources[1] = mode ? st.host.v_pool : st.v_pool; - } - store.alloc(st.idx_pooled, sizes[4]); sources[4] = st.idx_pooled; - store.alloc(st.page_table, st.n_pages * 4); - if (mode == 1) { - auto& m = st.map; - m.page_table = st.page_table; m.n_blocks = st.n_pages; m.n_slots = st.n_slots; - store.alloc(m.slot_block, st.n_slots * 4); store.alloc(m.slot_stamp, st.n_slots * 4); store.alloc(m.slot_ref, st.n_slots * 4); - store.alloc(m.miss_block, st.n_slots * 4); store.alloc(m.miss_slot, st.n_slots * 4); store.alloc(m.ctl, kKvCtlInts * 4); - } else if (mode == 2) { - // the ring table is device-initialized in the real tool; only its presence matters here - } - } - void fill(uint8_t salt) { - for (size_t i = 0; i < sources.size(); ++i) - for (size_t j = 0; j < sizes[i]; ++j) - static_cast(sources[i])[j] = (uint8_t) (salt + i * 31 + j * 7 + j / 257); - } -}; - -std::string kv_json(const ConversationKv& k) { - return "{\"format\":" + std::to_string(k.format) + ",\"cells\":" + std::to_string(k.cells) + ",\"heads\":" + std::to_string(k.heads) + - ",\"head_dim\":" + std::to_string(k.head_dim) + ",\"page_size\":" + std::to_string(k.page_size) + - ",\"pooled_rows\":" + std::to_string(k.pooled_rows) + ",\"idx_dim\":" + std::to_string(k.idx_dim) + - ",\"bytes\":" + std::to_string(k.bytes()) + ",\"sizes\":[" + std::to_string(k.k.size()) + "," + std::to_string(k.v.size()) + "," + - std::to_string(k.k_scale.size()) + "," + std::to_string(k.v_scale.size()) + "," + std::to_string(k.pooled.size()) + - "],\"hash\":[" + q(hash_buf(k.k)) + "," + q(hash_buf(k.v)) + "," + q(hash_buf(k.k_scale)) + "," + q(hash_buf(k.v_scale)) + "," + - q(hash_buf(k.pooled)) + "]}"; -} - -void state_cases(std::string& out) { - out += "\"state_cases\":["; - bool first = true; - auto emit = [&](const ModelGeometry& g, int64_t gdn_alloc, int64_t qsa_ord0, int64_t qsa_alloc, const char* what) { - ConversationStateSizes z; - std::string err; - const bool ok_whole = conversation_state_sizes(g, z, err); - SessionState ss; - ss.gdn_alloc = gdn_alloc; ss.qsa_ord0 = qsa_ord0; ss.qsa_alloc = qsa_alloc; - ConversationStateSizes zs; - const bool ok_session = conversation_session_sizes(g, ss, zs, err); - const auto k = std::array{g.n_embd, g.n_layers, g.qsa_interval, g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads, g.ssm_d_conv, - g.ssm_conv_channels, g.ssm_value_dim, g.n_head, g.n_head_kv, g.head_dim, g.idx_q_heads, g.idx_key_dim, - g.hc, g.hc_lr, g.n_expert, g.n_ff}; - std::string key = "["; - for (size_t i = 0; i < k.size(); ++i) key += (i ? "," : "") + std::to_string(k[i]); - key += "]"; - out += (first ? "" : ",") + std::string("{\"what\":") + q(what) + ",\"geometry\":" + key + ",\"gdn_alloc\":" + std::to_string(gdn_alloc) + - ",\"qsa_ord0\":" + std::to_string(qsa_ord0) + ",\"qsa_alloc\":" + std::to_string(qsa_alloc) + ",\"whole_ok\":" + (ok_whole ? "true" : "false") + - ",\"whole\":[" + std::to_string(ok_whole ? z.gdn : 0) + "," + std::to_string(ok_whole ? z.ple : 0) + "," + std::to_string(ok_whole ? z.tail : 0) + "," + - std::to_string(ok_whole ? z.dead : 0) + "," + std::to_string(ok_whole ? z.block_pos : 0) + "],\"session_ok\":" + (ok_session ? "true" : "false") + - ",\"session\":[" + std::to_string(ok_session ? zs.gdn : 0) + "," + std::to_string(ok_session ? zs.ple : 0) + "," + std::to_string(ok_session ? zs.tail : 0) + - "," + std::to_string(ok_session ? zs.dead : 0) + "," + std::to_string(ok_session ? zs.block_pos : 0) + "]}"; - first = false; - }; - ModelGeometry original; - emit(original, original.n_gdn_layers(), 0, original.n_qsa_layers(), "original whole model"); - emit(original, 3, 1, 1, "single stage carve"); - emit(original, 37, 0, 12, "gdn_alloc past rows"); - emit(original, 36, 0, 13, "qsa_alloc past ordinals"); - emit(original, 0, 12, 0, "empty tail carve"); - emit(original, -1, 0, 0, "negative gdn_alloc"); - emit(original, 36, 13, 0, "ord0 past last"); - ModelGeometry small = original; - small.n_layers = 8; small.ssm_state_size = 2; small.ssm_v_heads = 2; small.ssm_conv_channels = 8; small.n_head_kv = 1; small.head_dim = 64; small.idx_key_dim = 8; - emit(small, 6, 0, 2, "small whole"); - emit(small, 3, 1, 1, "small carve"); - small.n_layers = 3; - emit(small, 3, 0, 0, "zero QSA layers"); - ModelGeometry bad = original; bad.qsa_interval = 0; emit(bad, 0, 0, 0, "zero interval"); - bad = original; bad.ssm_state_size = INT64_MAX; emit(bad, 36, 0, 12, "overflow state"); - bad = original; bad.n_expert = 0; emit(bad, 36, 0, 12, "zero experts"); - bad = original; bad.n_layers = 0; emit(bad, 0, 0, 0, "zero layers"); - bad = original; bad.idx_key_dim = -1; emit(bad, 36, 0, 12, "negative idx"); - bad = original; bad.n_layers = 50; emit(bad, 38, 0, 12, "50 layers"); - bad = original; bad.ssm_d_conv = 1; emit(bad, 36, 0, 12, "conv width 1"); - out += "]"; -} - -void kv_cases(std::string& out) { - out += "\"kv_cases\":["; - bool first = true; - for (int fmt : std::array{kKvF16, kKvInt8, kKvQ4, 3, kKvValueInt8}) for (int mode : {0, 1, 2}) for (int rot : {0, 1}) { - if (fmt == 3 && mode != 0) continue; - Fixture f(fmt, mode); - f.state.kv_rot = rot != 0; - f.fill(13); - for (int64_t upto : {0, 1, 3, 4, 5, 63, 64, 65, 96, 97, -1}) { - const bool index = mode != 2; - ConversationKv a; - std::string err; - const size_t bytes = conversation_kv_bytes(f.state, f.g, upto, index); - const bool ok = conversation_kv_save(a, f.state, f.g, upto, index, err); - out += (first ? "" : ",") + std::string("{\"fmt\":") + std::to_string(fmt) + ",\"mode\":" + std::to_string(mode) + ",\"rot\":" + std::to_string(rot) + - ",\"upto\":" + std::to_string(upto) + ",\"bytes\":" + std::to_string(bytes) + ",\"ok\":" + (ok ? "true" : "false") + - ",\"image\":" + (ok ? kv_json(a) : "null") + "}"; - first = false; - } - } - out += "]"; -} - -// Mirrors conversation_snapshot_test.cpp full_session(): A captured, state overwritten, A restored, re-captured. -void session_cases(std::string& out) { - out += "\"session_cases\":["; - bool first = true; - for (int fmt : std::array{kKvF16, kKvInt8, kKvQ4, kKvValueInt8, 3}) for (int mode : {0, 1}) for (int experts : {256, 512}) { - if (fmt == 3 && mode != 0) continue; - Fixture main(fmt, mode), draft((fmt == 3 || fmt == kKvValueInt8) ? kKvInt8 : fmt, 2); - auto& g = main.g; - g.n_layers = 4; g.n_expert = experts; g.ssm_state_size = 2; g.ssm_v_heads = 2; g.ssm_conv_channels = 8; - SessionState ss; - ss.max_cells = 96; ss.qsa_states = &main.state; - ss.layer_hi = g.n_layers; ss.gdn_alloc = g.n_gdn_layers(); ss.qsa_alloc = g.n_qsa_layers(); - std::string err; - ConversationStateSizes sizes; - conversation_state_sizes(g, sizes, err); - main.store.alloc(ss.gdn_state, sizes.gdn); main.store.alloc(ss.ple_hist, sizes.ple); - main.store.alloc(main.state.idx_tail, sizes.tail); main.store.alloc(main.state.idx_dead, sizes.dead); - main.store.alloc(main.state.idx_block_pos, sizes.block_pos); - std::vector ids(65); - for (size_t i = 0; i < ids.size(); ++i) ids[i] = (int32_t) i + 1; - std::vector images; - std::vector checkpoints; - auto fill = [&](uint8_t salt) { - main.fill(salt); draft.fill(salt); - for (const auto& [p, n] : std::vector>{{ss.gdn_state, sizes.gdn}, {ss.ple_hist, sizes.ple}, - {main.state.idx_tail, sizes.tail}, {main.state.idx_dead, sizes.dead}, {main.state.idx_block_pos, sizes.block_pos}}) - std::memset(p, salt, n); - std::memcpy(main.state.idx_pooled + (ids.size() / 4) * g.idx_key_dim, main.state.idx_dead, sizes.dead); - }; - fill(13); - ConversationCheckpoint checkpoint; - checkpoint.ids.assign(ids.begin(), ids.begin() + 3); - conversation_checkpoint_save(checkpoint, ss, g, err); - checkpoint.used = 17; - checkpoints.push_back(std::move(checkpoint)); - const ConversationView view{ids, images, checkpoints, true}; - size_t estimate = 0; - conversation_snapshot_bytes(view, ss, g, draft.state, estimate, err); - SavedConversation a, b, restored; - conversation_snapshot_save(a, view, ss, g, draft.state, err); - fill(177); - conversation_snapshot_save(b, view, ss, g, draft.state, err); - const bool restored_ok = conversation_snapshot_restore(a, ss, g, draft.state, err) == ConversationRestore::restored; - conversation_snapshot_save(restored, view, ss, g, draft.state, err); - auto cp_json = [](const ConversationCheckpoint& c) { - return "{\"ids\":" + std::to_string(c.ids.size()) + ",\"used\":" + std::to_string(c.used) + ",\"bytes\":" + std::to_string(c.bytes()) + - ",\"hash\":[" + q(hash_hex(c.gdn)) + "," + q(hash_hex(c.ple)) + "," + q(hash_hex(c.tails)) + "," + q(hash_hex(c.dead)) + "," + - q(hash_hex(c.block_pos)) + "]}"; - }; - auto image_json = [&](const SavedConversation& s) { - std::string kv = "["; - for (size_t i = 0; i < s.kv.size(); ++i) kv += (i ? "," : "") + kv_json(s.kv[i]); - kv += "]"; - return "{\"bytes\":" + std::to_string(s.bytes()) + ",\"live\":" + cp_json(s.live) + ",\"checkpoint\":" + cp_json(s.checkpoints[0]) + ",\"kv\":" + kv + "}"; - }; - out += (first ? "" : ",") + std::string("{\"fmt\":") + std::to_string(fmt) + ",\"mode\":" + std::to_string(mode) + ",\"experts\":" + std::to_string(experts) + - ",\"estimate\":" + std::to_string(estimate) + ",\"a\":" + image_json(a) + ",\"b\":" + image_json(b) + ",\"restored_ok\":" + (restored_ok ? "true" : "false") + - ",\"restored\":" + image_json(restored) + ",\"ple_prev\":[" + std::to_string(ss.ple_prev[0]) + "," + std::to_string(ss.ple_prev[1]) + "]}"; - first = false; - } - out += "]"; -} -} // namespace - -int main() { - std::string out = "{"; - state_cases(out); - out += ","; - kv_cases(out); - out += ","; - session_cases(out); - out += "}\n"; - std::fputs(out.c_str(), stdout); -} diff --git a/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h b/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h deleted file mode 100644 index 486ffa19..00000000 --- a/crates/engine-core/src/conversation/golden/stub/cuda_runtime.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include -#include -#include -typedef int cudaError_t; -enum { cudaSuccess = 0, cudaErrorInvalidValue = 1, cudaErrorUnknown = 999 }; -typedef int cudaMemcpyKind; -enum { cudaMemcpyDefault = 4, cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2, cudaMemcpyDeviceToDevice = 3 }; -typedef struct CUstream_st* cudaStream_t; -typedef struct CUevent_st* cudaEvent_t; -inline const char* cudaGetErrorString(cudaError_t) { return "stub"; } -extern "C" cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind); -extern "C" cudaError_t cudaDeviceSynchronize(); -extern "C" cudaError_t cudaGetLastError(); -typedef struct CUgraphExec_st* cudaGraphExec_t; -typedef struct CUgraph_st* cudaGraph_t; diff --git a/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py b/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py deleted file mode 100644 index bb12a6da..00000000 --- a/crates/engine-qwen35-cuda/tests/stra161_reference/reference.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Independent STRA161 offline integer/decode oracle; imports no candidate code.""" -import hashlib, json, re, struct -from pathlib import Path -ROOT=Path(__file__).resolve().parents[4] -OUT=Path(__file__).with_name('fixtures.json') -MULT=[23703573157769,20109073645365,8052911324071] -VOCAB=[20000003,20000023,20000033,20000047,20000059,20000063,20000069,20000077,20000081,20000093,20000107,20000147,20000153,20000159,20000161,20000171] -OFF=[0,20000003,40000026,60000059,80000106,100000165,120000228,140000297,160000374,180000455,200000548,220000655,240000802,260000955,280001114,300001275] -EOS=248044 -MASK=(1<<64)-1 -CODE=[-127,-104,-83,-65,-49,-35,-22,-10,1,13,25,38,53,69,89,113] -def mixed(ctx): - v=0 - for x,m in zip(ctx,MULT):v^=(x*m)&MASK - return v -def rows(token,prev): - ctx=[token];cut=False - for t in reversed(prev): - cut=cut or t<0 or t==EOS - ctx.append(EOS if cut else t) - return [(mixed(ctx[:2 if h<8 else 3])%VOCAB[h])+OFF[h] for h in range(16)] -def words(raw): - out=[] - for b in range(5): - d=struct.unpack('>4]))[0] for q in qs) - return out -# An independently generated original-source oracle predating this candidate. -inc=(ROOT/'engine/strata/src/kernels/ple_oracle_vectors.inc').read_text() -cases=[] -for c in range(6): - def arr(name):return [int(x) for x in re.search(r'case'+str(c)+'_'+name+r'\[\d+\] = \{(.*?)\};',inc,re.S).group(1).replace('\n','').split(',') if x.strip()] - ts,pv,want=arr('tokens'),arr('prev'),arr('rows') - for i,t in enumerate(ts): - # The retained source parity harness passes these original literal predecessor arrays unchanged. - prev=pv[2*i:2*i+2]; got=rows(t,prev) - assert got==want[16*i:16*i+16],(c,i,got,want[16*i:16*i+16]) - cases.append({'name':f'original-{c}-{i}','token':t,'prev_oldest_first':prev,'rows':got}) -for name,t,prev in [('zero',0,[0,0]),('oldest-null',8,[-1,7]),('newest-null',8,[7,-1]),('oldest-eos',9,[EOS,7]),('newest-eos',9,[7,EOS]),('tokenizer-eos-not-ple-eos',9,[7,248046]),('current-eos-keeps-context',EOS,[11,22]),('max-vocabulary',248319,[248318,248319])]:cases.append({'name':name,'token':t,'prev_oldest_first':prev,'rows':rows(t,prev)}) -# Finite synthetic encoded rows, no actual model payload. Exact dyadic scale*integer product. -decode=[] -for name,scales in [('split-nibbles',[0x3c00,0xbc00,0x3800,1,0x8000]),('scale-domains',[0,0x0400,0x7bff,0xfbff,0x3555])]: - raw=b''.join(struct.pack('0)-(s<0));return sigmoid(f32(sign*mag)) -def silu(v):return f32(v/f32(1.0+libm.expf(f32(-v)))) -def bf16(v): - i=word(v);return ((i+((i>>16)&1)+0x7fff)>>16)&0xffff -fp={'profile':'CPU source-ordered probes of default ple.cu(native_postops=false,native_bf16=false), NOT CUDA parity','host':platform.platform(),'libm':'current process C sqrtf/expf/fmaf via ctypes; Darwin libSystem','acceptance':{'integer_decode':{'abs':0,'rel':0,'ulp':0},'CPU_projection_norm_gate_broadcast_conv_residual':{'abs':0,'rel':0,'ulp':0,'scope':'exact frozen finite F32 words for these source-ordered CPU probes only; do not apply to a different reduction/libm/GPU backend'},'CUDA_floating_stages':'Unqualified: requires independently justified backend-specific bounds or source/order/compile equivalence; no guessed abs/rel/ULP'},'gate':[{'input_word':word(x),'expected_word':word(gate(x))} for x in [-1.,-1e-9,-0.,0.,1e-9,1.]],'bf16_round':[{'input_word':word(x),'expected_bf16':bf16(x)} for x in [0.,-0.,1.,1.+2**-8,1.+3*2**-8,-1.-2**-8]],'constant_norm':[],'conv':[],'residual_rival':{}} -for x,gamma in [(0.,1.),(1.,1.),(-1.,0.5),(0.25,-2.)]: - # 2560 repeated values: f32 square, double sum (exact on this fixture), - # double division, materialized F32 mean then F32 epsilon/sqrt/divide, - # source left-to-right x*scale*gamma. - mean=f32(float(f32(x*x))*2560/2560) - scale=f32(1.0/libm.sqrtf(f32(mean+f32(1e-6)))) - fp['constant_norm'].append({'input_word':word(x),'gamma_word':word(gamma),'mean_word':word(mean),'scale_word':word(scale),'expected_word':word(f32(f32(x*scale)*gamma)),'columns':2560}) -for h,current,taps in [([1.,2.,3.],4.,[0.5,-1.,2.,-0.25]),([-1.,0.,1.],-2.,[1.,0.5,-0.25,2.])]: - acc=0. - for x,w in zip(h+[current],taps):acc=libm.fmaf(w,x,acc) - fp['conv'].append({'history_rows':[0,3,6],'history_words':[word(x) for x in h],'current_word':word(current),'tap_words':[word(x) for x in taps],'tap_index':'k+4*channel','acc_word':word(acc),'silu_word':word(silu(acc))}) -a=silu(1.);R=16777216.;g=-16777216. -fp['residual_rival']={'R_word':word(R),'gated_word':word(g),'conv_word':word(a),'default_left_word':word(f32(f32(R+g)+a)),'native_right_word':word(f32(R+f32(g+a)))} - -def from_bf16(v):return struct.unpack(' -#include -#include -#include -#include -#include -#include -#include -#include - -// ---- stand-ins for what the extracted function touches -struct Options { - std::vector> cvec_files; - int cvec_first = -1, cvec_last = -1; - int cvec_mode = 1; - int cvec_single = -1; -}; -namespace strata::kernels { -struct Recorded { std::vector dir, s; int mode = -1, first = 0, last = 0; int64_t n_embd = 0, hc = 0; bool called = false; }; -inline Recorded g_recorded; -inline bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, - int64_t n_embd, int64_t hc, std::string&) { - g_recorded = {dir, s, mode, first, last, n_embd, hc, true}; - return true; -} -} // namespace strata::kernels - -#include "fragment_load_control_vectors.inc" - -namespace { -uint64_t lcg_state = 77; -uint32_t next32() { lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t) (lcg_state >> 32); } -float value() { return (float) ((int32_t) (next32() >> 8) - (1 << 23)) / 8388608.0f * 2.0f; } -uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } - -void put_u32(std::string& b, uint32_t v) { b.append((const char*) &v, 4); } -void put_u64(std::string& b, uint64_t v) { b.append((const char*) &v, 8); } -void put_str(std::string& b, const std::string& s) { put_u64(b, s.size()); b += s; } -struct T { std::string name; std::vector data; uint32_t type = 0; }; -std::string gguf(const std::string& arch, const std::vector& ts, bool hint = false) { - std::string b; - put_u32(b, 0x46554747u); put_u32(b, 3); put_u64(b, ts.size()); put_u64(b, 1 + (hint ? 1 : 0)); - put_str(b, "general.architecture"); put_u32(b, 8); put_str(b, arch); - if (hint) { put_str(b, "controlvector.model_hint"); put_u32(b, 8); put_str(b, "qwen4exp"); } - uint64_t off = 0; - for (const T& t : ts) { - put_str(b, t.name); put_u32(b, 1); put_u64(b, t.data.size()); put_u32(b, t.type); put_u64(b, off); - off += (t.data.size() * 4 + 31) / 32 * 32; - } - while (b.size() % 32) b.push_back(0); - for (const T& t : ts) { - b.append((const char*) t.data.data(), t.data.size() * 4); - while (b.size() % 32) b.push_back(0); - } - return b; -} -std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} -std::vector vec(int n) { std::vector v(n); for (auto& x : v) x = value(); return v; } - -struct Case { std::string name; std::vector> files; std::vector contents; Options o; }; -} // namespace - -int main() { - const int L = 6, N = 40, HC = 4; - strata::core::ModelGeometry g; - g.n_layers = L; g.n_embd = N; g.hc = HC; - const std::string dir = std::string(getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp") + "/leleka_cvec_golden"; - std::system(("mkdir -p " + dir).c_str()); - - std::vector A = {gguf("controlvector", {{"direction.0", vec(N)}, {"direction.2", vec(N)}, {"direction.3", vec(N)}, {"direction.9", vec(N)}}, true), - gguf("controlvector", {{"direction.2", vec(N)}, {"direction.4", vec(N)}})}; - const std::string wrong_arch = gguf("llama", {{"direction.2", vec(N)}}); - const std::string wrong_shape = gguf("controlvector", {{"direction.2", vec(N + 1)}}); - const std::string wrong_type = gguf("controlvector", {{"direction.2", vec(N), 1}}); - const std::string no_dirs = gguf("controlvector", {{"other.2", vec(N)}}); - const std::string only_layer0 = gguf("controlvector", {{"direction.0", vec(N)}}); - const std::string zero_dir = gguf("controlvector", {{"direction.2", std::vector(N, 0.0f)}}); - const std::string truncated = A[0].substr(0, 60); - std::string bad_magic = A[0]; bad_magic[0] = 'X'; - std::string v2 = A[0]; v2[4] = 2; - - std::vector cases; - auto mk = [&](const std::string& name, std::vector> files, std::vector contents, Options o) { - cases.push_back({name, std::move(files), std::move(contents), o}); - }; - Options add; add.cvec_mode = 1; - Options proj; proj.cvec_mode = 0; - Options range = add; range.cvec_first = 2; range.cvec_last = 4; - Options proj_range = proj; proj_range.cvec_first = 2; proj_range.cvec_last = 5; - Options single = proj; single.cvec_single = 3; - Options single_missing = proj; single_missing.cvec_single = 5; - Options single_ignored_in_add = add; single_ignored_in_add.cvec_single = 5; - Options out_of_range = add; out_of_range.cvec_first = 5; out_of_range.cvec_last = 5; - Options wide = add; wide.cvec_last = 100; - mk("add_two_files", {{"a.gguf", 1.5f}, {"b.gguf", -0.5f}}, {A[0], A[1]}, add); - mk("add_range", {{"a.gguf", 1.0f}, {"b.gguf", 2.0f}}, {A[0], A[1]}, range); - mk("add_last_beyond_model", {{"a.gguf", 0.25f}}, {A[0]}, wide); - mk("project_two_files", {{"a.gguf", 1.0f}, {"b.gguf", 1.0f}}, {A[0], A[1]}, proj); - mk("project_range", {{"a.gguf", 0.75f}, {"b.gguf", 0.5f}}, {A[0], A[1]}, proj_range); - mk("project_single_layer", {{"a.gguf", 1.0f}}, {A[0]}, single); - mk("project_single_missing", {{"a.gguf", 1.0f}}, {A[0]}, single_missing); - mk("add_ignores_single", {{"a.gguf", 1.0f}}, {A[0]}, single_ignored_in_add); - mk("nothing_in_range", {{"a.gguf", 1.0f}}, {A[0]}, out_of_range); - mk("zero_scale_project", {{"a.gguf", 0.0f}}, {A[0]}, proj); - mk("zero_direction_project", {{"z.gguf", 1.0f}}, {zero_dir}, proj); - mk("wrong_architecture", {{"w.gguf", 1.0f}}, {wrong_arch}, add); - mk("wrong_shape", {{"s.gguf", 1.0f}}, {wrong_shape}, add); - mk("wrong_type", {{"t.gguf", 1.0f}}, {wrong_type}, add); - mk("no_direction_tensors", {{"n.gguf", 1.0f}}, {no_dirs}, add); - mk("only_layer_zero", {{"o.gguf", 1.0f}}, {only_layer0}, add); - mk("truncated", {{"x.gguf", 1.0f}}, {truncated}, add); - mk("bad_magic", {{"m.gguf", 1.0f}}, {bad_magic}, add); - mk("version_2", {{"v.gguf", 1.0f}}, {v2}, add); - - std::printf("{\"n_layers\":%d,\"n_embd\":%d,\"hc\":%d,\"cases\":[", L, N, HC); - for (size_t ci = 0; ci < cases.size(); ++ci) { - Case& c = cases[ci]; - Options o = c.o; - for (size_t i = 0; i < c.files.size(); ++i) { - const std::string path = dir + "/" + std::to_string(ci) + "_" + c.files[i].first; - std::ofstream(path, std::ios::binary).write(c.contents[i].data(), (std::streamsize) c.contents[i].size()); - o.cvec_files.push_back({path, c.files[i].second}); - } - strata::kernels::g_recorded = {}; - std::string summary, err; - const bool ok = load_control_vectors(o, g, summary, err); - // the error text names the temp path; record it with that prefix replaced by the file label - for (size_t i = 0; i < c.files.size(); ++i) { - const std::string path = dir + "/" + std::to_string(ci) + "_" + c.files[i].first; - for (size_t at; (at = err.find(path)) != std::string::npos;) err.replace(at, path.size(), c.files[i].first); - } - std::printf("%s\n{\"name\":\"%s\",\"options\":{\"first\":%d,\"last\":%d,\"mode\":%d,\"single\":%d},\"files\":[", ci ? "," : "", c.name.c_str(), - o.cvec_first, o.cvec_last, o.cvec_mode, o.cvec_single); - for (size_t i = 0; i < c.files.size(); ++i) - std::printf("%s{\"label\":\"%s\",\"scale\":%u,\"bytes\":\"%s\"}", i ? "," : "", c.files[i].first.c_str(), bits(c.files[i].second), hex(c.contents[i]).c_str()); - std::printf("],\"ok\":%d,\"error\":\"%s\"", ok ? 1 : 0, ok ? "" : err.c_str()); - if (ok) { - const auto& r = strata::kernels::g_recorded; - std::printf(",\"summary\":\"%s\",\"mode\":%d,\"first\":%d,\"last\":%d,\"dir\":[", summary.c_str(), r.mode, r.first, r.last); - for (size_t i = 0; i < r.dir.size(); ++i) std::printf("%s%u", i ? "," : "", bits(r.dir[i])); - std::printf("],\"s\":["); - for (size_t i = 0; i < r.s.size(); ++i) std::printf("%s%u", i ? "," : "", bits(r.s[i])); - std::printf("]"); - } - std::printf("}"); - } - std::printf("]}\n"); - std::system(("rm -rf " + dir).c_str()); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_cvec_golden.sh b/crates/experimental-ref/oracle/gen_cvec_golden.sh deleted file mode 100755 index 5849e650..00000000 --- a/crates/experimental-ref/oracle/gen_cvec_golden.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/cvec_golden.json from generate.cpp's own load_control_vectors (extracted verbatim) -# running on synthetic control-vector GGUF files. Host-only; `cvec_upload` is a recorder. -# crates/experimental-ref/oracle/gen_cvec_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -awk '/^bool load_control_vectors\(const Options& o, const strata::core::ModelGeometry& g, std::string& summary, std::string& err\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/program/generate.cpp" > "$work/fragment_load_control_vectors.inc" -test -s "$work/fragment_load_control_vectors.inc" -# -ffp-contract=off: the Original's host build has no FMA, `data += scale * src` is a multiply then an add -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -Wno-unused-function -Wno-unused-variable -I"$strata/include" -I"$work" \ - "$here/gen_cvec_golden.cpp" -o "$work/gen_cvec" -mkdir -p "$out" -"$work/gen_cvec" > "$out/cvec_golden.json" -echo "wrote $out/cvec_golden.json" diff --git a/crates/experimental-ref/oracle/gen_kv_golden.cpp b/crates/experimental-ref/oracle/gen_kv_golden.cpp deleted file mode 100644 index e7d77e81..00000000 --- a/crates/experimental-ref/oracle/gen_kv_golden.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// Golden fixtures for the Q4_0 / INT8 / FWHT arithmetic and the KV layout sizes, produced by the Original's own -// host code: the functions below are included VERBATIM (extracted by gen_kv_golden.sh with awk, never retyped) -// from engine/strata/src/kernels/kv_q4_parity.cpp (fwht256_host_reference, quantize_block_q4_0_host), -// kv_hybrid_parity.cpp (the INT8 K host reference) and the layer.cpp / kv_stream.cu size functions. -// usage: gen_kv_golden (the script builds it twice: -ffp-contract=off and =fast) -#include "strata/kernels/f16_bits.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include -#include -#include -#include -#include -#include - -namespace k = strata::kernels; -using namespace strata::kernels; - -namespace { -bool g_without_key = false, g_kv_q4 = false; -#include "fragment_fwht_q4.inc" -#include "fragment_pool_bytes.inc" -} // namespace -namespace strata::kernels { -#include "fragment_block_bytes.inc" -} - -namespace { -uint64_t lcg_state = 0x9e3779b97f4a7c15ull; -uint32_t next32() { - lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; - return (uint32_t) (lcg_state >> 32); -} -float uniform() { return (float) (next32() >> 8) / 16777216.0f; } // [0, 1) -float gauss() { // sum of 12 uniforms - 6 - float s = 0.0f; - for (int i = 0; i < 12; ++i) s += uniform(); - return s - 6.0f; -} -uint32_t bits(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } -void print_u32(FILE* o, const float* v, int n) { - std::fprintf(o, "["); - for (int i = 0; i < n; ++i) std::fprintf(o, "%s%u", i ? "," : "", bits(v[i])); - std::fprintf(o, "]"); -} -} // namespace - -int main(int argc, char** argv) { - const std::string mode = argc > 1 ? argv[1] : "separate"; - // The fused build only needs the Q4_0 section (the one place a fused multiply-add changes a result); the - // other sections are generated identically in both builds so the LCG sequence stays aligned. - const bool full = mode == "separate"; - FILE* null_out = std::fopen("/dev/null", "w"); - FILE* o = full ? stdout : null_out; - std::fprintf(o, "{\"mode\":\"%s\",\n", mode.c_str()); - - // ---- FWHT rows (the Original's host reference, butterflies then 1/16) - std::fprintf(o, "\"fwht\":["); - for (int r = 0; r < 24; ++r) { - float in[256], out[256]; - const float scale = r < 8 ? 1.0f : (r < 16 ? 37.5f : 0.003f); - for (int i = 0; i < 256; ++i) in[i] = (r == 23 ? (i == 5 ? 1.0f : 0.0f) : gauss() * scale); - std::memcpy(out, in, sizeof in); - fwht256_host_reference(out); - std::fprintf(o, "%s{\"in\":", r ? ",\n" : "\n"); - print_u32(o, in, 256); - std::fprintf(o, ",\"out\":"); - print_u32(o, out, 256); - std::fprintf(o, "}"); - } - std::fprintf(o, "],\n"); - - // ---- Q4_0 groups (quantize_block_q4_0_host on separate or fused arithmetic, whatever this build does) - o = stdout; - if (!full) std::fprintf(o, "{\"mode\":\"%s\",\n", mode.c_str()); - std::fprintf(o, "\"q4\":["); - const int groups = 480 + 96; // the last 96 sit on the code boundaries where fused and separate evaluation differ - for (int g = 0; g < groups; ++g) { - float x[32]; - const int cls = g >= 480 ? 8 : g % 8; - const float M = 0.05f + uniform() * 9.0f; - for (int i = 0; i < 32; ++i) { - float v = gauss(); - switch (cls) { - case 1: v *= 0.01f; break; - case 2: v *= 300.0f; break; - case 3: v = (i % 2 ? 1.0f : -1.0f) * (float) (i / 2) * 0.25f; break; // exact multiples - case 4: v = (float) ((int) (next32() % 17) - 8) * 0.5f; break; // ties and boundaries - case 5: v = i == 7 ? 1e4f : v * 1e-3f; break; // one outlier - case 6: v = 0.0f; break; - case 7: v = v * 1e-8f; break; // fp16 subnormal scales - case 8: { // x on the half-multiples of d, +-1 ulp - v = i == 0 ? M : (float) ((double) M * ((double) (i % 8) + 0.5) / 8.0); - if (i > 0 && (next32() & 1)) v = nextafterf(v, 0.0f); - if (i > 0 && (next32() & 2)) v = nextafterf(v, 100.0f); - break; - } - default: break; - } - x[i] = v; - } - if (cls == 0 && g % 16 == 0) { x[3] = 2.0f; x[20] = -2.0f; } // tied magnitudes, opposite sign - k::block_q4_0 blk; - quantize_block_q4_0_host(x, blk); - unsigned char raw[18]; - std::memcpy(raw, &blk, 18); - std::fprintf(o, "%s{\"x\":", g ? ",\n" : "\n"); - print_u32(o, x, 32); - std::fprintf(o, ",\"block\":\""); - for (int i = 0; i < 18; ++i) std::fprintf(o, "%02x", raw[i]); - std::fprintf(o, "\"}"); - } - std::fprintf(o, "]"); - - // ---- INT8 K groups (kv_hybrid_parity.cpp's host reference for K) - if (!full) { std::fprintf(o, "}\n"); return 0; } - std::fprintf(o, ",\n"); - std::fprintf(o, "\"q8\":["); - { - const int cells = 12, H = 2, D = 256, G = D / k::KV_Q8_GROUP; - std::vector K((size_t) cells * H * D); - for (size_t i = 0; i < K.size(); ++i) K[i] = gauss() * ((i / 64) % 5 == 0 ? 0.0f : ((i / 64) % 5) * 0.4f); - std::vector rk((size_t) cells * H * D); - std::vector rk_s((size_t) cells * H * G); -#include "fragment_q8_k.inc" - for (int c = 0; c < cells; ++c) - for (int h = 0; h < H; ++h) - for (int g = 0; g < G; ++g) { - const size_t base = ((size_t) c * H + h) * D + (size_t) g * k::KV_Q8_GROUP; - std::fprintf(o, "%s{\"x\":", (c || h || g) ? ",\n" : "\n"); - print_u32(o, &K[base], 64); - std::fprintf(o, ",\"scale\":%u,\"codes\":[", (unsigned) rk_s[((size_t) c * H + h) * G + g]); - for (int t = 0; t < 64; ++t) std::fprintf(o, "%s%d", t ? "," : "", (int) rk[base + t]); - std::fprintf(o, "]}"); - } - } - std::fprintf(o, "],\n"); - - // ---- layout sizes: the Original's own functions - const k::QsaShapes s = k::qsa_real_shapes(); - std::fprintf(o, "\"per_cell\":{\"q8\":%llu,\"q4\":%llu},\n", (unsigned long long) k::kv_q8_bytes_per_cell(s), - (unsigned long long) k::kv_q4_bytes_per_cell(s)); - std::fprintf(o, "\"block_bytes\":{\"f16\":%llu,\"int8\":%llu,\"q4\":%llu,\"value_int8\":%llu},\n", - (unsigned long long) k::kv_block_bytes(s, k::kKvF16), (unsigned long long) k::kv_block_bytes(s, k::kKvInt8), - (unsigned long long) k::kv_block_bytes(s, k::kKvQ4), (unsigned long long) k::kv_block_bytes(s, k::kKvValueInt8)); - std::fprintf(o, "\"pool_bytes\":["); - bool first = true; - for (int64_t pages : {1, 5, 64, 5120, 131072}) { - struct Case { const char* name; bool without_key, q4, hybrid, int8; } cases[] = { - {"fp16", false, false, false, false}, {"int8", false, false, false, true}, {"q4_0", false, true, false, true}, - {"k8v4", false, false, true, true}, {"int8-keyless", true, false, false, true}}; - for (const Case& c : cases) { - g_without_key = c.without_key; - g_kv_q4 = c.q4; - std::fprintf(o, "%s{\"format\":\"%s\",\"pages\":%lld,\"bytes\":%llu}", first ? "\n" : ",\n", c.name, (long long) pages, - (unsigned long long) kv_pool_bytes(s, pages, c.hybrid, c.int8)); - first = false; - } - } - std::fprintf(o, "]}\n"); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_kv_golden.sh b/crates/experimental-ref/oracle/gen_kv_golden.sh deleted file mode 100755 index 646051c8..00000000 --- a/crates/experimental-ref/oracle/gen_kv_golden.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/kv_golden_{separate,fused}.json from the Original's host code (macOS or Linux, any -# C++17 compiler, no CUDA). The reference functions are extracted verbatim from engine/strata with awk. -# crates/experimental-ref/oracle/gen_kv_golden.sh -# `separate` is compiled with -ffp-contract=off (every x * id + 8.5f is a multiply then an add), `fused` with -# -ffp-contract=fast (-mfma on x86; arm64 fuses natively), which is how nvcc compiles the same expression. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# 1. fwht256_host_reference + quantize_block_q4_0_host, up to the end of the anonymous namespace -awk '/^void fwht256_host_reference\(float\* x\) \{/ {on=1} on && /^} \/\/ namespace/ {exit} on {print}' \ - "$strata/src/kernels/kv_q4_parity.cpp" > "$work/fragment_fwht_q4.inc" -# 2. kv_pool_bytes of layer.cpp -awk '/^uint64_t kv_pool_bytes\(const QsaShapes& s, int64_t pages, bool hybrid, bool int8\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/core/layer.cpp" > "$work/fragment_pool_bytes.inc" -# 3. kv_block_bytes of kv_stream.cu -awk '/^uint64_t kv_block_bytes\(const QsaShapes& s, int fmt\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$strata/src/kernels/cuda/kv_stream.cu" > "$work/fragment_block_bytes.inc" -# 4. the INT8 K host reference loop of kv_hybrid_parity.cpp (from after the rk_s declaration to Vrot's) -awk '/std::vector rk_s\(/ {skip=1; next} skip && /std::vector Vrot/ {exit} skip {print}' \ - "$strata/src/kernels/kv_hybrid_parity.cpp" > "$work/fragment_q8_k.inc" -for f in fragment_fwht_q4 fragment_pool_bytes fragment_block_bytes fragment_q8_k; do test -s "$work/$f.inc"; done -CXX=${CXX:-clang++} -FMA="" -case $(uname -m) in x86_64|amd64) FMA="-mfma" ;; esac -common="-std=c++17 -O1 -Wno-unused-function -I$strata/include -I$here/stub -I$work" -$CXX $common -ffp-contract=off -o "$work/gen_separate" "$here/gen_kv_golden.cpp" -$CXX $common -ffp-contract=fast $FMA -o "$work/gen_fused" "$here/gen_kv_golden.cpp" -mkdir -p "$out" -"$work/gen_separate" separate > "$out/kv_golden_separate.json" -"$work/gen_fused" fused > "$out/kv_golden_fused.json" -echo "wrote $out/kv_golden_separate.json and kv_golden_fused.json" diff --git a/crates/experimental-ref/oracle/gen_remote_golden.cpp b/crates/experimental-ref/oracle/gen_remote_golden.cpp deleted file mode 100644 index 3c529705..00000000 --- a/crates/experimental-ref/oracle/gen_remote_golden.cpp +++ /dev/null @@ -1,200 +0,0 @@ -// Golden fixtures for the second-GPU expert tier. The decision code of engine/strata/src/core/remote_experts.cpp -// (selection, slot sizing, claim bookkeeping, window guard + grouping, RemoteMeta packing, the result scatter) is -// included VERBATIM through the fragments extracted by gen_remote_golden.sh; the harness provides the members and -// recorder stand-ins for the cache and layout they touch. -#include -#include -#include -#include -#include -#include - -namespace strata::kernels::cpu { constexpr int64_t MAXT = 8; } -namespace { -constexpr int64_t H = 2560; -constexpr int64_t CAP = 8 * 10; -#include "f_struct.inc" - -struct Layout { - bool native = false; - uint64_t max_blob = 1382400; - std::vector blobs; - uint64_t blob_bytes(int64_t layer) const { return blobs[(size_t) layer]; } -}; -struct Cache { - std::vector> sel; - int32_t slot_of(int64_t layer, int64_t expert) const { - for (size_t i = 0; i < sel.size(); ++i) if (sel[i].first == layer && sel[i].second == expert) return (int32_t) i; - return -1; - } - uint64_t device_slot(int32_t slot) const { return 0x100000000ull + (uint64_t) slot * 0x200000ull; } -}; -struct Primary { - std::vector has; // layers * experts - int64_t experts = 0; - int32_t slot_of(int64_t layer, int64_t expert) const { return has[(size_t) (layer * experts + expert)] ? 3 : -1; } -}; - -struct Tier { - int device = 1; - int64_t n_expert_ = 0; - int device_ = 1; - Layout lay; - Cache cache_; - std::vector owned_ = std::vector(CAP, 0), layers_present_; - std::vector group_of_ = std::vector(CAP, -1), group_id_; - std::vector ptr_; - std::vector start_, dst_, tok_, original_row_; - uint64_t computed_ = 0; - unsigned char h_meta_[sizeof(RemoteMeta)] = {}; - const float* h_out_ = nullptr; - std::string err; - void close() {} - - // open() up to the memory check; returns selected.empty() == false - bool select(int slots, int64_t layers, int64_t experts, const std::vector>& ranked, - const Primary& primary, std::vector& claimed, std::vector>& selected_out, - uint64_t& needed_out) { - n_expert_ = experts; -#include "f_select.inc" - uint64_t needed_total = 0; - { -#include "f_needed.inc" - needed_total = needed; - } - layers_present_.assign((size_t) layers, 0); -#include "f_mark.inc" - selected_out = selected; - cache_.sel = selected; - needed_out = needed_total; - return true; - } - - bool begin(int64_t layer, const int32_t* ids, int64_t n_tok, int64_t k, const int32_t* kind, const int32_t* primary_res) { - const int64_t n = n_tok * k; -#include "f_begin.inc" - return true; - } - void pack(int64_t) { -#include "f_meta.inc" - } - void finish(float* out) { -#include "f_finish.inc" - } -}; - -uint64_t lcg_state = 4242; -uint32_t next32() { lcg_state = lcg_state * 6364136223846793005ull + 1442695040888963407ull; return (uint32_t) (lcg_state >> 32); } -uint32_t below(uint32_t n) { return next32() % n; } - -template void arr(const char* name, const std::vector& v, bool comma = true) { - std::printf("\"%s\":[", name); - for (size_t i = 0; i < v.size(); ++i) std::printf("%s%lld", i ? "," : "", (long long) v[i]); - std::printf("]%s", comma ? "," : ""); -} -} // namespace - -int main() { - std::printf("{\"open\":["); - const int L = 6, E = 24; - std::vector tiers; - std::vector primaries; - for (int c = 0; c < 40; ++c) { - Tier t; - Primary p; - p.experts = E; - p.has.assign((size_t) L * E, 0); - for (auto& h : p.has) h = below(5) == 0; - std::vector claimed((size_t) L * E, 0); - for (auto& v : claimed) v = below(6) == 0; - std::vector> ranked; - const int rn = 5 + (int) below(60); - for (int i = 0; i < rn; ++i) ranked.push_back({(int32_t) below(L + 2) - 1, (int32_t) below(E + 3) - 1}); - if (c % 5 == 3) ranked.insert(ranked.begin() + 1, ranked[0]); - t.lay.native = c % 2 == 1; - for (int l = 0; l < L; ++l) t.lay.blobs.push_back(100000 + below(900000)); - const int slots = 1 + (int) below(30); - const std::vector claimed_in = claimed; - std::vector> sel; - uint64_t needed = 0; - t.select(slots, L, E, ranked, p, claimed, sel, needed); - std::printf("%s{\"slots\":%d,\"native\":%d,", c ? "," : "", slots, t.lay.native ? 1 : 0); - arr("blobs", t.lay.blobs); - std::printf("\"max_blob\":%llu,", (unsigned long long) t.lay.max_blob); - arr("primary", p.has); - arr("claimed_in", claimed_in); - std::printf("\"ranked\":["); - for (size_t i = 0; i < ranked.size(); ++i) std::printf("%s[%d,%d]", i ? "," : "", ranked[i].first, ranked[i].second); - std::printf("],\"selected\":["); - for (size_t i = 0; i < sel.size(); ++i) std::printf("%s[%d,%d]", i ? "," : "", sel[i].first, sel[i].second); - std::printf("],\"needed\":%llu,", (unsigned long long) needed); - arr("layers_present", t.layers_present_); - arr("claimed_out", claimed, false); - std::printf("}"); - tiers.push_back(t); - primaries.push_back(p); - } - std::printf("],\"begin\":["); - int emitted = 0; - for (int c = 0; c < 200; ++c) { - Tier& t = tiers[(size_t) (c % tiers.size())]; - if (t.cache_.sel.empty()) continue; - const Primary& p = primaries[(size_t) (c % tiers.size())]; - const int64_t n_tok = c % 23 == 0 ? 9 : 1 + below(8); - int64_t k = c % 31 == 0 ? 9 : 10; - int64_t layer = c % 29 == 0 ? L : (int64_t) below(L); - // bias ids toward held experts so groups form - std::vector ids((size_t) (n_tok * k) + 1); - for (auto& id : ids) { - const uint32_t r = below(10); - if (r < 6) id = t.cache_.sel[below((uint32_t) t.cache_.sel.size())].second; - else if (r == 9) id = (int32_t) below(4) - 2 + (r == 9 ? E : 0); - else id = (int32_t) below(E); - } - const bool use_kind = c % 3 == 1, use_primary = c % 4 == 2; - std::vector kind(ids.size()), pres((size_t) L * E); - for (auto& v : kind) v = below(4) == 0 ? 2 : -1; - for (size_t i = 0; i < pres.size(); ++i) pres[i] = p.has[i] ? 1 : -1; - t.start_.clear(); t.dst_.clear(); t.tok_.clear(); t.original_row_.clear(); t.group_id_.clear(); t.ptr_.clear(); - t.computed_ = 0; - t.owned_.assign(CAP, 0); - const bool ok = t.begin(layer, ids.data(), n_tok, k, use_kind ? kind.data() : nullptr, use_primary ? pres.data() : nullptr); - std::printf("%s{\"layer\":%lld,\"n_tok\":%lld,\"k\":%lld,\"tier\":%d,", emitted++ ? "," : "", (long long) layer, (long long) n_tok, (long long) k, (int) (c % tiers.size())); - arr("ids", std::vector(ids.begin(), ids.begin() + (size_t) (n_tok * k))); - std::printf("\"use_kind\":%d,\"use_primary\":%d,", use_kind, use_primary); - arr("kind", std::vector(kind.begin(), kind.begin() + (size_t) (n_tok * k))); - std::printf("\"ok\":%d,", ok ? 1 : 0); - if (ok) { - arr("owned", t.owned_); - arr("group_id", t.group_id_); - arr("ptr", t.ptr_); - arr("start", t.start_); - arr("dst", t.dst_); - arr("tok", t.tok_); - arr("original_row", t.original_row_); - std::printf("\"computed\":%llu,", (unsigned long long) t.computed_); - if (!t.group_id_.empty()) { - std::memset(t.h_meta_, 0, sizeof t.h_meta_); - t.pack(n_tok); - std::printf("\"meta\":["); - for (size_t i = 0; i < sizeof t.h_meta_; ++i) std::printf("%s%u", i ? "," : "", t.h_meta_[i]); - std::printf("],"); - // finish: rows of 4 floats stand in for H (the verbatim loop uses H; use the real width on a sparse check) - std::vector compact(t.dst_.size() * H); - for (size_t i = 0; i < compact.size(); ++i) compact[i] = (float) (i / H) + 1.0f + (float) (i % H) * 0.0001f; - std::vector out((size_t) (n_tok * k) * H, -1.0f); - // run the verbatim scatter with the real width - t.h_out_ = compact.data(); - t.finish(out.data()); - std::printf("\"scatter_rows\":["); - for (size_t r = 0; r < (size_t) (n_tok * k); ++r) { - // row signature: first, middle, last element - std::printf("%s[%.7g,%.7g,%.7g]", r ? "," : "", out[r * H], out[r * H + H / 2], out[r * H + H - 1]); - } - std::printf("],"); - } - } - std::printf("\"end\":0}"); - } - std::printf("]}\n"); -} diff --git a/crates/experimental-ref/oracle/gen_remote_golden.sh b/crates/experimental-ref/oracle/gen_remote_golden.sh deleted file mode 100755 index 9aaebc7d..00000000 --- a/crates/experimental-ref/oracle/gen_remote_golden.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/remote_golden.json from the Original's remote_experts.cpp: the expert selection of -# `open`, the grouping of `begin`, the RemoteMeta packing and `finish`'s scatter are extracted VERBATIM (awk) and -# compiled on the host against recorder stand-ins for the cache / layout. No CUDA involved. -# crates/experimental-ref/oracle/gen_remote_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -src="$strata/src/core/remote_experts.cpp" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -# open(): rank filter ... "no unclaimed experts" check -awk '/^ std::vector> selected;$/ {on=1} on {print} on && /selected\.empty\(\)/ {exit}' "$src" > "$work/f_select.inc" -# open(): device bytes of the chosen slots -awk '/^ uint64_t needed = 0;$/ {on=1} on {print; n++} on && n==3 {exit}' "$src" > "$work/f_needed.inc" -# open(): claim bookkeeping -awk '{ if (hold != "" && index($0, "layers_present_[(size_t) pair.first] = 1;")) { print hold; on=1 } hold=$0 } on {print} on && /^ }$/ {exit}' "$src" > "$work/f_mark.inc" -# begin(): window guard ... group/start/dst/tok construction -awk '/^ if \(n <= 0 \|\| n > CAP/ {on=1} on {print} on && /^ start_\.push_back\(\(int32_t\) dst_\.size\(\)\);$/ {exit}' "$src" > "$work/f_begin.inc" -# begin(): metadata packing -awk '/auto\* meta = \(RemoteMeta\*\) h_meta_;/ {on=1} on {print} on && /meta->count = / {exit}' "$src" > "$work/f_meta.inc" -# finish(): scatter -awk '/^ for \(size_t i = 0; i < original_row_\.size\(\); \+\+i\)$/ {on=1} on {print; n++} on && n==2 {exit}' "$src" > "$work/f_finish.inc" -# struct RemoteMeta -awk '/^struct RemoteMeta \{/ {on=1} on {print} on && /^};/ {exit}' "$src" > "$work/f_struct.inc" -for f in select needed mark begin meta finish struct; do test -s "$work/f_$f.inc" || { echo "empty fragment $f" >&2; exit 1; }; done -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -I"$work" "$here/gen_remote_golden.cpp" -o "$work/gen_remote" -mkdir -p "$out" -"$work/gen_remote" > "$out/remote_golden.json" -echo "wrote $out/remote_golden.json" diff --git a/crates/experimental-ref/oracle/gen_seal_additions.py b/crates/experimental-ref/oracle/gen_seal_additions.py deleted file mode 100644 index 2c05ec51..00000000 --- a/crates/experimental-ref/oracle/gen_seal_additions.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 -"""Regenerates crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json (sha256 + bytes of the six experimental .cu assets -and their Rust consumers). Run from the repository root after any edit to those files: - python3 crates/experimental-ref/oracle/gen_seal_additions.py -Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list and the -target sets only CUDA_STANDARD 17, so the build is precise, default -fmad.""" -import hashlib, json - -def sha(path): - data = open(path, "rb").read() - return {"sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)} - -PROGRAMS = [ - ("kv_q4", "kv_q4.cu", "FWHT-256 + Q4_0 append (step/batched) + gather; Original kv_q4.cu precise (default flags, not in the fast-math list); K8V4's Q4_0 V half and rotated INT8's FWHT"), - ("kv_q8", "kv_q8.cu", "INT8 append (K+V, K8V4 K half, V-only) + gather; Original kv_q8.cu precise"), - ("kv_stream", "kv_stream.cu", "CLOCK residency resolver, block copy, ring table, u4 copy; Original kv_stream.cu precise; integer only"), - ("keyless", "keyless.cu", "per-head query routing (fmaf-ordered 256x256); Original keyless.cu precise"), - ("qsa_attn", "qsa_decode_attn.cu", "experimental attention modes 2/3/4 + merge; Original qsa_decode_attn.cu precise (expf/exp2f exact, not in the fast-math list)"), - ("cvec", "cvec.cu", "control-vector apply; Original cvec.cu default flags (its own __expf in sigmoidf_ is explicit in the source)"), -] -src = "crates/cuda-driver/src/" -assets = [] -for i, (name, original, policy) in enumerate(PROGRAMS): - assets.append({ - "cu": f"{src}experimental_{name}.cu", - "cu_pin": sha(f"{src}experimental_{name}.cu"), - "ptx": f"{src}experimental_{name}.ptx", - "flags": ["-ptx", "-O3", "-arch=sm_120", "-std=c++17"], - "policy": "EXPERIMENTAL, off by default (OptIn). " + policy, - "direct_original_headers": [], - "original": f"engine/strata/src/kernels/cuda/{original}", - "rust_consumers": {"experimental.rs": sha(src + "experimental.rs"), "experimental_gpu.rs": sha(src + "experimental_gpu.rs")}, - "rust_fields_to_fill": {"experimental.rs": [f"PINS[{i}].source_sha256", f"PINS[{i}].ptx_sha256"]}, - "encoding": "concat_include_str", - "seal_sha256": None, - "seal_length": None, - }) -doc = { - "schema": 1, - "note": "Additions for the experimental Strata modes. None of these six .cu files has been compiled; PINS in experimental.rs are all zero and admit_ptx refuses every asset until Root builds the PTX and freezes the digests. Flags follow engine/strata/CMakeLists.txt: none of the six Original TUs is in the --use_fast_math list (native_* only) and the strata_kernels target adds no other CUDA flag besides CUDA_STANDARD 17, so the build is precise (no --use_fast_math) with default -fmad contraction.", - "assets": assets, -} -with open("crates/cuda-driver/seal-plans/cuda-seal-plan-additions-experimental.json", "w") as f: - json.dump(doc, f, indent=2) - f.write("\n") diff --git a/crates/experimental-ref/oracle/gen_stream_golden.cpp b/crates/experimental-ref/oracle/gen_stream_golden.cpp deleted file mode 100644 index dedfe0f2..00000000 --- a/crates/experimental-ref/oracle/gen_stream_golden.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Golden fixtures for the KV streaming planner: `kv_plan`, `kv_pool_bytes`, `qsa_state_bytes`, `qsa_shapes`, -// `align_up16` and `qsa_kv_resident_min` of engine/strata/src/core/layer.cpp, included VERBATIM (extracted by -// gen_stream_golden.sh with awk, never retyped) and driven over a grid of formats, contexts, rings and -// --kv-resident values. Host-only: no CUDA symbol is needed. -#include "strata/core/layout.hpp" -#include "strata/kernels/kv_q4.hpp" -#include "strata/kernels/kv_q8.hpp" -#include "strata/kernels/kv_stream.hpp" -#include "strata/kernels/qsa.hpp" - -#include -#include -#include -#include -#include - -namespace strata::core { -using strata::kernels::QsaShapes; -int64_t qsa_kv_resident_min(); -#include "fragment_flags.inc" -namespace { -#include "fragment_shapes.inc" -#include "fragment_streaming.inc" -} // namespace -#include "fragment_state_bytes.inc" -#include "fragment_resident_min.inc" - -void emit() { - const ModelGeometry g; - struct Fmt { const char* name; bool without_key, int8, q4, hybrid; } fmts[] = { - {"fp16", false, false, false, false}, {"int8", false, true, false, false}, {"q4_0", false, false, true, false}, - {"k8v4", false, false, false, true}, {"int8-keyless", true, true, false, false}}; - std::printf("{\"cases\":["); - bool first = true; - for (const Fmt& f : fmts) - for (int64_t max_cells : {4096ll, 32768ll, 262144ll, 524288ll}) - for (int64_t ring : {0ll, 256ll, -1ll}) - for (int64_t resident : {0ll, 1000ll, 20480ll, 65536ll}) - for (int rope = 0; rope < 2; ++rope) { - g_without_key = f.without_key; - g_kv_int8 = f.int8; - g_kv_q4 = f.q4; - g_kv_hybrid = f.hybrid; - g_kv_resident = resident; - const QsaShapes s = qsa_shapes(g); - const KvPlan p = kv_plan(s, max_cells, ring); - const uint64_t bytes = qsa_state_bytes(g, max_cells, rope != 0, ring); - std::printf("%s\n{\"format\":\"%s\",\"max_cells\":%lld,\"ring\":%lld,\"resident\":%lld,\"rope\":%d," - "\"mode\":%d,\"pages\":%lld,\"slots\":%lld,\"pooled_rows\":%lld,\"state_bytes\":%llu}", - first ? "" : ",", f.name, (long long) max_cells, (long long) ring, (long long) resident, rope, - p.mode, (long long) p.pages, (long long) p.slots, (long long) p.pooled_rows, - (unsigned long long) bytes); - first = false; - } - std::printf("],\"resident_min\":%lld,\"map_bytes_5120\":%llu}\n", (long long) qsa_kv_resident_min(), - (unsigned long long) strata::kernels::kv_stream_map_bytes(5120)); -} -} // namespace strata::core - -int main() { - strata::core::emit(); - return 0; -} diff --git a/crates/experimental-ref/oracle/gen_stream_golden.sh b/crates/experimental-ref/oracle/gen_stream_golden.sh deleted file mode 100755 index 71a271e1..00000000 --- a/crates/experimental-ref/oracle/gen_stream_golden.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -# Regenerates tests/fixtures/stream_plan_golden.json from layer.cpp's own planner functions (extracted verbatim). -# crates/experimental-ref/oracle/gen_stream_golden.sh -set -eu -here=$(cd "$(dirname "$0")" && pwd) -strata="$here/../../../engine/strata" -out="$here/../tests/fixtures" -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -layer="$strata/src/core/layer.cpp" -grep -m1 '^namespace { bool g_without_key' "$layer" | sed 's/^namespace {//; s/}$//' > "$work/fragment_flags.inc" -grep -m1 '^QsaShapes qsa_shapes(const ModelGeometry& g) {' "$layer" > "$work/fragment_shapes.inc" -grep -m1 '^uint64_t align_up16(uint64_t n) {' "$layer" >> "$work/fragment_shapes.inc" -# the streaming chunk: from the globals to the end of kv_pool_bytes (the anonymous namespace closes after it) -awk '/^int64_t g_kv_resident = 0;/ {on=1} on && /^} \/\/ namespace/ {exit} on {print}' "$layer" > "$work/fragment_streaming.inc" -awk '/^uint64_t qsa_state_bytes\(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells\) \{/ {on=1} on {print} on && /^}/ {exit}' \ - "$layer" > "$work/fragment_state_bytes.inc" -grep -m1 '^int64_t qsa_kv_resident_min()' "$layer" > "$work/fragment_resident_min.inc" -for f in fragment_flags fragment_shapes fragment_streaming fragment_state_bytes fragment_resident_min; do test -s "$work/$f.inc"; done -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -Wno-unused-function -Wno-unused-variable -I"$strata/include" -I"$here/stub" -I"$work" \ - "$here/gen_stream_golden.cpp" -o "$work/gen_stream" -mkdir -p "$out" -"$work/gen_stream" > "$out/stream_plan_golden.json" -echo "wrote $out/stream_plan_golden.json" diff --git a/crates/experimental-ref/oracle/stub/cuda_runtime.h b/crates/experimental-ref/oracle/stub/cuda_runtime.h deleted file mode 100644 index 18d0d282..00000000 --- a/crates/experimental-ref/oracle/stub/cuda_runtime.h +++ /dev/null @@ -1,3 +0,0 @@ -// Host-only stand-in: the Original headers pulled in by the oracle harnesses need no CUDA symbol, only the -// include to resolve. Nothing here is ever linked or executed on a device. -#pragma once diff --git a/crates/experimental-ref/src/lib.rs b/crates/experimental-ref/src/lib.rs index 283b8044..2886c44b 100644 --- a/crates/experimental-ref/src/lib.rs +++ b/crates/experimental-ref/src/lib.rs @@ -1,5 +1,5 @@ //! CPU references, cell layouts and planners for the *experimental* modes of the Original Strata engine -//! (`engine/strata`), in safe Rust. Every mode here is lossy or otherwise unqualified and is therefore OFF by +//! (Strata 41cf05a0), in safe Rust. Every mode here is lossy or otherwise unqualified and is therefore OFF by //! default; callers must name the mode explicitly (see `leleka-cuda-driver::experimental`). //! //! * [`f16`], [`fwht`], [`q4_0`], [`kv_q8`] - the arithmetic of `f16_bits.hpp`, `kv_q4.cu`, `kv_q8.cu`. diff --git a/crates/experimental-ref/tests/kv_golden.rs b/crates/experimental-ref/tests/kv_golden.rs index 26dec0bd..0ea48e10 100644 --- a/crates/experimental-ref/tests/kv_golden.rs +++ b/crates/experimental-ref/tests/kv_golden.rs @@ -1,5 +1,5 @@ //! Golden tests: the Rust references against fixtures produced by the Original's own host code -//! (`oracle/gen_kv_golden.sh`; the reference functions are extracted verbatim from `engine/strata`). +//! (`oracle/gen_kv_golden.sh`; the reference functions are extracted verbatim from Strata 41cf05a0). use leleka_experimental_ref::{ fwht, kv_q8, diff --git a/crates/experimental-ref/tests/literal_port.rs b/crates/experimental-ref/tests/literal_port.rs deleted file mode 100644 index f43682d9..00000000 --- a/crates/experimental-ref/tests/literal_port.rs +++ /dev/null @@ -1,346 +0,0 @@ -//! Drift guard for the six CUDA ports: every line of every `__device__` / `__global__` function body of the -//! Original (`engine/strata/src/kernels/cuda/*.cu`) must still appear, whitespace-normalised, in the checked-in -//! port (`crates/cuda-driver/src/experimental_*.cu`). Signatures, host wrappers and error handling are the -//! documented deviations; kernel bodies are not allowed to differ. -//! -//! A device function of the Original that the port deliberately does not carry is named in that pair's -//! `EXCLUDED` list with its reason. The list is the only way past the guard, it is checked both ways (a name that -//! no longer exists in the Original fails, so the list cannot rot), and a NEW device function of the Original -//! that is neither in the port nor in the list fails the test: the upstream sync has to be looked at. -//! -//! History: the 2026-10-25 sync of `engine/strata` to upstream `41cf05a0` moved the Original kernels and the -//! ports were re-synced on 2026-11-03. - -use std::collections::HashSet; - -fn norm(line: &str) -> String { - line.split_whitespace().collect::>().join(" ") -} - -/// One `__global__` / `__device__` function of a source: its name and the normalised lines of its body. -#[derive(Debug)] -struct Body { - name: String, - lines: Vec, -} - -/// The function name of a signature (text between the `__global__` / `__device__` marker and the opening brace): -/// the identifier right before the first `(` once `__launch_bounds__(..)` is removed. -fn signature_name(signature: &str) -> String { - let mut text = signature.to_string(); - while let Some(i) = text.find("__launch_bounds__") { - let open = text[i..].find('(').map(|k| i + k); - let close = open.and_then(|o| text[o..].find(')').map(|k| o + k)); - match close { - Some(c) => text.replace_range(i..=c, " "), - None => break, - } - } - let head = match text.find('(') { - Some(i) => &text[..i], - None => &text[..], - }; - head.trim_end() - .rsplit(|c: char| !(c.is_alphanumeric() || c == '_')) - .next() - .unwrap_or("") - .to_string() -} - -/// Offset (from `after`) of the `}` that closes the `{` at `open`. -fn matching_brace(after: &str, open: usize) -> usize { - let mut depth = 0i32; - for (k, ch) in after[open..].char_indices() { - match ch { - '{' => depth += 1, - '}' => { - depth -= 1; - if depth == 0 { - return open + k; - } - } - _ => {} - } - } - panic!("unbalanced braces") -} - -/// The normalised, non-trivial lines of a function body. -fn body_lines(body: &str) -> Vec { - let mut lines = Vec::new(); - for line in body.lines() { - let l = norm(line); - if l.len() >= 6 && !l.starts_with("//") { - lines.push(l); - } - } - lines -} - -/// The first `__global__` / `__device__` marker of `rest`: its offset and length. -fn next_marker(rest: &str) -> Option<(usize, usize)> { - ["__global__", "__device__"] - .iter() - .filter_map(|m| rest.find(m).map(|i| (i, m.len()))) - .min() -} - -/// Bodies of all device functions (text between the first `{` after the `__global__` / `__device__` marker and its -/// matching `}`), signatures excluded. -fn device_bodies(source: &str) -> Vec { - let mut out = Vec::new(); - let text = source; - let mut search = 0; - while search < text.len() { - let Some((i, len)) = next_marker(&text[search..]) else { break }; - let from = search + i + len; - // a declaration like `__device__ int x;` has `;` before any `{` - let after = &text[from..]; - let (brace, semi) = (after.find('{'), after.find(';')); - match (brace, semi) { - (Some(b), Some(s)) if s < b => { - search = from + s; - continue; - } - (Some(b), _) => { - let end = matching_brace(after, b); - out.push(Body { - name: signature_name(&after[..b]), - lines: body_lines(&after[b + 1..end]), - }); - search = from + end; - } - _ => break, - } - } - out -} - -/// A device function of the Original that the port does not carry, and why. -type Excluded = (&'static str, &'static str); - -/// Every exclusion names a device function of the Original and carries a reason. -fn assert_exclusions_are_live(name: &str, names: &HashSet<&str>, excluded: &[Excluded]) { - for (function, reason) in excluded { - assert!( - names.contains(function), - "{name}: EXCLUDED names `{function}` ({reason}) but the Original has no such device \ - function; remove or rename the entry" - ); - assert!( - !reason.is_empty(), - "{name}: `{function}` is excluded without a reason" - ); - } -} - -/// The body lines that appear neither as a line of the port nor in its whitespace-flattened text. -fn missing_lines<'a>(lines: &[&'a String], have: &HashSet, flat: &str) -> Vec<&'a String> { - lines - .iter() - .copied() - .filter(|l| !have.contains(*l) && !flat.contains(l.as_str())) - .collect() -} - -fn check(name: &str, original: &str, port: &str, excluded: &[Excluded]) { - let have: HashSet = port.lines().map(norm).collect(); - let flat = norm(port); - let bodies = device_bodies(original); - let names: HashSet<&str> = bodies.iter().map(|b| b.name.as_str()).collect(); - assert_exclusions_are_live(name, &names, excluded); - let skip: HashSet<&str> = excluded.iter().map(|(f, _)| *f).collect(); - let kept: Vec<&Body> = bodies.iter().filter(|b| !skip.contains(b.name.as_str())).collect(); - let lines: Vec<&String> = kept.iter().flat_map(|b| b.lines.iter()).collect(); - assert!(lines.len() > 5, "{name}: found no device bodies"); - let missing = missing_lines(&lines, &have, &flat); - assert!( - missing.is_empty(), - "{name}: {} original kernel-body lines are not in the port:\n{}", - missing.len(), - missing - .iter() - .map(|l| l.as_str()) - .collect::>() - .join("\n") - ); - println!( - "{name}: {} kernel-body lines of {} device functions all present; {} functions excluded \ - with a reason", - lines.len(), - kept.len(), - excluded.len() - ); -} - -macro_rules! pair { - ($test:ident, $name:literal, $orig:literal, $port:literal, $excluded:expr) => { - #[test] - fn $test() { - check( - $name, - include_str!(concat!("../../../engine/strata/src/kernels/cuda/", $orig)), - include_str!(concat!("../../cuda-driver/src/", $port)), - $excluded, - ); - } - }; -} - -// kv_q8.cu: the 8-wide gather exists only in the experimental SM60 build of the Original (`#if -// defined(STRATA_EXPERIMENTAL_SM60)`, Pascal / Volta). The ready-made engine, and this port (sm_120, sm_86), run the -// 4-wide `kv_gather_q8_kernel`, which is ported. The Original states the wide kernel is bitwise the same. -const KV_Q8_EXCLUDED: &[Excluded] = &[ - ( - "q8_pair_to_f16x2", - "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); compiled out of the ready-made engine", - ), - ( - "kv_gather_q8_wide_kernel", - "STRATA_EXPERIMENTAL_SM60 build only (sm_60/sm_70); bitwise the 4-wide gather, which is ported", - ), -]; - -// qsa_decode_attn.cu: the port carries the reference schedule of KV modes 2, 3 and 4 and the merge. The Original -// grew alternate schedules and batch variants of the same arithmetic, picked by architecture or environment, none -// of which the six closed programs expose as an entry. The Original proves the alternates bitwise equal to the -// reference schedule (its `qsa_merge_daily_parity` and `kv_hybrid_parity` harnesses, header comment of -// `qsa_decode_attn_chunks_only`); here the emulated reference schedule is compared with the Rust CPU reference -// (tests/emulated_kernels.rs). -const QSA_ATTN_EXCLUDED: &[Excluded] = &[ - ( - "attn_chunk_kernel", - "thin __global__ wrapper over attn_chunk_body; the extern \"C\" entries of the port are the equivalent \ - wrappers", - ), - ( - "attn_chunk_slots_kernel", - "same body over a per-query pool set (QsaAttnSlotPools kernel argument): engine batch slots, not an \ - experimental entry", - ), - ( - "attn_chunk_rows_kernel", - "same body over per-query pool rows (QsaAttnPoolsRows kernel argument): engine batch windows, not an \ - experimental entry", - ), - ( - "attn_chunk_q8_v3_kernel", - "INT8 (KV_MODE 1) Turing schedule; the port instantiates modes 2, 3 and 4 only", - ), - ( - "attn_chunk_kernel_pre75", - "alternate schedule of attn_chunk_body (NC cells per step, reduce12); bitwise the reference schedule per the \ - Original's parity harness; the Original selects it for pre-sm_75 cards and, by default, compute capability \ - 12.0 (STRATA_ATTN_DAILY)", - ), - ("shfl_x", "helper of attn_chunk_kernel_pre75 only"), - ("warp_sum_x", "helper of attn_chunk_kernel_pre75 only"), - ("warp_max_x", "helper of attn_chunk_kernel_pre75 only"), - ( - "reduce12", - "helper of attn_chunk_kernel_pre75 only (reduce12_gfx906 is the ported twin used by attn_chunk_body)", - ), - ( - "head_of_lane", - "helper of attn_chunk_kernel_pre75 only (reduce12_head_of_lane is the ported twin)", - ), - ("load_v1", "helper of attn_chunk_kernel_pre75 only"), - ("merge_max_block", "helper of attn_merge_v2_kernel only"), - ("merge_sum_block", "helper of attn_merge_v2_kernel only"), - ( - "attn_merge_v2_kernel", - "alternate merge (width-bounded, batched loads); bitwise attn_merge_kernel per the Original's parity harness; \ - follows STRATA_ATTN_DAILY", - ), -]; - -pair!( - kv_q4_bodies_are_literal, - "kv_q4", - "kv_q4.cu", - "experimental_kv_q4.cu", - &[] -); -pair!( - kv_q8_bodies_are_literal, - "kv_q8", - "kv_q8.cu", - "experimental_kv_q8.cu", - KV_Q8_EXCLUDED -); -pair!( - kv_stream_bodies_are_literal, - "kv_stream", - "kv_stream.cu", - "experimental_kv_stream.cu", - &[] -); -pair!( - keyless_bodies_are_literal, - "keyless", - "keyless.cu", - "experimental_keyless.cu", - &[] -); -pair!( - qsa_attn_bodies_are_literal, - "qsa_attn", - "qsa_decode_attn.cu", - "experimental_qsa_attn.cu", - QSA_ATTN_EXCLUDED -); -pair!( - cvec_bodies_are_literal, - "cvec", - "cvec.cu", - "experimental_cvec.cu", - &[] -); - -/// A synthetic Original: one kernel and one helper device function. -fn synthetic_original() -> &'static str { - concat!( - "__global__ void k(int a) {\n int x = a + 1;\n int y = x * 2;\n int u = y + x;\n", - " int v = u + y;\n int z = y - 3;\n int w = z;\n return;\n}\n", - "__device__ __forceinline__ float helper(float v) {\n", - " float s = v * 3.0f + 1.0f;\n return s * s;\n}\n" - ) -} - -fn check_panics(original: &str, port: &str, excluded: &[Excluded]) -> bool { - std::panic::catch_unwind(|| check("synthetic", original, port, excluded)).is_err() -} - -#[test] -fn the_guard_notices_a_changed_or_unlisted_device_function() { - let original = synthetic_original(); - let port_same = original.replace("__global__ void k(int a)", "__device__ void k_body(int a)"); - check("synthetic", original, &port_same, &[]); - let changed = port_same.replace("int y = x * 2;", "int y = x * 3;"); - assert!(check_panics(original, &changed, &[])); - let without_helper = port_same.replace("float s = v * 3.0f + 1.0f;", "float s = v;"); - assert!(check_panics(original, &without_helper, &[])); - // an exclusion lets the function go, a stale one is refused - check("synthetic", original, &without_helper, &[("helper", "test")]); - assert!(check_panics(original, &port_same, &[("gone", "test")])); -} - -#[test] -fn signature_names_survive_launch_bounds_and_templates() { - assert_eq!( - signature_name( - " void __launch_bounds__(THREADS) attn_chunk_kernel_pre75(const float* q, int n)" - ), - "attn_chunk_kernel_pre75" - ); - assert_eq!( - signature_name(" __forceinline__ float warp_sum(float v)"), - "warp_sum" - ); - assert_eq!( - signature_name( - "\n__device__ __forceinline__ void attn_chunk_body(const float* __restrict__ q, QsaAttnPools p," - ), - "attn_chunk_body" - ); -} diff --git a/crates/gateway-domain/src/reasoning_budget.rs b/crates/gateway-domain/src/reasoning_budget.rs index 8dd2f094..742ceca9 100644 --- a/crates/gateway-domain/src/reasoning_budget.rs +++ b/crates/gateway-domain/src/reasoning_budget.rs @@ -1,6 +1,6 @@ //! `reasoning_budget_tokens` (#123): the most tokens a request may think before the thinking is closed for it. //! -//! Port of `Service.reasoning_budget` and of the budget part of `Service.run` in `engine/strata/serve/server.py`. +//! Port of `Service.reasoning_budget` and of the budget part of `Service.run` in `Strata 41cf05a0, serve/server.py`. //! The driver is generic over the engine and the tokenizer so the exact control flow (the clean-point rule, the //! wrap-up, the continuation prompt, the room check) is testable without a model; `tests/reasoning_budget_oracle.rs` //! replays cases produced by the unmodified Python `Service.run`. diff --git a/crates/gateway-text/src/prompt.rs b/crates/gateway-text/src/prompt.rs index de408ed0..e6750fe2 100644 --- a/crates/gateway-text/src/prompt.rs +++ b/crates/gateway-text/src/prompt.rs @@ -1,6 +1,6 @@ //! Chat prompt rendering: the model's real Jinja chat template, executed natively. //! -//! The pinned Strata template (`engine/strata/serve/chat_template.jinja`, the Qwen3.8-Flash-Next template with +//! The pinned Strata template (`third_party/strata/serve/chat_template.jinja`, the Qwen3.8-Flash-Next template with //! Unsloth's developer-role and tool fixes) is rendered with `minijinja`, configured like the Python server's //! `ChatTemplate` (`serve/frontend.py`): `trim_blocks` and `lstrip_blocks`, no autoescape, Python-style string //! methods, a `raise_exception` global, and Python-compatible `tojson` and `trim` filters. All ten cases of @@ -32,7 +32,7 @@ use serde::{ use serde_json::Value as Plain; /// The pinned chat template, embedded at build time. -pub const PINNED_TEMPLATE: &str = include_str!("../../../engine/strata/serve/chat_template.jinja"); +pub const PINNED_TEMPLATE: &str = include_str!("../../../third_party/strata/serve/chat_template.jinja"); // --------------------------------------------------------------------------------------------------------------- // ordered JSON diff --git a/crates/gateway-text/src/prompt/tests.rs b/crates/gateway-text/src/prompt/tests.rs index 14cc439c..d69326ab 100644 --- a/crates/gateway-text/src/prompt/tests.rs +++ b/crates/gateway-text/src/prompt/tests.rs @@ -21,7 +21,7 @@ struct Case { } fn golden() -> Vec { - serde_json::from_str(include_str!("../../../../engine/strata/serve/chat_golden.json")).unwrap() + serde_json::from_str(include_str!("../../../../third_party/strata/serve/chat_golden.json")).unwrap() } /// All ten cases of `serve/chat_golden.json`, straight through the Jinja template: system merging, tool diff --git a/crates/model-format/README.md b/crates/model-format/README.md index 2cbd2b4a..5bc471e1 100644 --- a/crates/model-format/README.md +++ b/crates/model-format/README.md @@ -9,7 +9,7 @@ their public paths. The original parser geometry and its three tests were moved unchanged from `control-plane/src/gguf.rs`. Tensor block geometry and the legacy Flash-Next metadata guard retain their -upstream references; see the provenance record (`engine/upstream.md`). +upstream references; see the provenance record (`third_party/strata/UPSTREAM.md`). Those helpers inspect metadata and byte layout, not tensor values or inference. Recognizing a quantization block size is not support for decoding or serving it. diff --git a/crates/model-format/src/gguf/read_index_file.rs b/crates/model-format/src/gguf/read_index_file.rs index 003eaf1a..d6953f9f 100644 --- a/crates/model-format/src/gguf/read_index_file.rs +++ b/crates/model-format/src/gguf/read_index_file.rs @@ -15,9 +15,9 @@ pub(super) fn read_index_file(file: &mut File, size: u64, strict: bool) -> Resul /// (values per block, bytes per block) of each tensor kind. /// -/// Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the -/// upstream commit recorded in engine/upstream.md, plus the kinds -/// engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, +/// Mirrors Strata 41cf05a0, include/strata/artifact/gguf_reader.hpp at the +/// upstream commit recorded in third_party/strata/UPSTREAM.md, plus the kinds +/// Strata 41cf05a0, tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, /// IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a /// consumer that cannot decode a kind still refuses it at use. Differential: /// control-plane/tests/gguf_header_differential.rs. diff --git a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs index 67efa558..9f237c49 100644 --- a/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs +++ b/crates/native-cpu-expert/examples/kernel_ab/cmd_alternate.rs @@ -80,7 +80,7 @@ fn alt_paths(a: &AltArgs) -> Result { let kab = kab_path(a); if !kab.is_file() { return Err(format!( - "the C++ driver {} does not exist (build tools/kernel-ab/cpp, or pass --kab / set KAB)", + "the C++ driver {} does not exist (retired with the vendored Strata tree; pass --kab or set KAB)", kab.display() )); } diff --git a/crates/offline-tools/src/lib.rs b/crates/offline-tools/src/lib.rs index 8b919b43..8dd99d05 100644 --- a/crates/offline-tools/src/lib.rs +++ b/crates/offline-tools/src/lib.rs @@ -1,4 +1,4 @@ -//! Offline tooling ported from `engine/strata/tools/*.py`, byte for byte, with no Python at run time. +//! Offline tooling ported from `Strata 41cf05a0, tools/*.py`, byte for byte, with no Python at run time. //! //! | Rust module | Python oracle | what it writes | //! |--------------------|------------------------------|-------------------------------------------------------| diff --git a/crates/offline-tools/tests/oracle.rs b/crates/offline-tools/tests/oracle.rs index 6d9448d6..142da7e8 100644 --- a/crates/offline-tools/tests/oracle.rs +++ b/crates/offline-tools/tests/oracle.rs @@ -1,7 +1,7 @@ //! The ported tools against the Python originals' exact outputs. //! //! `tests/fixtures/tools_oracle.json` is written by `scripts/offline/gen_goldens.py tools_oracle`, which runs the -//! unmodified `engine/strata/tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny +//! unmodified `Strata 41cf05a0, tools/{embd_bf16_pack,ple_fp8_pack,draft_vocab,make_profile,mtp_rt}.py` on tiny //! synthetic inputs. `scripts/offline/diff_tools.py` is the live differential over more cases. use std::{ fs, diff --git a/crates/sampler-ref/oracle/build_oracle.sh b/crates/sampler-ref/oracle/build_oracle.sh deleted file mode 100755 index 3bdc415d..00000000 --- a/crates/sampler-ref/oracle/build_oracle.sh +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# Rebuild the host oracle and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA. -# crates/sampler-ref/oracle/build_oracle.sh [output_dir] -# -ffp-contract=off pins the host float evaluation to separate IEEE operations (no FMA), which is the -# contract the Rust reference documents. Compile flags are echoed into the fixture header. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../.." && pwd) -out=${1:-"$here/../tests/fixtures"} -bin=${TMPDIR:-/tmp}/leleka_sampler_oracle.$$ -${CXX:-clang++} -std=c++17 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable \ - -I "$root/engine/strata/include" -I "$here/stub" "$here/gen_fixtures.cpp" -o "$bin" -mkdir -p "$out" -"$bin" "$out/sampler_oracle.json" -rm -f "$bin" diff --git a/crates/sampler-ref/oracle/gen_fixtures.cpp b/crates/sampler-ref/oracle/gen_fixtures.cpp deleted file mode 100644 index 73c24099..00000000 --- a/crates/sampler-ref/oracle/gen_fixtures.cpp +++ /dev/null @@ -1,507 +0,0 @@ -// Golden-fixture generator for the Rust CPU sampler reference (crates/sampler-ref). -// -// WHAT THIS RUNS. The Original's own host-side logic, not a re-implementation: -// * `engine/strata/src/kernels/sampler_parity.cpp` is #included UNMODIFIED (its `main` renamed, a -// header-only stub standing in for ) so that `host_philox_uniform`, -// `sampled_reference`, `mirror_select`, `mirror_pick`, `sampled_k` are the Original's code; -// * `strata/kernels/sampler.hpp` (`penalty_rows`) and `strata/core/coupled_draft.hpp` -// (`coupled_draft_cell/counter`, `coupled_hist_len/start`, `coupled_hist_base`) are the Original's headers. -// The only code written here is the case generator, the JSON writer and `coupled_ref` below, which -// transcribes the DEVICE-ONLY coupled kernels (`coupled_penalize_kernel`, `coupled_merge_kernel`, -// `sampled_tail_warp` in sampler.cu) because the Original has no host twin for them; it is -// cross-checked against the Original's `mirror_pick` on every case. -// -// Build/run: crates/sampler-ref/oracle/build_oracle.sh (compiles with -ffp-contract=off). -#define main original_sampler_parity_main -#include "../../../engine/strata/src/kernels/sampler_parity.cpp" -#undef main - -#include "strata/core/coupled_draft.hpp" - -#include -#include -#include - -namespace { - -using strata::kernels::SamplerParams; - -// ---- deterministic case source (splitmix64; no std::random distributions, which differ per stdlib) ---- -struct Rng { - uint64_t s; - uint64_t next() { - uint64_t z = (s += 0x9E3779B97F4A7C15ull); - z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; - z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; - return z ^ (z >> 31); - } - double uni() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); } - int below(int n) { return (int) (next() % (uint64_t) n); } - double normal() { return (uni() + uni() + uni() + uni() - 2.0) * 1.7; } - template T pick(std::initializer_list v) { return *(v.begin() + below((int) v.size())); } -}; - -uint32_t bits_of(float f) { uint32_t u; std::memcpy(&u, &f, 4); return u; } -float float_of(uint32_t u) { float f; std::memcpy(&f, &u, 4); return f; } -constexpr uint32_t kNaN = 0x7fc00000u, kNegNaN = 0xffc00000u, kInf = 0x7f800000u, kNegInf = 0xff800000u; - -FILE* out = nullptr; -bool first_item = true; -void comma() { if (!first_item) std::fputs(",", out); first_item = false; } - -void put_u32s(const std::vector& v) { - std::fputc('[', out); - for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%u" : "%u", bits_of(v[i])); - std::fputc(']', out); -} -void put_ints(const std::vector& v) { - std::fputc('[', out); - for (size_t i = 0; i < v.size(); ++i) std::fprintf(out, i ? ",%d" : "%d", v[i]); - std::fputc(']', out); -} -void put_i32s(const std::vector& v) { put_ints(std::vector(v.begin(), v.end())); } -void put_params(const SamplerParams& p) { - std::fprintf(out, - "{\"top_k\":%d,\"top_p\":%u,\"min_p\":%u,\"temperature\":%u,\"min_keep\":%d,\"penalty_last_n\":%d," - "\"penalty_repeat\":%u,\"penalty_freq\":%u,\"penalty_present\":%u,\"seed\":%" PRIu64 - ",\"counter\":%" PRIu64 ",\"greedy\":%s}", - p.top_k, bits_of(p.top_p), bits_of(p.min_p), bits_of(p.temperature), p.min_keep, p.penalty_last_n, - bits_of(p.penalty_repeat), bits_of(p.penalty_freq), bits_of(p.penalty_present), p.seed, p.counter, - p.greedy ? "true" : "false"); -} - -std::vector window_of(const std::vector& hist, int penalty_last_n) { - // sampler.cu: hlen = min(penalty_last_n, history_len), clamped at 0; the window is the TAIL of the row - int hlen = std::min(penalty_last_n, (int) hist.size()); - if (hlen < 0) hlen = 0; - return std::vector(hist.end() - hlen, hist.end()); -} - -bool all_finite(const std::vector& l) { - for (float x : l) if (!std::isfinite(x)) return false; - return true; -} - -int mismatches = 0; -int n_cases = 0; - -// One chain case: either a dense logit vector or a sparse full-vocabulary description. -struct SparseLogits { - int n = 0; - float fill = 0; - std::vector> set; -}; - -void emit_chain_case(const char* name, const std::vector& logits, const SparseLogits* sparse, - const SamplerParams& p, int row, const std::vector& hist) { - const int nv = (int) logits.size(); - const std::vector window = window_of(hist, p.penalty_last_n); - const int k = sampled_k(p.top_k, nv); - const bool greedy = p.greedy || p.temperature <= 0.0f; - // the Original's own semantics for the row: greedy = the first entry of the k=1 selection - const SelList sel1 = mirror_select(logits.data(), nv, window, p, 1); - const SelList sel = greedy ? sel1 : mirror_select(logits.data(), nv, window, p, k); - const int token = greedy ? sel1.ids[0] : mirror_pick(sel, k, p, row); - // cross-check the two Original references on rows where they must agree (finite, sampled) - if (!greedy && all_finite(logits)) { - const int ref = sampled_reference(logits, window, p, row); - if (ref != token) { - ++mismatches; - std::fprintf(stderr, "reference disagreement in %s: mirror %d vs sampled_reference %d\n", name, token, ref); - } - } - comma(); - std::fprintf(out, "\n{\"name\":\"%s\",\"n_vocab\":%d,\"row\":%d,\"params\":", name, nv, row); - put_params(p); - if (sparse) { - std::fprintf(out, ",\"sparse\":{\"fill\":%u,\"set\":[", bits_of(sparse->fill)); - for (size_t i = 0; i < sparse->set.size(); ++i) - std::fprintf(out, i ? ",[%d,%u]" : "[%d,%u]", sparse->set[i].first, bits_of(sparse->set[i].second)); - std::fputs("]}", out); - } else { - std::fputs(",\"logits\":", out); - put_u32s(logits); - } - std::fputs(",\"history\":", out); - put_ints(hist); - std::fprintf(out, ",\"expect\":{\"token\":%d,\"sel_ids\":", token); - put_ints(sel.ids); - std::fputs(",\"sel_logits\":", out); - put_u32s(sel.logit); - if (!greedy) std::fprintf(out, ",\"u\":%u", bits_of(host_philox_uniform(p.seed, p.counter + (uint64_t) row))); - std::fputs("}}", out); - ++n_cases; -} - -std::vector make_logits(Rng& g, int nv, int mode) { - std::vector l((size_t) nv); - for (int v = 0; v < nv; ++v) { - double x = g.normal(); - switch (mode) { - case 0: l[(size_t) v] = (float) x; break; // plain - case 1: l[(size_t) v] = (float) (std::round(x * 2.0) / 2.0); break; // many exact ties - case 2: l[(size_t) v] = 1.25f; break; // all equal - case 3: { // non-finite mix - const int r = g.below(12); - l[(size_t) v] = r == 0 ? float_of(kNegInf) : r == 1 ? float_of(kNaN) : r == 2 ? float_of(kInf) - : r == 3 ? float_of(kNegNaN) : (float) x; - break; - } - case 4: l[(size_t) v] = (float) (x * 1e30); break; // huge magnitudes - case 5: l[(size_t) v] = (float) (x * 1e-40); break; // denormals - default: l[(size_t) v] = float_of(kNegInf); break; // all -inf - } - } - return l; -} - -SamplerParams make_params(Rng& g, bool allow_greedy) { - SamplerParams p; - p.top_k = g.pick({0, 1, 2, 5, 20, 20, 40, 63, 64, 65, 200, -3}); - p.top_p = g.pick({1.0f, 1.0f, 0.95f, 0.9f, 0.5f, 0.2f, 0.0f}); - p.min_p = g.pick({0.0f, 0.0f, 0.01f, 0.1f, 0.5f, 1.0f}); - p.temperature = g.pick({0.3f, 0.7f, 1.0f, 1.0f, 1.5f, 2.0f}); - if (allow_greedy && g.below(6) == 0) p.temperature = g.pick({0.0f, -1.0f}); - p.greedy = allow_greedy && g.below(12) == 0; - p.min_keep = g.pick({1, 1, 1, 2, 3}); - p.penalty_last_n = g.pick({0, 0, 4, 16, 64, 5000, -2}); - p.penalty_repeat = g.pick({1.0f, 1.1f, 1.5f, 2.0f, 0.8f}); - p.penalty_freq = g.pick({0.0f, 0.25f, 0.5f}); - p.penalty_present = g.pick({0.0f, 0.5f, 1.5f}); - p.seed = g.pick({0ull, 1ull, 42ull, 123456789ull, 0xFFFFFFFFull, 0x1FFFFFFFFull, 0xDEADBEEFCAFEF00Dull, - ~0ull}); - p.counter = g.pick({0ull, 1ull, 7ull, 1000ull, (1ull << 32) + 7ull, 0xFFFFFFFFull, ~0ull - 3ull}); - return p; -} - -std::vector make_history(Rng& g, int nv, int pln) { - int hl = g.pick({0, 8, 32, 80}); - if (pln > 0 && hl == 0) hl = 8; - std::vector h((size_t) hl); - for (auto& t : h) { - const int r = g.below(10); - t = r < 2 ? -1 : r == 2 ? nv + g.below(3) : g.below(std::min(nv + 1, 12)); - } - return h; -} - -// ---- the coupled draft, serial (TRANSCRIPTION of the device-only kernels; see the file header) ---- -struct CoupledResult { int id; float prob; int sub; }; - -CoupledResult coupled_ref(std::vector l, const std::vector& sub_to_id, const std::vector& id_to_sub, - int id_vocab, const SamplerParams& params, std::vector& ring, int cap, int j, - int step0, int& tail_pick_check) { - const int nv = (int) l.size(); - // coupled_penalize_kernel - const int h = strata::core::coupled_hist_len(params.penalty_last_n, cap); - if (h > 0) { - const int* hrow = ring.data() + strata::core::coupled_hist_start(cap, j, h); - std::vector seen((size_t) nv, 0); - for (int i = 0; i < h; ++i) { - const int v = hrow[i]; - if (v < 0 || v >= id_vocab) continue; - const int s = id_to_sub.empty() ? v : id_to_sub[(size_t) v]; - if (s < 0 || s >= nv) continue; - if (seen[(size_t) s]) continue; - seen[(size_t) s] = 1; - int c = 0; - for (int q = 0; q < h; ++q) c += hrow[q] == v; - float x = l[(size_t) s]; - if (c > 0) { - if (x <= 0.0f) x *= params.penalty_repeat; else x /= params.penalty_repeat; - x -= (float) c * params.penalty_freq + (c > 0 ? 1.0f : 0.0f) * params.penalty_present; - } - l[(size_t) s] = x; - } - } - // coupled_merge_kernel - SamplerParams p = params; - p.counter = strata::core::coupled_draft_counter((int64_t) step0); - const int k = sampled_k(p.top_k, nv); - SamplerParams none; // the split-part launch passes SamplerParams{} (no penalties) - const SelList sel = mirror_select(l.data(), nv, std::vector(), none, k); - int pick_idx = 0; - float prob = 1.0f; - if (p.greedy || p.temperature <= 0.0f) { - pick_idx = 0; - tail_pick_check = sel.ids[0]; - } else { - // sampled_tail_warp: top_p, min_p, temperature, draw, and the pick's probability - int n_keep = k; - float mx = sel.logit[0]; - for (int i = 1; i < k; ++i) mx = std::fmax(mx, sel.logit[(size_t) i]); - if (p.top_p < 1.0f) { - double sum = 0.0; - for (int i = 0; i < k; ++i) sum += std::exp((double) sel.logit[(size_t) i] - (double) mx); - double cum = 0.0; - int cut = k; - for (int i = 0; i < k; ++i) { - cum += std::exp((double) sel.logit[(size_t) i] - (double) mx) / sum; - if (cum >= (double) p.top_p) { cut = i + 1; break; } - } - if (cut < p.min_keep) cut = p.min_keep < k ? p.min_keep : k; - n_keep = cut; - } - if (p.min_p > 0.0f) { - const float thresh = sel.logit[0] + std::log(p.min_p); - for (int i = 0; i < n_keep; ++i) - if (sel.logit[(size_t) i] < thresh) { n_keep = i; break; } - } - const float inv_t = p.temperature > 0.0f ? 1.0f / p.temperature : 0.0f; - float smx = sel.logit[0] * inv_t; - for (int i = 1; i < n_keep; ++i) smx = std::fmax(smx, sel.logit[(size_t) i] * inv_t); - std::vector ex((size_t) std::max(n_keep, 1)); - for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = std::exp((double) (sel.logit[(size_t) i] * inv_t) - (double) smx); - double sum = 0.0; - for (int i = 0; i < n_keep; ++i) sum += ex[(size_t) i]; - for (int i = 0; i < n_keep; ++i) ex[(size_t) i] = ex[(size_t) i] / sum; - const float u = host_philox_uniform(p.seed, p.counter + 0u); - double cum = 0.0; - pick_idx = n_keep > 0 ? n_keep - 1 : 0; - for (int i = 0; i < n_keep; ++i) { - cum += ex[(size_t) i]; - if ((double) u < cum) { pick_idx = i; break; } - } - prob = n_keep > 0 ? (float) ex[(size_t) pick_idx] : 1.0f; - tail_pick_check = mirror_pick(sel, k, p, 0); // the Original's own tail must agree - } - const int s = sel.ids[(size_t) pick_idx]; - const int id = sub_to_id.empty() ? s : sub_to_id[(size_t) s]; - ring[(size_t) (cap + j)] = id; - return {id, prob, s}; -} - -} // namespace - -int main(int argc, char** argv) { - if (argc < 2) { std::fprintf(stderr, "usage: %s out.json\n", argv[0]); return 2; } - out = std::fopen(argv[1], "w"); - if (!out) { std::perror("open"); return 2; } - Rng g{0x5A17E7E5ull}; - - std::fputs("{\n\"meta\":{\"generator\":\"crates/sampler-ref/oracle/gen_fixtures.cpp\"," - "\"oracle\":\"Original engine/strata sampler_parity.cpp host reference, included unmodified; " - "sampler.hpp + coupled_draft.hpp headers\"," - "\"compile\":\"-std=c++17 -O1 -ffp-contract=off -fno-fast-math\"," - "\"encoding\":\"floats are IEEE-754 binary32 bit patterns (u32)\"},\n", out); - - // ---------------- philox ---------------- - std::fputs("\"philox\":[", out); - first_item = true; - { - std::vector> pts = { - {0, 0}, {0, 1}, {1, 0}, {1, 1}, {42, 7}, {123, (1ull << 32) + 7}, {0xFFFFFFFFull, 0xFFFFFFFFull}, - {0x100000000ull, 0}, {0, 0x100000000ull}, {~0ull, ~0ull}, {0xDEADBEEFCAFEF00Dull, 12345678901234ull}}; - for (int i = 0; i < 80; ++i) pts.push_back({g.next(), g.next() >> (g.below(40))}); - for (auto& pr : pts) { - comma(); - std::fprintf(out, "\n[%" PRIu64 ",%" PRIu64 ",%u]", pr.first, pr.second, - bits_of(host_philox_uniform(pr.first, pr.second))); - } - } - std::fputs("\n],\n", out); - - // ---------------- chain ---------------- - std::fputs("\"chain\":[", out); - first_item = true; - { - int idx = 0; - char name[64]; - // random dense rows over several vocabularies and logit shapes - for (int nv : {1, 2, 5, 16, 33, 64, 65, 100, 257}) - for (int rep = 0; rep < (nv > 100 ? 2 : 14); ++rep) { - const int mode = rep % 7 == 6 ? 1 : (rep % 11 == 10 ? 2 : 0); - SamplerParams p = make_params(g, true); - const auto l = make_logits(g, nv, mode); - const auto h = make_history(g, nv, p.penalty_last_n); - std::snprintf(name, sizeof name, "rand-%d-%d", nv, rep); - emit_chain_case(name, l, nullptr, p, g.below(4), h); - ++idx; - } - // edge shapes: non-finite mix, huge, denormal, all -inf, ties, k larger than the finite count - for (int mode : {3, 3, 3, 3, 4, 4, 5, 5, 6, 1, 1, 2}) - for (int nv : {3, 12, 70}) { - SamplerParams p = make_params(g, true); - const auto l = make_logits(g, nv, mode); - const auto h = make_history(g, nv, p.penalty_last_n); - std::snprintf(name, sizeof name, "edge-m%d-%d-%d", mode, nv, idx++); - emit_chain_case(name, l, nullptr, p, g.below(3), h); - } - // penalties that matter: a clear head token repeatedly in the window - for (int rep = 0; rep < 16; ++rep) { - SamplerParams p = make_params(g, false); - p.penalty_last_n = 16; - p.penalty_repeat = g.pick({1.5f, 2.0f, 3.0f}); - p.penalty_freq = g.pick({0.0f, 0.5f, 0.25f}); - p.penalty_present = g.pick({0.0f, 1.0f, 0.5f}); - p.top_k = 8; - p.top_p = g.pick({1.0f, 0.9f}); - auto l = make_logits(g, 24, 0); - l[3] = 6.0f; l[9] = 5.5f; l[17] = -2.0f; - std::vector h = {-1, -1, 3, 3, 3, 9, 17, 17, 40, -1, 3, 9, 17, 5, 5, 3}; - std::snprintf(name, sizeof name, "penal-%d", rep); - emit_chain_case(name, l, nullptr, p, rep % 3, h); - } - // top_p lands EXACTLY on a cumulative boundary (equal logits: cum = 1/n, 2/n, ...), so `cum >= top_p` vs `>` is - // observable; 16 seeds per case so the draw reaches the entry that only the wrong comparison would keep - for (int n : {4, 8}) - for (int step = 1; step < n; ++step) - for (int sd = 0; sd < 6; ++sd) { - SamplerParams p; - p.top_k = n; p.top_p = (float) step / (float) n; p.temperature = 1.0f; p.min_p = 0.0f; - p.seed = 1000 + (uint64_t) sd * 7919; p.counter = (uint64_t) sd; - std::vector l((size_t) n + 2, 3.0f); - l[(size_t) n] = -20.0f; l[(size_t) n + 1] = -20.0f; - std::snprintf(name, sizeof name, "tp-boundary-%d-%d-%d", n, step, sd); - emit_chain_case(name, l, nullptr, p, 0, std::vector()); - } - // full-vocabulary sparse rows (the closed GPU op's geometry: 248,320 logits, up to 4,096 history slots) - for (int rep = 0; rep < 36; ++rep) { - SparseLogits sp; - sp.n = 248320; - sp.fill = g.pick({-5.0f, -9.5f, 0.0f}); - std::vector l((size_t) sp.n, sp.fill); - const int n_set = 6 + g.below(120); - for (int i = 0; i < n_set; ++i) { - const int at = g.below(sp.n); - const float val = (float) (g.normal() * 3.0 + 2.0); - sp.set.push_back({at, val}); - l[(size_t) at] = val; - } - if (rep % 4 == 1) - for (int i = 0; i < 8; ++i) { sp.set.push_back({1000 + 7 * i, 4.5f}); l[(size_t) (1000 + 7 * i)] = 4.5f; } // ties - if (rep % 13 == 12) { sp.set.push_back({5, float_of(kNegInf)}); l[5] = float_of(kNegInf); } - if (rep % 17 == 16) { sp.set.push_back({248319, float_of(kNaN)}); l[248319] = float_of(kNaN); } // last index: NaN is never picked - SamplerParams p = make_params(g, rep % 5 == 4); - if (rep % 3 == 0) { p.penalty_last_n = 64; } - std::vector h(rep == 2 ? 4096 : 64, -1); - for (size_t i = h.size() > 40 ? h.size() - 40 : 0; i < h.size(); ++i) - h[i] = sp.set.empty() ? 0 : sp.set[(size_t) g.below((int) sp.set.size())].first; - if (rep == 2) p.penalty_last_n = 4096; - if (p.penalty_last_n > 0 && h.empty()) h.assign(8, -1); - std::snprintf(name, sizeof name, "full-%d", rep); - emit_chain_case(name, l, &sp, p, 0, h); - } - } - std::fputs("\n],\n", out); - - // ---------------- ABI of strata::kernels::SamplerParams (the 64-byte blob every Original kernel takes by value) ---------------- - std::fprintf(out, "\"abi\":{\"size\":%zu,\"align\":%zu,\"offsets\":{", sizeof(SamplerParams), alignof(SamplerParams)); - std::fprintf(out, "\"top_k\":%zu,\"top_p\":%zu,\"min_p\":%zu,\"temperature\":%zu,\"min_keep\":%zu,\"penalty_last_n\":%zu," - "\"penalty_repeat\":%zu,\"penalty_freq\":%zu,\"penalty_present\":%zu,\"seed\":%zu,\"counter\":%zu,\"greedy\":%zu},\"samples\":[", - offsetof(SamplerParams, top_k), offsetof(SamplerParams, top_p), offsetof(SamplerParams, min_p), - offsetof(SamplerParams, temperature), offsetof(SamplerParams, min_keep), offsetof(SamplerParams, penalty_last_n), - offsetof(SamplerParams, penalty_repeat), offsetof(SamplerParams, penalty_freq), offsetof(SamplerParams, penalty_present), - offsetof(SamplerParams, seed), offsetof(SamplerParams, counter), offsetof(SamplerParams, greedy)); - first_item = true; - for (int rep = 0; rep < 12; ++rep) { - SamplerParams p = rep == 0 ? SamplerParams() : make_params(g, true); - alignas(SamplerParams) unsigned char raw[sizeof(SamplerParams)]; - std::memset(raw, 0, sizeof raw); - SamplerParams* q = new (raw) SamplerParams(); // default member initialisers, padding left as the memset made it - q->top_k = p.top_k; q->top_p = p.top_p; q->min_p = p.min_p; q->temperature = p.temperature; q->min_keep = p.min_keep; - q->penalty_last_n = p.penalty_last_n; q->penalty_repeat = p.penalty_repeat; q->penalty_freq = p.penalty_freq; - q->penalty_present = p.penalty_present; q->seed = p.seed; q->counter = p.counter; q->greedy = p.greedy; - comma(); - std::fputs("\n{\"params\":", out); put_params(p); - std::fputs(",\"bytes\":[", out); - for (size_t i = 0; i < sizeof raw; ++i) std::fprintf(out, i ? ",%u" : "%u", (unsigned) raw[i]); - std::fputs("]}", out); - } - std::fputs("\n]},\n", out); - - // ---------------- counters (coupled_draft.hpp, verbatim header functions) ---------------- - std::fputs("\"counters\":{\"cells\":[", out); - first_item = true; - for (int64_t p : {0ll, 1ll, 100ll, 4095ll, 1000000ll, (long long) 1 << 40}) - for (int a : {0, 1, 7}) - for (int j : {0, 1, 6}) { - comma(); - const int64_t cell = strata::core::coupled_draft_cell(p, a, j); - std::fprintf(out, "\n[%" PRId64 ",%d,%d,%" PRId64 ",%" PRIu64 "]", p, a, j, cell, - strata::core::coupled_draft_counter(cell)); - } - std::fputs("\n],\"hist_len\":[", out); - first_item = true; - for (int cap : {8, 64, strata::core::kCoupledHistCap}) - for (int pln : {-1, 0, 1, 7, 8, 9, 64, 4095, 4096, 4097, 100000}) { - comma(); - std::fprintf(out, "\n[%d,%d,%d]", pln, cap, strata::core::coupled_hist_len(pln, cap)); - } - std::fputs("\n],\"hist_start\":[", out); - first_item = true; - for (int cap : {8, 64, strata::core::kCoupledHistCap}) - for (int h : {1, 3, 8}) - for (int j : {0, 1, 6}) { - comma(); - std::fprintf(out, "\n[%d,%d,%d,%d]", cap, j, h, strata::core::coupled_hist_start(cap, j, h)); - } - std::fputs("\n]},\n", out); - - // ---------------- penalty_rows + coupled_hist_base (sampler.hpp / coupled_draft.hpp, verbatim) ---------------- - std::fputs("\"penalty_rows\":[", out); - first_item = true; - for (int rep = 0; rep < 60; ++rep) { - const int n_tail = g.pick({0, 1, 2, 5, 7, 20}); - const int T = 1 + g.below(8); - const int h = g.pick({1, 3, 8, 16}); - std::vector tail((size_t) n_tail), window((size_t) T), rows((size_t) T * (size_t) h); - for (auto& t : tail) t = g.below(1000); - for (auto& t : window) t = g.below(1000); - strata::kernels::penalty_rows(tail.data(), n_tail, window.data(), T, h, rows.data()); - comma(); - std::fputs("\n{\"tail\":", out); put_i32s(tail); - std::fputs(",\"window\":", out); put_i32s(window); - std::fprintf(out, ",\"h\":%d,\"rows\":", h); put_i32s(rows); - const int32_t next = g.below(1000); - std::vector base((size_t) h, 777777); - strata::core::coupled_hist_base(tail.data(), n_tail, next, h, base.data()); - std::fprintf(out, ",\"next\":%d,\"base\":", next); put_i32s(base); - std::fputs("}", out); - } - std::fputs("\n],\n", out); - - // ---------------- coupled draft sampling (transcribed kernels, cross-checked against mirror_pick) ---------------- - std::fputs("\"coupled\":[", out); - first_item = true; - for (int rep = 0; rep < 60; ++rep) { - const int nv = g.pick({7, 24, 70, 130}); - const bool subset = rep % 3 == 1; - const int id_vocab = subset ? nv * 3 : nv; - std::vector sub_to_id, id_to_sub; - if (subset) { - id_to_sub.assign((size_t) id_vocab, -1); - for (int s = 0; s < nv; ++s) { // subset s -> token id 3 s + 1 (an injective map) - sub_to_id.push_back(3 * s + 1); - id_to_sub[(size_t) (3 * s + 1)] = s; - } - } - SamplerParams p = make_params(g, false); - p.penalty_last_n = g.pick({0, 3, 8, 12, 20}); - auto l = make_logits(g, nv, rep % 9 == 8 ? 1 : 0); - const int cap = g.pick({16, 32}); - const int j = g.below(4); - std::vector ring((size_t) cap + 8, -1); - for (int i = 0; i < cap + j; ++i) - ring[(size_t) i] = g.below(5) == 0 ? -1 : (subset ? 3 * g.below(std::min(nv, 6)) + 1 : g.below(std::min(nv, 6))); - if (rep % 7 == 3) for (int i = 0; i < cap + j; ++i) if (g.below(4) == 0) ring[(size_t) i] = id_vocab + 1; // out of vocab - const int step0 = g.below(100000); - const std::vector ring_in = ring; - int check = -1; - const CoupledResult r = coupled_ref(l, sub_to_id, id_to_sub, id_vocab, p, ring, cap, j, step0, check); - if (check != r.sub) { ++mismatches; std::fprintf(stderr, "coupled tail disagreement in case %d\n", rep); } - comma(); - std::fprintf(out, "\n{\"cap\":%d,\"j\":%d,\"step0\":%d,\"id_vocab\":%d,\"logits\":", cap, j, step0, id_vocab); - put_u32s(l); - std::fputs(",\"params\":", out); put_params(p); - std::fputs(",\"sub_to_id\":", out); put_ints(sub_to_id); - std::fputs(",\"id_to_sub\":", out); put_ints(id_to_sub); - std::fputs(",\"ring\":", out); put_ints(ring_in); - std::fprintf(out, ",\"expect\":{\"id\":%d,\"sub\":%d,\"prob\":%u}}", r.id, r.sub, bits_of(r.prob)); - ++n_cases; - } - std::fputs("\n]\n}\n", out); - std::fclose(out); - std::fprintf(stderr, "wrote %d cases, %d oracle disagreements\n", n_cases, mismatches); - return mismatches == 0 ? 0 : 3; -} diff --git a/crates/sampler-ref/oracle/gen_sampling_keys.py b/crates/sampler-ref/oracle/gen_sampling_keys.py deleted file mode 100644 index 85a4a95c..00000000 --- a/crates/sampler-ref/oracle/gen_sampling_keys.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Offline fixture generator (Python is allowed for experiments/fixtures, never for serving). - -Runs the Original's `StrataEngine.sampling_keys` (engine/strata/serve/server.py) over a table of requests and -records the exact GEN key string it emits, plus the ranges `clean_shared_defaults` / -`sampling_defaults_from_config` enforce. Usage: - - python3 -I crates/sampler-ref/oracle/gen_sampling_keys.py crates/sampler-ref/tests/fixtures/sampling_keys.json - -The two pure functions are lifted verbatim from the Original's AST; nothing else of server.py is imported. -""" -import ast -import json -import os -import sys - -here = os.path.dirname(os.path.abspath(__file__)) -server_py = os.path.normpath(os.path.join(here, "..", "..", "..", "engine", "strata", "serve", "server.py")) - -# server.py imports the whole serving stack (jinja2, sockets, ...). The two functions under test are pure, so lift -# their source verbatim out of the AST instead of importing the module. -tree = ast.parse(open(server_py).read(), server_py) -engine = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "StrataEngine") -wanted = [n for n in engine.body if isinstance(n, ast.FunctionDef) and n.name in ("sampling_keys", "projection_key")] -assert {n.name for n in wanted} == {"sampling_keys", "projection_key"} -lifted = ast.Module(body=[ast.ClassDef(name="StrataEngine", bases=[], keywords=[], body=wanted, decorator_list=[])], - type_ignores=[]) -ast.fix_missing_locations(lifted) -ns = {} -exec(compile(lifted, server_py, "exec"), ns) - - -class server: # noqa: N801 - keeps the call below readable - StrataEngine = ns["StrataEngine"] - - -keys = server.StrataEngine.sampling_keys - -cases = [ - {}, - {"temperature": 0.0}, - {"temperature": 0.7}, - {"temperature": 1}, - {"temperature": 2.0}, - {"temperature": 0.1 + 0.2}, - {"temperature": 1e-7}, - {"temperature": 0.7, "top_p": 0.95}, - {"temperature": 0.7, "top_p": 1.0}, - {"top_p": 0.0}, - {"top_p": 0.5}, - {"top_k": 0}, {"top_k": 1}, {"top_k": 20}, {"top_k": 64}, {"top_k": 65}, {"top_k": 100000}, - {"min_p": 0.0}, {"min_p": 0.05}, {"min_p": 1.0}, {"min_p": 1e-5}, - {"repetition_penalty": 1.0}, - {"repetition_penalty": 1.1}, - {"repetition_penalty": 1.1, "penalty_last_n": 256}, - {"repetition_penalty": 1.1, "penalty_last_n": 0}, - {"repetition_penalty": 1.1, "penalty_last_n": 5000}, - {"frequency_penalty": 0.5}, - {"frequency_penalty": -0.5}, - {"presence_penalty": 0.25}, - {"presence_penalty": 1.5, "frequency_penalty": 0.5, "repetition_penalty": 1.05}, - {"presence_penalty": 0.0, "frequency_penalty": 0.0, "repetition_penalty": 1.0, "penalty_last_n": 33}, - {"penalty_last_n": 33}, - {"seed": 1}, {"seed": 42}, {"seed": 18446744073709551615}, - {"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.02, "repetition_penalty": 1.1, - "presence_penalty": 0.5, "frequency_penalty": 0.25, "penalty_last_n": 128, "seed": 7}, - {"temperature": 1e16}, {"temperature": 1.5e-5}, -] -# the request-boundary rule (Rust) is stricter than the Original's silent skipping: those are tested in Rust only -out = { - "meta": {"generator": "crates/sampler-ref/oracle/gen_sampling_keys.py", - "oracle": "engine/strata/serve/server.py StrataEngine.sampling_keys"}, - "cases": [{"request": c, "keys": keys(dict(c))} for c in cases], -} -with open(sys.argv[1], "w") as f: - f.write('{"meta":' + json.dumps(out["meta"]) + ',\n"cases":[\n') - f.write(",\n".join(json.dumps(c) for c in out["cases"])) - f.write("\n]}\n") -print(f"wrote {len(cases)} cases") diff --git a/crates/sampler-ref/oracle/stub/cuda_runtime.h b/crates/sampler-ref/oracle/stub/cuda_runtime.h deleted file mode 100644 index 4a75f151..00000000 --- a/crates/sampler-ref/oracle/stub/cuda_runtime.h +++ /dev/null @@ -1,38 +0,0 @@ -// Host-only stand-in for so the Original's sampler_parity.cpp host reference -// (host_philox_uniform, sampled_reference, mirror_select, mirror_pick) can be compiled UNMODIFIED -// on a machine without CUDA. Nothing here is ever called by the fixture generator; every entry -// point aborts. The declarations only have to be enough for the file to parse. -#pragma once -#include -#include -#include - -typedef int cudaError_t; -typedef void* cudaStream_t; -typedef void* cudaEvent_t; -typedef void* cudaGraph_t; -typedef void* cudaGraphExec_t; -enum { cudaSuccess = 0 }; -enum cudaMemcpyKind { cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2 }; -enum cudaStreamCaptureMode { cudaStreamCaptureModeThreadLocal = 1 }; - -[[noreturn]] inline void oracle_stub_abort() { std::fprintf(stderr, "cuda stub called\n"); std::abort(); } -inline const char* cudaGetErrorString(cudaError_t) { oracle_stub_abort(); } -template inline cudaError_t cudaMalloc(T**, size_t) { oracle_stub_abort(); } -inline cudaError_t cudaFree(void*) { oracle_stub_abort(); } -inline cudaError_t cudaMemcpy(void*, const void*, size_t, cudaMemcpyKind) { oracle_stub_abort(); } -inline cudaError_t cudaMemset(void*, int, size_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamCreate(cudaStream_t*) { oracle_stub_abort(); } -inline cudaError_t cudaStreamDestroy(cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamSynchronize(cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaStreamBeginCapture(cudaStream_t, cudaStreamCaptureMode) { oracle_stub_abort(); } -inline cudaError_t cudaStreamEndCapture(cudaStream_t, cudaGraph_t*) { oracle_stub_abort(); } -inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t*, cudaGraph_t, unsigned long long) { oracle_stub_abort(); } -inline cudaError_t cudaGraphLaunch(cudaGraphExec_t, cudaStream_t) { oracle_stub_abort(); } -inline cudaError_t cudaGraphDestroy(cudaGraph_t) { oracle_stub_abort(); } -inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventCreate(cudaEvent_t*) { oracle_stub_abort(); } -inline cudaError_t cudaEventDestroy(cudaEvent_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventRecord(cudaEvent_t, cudaStream_t = nullptr) { oracle_stub_abort(); } -inline cudaError_t cudaEventSynchronize(cudaEvent_t) { oracle_stub_abort(); } -inline cudaError_t cudaEventElapsedTime(float*, cudaEvent_t, cudaEvent_t) { oracle_stub_abort(); } diff --git a/crates/sampler-ref/src/chain.rs b/crates/sampler-ref/src/chain.rs index d0279eda..7ee2e344 100644 --- a/crates/sampler-ref/src/chain.rs +++ b/crates/sampler-ref/src/chain.rs @@ -4,7 +4,7 @@ //! penalties -> top_k -> top_p -> min_p -> temperature -> inverse-CDF pick //! ``` //! -//! Source of truth: `engine/strata/src/kernels/cuda/sampler.cu` +//! Source of truth: `Strata 41cf05a0, src/kernels/cuda/sampler.cu` //! (`sampler_greedy_kernel`, `sampler_kernel`, `sampler_one_block_kernel`, //! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick` //! in `sampler_parity.cpp`. The three sampled kernels of the Original (old, diff --git a/crates/sampler-ref/src/coupled.rs b/crates/sampler-ref/src/coupled.rs index d6df7784..db70c329 100644 --- a/crates/sampler-ref/src/coupled.rs +++ b/crates/sampler-ref/src/coupled.rs @@ -1,7 +1,7 @@ //! Coupled draft sampling arithmetic and the host penalty-history helpers. //! -//! Sources: `engine/strata/include/strata/core/coupled_draft.hpp` (cell / -//! counter / ring arithmetic), `engine/strata/include/strata/kernels/sampler.hpp` +//! Sources: `Strata 41cf05a0, include/strata/core/coupled_draft.hpp` (cell / +//! counter / ring arithmetic), `Strata 41cf05a0, include/strata/kernels/sampler.hpp` //! (`penalty_rows`) and the coupled kernels of `sampler.cu` //! (`coupled_penalize_kernel`, `coupled_merge_kernel`). //! diff --git a/crates/sampler-ref/src/lib.rs b/crates/sampler-ref/src/lib.rs index 36429cbe..6913283d 100644 --- a/crates/sampler-ref/src/lib.rs +++ b/crates/sampler-ref/src/lib.rs @@ -1,4 +1,4 @@ -//! CPU reference of the Original Strata sampler (`engine/strata`), in safe Rust. +//! CPU reference of the Original Strata sampler (Strata 41cf05a0), in safe Rust. //! //! This crate is a *literal transcription* of the Original host/device sampler //! logic, not a re-design: diff --git a/crates/sampler-ref/src/params.rs b/crates/sampler-ref/src/params.rs index 2168c73d..62331b1a 100644 --- a/crates/sampler-ref/src/params.rs +++ b/crates/sampler-ref/src/params.rs @@ -3,11 +3,11 @@ //! //! Sources of truth in the Original: //! -//! * `engine/strata/src/program/generate.cpp` (`GEN` key grammar and the +//! * `Strata 41cf05a0, src/program/generate.cpp` (`GEN` key grammar and the //! defaults an absent key keeps): greedy, `top_p = 1.0`, `top_k = 20`, //! `min_p = 0`, no penalties, `seed = 0` meaning "clock seed"; `min_p` is //! clamped to `[0, 1]` and `penalty_last_n` to `>= 0`. -//! * `engine/strata/serve/server.py` `StrataEngine.sampling_keys` (which keys are +//! * `Strata 41cf05a0, serve/server.py` `StrataEngine.sampling_keys` (which keys are //! emitted and how floats are printed) and `sampling_defaults_from_config` / //! `clean_shared_defaults` (the ranges the server enforces on configured //! defaults). diff --git a/crates/sampler-ref/src/philox.rs b/crates/sampler-ref/src/philox.rs index 2ea35ee1..bc9b99f0 100644 --- a/crates/sampler-ref/src/philox.rs +++ b/crates/sampler-ref/src/philox.rs @@ -1,7 +1,7 @@ //! The Original's counter-based uniform generator. //! //! Transcribed from `philox4x32_round` / `philox_uniform` in -//! `engine/strata/src/kernels/cuda/sampler.cu` (host twin: `host_philox_uniform` +//! `Strata 41cf05a0, src/kernels/cuda/sampler.cu` (host twin: `host_philox_uniform` //! in `sampler_parity.cpp`). NOTE: this is "Philox-shaped", not the textbook //! Philox4x32-10: the multipliers are the golden-ratio constants //! `0x9E3779B9` / `0xBB67AE85` and the round key is the bare round index diff --git a/crates/serving-policy/oracle/build_oracle.sh b/crates/serving-policy/oracle/build_oracle.sh deleted file mode 100755 index 3391284e..00000000 --- a/crates/serving-policy/oracle/build_oracle.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh -# Rebuild the host oracles and regenerate the committed fixtures. macOS or Linux, clang++ or g++, no CUDA. -# crates/serving-policy/oracle/build_oracle.sh [output_dir] -# The vision oracle compiles code EXTRACTED from the pinned generate.cpp (not retyped): the GENI embeddings / -# M-RoPE block and fnv1a, found by their text, so a change in the pinned source shows up as a failed extraction -# or a fixture diff. -set -eu -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../../.." && pwd) -engine="$root/engine/strata" -out=${1:-"$here/../tests/fixtures"} -work=${TMPDIR:-/tmp}/leleka_serving_oracle.$$ -mkdir -p "$work" "$out" -trap 'rm -rf "$work"' EXIT - -# ---- stride + watchdog -${CXX:-clang++} -std=c++17 -O1 -Wno-unused-function -I "$engine/include" "$here/gen_host_fixtures.cpp" -o "$work/host" -"$work/host" "$out/host_oracle.json" - -# ---- GENI embeddings block, verbatim -gen="$engine/src/program/generate.cpp" -awk '/^uint64_t fnv1a\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/fnv1a.inc" -awk '/if \(geni \|\| !mrope_identity\) \{/ {p=1} /tr\("positions built"/ {p=0} p {print}' "$gen" > "$work/generate_block.inc" -[ -s "$work/fnv1a.inc" ] && [ -s "$work/generate_block.inc" ] || { echo "could not extract the GENI block from $gen" >&2; exit 1; } -grep -q 'bad embeddings file' "$work/generate_block.inc" || { echo "extracted block is not the GENI embeddings code" >&2; exit 1; } -${CXX:-clang++} -std=c++20 -O1 -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ - "$here/gen_vision_fixtures.cpp" -o "$work/vision" -"$work/vision" "$out/vision_oracle.json" - -# ---- control vector loader, verbatim -awk '/^bool load_control_vectors\(/ {p=1} p {print} p && /^}/ {exit}' "$gen" > "$work/load_control_vectors.inc" -[ -s "$work/load_control_vectors.inc" ] && grep -q 'no direction. tensors' "$work/load_control_vectors.inc" \ - || { echo "could not extract load_control_vectors from $gen" >&2; exit 1; } -${CXX:-clang++} -std=c++20 -O1 -ffp-contract=off -fno-fast-math -Wno-unused-function -Wno-unused-variable -I "$engine/include" -I "$work" \ - "$here/gen_cvec_fixtures.cpp" -o "$work/cvec" -"$work/cvec" "$out/cvec_oracle.json" diff --git a/crates/serving-policy/oracle/gen_cvec_fixtures.cpp b/crates/serving-policy/oracle/gen_cvec_fixtures.cpp deleted file mode 100644 index 2338d434..00000000 --- a/crates/serving-policy/oracle/gen_cvec_fixtures.cpp +++ /dev/null @@ -1,206 +0,0 @@ -// Host oracle for control vectors: `load_control_vectors` of src/program/generate.cpp INCLUDED VERBATIM -// (extracted by build_oracle.sh) with the Options / ModelGeometry / cvec_upload it needs stubbed, driven over -// small GGUF control-vector files this harness writes. The tables it would upload (dir, s) are recorded as -// raw float bits, so the Rust loader can be compared bit for bit (-ffp-contract=off pins the host arithmetic). -// -// Usage: gen_cvec_fixtures OUT.json -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "strata/artifact/gguf_reader.hpp" - -struct Options { - std::vector> cvec_files; - int cvec_first = -1, cvec_last = -1; - int cvec_mode = 1; - int cvec_single = -1; -}; -namespace strata::core { struct ModelGeometry { int64_t n_layers = 0, n_embd = 0, hc = 0; }; } -namespace strata::kernels { -struct Captured { std::vector dir, s; int mode = 0, first = 0, last = 0; bool called = false; }; -Captured g_up; -bool cvec_upload(const std::vector& dir, const std::vector& s, int mode, int first, int last, int64_t, int64_t, - std::string&) { - g_up = {dir, s, mode, first, last, true}; - return true; -} -} // namespace strata::kernels - -#include "load_control_vectors.inc" - -// ---- a minimal GGUF v3 writer --------------------------------------------------------------------------------- -struct Tensor { std::string name; uint32_t type; std::vector dims; std::vector data; }; -static void w32(std::string& s, uint32_t v) { s.append((const char*) &v, 4); } -static void w64(std::string& s, uint64_t v) { s.append((const char*) &v, 8); } -static void wstr(std::string& s, const std::string& v) { w64(s, v.size()); s += v; } -static std::string gguf(const std::vector>& kv, const std::vector& ts) { - std::string s = "GGUF"; - w32(s, 3); - w64(s, ts.size()); - w64(s, kv.size()); - for (const auto& [k, v] : kv) { wstr(s, k); w32(s, 8); wstr(s, v); } - uint64_t offset = 0; - std::vector offsets; - for (const Tensor& t : ts) { - wstr(s, t.name); - w32(s, (uint32_t) t.dims.size()); - for (uint64_t d : t.dims) w64(s, d); - w32(s, t.type); - w64(s, offset); - offsets.push_back(offset); - offset += (t.data.size() * 4 + 31) / 32 * 32; - } - while (s.size() % 32) s += '\0'; - for (const Tensor& t : ts) { - s.append((const char*) t.data.data(), t.data.size() * 4); - while (s.size() % 32) s += '\0'; - } - return s; -} -static std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} -static std::string jstr(const std::string& s) { - std::string o = "\""; - for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } - return o + "\""; -} -static Tensor dir(const std::string& name, int64_t n, float seed, float step = 0.37f) { - Tensor t{name, 0, {(uint64_t) n}, {}}; - for (int64_t j = 0; j < n; ++j) t.data.push_back(seed + step * (float) j - (j % 3 == 0 ? 0.5f : 0.0f)); - return t; -} - -struct Case { - std::string name; - std::vector> files; // index into blobs, scale - int first, last, mode, single; -}; - -int main(int argc, char** argv) { - if (argc < 2) return 2; - constexpr int64_t L = 6, N = 5, HC = 2; - const std::string base = std::string(std::getenv("TMPDIR") ? std::getenv("TMPDIR") : "/tmp") + "/strata_cvec_oracle_" + std::to_string((long long) getpid()); - const std::vector> good = {{"general.architecture", "controlvector"}, {"controlvector.model_hint", "qwen4exp"}}; - std::vector blobs = { - // 0: directions for layers 1, 2, 4 (3 and 5 have none) - gguf(good, {dir("direction.1", N, 1.0f), dir("direction.2", N, -0.5f), dir("direction.4", N, 2.0f)}), - // 1: directions for 2, 3 - gguf(good, {dir("direction.2", N, 0.25f, 0.11f), dir("direction.3", N, 3.0f)}), - // 2: not a control vector - gguf({{"general.architecture", "llama"}}, {dir("direction.1", N, 1.0f)}), - // 3: no direction tensors - gguf(good, {dir("other.1", N, 1.0f)}), - // 4: wrong size - gguf(good, {dir("direction.1", N + 1, 1.0f)}), - // 5: wrong type (F16 id 1) - gguf(good, {Tensor{"direction.1", 1, {(uint64_t) N}, std::vector(3, 0.0f)}}), - // 6: layer 0, past the model, a non-number, a padded number: ignored / strtol semantics - gguf(good, {dir("direction.0", N, 9.0f), dir("direction.6", N, 9.0f), dir("direction.99", N, 9.0f), dir("direction.abc", N, 9.0f), - dir("direction.03", N, 0.75f)}), - // 7: all zeros - gguf(good, {Tensor{"direction.1", 0, {(uint64_t) N}, std::vector(N, 0.0f)}, Tensor{"direction.2", 0, {(uint64_t) N}, std::vector(N, 0.0f)}}), - // 8: another model's hint (a warning on stderr only) - gguf({{"general.architecture", "controlvector"}, {"controlvector.model_hint", "llama"}}, {dir("direction.1", N, 1.0f)}), - // 9: no hint at all - gguf({{"general.architecture", "controlvector"}}, {dir("direction.5", N, -1.0f)}), - }; - std::vector cases = { - {"add, one file, default range", {{"0", 1.0f}}, -1, -1, 1, -1}, - {"add, two files scaled and summed", {{"0", 0.5f}, {"1", -2.0f}}, -1, -1, 1, -1}, - {"project, one file", {{"0", 1.0f}}, -1, -1, 0, -1}, - {"project, two files", {{"0", 1.5f}, {"1", 1.0f}}, -1, -1, 0, -1}, - {"add, layer range 2..3", {{"0", 1.0f}, {"1", 1.0f}}, 2, 3, 1, -1}, - {"add, range past the model", {{"0", 1.0f}}, 1, 99, 1, -1}, - {"project, range first only", {{"0", 1.0f}}, 3, -1, 0, -1}, - {"project single:2", {{"0", 1.0f}}, -1, -1, 0, 2}, - {"project single:2 over a range", {{"0", 1.0f}, {"1", 1.0f}}, 2, 5, 0, 2}, - {"add ignores single", {{"0", 1.0f}}, -1, -1, 1, 2}, - {"project single without a direction", {{"0", 1.0f}}, -1, -1, 0, 3}, - {"project single past the model", {{"0", 1.0f}}, -1, -1, 0, 6}, - {"scale zero adds nothing but still counts as found", {{"0", 0.0f}}, -1, -1, 1, -1}, - {"scale zero in project mode steers nothing", {{"0", 0.0f}}, -1, -1, 0, -1}, - {"layers 0 / past-model / non-numeric ignored, 03 is layer 3", {{"6", 1.0f}}, -1, -1, 1, -1}, - {"not a control vector", {{"2", 1.0f}}, -1, -1, 1, -1}, - {"no direction tensors", {{"3", 1.0f}}, -1, -1, 1, -1}, - {"wrong tensor size", {{"4", 1.0f}}, -1, -1, 1, -1}, - {"wrong tensor type", {{"5", 1.0f}}, -1, -1, 1, -1}, - {"all-zero directions in project mode", {{"7", 1.0f}}, -1, -1, 0, -1}, - {"all-zero directions in add mode", {{"7", 1.0f}}, -1, -1, 1, -1}, - {"another model's hint still loads", {{"8", 1.0f}}, -1, -1, 1, -1}, - {"no hint", {{"9", 1.0f}}, -1, -1, 1, -1}, - {"second file bad", {{"0", 1.0f}, {"3", 1.0f}}, -1, -1, 1, -1}, - {"no steered layer in the range", {{"0", 1.0f}}, 5, 5, 1, -1}, - }; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp load_control_vectors (verbatim) over GGUF files written by gen_cvec_fixtures.cpp\",\n" - " \"n_layers\": %lld, \"n_embd\": %lld, \"hc\": %lld,\n \"blobs\": [", (long long) L, (long long) N, (long long) HC); - for (size_t i = 0; i < blobs.size(); ++i) std::fprintf(f, "%s\"%s\"", i ? "," : "", hex(blobs[i]).c_str()); - std::fprintf(f, "],\n \"cases\": ["); - bool first = true; - for (const Case& c : cases) { - Options o; - o.cvec_first = c.first; - o.cvec_last = c.last; - o.cvec_mode = c.mode; - o.cvec_single = c.single; - std::vector> used; - for (size_t k = 0; k < c.files.size(); ++k) { - const int blob = std::atoi(c.files[k].first.c_str()); - const std::string path = base + "_" + std::to_string(blob) + ".gguf"; - std::FILE* w = std::fopen(path.c_str(), "wb"); - std::fwrite(blobs[(size_t) blob].data(), 1, blobs[(size_t) blob].size(), w); - std::fclose(w); - o.cvec_files.push_back({path, c.files[k].second}); - used.push_back({blob, c.files[k].second}); - } - strata::core::ModelGeometry g; - g.n_layers = L; g.n_embd = N; g.hc = HC; - strata::kernels::g_up = {}; - std::string summary, err; - const bool ok = load_control_vectors(o, g, summary, err); - // the temp paths carry this process's id: name the files by their blob instead - for (size_t k = 0; k < used.size(); ++k) { - const std::string path = o.cvec_files[k].first, label = "FILE" + std::to_string(used[k].first); - for (size_t at = err.find(path); at != std::string::npos; at = err.find(path)) err.replace(at, path.size(), label); - } - std::fprintf(f, "%s\n {\"name\": %s, \"files\": [", first ? "" : ",", jstr(c.name).c_str()); - for (size_t k = 0; k < used.size(); ++k) { - uint32_t bits; std::memcpy(&bits, &used[k].second, 4); - std::fprintf(f, "%s[%d, %u]", k ? "," : "", used[k].first, bits); - } - std::fprintf(f, "], \"first\": %d, \"last\": %d, \"mode\": \"%s\", \"single\": %d, \"ok\": %s, \"err\": %s, \"summary\": %s", - c.first, c.last, c.mode == 0 ? "project" : "add", c.single, ok ? "true" : "false", jstr(err).c_str(), jstr(summary).c_str()); - if (ok) { - std::fprintf(f, ", \"up\": {\"mode\": %d, \"first\": %d, \"last\": %d, \"dir_bits\": [", strata::kernels::g_up.mode, - strata::kernels::g_up.first, strata::kernels::g_up.last); - for (size_t i = 0; i < strata::kernels::g_up.dir.size(); ++i) { - uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.dir[i], 4); - std::fprintf(f, "%s%u", i ? "," : "", bits); - } - std::fprintf(f, "], \"s_bits\": ["); - for (size_t i = 0; i < strata::kernels::g_up.s.size(); ++i) { - uint32_t bits; std::memcpy(&bits, &strata::kernels::g_up.s[i], 4); - std::fprintf(f, "%s%u", i ? "," : "", bits); - } - std::fprintf(f, "]}"); - } - std::fprintf(f, "}"); - first = false; - for (const auto& [p, s] : o.cvec_files) { (void) s; std::remove(p.c_str()); } - } - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/oracle/gen_host_fixtures.cpp b/crates/serving-policy/oracle/gen_host_fixtures.cpp deleted file mode 100644 index 44f6675b..00000000 --- a/crates/serving-policy/oracle/gen_host_fixtures.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Host oracle for the serving policies that are plain C++ in the Original (no CUDA): -// * logits_selection.hpp - compiled UNMODIFIED from engine/strata/include; -// * the stall watchdog: core/progress.hpp (Progress, progress_now_ms) compiled unmodified, and the -// poll body of the watchdog thread in src/program/generate.cpp (the lines marked below) driven by an -// injected clock instead of sleep_for(1 s). -// Output: tests/fixtures/host_oracle.json (stride + watchdog scenarios). Usage: gen_host_fixtures OUT.json -#include -#include -#include -#include - -#include "strata/core/progress.hpp" -#include "strata/program/logits_selection.hpp" - -namespace ls = strata::program::logits_selection; - -static std::string esc(const std::string& s) { - std::string o; - for (char c : s) { - if (c == '"' || c == '\\') o += '\\'; - o += c; - } - return o; -} - -// ---- the watchdog thread of generate.cpp, with the clock and the counters passed in -------------------------- -struct Dog { - int limit; - uint64_t last; - uint64_t ticks_at; - int64_t since_ms; - Dog(int limit_s, int64_t now_ms, uint64_t beats, uint64_t ticks) - : limit(limit_s), last(beats), ticks_at(ticks), since_ms(now_ms) {} - // Returns -1 healthy, otherwise the "layers served since the last finished step" the report prints. - // The statements below are generate.cpp's loop body (lines "const uint64_t b = ..." to "std::abort()"). - int64_t poll(int64_t now_ms, uint64_t beats, bool busy, uint64_t ticks) { - if (limit <= 0) return -1; // `if (limit > 0) std::thread(...)`: no thread at all - const uint64_t b = beats; - if (!busy || b != last) { last = b; ticks_at = ticks; since_ms = now_ms; return -1; } - if (now_ms - since_ms < (int64_t) limit * 1000) return -1; - return (int64_t) (ticks - ticks_at); // stall_report(stderr, p.ticks.load() - ticks_at); abort - } -}; - -int main(int argc, char** argv) { - if (argc < 2) return 2; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"include/strata/program/logits_selection.hpp + core/progress.hpp + the watchdog thread of src/program/generate.cpp (host build)\",\n"); - - // ---- stride - std::fprintf(f, " \"parse\": ["); - const char* texts[] = {"1", "2", "128", "9223372036854775807", "9223372036854775808", "0", "00", "007", "-1", "+1", - " 1", "1 ", "1x", "x", "", "1.5", "99999999999999999999", "12345678901234567890"}; - bool first = true; - for (const char* t : texts) { - int64_t v = -777; - const bool ok = ls::parse_stride(t, v); - std::fprintf(f, "%s\n {\"text\": \"%s\", \"ok\": %s, \"value\": %lld}", first ? "" : ",", esc(t).c_str(), ok ? "true" : "false", - (long long) (ok ? v : -777)); - first = false; - } - std::fprintf(f, "\n ],\n \"selected\": ["); - first = true; - const int64_t totals[] = {-1, 0, 1, 2, 5, 9, 10, 11, 64, 100}; - const int64_t strides[] = {-1, 0, 1, 2, 3, 4, 7, 10, 64, 1000}; - for (int64_t total : totals) - for (int64_t stride : strides) { - std::fprintf(f, "%s\n {\"total\": %lld, \"stride\": %lld, \"rows\": %lld, \"kept\": [", first ? "" : ",", (long long) total, - (long long) stride, (long long) ls::row_count(total, stride)); - bool kf = true; - for (int64_t p = -2; p < total + 2; ++p) - if (ls::selected(p, total, stride)) { - std::fprintf(f, "%s%lld", kf ? "" : ",", (long long) p); - kf = false; - } - std::fprintf(f, "]}"); - first = false; - } - std::fprintf(f, "\n ],\n"); - - // ---- watchdog scenarios: [limit_s, [[dt_ms, beats, busy, ticks], ...]] -> verdicts - struct Step { int64_t at_ms; uint64_t beats; bool busy; uint64_t ticks; }; - struct Scenario { int limit; std::vector steps; }; - std::vector sc = { - {3, {{1000, 0, true, 0}, {2000, 0, true, 5}, {2999, 0, true, 9}, {3000, 0, true, 9}, {4000, 0, true, 9}}}, - {2, {{1900, 1, true, 40}, {3800, 1, true, 40}, {3900, 1, true, 40}, {4000, 2, true, 41}, {5999, 2, true, 41}, {6000, 2, true, 80}}}, - {2, {{1000, 0, false, 1}, {2000, 0, false, 2}, {3000, 0, false, 3}, {100000, 0, true, 100}, {101999, 0, true, 100}, {102000, 0, true, 100}}}, - {0, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, - {-5, {{1000, 0, true, 0}, {10000000, 0, true, 0}}}, - {1, {{1000, 0, true, 3}, {2000, 0, true, 3}, {3000, 1, true, 3}, {3999, 1, true, 7}, {4000, 1, true, 7}}}, - {60, {{59000, 0, true, 0}, {59999, 0, true, 0}, {60000, 0, true, 12}, {61000, 5, false, 12}, {200000, 5, true, 12}}}, - }; - std::fprintf(f, " \"watchdog\": ["); - first = true; - for (const Scenario& s : sc) { - Dog dog(s.limit, 0, 0, 0); - std::fprintf(f, "%s\n {\"limit_s\": %d, \"steps\": [", first ? "" : ",", s.limit); - bool sf = true; - for (const Step& st : s.steps) { - const int64_t v = dog.poll(st.at_ms, st.beats, st.busy, st.ticks); - std::fprintf(f, "%s\n {\"at_ms\": %lld, \"beats\": %llu, \"busy\": %s, \"ticks\": %llu, \"layers_since\": %lld}", sf ? "" : ",", - (long long) st.at_ms, (unsigned long long) st.beats, st.busy ? "true" : "false", (unsigned long long) st.ticks, - (long long) v); - sf = false; - } - std::fprintf(f, "\n ]}"); - first = false; - } - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/oracle/gen_vision_fixtures.cpp b/crates/serving-policy/oracle/gen_vision_fixtures.cpp deleted file mode 100644 index 335a36e0..00000000 --- a/crates/serving-policy/oracle/gen_vision_fixtures.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// Host oracle for the image-embeddings path of `--serve` (GENI): the SVE1 record reader and the M-RoPE -// position table of src/program/generate.cpp. -// -// The block between "if (geni || !mrope_identity) {" and "tr(\"positions built\"" is INCLUDED VERBATIM from the -// pinned generate.cpp (extracted by build_oracle.sh, see generate_block.inc) - not retyped - and so is `fnv1a`. -// Everything around it (the variables the block reads, a CUDA-free `put` target) is declared here. -// -// Usage: gen_vision_fixtures OUT.json (writes its scratch embedding files to $TMPDIR) -#include -#include -#include -#include -#include -#include -#include -#include - -#include "strata/core/conversation_cache.hpp" - -using ImgKey = strata::core::ConversationImageKey; - -#include "fnv1a.inc" - -struct Geometry { int64_t n_embd; }; - -struct Result { - std::string ve; - std::vector table; - std::vector row_offset; // float offset into img_rows per token, -1 = none - std::vector imgs; -}; - -constexpr int64_t kImagePad = 248056; - -static Result run(bool geni, const std::vector& ids, const std::string& emb_path, int64_t n_embd, int64_t cells, - bool mrope_identity) { - Geometry g{n_embd}; - const int64_t n = (int64_t) ids.size(); - std::vector req_imgs; - std::vector mrope_host((size_t) cells * 3); - for (int64_t c = 0; c < cells; ++c) mrope_host[(size_t) c * 3] = mrope_host[(size_t) c * 3 + 1] = mrope_host[(size_t) c * 3 + 2] = (int32_t) c; - std::vector img_rows; - std::vector row_ptr; - Result out; - { - // ---------------------------------------------------------------- verbatim from generate.cpp -#include "generate_block.inc" - out.ve = ve; - } // closes the `if (geni || !mrope_identity) {` that the block opens - } - out.table = mrope_host; - out.imgs = req_imgs; - for (const float* p : row_ptr) out.row_offset.push_back(p ? (int64_t) (p - img_rows.data()) : -1); - return out; -} - -// ---- SVE1 file builders --------------------------------------------------------------------------------------- -static void put_i32(std::string& s, int32_t v) { s.append((const char*) &v, 4); } -static std::string image(int32_t n, int32_t nx, int32_t ny, int32_t width, float seed, int32_t magic = 0x31455653) { - std::string s; - for (int32_t v : {magic, n, nx, ny, width}) put_i32(s, v); - for (int32_t i = 0; i < n * width; ++i) { - const float f = seed + (float) i * 0.5f; - s.append((const char*) &f, 4); - } - return s; -} - -static std::string hex(const std::string& s) { - static const char* d = "0123456789abcdef"; - std::string o; - for (unsigned char c : s) { o += d[c >> 4]; o += d[c & 15]; } - return o; -} - -static std::string jstr(const std::string& s) { - std::string o = "\""; - for (char c : s) { if (c == '"' || c == '\\') o += '\\'; o += c; } - return o + "\""; -} - -int main(int argc, char** argv) { - if (argc < 2) return 2; - const char* tmp = std::getenv("TMPDIR"); - const std::string scratch = std::string(tmp ? tmp : "/tmp") + "/strata_sve_oracle_" + std::to_string((long long) getpid()) + ".sve"; - std::FILE* f = std::fopen(argv[1], "w"); - if (!f) return 2; - std::fprintf(f, "{\n \"source\": \"src/program/generate.cpp GENI embeddings block + fnv1a (verbatim, host build)\",\n \"cases\": ["); - - struct Case { const char* name; bool geni; std::vector ids; std::string file; int64_t n_embd; int64_t cells; bool identity; }; - const int64_t P = kImagePad; - const std::string i1 = image(1, 1, 1, 4, 1.0f), i6 = image(6, 3, 2, 4, 10.0f), i8 = image(8, 2, 4, 4, 20.0f), i25 = image(25, 5, 5, 4, 30.0f); - std::vector cases = { - {"text identity after an image request", false, {5, 6, 7}, "", 4, 32, false}, - {"text only with no file", true, {5, 6, 7, 8}, "", 4, 32, true}, - {"one 1x1 image", true, {1, 2, P, 3, 4}, i1, 4, 32, true}, - {"one 3x2 image", true, {1, P, P, P, P, P, P, 9, 10}, i6, 4, 40, true}, - {"one 2x4 image (tall: ny > nx)", true, {7, P, P, P, P, P, P, P, P, 8}, i8, 4, 40, true}, - {"two images in order", true, {1, P, P, P, P, P, P, 2, P, P, P, P, P, P, P, P, 3}, i6 + i8, 4, 64, true}, - {"5x5 image then text", true, {1, 2, 3, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, 4, 5}, i25, 4, 64, true}, - {"adjacent images", true, {P, P, P, P, P, P, P, P, P, P, P, P, P, P, 1}, i6 + i8, 4, 40, true}, - {"image at the start", true, {P, 4}, i1, 4, 16, true}, - {"identity request after (not geni, not identity)", false, {1, 2}, "", 4, 16, false}, - // errors - {"prompt ends in an image", true, {1, P, P, P, P, P, P}, i6, 4, 32, true}, - {"more images in the prompt than the file", true, {1, P, 2, P, 3}, i1, 4, 32, true}, - {"more images in the file than the prompt", true, {1, P, 2, 3}, i1 + i1, 4, 32, true}, - {"fewer image_pad tokens than rows", true, {1, P, P, 2, 3, 4, 5, 6, 7}, i6, 4, 32, true}, - {"bad magic", true, {1, P, 2}, image(1, 1, 1, 4, 1.0f, 0x12345678), 4, 32, true}, - {"wrong width", true, {1, P, 2}, image(1, 1, 1, 8, 1.0f), 4, 32, true}, - {"grid does not multiply", true, {1, P, 2}, image(6, 3, 3, 4, 1.0f), 4, 32, true}, - {"zero rows", true, {1, P, 2}, image(0, 0, 0, 4, 1.0f), 4, 32, true}, - {"short header", true, {1, P, 2}, i1.substr(0, 12), 4, 32, true}, - {"short data", true, {1, P, 2}, i1.substr(0, i1.size() - 3), 4, 32, true}, - {"second record truncated", true, {1, P, 2, P, 3}, i1 + i1.substr(0, 25), 4, 32, true}, - }; - bool first = true; - for (const Case& c : cases) { - if (!c.file.empty() || c.geni) { - std::FILE* w = std::fopen(scratch.c_str(), "wb"); - std::fwrite(c.file.data(), 1, c.file.size(), w); - std::fclose(w); - } - // "no file": point at a path that does not exist - const std::string path = c.file.empty() && c.geni ? std::string("/nonexistent/embeddings.sve") : scratch; - const Result r = run(c.geni, c.ids, path, c.n_embd, c.cells, c.identity); - std::fprintf(f, "%s\n {\"name\": %s, \"geni\": %s, \"mrope_identity\": %s, \"n_embd\": %lld, \"cells\": %lld, \"file_hex\": \"%s\", \"ids\": [", - first ? "" : ",", jstr(c.name).c_str(), c.geni ? "true" : "false", c.identity ? "true" : "false", - (long long) c.n_embd, (long long) c.cells, hex(c.file).c_str()); - for (size_t i = 0; i < c.ids.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) c.ids[i]); - std::fprintf(f, "], \"ve\": %s, \"table\": [", jstr(r.ve).c_str()); - for (size_t i = 0; i < r.table.size(); ++i) std::fprintf(f, "%s%d", i ? "," : "", r.table[i]); - std::fprintf(f, "], \"row_offset\": ["); - for (size_t i = 0; i < r.row_offset.size(); ++i) std::fprintf(f, "%s%lld", i ? "," : "", (long long) r.row_offset[i]); - std::fprintf(f, "], \"imgs\": ["); - for (size_t i = 0; i < r.imgs.size(); ++i) - std::fprintf(f, "%s[%lld,\"%016llx\"]", i ? "," : "", (long long) r.imgs[i].start, (unsigned long long) r.imgs[i].hash); - std::fprintf(f, "]}"); - first = false; - } - std::remove(scratch.c_str()); - std::fprintf(f, "\n ]\n}\n"); - std::fclose(f); - return 0; -} diff --git a/crates/serving-policy/src/lib.rs b/crates/serving-policy/src/lib.rs index 1799d354..4aa55e38 100644 --- a/crates/serving-policy/src/lib.rs +++ b/crates/serving-policy/src/lib.rs @@ -1,4 +1,4 @@ -//! Pure Rust ports of the Original Strata serving-layer policies (`engine/strata/serve/*.py` and the +//! Pure Rust ports of the Original Strata serving-layer policies (`Strata 41cf05a0, serve/*.py` and the //! host-side parts of `src/program/generate.cpp`). No I/O, no async runtime, no `unsafe`. //! //! Each module cites the Original code it transcribes and is tested against fixtures produced by running diff --git a/crates/tokenizer/tests/oracle_differential.rs b/crates/tokenizer/tests/oracle_differential.rs index 7c86760e..8de555f1 100644 --- a/crates/tokenizer/tests/oracle_differential.rs +++ b/crates/tokenizer/tests/oracle_differential.rs @@ -1,4 +1,4 @@ -//! Tokenizer versus `engine/strata/tools/strata_tokenizer.py` (the unmodified oracle, regex 2026.9.10). +//! Tokenizer versus `Strata 41cf05a0, tools/strata_tokenizer.py` (the unmodified oracle, regex 2026.9.10). //! //! `tests/fixtures/tokenizer_oracle.json` is produced by `scripts/offline/gen_goldens.py tokenizer_oracle`: a //! synthetic byte-level BPE vocabulary (256-byte alphabet, 300 trained merges that reach past the 64-symbol heap diff --git a/deploy/Dockerfile.static-cli b/deploy/Dockerfile.static-cli index 9a4fdad0..23b7e692 100644 --- a/deploy/Dockerfile.static-cli +++ b/deploy/Dockerfile.static-cli @@ -14,8 +14,8 @@ COPY crates/ ./crates/ COPY manifests/ ./manifests/ COPY desktop-core/ ./desktop-core/ COPY control-plane/ ./control-plane/ -COPY engine/strata/LICENSE ./engine/strata/LICENSE -COPY engine/strata/serve/chat_template.jinja ./engine/strata/serve/chat_template.jinja +COPY third_party/strata/LICENSE ./third_party/strata/LICENSE +COPY third_party/strata/serve/chat_template.jinja ./third_party/strata/serve/chat_template.jinja RUN cargo build --manifest-path control-plane/Cargo.toml --locked --release \ --target "${RUST_TARGET}" --bin leleka-api diff --git a/deploy/README.md b/deploy/README.md index 8f54d628..878be948 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -515,7 +515,7 @@ full payload and require memory and disk space proportional to its size. `leleka-api engine-help` materializes the embedded worker and runs its `--help` with no GPU visible; this checks loading and help output, not model readiness. `leleka-api --engine-license` prints the imported Strata MIT license. The -upstream record in `engine/upstream.md` remains authoritative and unchanged. +upstream record in `third_party/strata/UPSTREAM.md` remains authoritative and unchanged. Select the embedded worker explicitly in the usual configuration: ```json @@ -606,6 +606,9 @@ libraries. HIP and non-Linux/GNU configurations reject this option. On a Linux builder with the toolkit and CMake already installed: +> **Retired (STRA-406).** `scripts/build-static-cuda.sh` built the engine from the vendored Strata tree, which was removed from the repository +> (`third_party/strata/UPSTREAM.md`). Build the engine from an upstream checkout at the pin and pass the binary to `scripts/build-linux-package.py`. + ```sh export CUDACXX=/absolute/path/to/cuda/bin/nvcc export CUDAToolkit_ROOT=/absolute/path/to/cuda @@ -762,12 +765,10 @@ fail without publishing a pack. `conversions.json` records the changes and source tensor hashes; `source.json` records the verified shard identities; the receipt lists the optional files that are present. -`scripts/smoke-native-pack.py` compares dense bytes, index rows and the complete -v3/v4 expert table against the unmodified pinned `tools/iq_pack.py` oracle on -small single/split GGUF fixtures, including per-role shard offsets. Numerical -and byte tolerance is zero. `scripts/offline/diff_native_pack.py` extends this to -thousands of generated cases plus the full CLI with `--compat-bf16`, `--base` and -`--experts-bin` (see `spec node offline-port.md`). Python/numpy are test-only dependencies. This does +The pack bytes (dense bytes, index rows and the complete v3/v4 expert table) were compared against the unmodified pinned `tools/iq_pack.py` oracle +on small single/split GGUF fixtures, including per-role shard offsets, with zero numerical and byte tolerance (`scripts/smoke-native-pack.py` and +`scripts/offline/diff_native_pack.py`, retired with the vendored Strata tree in STRA-406; the Rust tests and the checked-in goldens remain; see +`spec node offline-port.md`). Python/numpy are test-only dependencies. This does not establish full-model GPU readiness: real-model pack parity and clean-node GPU startup still require their separate gates. Automatic fetch/prepare/start orchestration remains a subsequent integration step. @@ -895,7 +896,7 @@ readiness**. It neither converts a raw MTP GGUF nor quantizes new weights. The existing offline `mtp_rt.py` conversion remains separate; its dense Q8 conversion must not be described as lossless. MTP activation stays explicit and real-model qualification is still required. CPU verification: -`python3 scripts/smoke-mtp-pack.py /path/to/leleka-api` (synthetic sparse layout). +`scripts/smoke-mtp-pack.py` (synthetic sparse layout; retired with the vendored Strata tree in STRA-406, the Rust tests of `mtp_pack` remain). `scripts/smoke-native-bootstrap.py` verifies real HTTP acquisition, exact pack @@ -989,6 +990,8 @@ separate qualification step. On a Linux x86_64 build host with the CUDA toolkit, GNU toolchain, `musl-gcc`, Python 3.11+, `readelf`, and the pinned Rust toolchain/target installed: +> `scripts/build-static-cuda.sh` is retired (STRA-406, see above): produce the engine binary and `BUILD-FEATURES.json` from an upstream build. + ```sh scripts/build-static-cuda.sh engine="$PWD/artifacts/build-static-cuda/strata" diff --git a/engine/README.md b/engine/README.md deleted file mode 100644 index f67793b3..00000000 --- a/engine/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# 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 deleted file mode 100644 index 4f341af3..00000000 --- a/engine/strata/.dockerignore +++ /dev/null @@ -1,27 +0,0 @@ -# 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 deleted file mode 100644 index e9e15ba7..00000000 --- a/engine/strata/.gitattributes +++ /dev/null @@ -1,27 +0,0 @@ -# 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 -*.cmd text eol=crlf -*.ps1 text eol=crlf -bin/strata text eol=lf - -# copies of real packs' native_experts.txt, parsed byte for byte by tests/core/expert_layout_test.cpp -tests/data/native_experts/** -text - -# the quant yardstick's text set: tokenized byte for byte (set.ids.json), never convert its line endings -data/quant_quality/** -text - -# the license text is shipped and checked as LF text on every checkout -LICENSE text eol=lf - -# container scripts run in Linux: always LF -docker/*.sh text eol=lf -Dockerfile text eol=lf -docker/Dockerfile text eol=lf -docker/compose/* text eol=lf - -# Apple tools (codesign, plutil) read these: LF only, wherever the repository is cloned -*.plist text eol=lf diff --git a/engine/strata/.github/FUNDING.yml b/engine/strata/.github/FUNDING.yml deleted file mode 100644 index 35b26a9a..00000000 --- a/engine/strata/.github/FUNDING.yml +++ /dev/null @@ -1 +0,0 @@ -buy_me_a_coffee: strataengine diff --git a/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml b/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml deleted file mode 100644 index 2d2514b7..00000000 --- a/engine/strata/.github/ISSUE_TEMPLATE/benchmark.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Benchmark -description: Share measurements from your machine, or report a problem with the benchmark tools -title: "[Benchmark] " -labels: ["benchmark"] -body: - - type: markdown - value: | - The title must start with **[Benchmark]**. Keep it, and add the GPU and model after it. - - To share a full report, follow the [community benchmark guide](https://github.com/Niko1221/Strata/blob/main/docs/COMMUNITY_BENCHMARKS.md) and open a results-only pull request. The standard protocol is a [draft](https://github.com/Niko1221/Strata/blob/main/docs/BENCHMARK_PROTOCOL.md); existing tools do not implement it yet. Include poor results and failed requests. - - type: textarea - id: what - attributes: - label: What did you measure, or what went wrong - description: Hardware (GPU and VRAM, CPU, RAM, OS), Strata version, model and quantization, the exact command, and the numbers. Paste the report or link the pull request. - validations: - required: true - - type: dropdown - id: reproduction-status - attributes: - label: Reproduction status - options: - - Measured locally - - Unconfirmed (I did not run it) - validations: - required: true diff --git a/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml b/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 77692fbe..00000000 --- a/engine/strata/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Bug report -description: Something in Strata doesn't work as documented -title: "[Area] " -labels: ["bug"] -body: - - type: markdown - value: | - Thanks for the report. Please read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md) first. - - Search the [open and closed issues](https://github.com/Niko1221/Strata/issues?q=is%3Aissue) first: this may already be tracked, and new evidence belongs in that thread. - - Write only what you saw. Do not guess at steps, errors, hardware or severity. - - **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. - - type: dropdown - id: area - attributes: - label: Area - description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. - options: - - "[Engine] (speed, kernels, models, the server and API)" - - "[GUI] (the desktop app)" - - "[TUI] (the Terminal: strata launch, connect, monitor)" - - "[Benchmark] (measurements and reports)" - - "[Docs] (documentation)" - - "[Other] (anything else, including setup and installation)" - validations: - required: true - - type: dropdown - id: how - attributes: - label: Desktop app, Terminal or source? - options: - - Desktop app (Windows, Linux or Mac) - - Terminal (the `strata` command) - - Source (START-HERE.bat, setup.sh or a build) - - Docker - - Other - validations: - required: true - - type: textarea - id: what - attributes: - label: What happened - description: What you did, what you got, and what you expected instead. Paste the exact error text if there is one. - validations: - required: true - - type: textarea - id: reproduce - attributes: - label: Smallest steps or command that reproduce it - description: The shortest list of steps that shows the problem. If you cannot make it happen again, say so here. - validations: - required: false - - type: dropdown - id: reproduction-status - attributes: - label: Reproduction status - options: - - Reproduced locally - - Unconfirmed static analysis (I read code or ran a scanner; I did not see it fail) - validations: - required: true - - type: input - id: version - attributes: - label: Strata version - description: "In the app: Settings > About. In the Terminal: `strata --version`. From source: the About tab of the web page, or `engine` in `GET /v1/status`, or the git commit." - placeholder: "Strata 0.2.5 · engine 0.1.50" - validations: - required: true - - type: input - id: hardware - attributes: - label: Graphics card, memory and system - description: The card and its VRAM, the RAM of the PC, and the operating system. - placeholder: "RTX 5070 12 GB · 64 GB RAM · Windows 11" - validations: - required: true - - type: input - id: model - attributes: - label: Model, size and settings - description: The model and size you started, the context, and whether pictures were on. Write what is relevant. - placeholder: "Qwen3.8-Flash-Next IQ2_XS · 128K context · pictures on" - validations: - required: false - - type: textarea - id: log - attributes: - label: Logs - description: | - The app: Settings > Engine > Diagnostics > View logs > Save logs, then drag the file in. The Terminal: paste the output of `strata doctor`. From source: drag in `strata-.log` from your Strata folder. - Remove API keys, passwords and private text first. - validations: - required: false - - type: markdown - value: | - A couple of extras that help a lot: - - - Check the [troubleshooting page](https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md) first, many reports are already solved there. diff --git a/engine/strata/.github/ISSUE_TEMPLATE/config.yml b/engine/strata/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index be9cdf2e..00000000 --- a/engine/strata/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,5 +0,0 @@ -blank_issues_enabled: true -contact_links: - - name: Troubleshooting and known issues - url: https://github.com/Niko1221/Strata/blob/main/docs/TROUBLESHOOTING.md - about: Symptom-to-fix table for crashes, out of memory, hangs, and port problems. \ No newline at end of file diff --git a/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml b/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index 8a2b375e..00000000 --- a/engine/strata/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Feature request -description: Suggest something new or an improvement -title: "[Area] " -labels: ["enhancement"] -body: - - type: markdown - value: | - Explain what you want in plain language. For a large feature, a change to a default or a refactor, please agree the scope here first. Read [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md). - - **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. - - type: dropdown - id: area - attributes: - label: Area - description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. - options: - - "[Engine] (speed, kernels, models, the server and API)" - - "[GUI] (the desktop app)" - - "[TUI] (the Terminal: strata launch, connect, monitor)" - - "[Benchmark] (measurements and reports)" - - "[Docs] (documentation)" - - "[Other] (anything else, including setup and installation)" - validations: - required: true - - type: textarea - id: idea - attributes: - label: What do you want to do? - description: Describe the goal rather than the implementation. Say who needs it and why. - validations: - required: true - - type: textarea - id: workaround - attributes: - label: What do you do today instead? - description: The workaround you use now, if there is one. - validations: - required: false - - type: markdown - value: | - All of this counts: model and architecture support, the server and API, the app and the Terminal, multi-GPU and layer split, images and vision, MCP servers, setup and installation, and performance. diff --git a/engine/strata/.github/ISSUE_TEMPLATE/question.yml b/engine/strata/.github/ISSUE_TEMPLATE/question.yml deleted file mode 100644 index 345bf512..00000000 --- a/engine/strata/.github/ISSUE_TEMPLATE/question.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Question -description: Ask how to use Strata, or share a result -title: "[Area] " -labels: ["question"] -body: - - type: markdown - value: | - Not sure how to do something, or want to share numbers from your machine? Ask here. To share a full benchmark, see [CONTRIBUTING.md](https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md#share-a-benchmark). - - **The title must start with its area:** [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. Choose the same one below. - - type: dropdown - id: area - attributes: - label: Area - description: Start the issue title with the same area in square brackets, for example "[Engine] decode stops after 2 minutes". Pick Other if none fits. - options: - - "[Engine] (speed, kernels, models, the server and API)" - - "[GUI] (the desktop app)" - - "[TUI] (the Terminal: strata launch, connect, monitor)" - - "[Benchmark] (measurements and reports)" - - "[Docs] (documentation)" - - "[Other] (anything else, including setup and installation)" - validations: - required: true - - type: textarea - id: question - attributes: - label: Your question - description: What you're trying to do. Include your version, GPU, and OS if it affects the answer. - validations: - required: true - - type: textarea - id: tried - attributes: - label: What you tried - description: What you already did and where you got stuck. - validations: - required: false - - type: textarea - id: numbers - attributes: - label: Results (optional) - description: Only if you ran a benchmark or measured speed. Model, quant, context, and the tok/s you get. - validations: - required: false diff --git a/engine/strata/.github/pull_request_template.md b/engine/strata/.github/pull_request_template.md deleted file mode 100644 index 688f7aba..00000000 --- a/engine/strata/.github/pull_request_template.md +++ /dev/null @@ -1,30 +0,0 @@ -**The title must start with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], for example "[Engine] fix decode stop on long prompts" or "[GUI] keep the model list after a tab switch".** - - - -## Problem and result - - -## Related discussion - - -## Approach - - -## Validation - - -**Passed:** - - -**Failed:** - - -**Not run:** - - -## Limits - diff --git a/engine/strata/.github/scripts/item-check.js b/engine/strata/.github/scripts/item-check.js deleted file mode 100644 index b07b6350..00000000 --- a/engine/strata/.github/scripts/item-check.js +++ /dev/null @@ -1,218 +0,0 @@ -'use strict'; -// Format check for issues and pull requests (see CONTRIBUTING.md and .github/ISSUE_TEMPLATE/*.yml). -// Pure functions only: no network, no filesystem. Used by intake.yml and reopen.yml through reset-bot.js. - -const AREAS = ['Engine', 'GUI', 'TUI', 'Benchmark', 'Docs', 'Other']; -const TITLE_RE = new RegExp('^\\[(' + AREAS.join('|') + ')\\] \\S'); -const NO_ANSWER = /^(_no response_|none|n\/a|na|-|todo|tbd|\.|\?)$/i; -const NOT_RUN_LABELS = /^\*\*(passed|failed|not run)\s*:?\*\*\s*:?/gim; - -// Version the reopened work must be tested on. -const CURRENT_VERSION_RE = /\b0\.2\.\d+|0\.2\.0-beta/i; -// Any version or commit. -const ANY_VERSION_RE = /\bv?\d+\.\d+(\.\d+)*(-[a-z0-9.]+)?\b|\b[0-9a-f]{7,40}\b|\bcommit\b/i; -const HARDWARE_RE = /\b(rtx|gtx|geforce|quadro|tesla|radeon|rx ?\d|instinct|arc|a\d{3,4}|b\d{2,3}|apple|m[1-5]( pro| max| ultra)?|nvidia|amd|intel|gpu|cpu|vram|\d+ ?gb|ram|windows|linux|ubuntu|debian|fedora|arch|macos|mac os|wsl)\b/i; -const REVISION_RE = /0\.2\.\d|beta|\bmain\b|\b[0-9a-f]{7,40}\b/i; - -function stripComments(text) { - return String(text || '').replace(//g, ''); -} - -function hasAreaPrefix(title) { - return TITLE_RE.test(String(title || '')); -} - -// Issue forms render as "### Label\n\nvalue". Returns { label: value } for those headings. -function parseSections(body) { - const out = {}; - let cur = null; - for (const line of stripComments(body).split(/\r?\n/)) { - const m = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line); - if (m) { - cur = m[1].trim(); - out[cur] = ''; - } else if (cur !== null) { - out[cur] += line + '\n'; - } - } - for (const k of Object.keys(out)) out[k] = out[k].trim(); - return out; -} - -function realText(value) { - const t = String(value || '').replace(NOT_RUN_LABELS, '').replace(/\s+/g, ' ').trim(); - return NO_ANSWER.test(t) ? '' : t; -} - -function findSection(sections, re) { - for (const k of Object.keys(sections)) if (re.test(k)) return { key: k, value: sections[k] }; - return null; -} - -// Required parts of each issue form: [display name, heading regex, minimum characters of real text]. -const FORMS = { - bug: { - detect: /what happened/i, - parts: [ - ['Area', /^area$/i, 2], - ['Desktop app, Terminal or source?', /desktop app, terminal or source/i, 2], - ['What happened', /what happened/i, 20], - ['Reproduction status', /reproduction status/i, 2], - ['Strata version', /strata version/i, 3], - ['Graphics card, memory and system', /graphics card|memory and system/i, 3], - ], - needsCurrentVersion: 'Strata version', - }, - feature: { - detect: /what do you want to do/i, - parts: [ - ['Area', /^area$/i, 2], - ['What do you want to do?', /what do you want to do/i, 20], - ], - }, - question: { - detect: /your question/i, - parts: [ - ['Area', /^area$/i, 2], - ['Your question', /your question/i, 15], - ], - }, - benchmark: { - detect: /what did you measure/i, - parts: [ - ['What did you measure, or what went wrong', /what did you measure/i, 30], - ['Reproduction status', /reproduction status/i, 2], - ], - needsCurrentVersionInBody: true, - }, -}; - -function checkIssue({ title, body, labels = [], mode = 'intake' }) { - const missing = []; - if (!hasAreaPrefix(title)) { - missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] decode stops after 2 minutes".'); - } - const text = stripComments(body); - const sections = parseSections(text); - const labelSet = new Set(labels.map((l) => String(l).toLowerCase())); - const needCurrent = mode === 'reopen'; - - let formKey = null; - for (const [key, f] of Object.entries(FORMS)) { - if (findSection(sections, f.detect)) { formKey = key; break; } - } - - if (formKey) { - const form = FORMS[formKey]; - for (const [name, re, min] of form.parts) { - const s = findSection(sections, re); - if (!s || realText(s.value).length < min) missing.push('Fill in "' + name + '".'); - } - if (needCurrent && form.needsCurrentVersion) { - const s = findSection(sections, /strata version/i); - if (s && realText(s.value) && !CURRENT_VERSION_RE.test(s.value)) { - missing.push('Re-test on Strata 0.2.0-beta and put that version in "' + form.needsCurrentVersion + '". If it no longer happens, say so in a comment instead.'); - } - } - if (needCurrent && form.needsCurrentVersionInBody && !CURRENT_VERSION_RE.test(text)) { - missing.push('Say which Strata version you measured on. Re-measure on 0.2.0-beta if you can.'); - } - return { ok: missing.length === 0, missing, kind: formKey }; - } - - // Free-form text (older issues, blank issues). - const plain = realText(text); - const lenient = labelSet.has('enhancement') || labelSet.has('question'); - if (plain.length < (lenient ? 40 : 80)) { - missing.push('Describe it in the issue body: what happened, what you expected, and the exact error if there is one. The issue forms (New issue > Bug report) list what to include.'); - } - if (!lenient) { - if (!ANY_VERSION_RE.test(text)) missing.push('Add the Strata version (Settings > About, or `strata --version`).'); - else if (needCurrent && !CURRENT_VERSION_RE.test(text)) missing.push('Re-test on Strata 0.2.0-beta and name that version in the issue. If it no longer happens, say so in a comment instead.'); - if (!HARDWARE_RE.test(text)) missing.push('Add your graphics card with its VRAM, your RAM and your operating system.'); - } - return { ok: missing.length === 0, missing, kind: 'free-form' }; -} - -function checkPull({ title, body, mode = 'intake' }) { - const missing = []; - if (!hasAreaPrefix(title)) { - missing.push('Start the title with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other], then a short description. Example: "[Engine] fix decode stop on long prompts".'); - } - const text = stripComments(body); - const sections = parseSections(text); - const problem = findSection(sections, /problem|result|summary|what.*change/i); - const validation = findSection(sections, /validation|testing|tests?\b|how.*tested/i); - - let valText = ''; - if (problem || validation) { - if (!problem || realText(problem.value).length < 20) missing.push('Fill in "Problem and result": what triggered the change, and how it behaves before and after.'); - if (!validation || realText(validation.value).length < 20) { - missing.push('Fill in "Validation": the exact commands, the revision and environment tested, what you saw. Keep Passed, Failed and Not run apart.'); - } else { - valText = validation.value; - } - } else { - const plain = realText(text); - if (plain.length < 150) { - missing.push('Describe the pull request: the problem and the result. The pull request template shows the parts (Problem and result, Related discussion, Approach, Validation, Limits).'); - } - if (!/(problem|result|before|after|fix|because|bug)/i.test(plain)) missing.push('Add "Problem and result": what triggered the change, and how it behaves before and after.'); - if (!/(validat|tested|passed|ran |built|build|not run)/i.test(plain)) missing.push('Add "Validation": the exact commands, the revision and environment tested, and what you saw.'); - valText = plain; - } - if (mode === 'reopen' && valText && !REVISION_RE.test(valText)) { - missing.push('Say in Validation which revision you tested: rebase on main (or 0.2.0-beta) and re-run your checks.'); - } - return { ok: missing.length === 0, missing, kind: 'pull' }; -} - -function checkItem({ isPull, ...rest }) { - return isPull ? checkPull(rest) : checkIssue(rest); -} - -function checklist(missing) { - return missing.map((m) => '- [ ] ' + m).join('\n'); -} - -const CONTRIB = 'https://github.com/Niko1221/Strata/blob/main/CONTRIBUTING.md'; - -function intakeComment(isPull, missing) { - return [ - 'Thanks for the ' + (isPull ? 'pull request' : 'issue') + '. To keep the tracker readable, every item needs an area prefix in the title and the parts of the ' + (isPull ? 'pull request template' : 'issue form') + ' filled in. This one is missing:', - '', - checklist(missing), - '', - 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' (title and description) and this note goes away on its own. If it is still missing parts in 5 days it will be closed, which is not a rejection: fix it and comment `/reopen`.', - '', - 'Details: [CONTRIBUTING.md](' + CONTRIB + ')', - ].join('\n'); -} - -function reopenMissingComment(isPull, missing) { - return [ - 'Not reopened yet. Still missing:', - '', - checklist(missing), - '', - 'Edit the ' + (isPull ? 'pull request' : 'issue') + ' and comment `/reopen` again. Details: [CONTRIBUTING.md](' + CONTRIB + ')', - ].join('\n'); -} - -function reopenOkComment(isPull) { - return 'Reopened, thank you. A maintainer will pick it up from here.' + (isPull ? ' If it conflicts with main, rebase it first; that speeds up review.' : ''); -} - -function staleComment(isPull) { - return [ - 'Closing this ' + (isPull ? 'pull request' : 'issue') + ' because it still did not follow the format after 5 days. That is housekeeping, not a rejection.', - '', - 'To bring it back: fix the title (area prefix) and the missing parts, then comment `/reopen`. A check runs and reopens it, or tells you what is still missing. See [CONTRIBUTING.md](' + CONTRIB + ').', - ].join('\n'); -} - -module.exports = { - AREAS, TITLE_RE, hasAreaPrefix, parseSections, stripComments, realText, - checkIssue, checkPull, checkItem, checklist, - intakeComment, reopenMissingComment, reopenOkComment, staleComment, -}; diff --git a/engine/strata/.github/scripts/item-check.test.js b/engine/strata/.github/scripts/item-check.test.js deleted file mode 100644 index c870f144..00000000 --- a/engine/strata/.github/scripts/item-check.test.js +++ /dev/null @@ -1,192 +0,0 @@ -'use strict'; -const test = require('node:test'); -const assert = require('node:assert'); -const c = require('./item-check'); -const bot = require('./reset-bot'); - -const bugForm = (over = {}) => { - const f = { - 'Area': '[Engine] (speed, kernels, models, the server and API)', - 'Desktop app, Terminal or source?': 'Terminal (the `strata` command)', - 'What happened': 'Decode stops after two minutes with "CUDA error 700". I expected it to continue.', - 'Smallest steps or command that reproduce it': '_No response_', - 'Reproduction status': 'Reproduced locally', - 'Strata version': 'Strata 0.2.0-beta · engine 0.1.45.3', - 'Graphics card, memory and system': 'RTX 5070 12 GB · 64 GB RAM · Windows 11', - ...over, - }; - return Object.entries(f).map(([k, v]) => `### ${k}\n\n${v}`).join('\n\n'); -}; - -test('title prefix', () => { - assert.ok(c.hasAreaPrefix('[Engine] fix decode')); - assert.ok(c.hasAreaPrefix('[Docs] x')); - assert.ok(!c.hasAreaPrefix('Engine fix')); - assert.ok(!c.hasAreaPrefix('[engine] fix')); - assert.ok(!c.hasAreaPrefix('[Engine]')); - assert.ok(!c.hasAreaPrefix('[Engine] ')); - assert.ok(!c.hasAreaPrefix('[Area] foo')); - assert.ok(!c.hasAreaPrefix('')); - assert.ok(!c.hasAreaPrefix(undefined)); -}); - -test('filled bug form passes in both modes', () => { - for (const mode of ['intake', 'reopen']) { - const r = c.checkIssue({ title: '[Engine] decode stops', body: bugForm(), labels: ['bug'], mode }); - assert.deepStrictEqual(r.missing, []); - assert.strictEqual(r.kind, 'bug'); - } -}); - -test('bug form: missing parts are named', () => { - const r = c.checkIssue({ title: 'decode stops', body: bugForm({ 'Strata version': '_No response_', 'What happened': 'bad' }) }); - assert.ok(!r.ok); - assert.ok(r.missing.some((m) => /title/i.test(m))); - assert.ok(r.missing.some((m) => m.includes('What happened'))); - assert.ok(r.missing.some((m) => m.includes('Strata version'))); -}); - -test('reopen needs a 0.2 version, intake does not', () => { - const body = bugForm({ 'Strata version': 'Strata 0.1.44' }); - assert.ok(c.checkIssue({ title: '[Engine] x y', body, mode: 'intake' }).ok); - const r = c.checkIssue({ title: '[Engine] x y', body, mode: 'reopen' }); - assert.ok(!r.ok); - assert.ok(r.missing.some((m) => m.includes('0.2.0-beta'))); -}); - -test('html comments and placeholders do not count', () => { - const r = c.checkIssue({ title: '[Engine] x y', body: bugForm({ 'What happened': '' }) }); - assert.ok(r.missing.some((m) => m.includes('What happened'))); -}); - -test('feature and question forms', () => { - const f = '### Area\n\n[GUI] (the desktop app)\n\n### What do you want to do?\n\nLet me pin a model to the top of the list in the app.'; - assert.ok(c.checkIssue({ title: '[GUI] pin models', body: f, mode: 'reopen' }).ok); - assert.ok(!c.checkIssue({ title: '[GUI] pin models', body: '### Area\n\n[GUI]\n\n### What do you want to do?\n\n_No response_' }).ok); - const q = '### Area\n\n[Other]\n\n### Your question\n\nHow do I move the model folder to another drive?'; - assert.ok(c.checkIssue({ title: '[Other] model folder', body: q }).ok); -}); - -test('free-form issue', () => { - const good = 'Strata 0.2.0-beta on an RTX 3060 12 GB with 32 GB RAM on Linux: the server hangs when I send two requests at once. Expected both to finish.'; - assert.ok(c.checkIssue({ title: '[Engine] hang on two requests', body: good, mode: 'reopen' }).ok); - assert.ok(!c.checkIssue({ title: '[Engine] hang', body: 'it crashes', mode: 'intake' }).ok); - const old = good.replace('0.2.0-beta', '0.1.40'); - assert.ok(c.checkIssue({ title: '[Engine] hang', body: old, mode: 'intake' }).ok); - assert.ok(!c.checkIssue({ title: '[Engine] hang', body: old, mode: 'reopen' }).ok); - assert.ok(c.checkIssue({ title: '[Other] idea', body: 'It would help if the app remembered my last model between runs, today I pick it again.', labels: ['enhancement'], mode: 'reopen' }).ok); -}); - -const prBody = (over = {}) => { - const p = { - problem: 'Decode stopped on prompts above 8k because the stop check read the wrong length. Now it continues.', - validation: '**Passed:** `ctest -R decode`, commit abcdef1, RTX 3060, 12 of 12.\n\n**Failed:** none observed\n\n**Not run:** HIP build', - ...over, - }; - return `## Problem and result\n\n${p.problem}\n\n## Related discussion\nnone\n\n## Approach\nFix the length.\n\n## Validation\n${p.validation}\n\n## Limits\nnone`; -}; - -test('filled PR passes', () => { - assert.deepStrictEqual(c.checkPull({ title: '[Engine] fix stop', body: prBody(), mode: 'reopen' }).missing, []); -}); - -test('untouched PR template fails', () => { - const tpl = '## Problem and result\n\n\n## Validation\n\n\n**Passed:**\n\n\n**Failed:**\n\n**Not run:**\n'; - const r = c.checkPull({ title: '[Engine] fix stop', body: tpl }); - assert.ok(!r.ok); - assert.ok(r.missing.some((m) => m.includes('Problem and result'))); - assert.ok(r.missing.some((m) => m.includes('Validation'))); -}); - -test('PR: empty body and bad title', () => { - const r = c.checkPull({ title: 'fix', body: null }); - assert.ok(!r.ok); - assert.ok(r.missing.length >= 2); -}); - -test('PR reopen needs a revision', () => { - const body = prBody({ validation: '**Passed:** I tried it and it worked for me on my machine, looked fine.' }); - assert.ok(c.checkPull({ title: '[Engine] x y', body, mode: 'intake' }).ok); - assert.ok(!c.checkPull({ title: '[Engine] x y', body, mode: 'reopen' }).ok); -}); - -test('free-form PR', () => { - const body = 'This fixes a crash when the context is above 8k, because the length was read from the wrong field. Before it aborted, after it continues. I built it on CUDA and ran the decode test, passed.'; - assert.ok(c.checkPull({ title: '[Engine] fix crash', body }).ok); - assert.ok(!c.checkPull({ title: '[Engine] fix crash', body: 'fixes stuff' }).ok); -}); - -test('messages', () => { - const m = c.intakeComment(false, ['a', 'b']); - assert.ok(m.includes('- [ ] a') && m.includes('/reopen') && m.includes('CONTRIBUTING.md')); - assert.ok(c.staleComment(true).includes('/reopen')); -}); - -// handlers with a fake GitHub client -function fake(calls, extra = {}) { - const rest = { - issues: { - getLabel: async () => ({}), - createLabel: async (a) => calls.push(['createLabel', a.name]), - addLabels: async (a) => calls.push(['addLabels', a.labels]), - removeLabel: async (a) => calls.push(['removeLabel', a.name]), - createComment: async (a) => calls.push(['comment', a.body]), - update: async (a) => calls.push(['update', a.state]), - get: async () => ({ data: extra.live }), - listEvents: async () => {}, - listForRepo: async () => {}, - }, - pulls: { get: async () => ({ data: { mergeable_state: 'clean' } }) }, - }; - return { rest, paginate: async (fn) => (fn === rest.issues.listEvents ? (extra.events || []) : (extra.items || [])) }; -} -const core = { info() {} }; -const repo = { owner: 'o', repo: 'r' }; - -test('intake labels and comments once', async () => { - const calls = []; - const item = { number: 1, title: 'bad', body: '', labels: [], user: { type: 'User' }, author_association: 'NONE' }; - await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'opened', issue: item } }, core }); - assert.deepStrictEqual(calls.map((c) => c[0]), ['addLabels', 'comment']); - calls.length = 0; - item.labels = [{ name: 'needs-format' }]; - await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); - assert.deepStrictEqual(calls, []); -}); - -test('intake clears the label when edited into shape', async () => { - const calls = []; - const item = { number: 1, title: '[Engine] x y', body: bugForm(), labels: [{ name: 'needs-format' }], user: { type: 'User' } }; - await bot.intake({ github: fake(calls), context: { repo, payload: { action: 'edited', issue: item } }, core }); - assert.deepStrictEqual(calls.map((c) => c[0]), ['removeLabel', 'comment']); -}); - -test('reopen: ignores strangers, reopens the author when it passes', async () => { - const issue = { number: 5, state: 'closed', user: { login: 'amy' }, labels: [] }; - let calls = []; - const comment = { body: '/reopen', user: { login: 'bob', type: 'User' }, author_association: 'NONE' }; - await bot.reopen({ github: fake(calls), context: { repo, payload: { issue, comment } }, core }); - assert.deepStrictEqual(calls, []); - - const live = { number: 5, title: '[Engine] x y', body: bugForm(), labels: [] }; - comment.user.login = 'amy'; - await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); - assert.deepStrictEqual(calls.map((c) => c[0]), ['update', 'removeLabel', 'comment']); - assert.strictEqual(calls[0][1], 'open'); - - calls = []; - live.title = 'no prefix'; - await bot.reopen({ github: fake(calls, { live }), context: { repo, payload: { issue, comment } }, core }); - assert.deepStrictEqual(calls.map((c) => c[0]), ['comment']); - assert.ok(calls[0][1].includes('Not reopened')); -}); - -test('sweep closes only old flagged items', async () => { - const calls = []; - const old = new Date(Date.now() - 6 * 86400000).toISOString(); - const fresh = new Date(Date.now() - 1 * 86400000).toISOString(); - const mk = (n, created) => ({ number: n, title: 'bad', body: '', labels: [{ name: 'needs-format' }], created_at: created }); - const gh = fake(calls, { items: [mk(1, old), mk(2, fresh)] }); - await bot.sweep({ github: gh, context: { repo }, core }); - assert.deepStrictEqual(calls.map((c) => c[0]), ['comment', 'update']); -}); diff --git a/engine/strata/.github/scripts/reset-bot.js b/engine/strata/.github/scripts/reset-bot.js deleted file mode 100644 index 11eb63ae..00000000 --- a/engine/strata/.github/scripts/reset-bot.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; -// GitHub-side handlers for intake.yml, reopen.yml and the 5-day sweep. -// They take the actions/github-script objects ({ github, context, core }) and never touch PR code: -// everything comes from the event payload and the REST API. - -const check = require('./item-check'); - -const LABEL = 'needs-format'; -const STALE_DAYS = 5; -const MAINTAINER = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); -// Items a maintainer closed on purpose stay closed. -const BLOCK_LABELS = new Set(['wontfix', 'invalid', 'duplicate', 'declined']); - -function labelNames(item) { - return (item.labels || []).map((l) => (typeof l === 'string' ? l : l.name)); -} - -async function ensureLabel(github, context) { - const { owner, repo } = context.repo; - try { - await github.rest.issues.getLabel({ owner, repo, name: LABEL }); - } catch (e) { - if (e.status !== 404) throw e; - await github.rest.issues.createLabel({ - owner, repo, name: LABEL, color: 'fbca04', - description: 'Title or description does not follow CONTRIBUTING.md yet', - }); - } -} - -async function removeLabel(github, context, number) { - const { owner, repo } = context.repo; - try { - await github.rest.issues.removeLabel({ owner, repo, issue_number: number, name: LABEL }); - } catch (e) { - if (e.status !== 404) throw e; - } -} - -function itemFromPayload(context) { - const p = context.payload; - return p.pull_request || p.issue; -} - -function isPullItem(item, context) { - return Boolean(context.payload.pull_request || item.pull_request); -} - -// issues: opened/edited/reopened, pull_request_target: opened/edited/reopened -async function intake({ github, context, core }) { - const { owner, repo } = context.repo; - const item = itemFromPayload(context); - if (!item || (item.user && item.user.type === 'Bot')) return; - if (MAINTAINER.has(item.author_association) && context.payload.action === 'opened') { - // Maintainer items are not nagged on creation. - return; - } - const isPull = isPullItem(item, context); - const labels = labelNames(item); - const hasLabel = labels.includes(LABEL); - const res = check.checkItem({ isPull, title: item.title, body: item.body, labels, mode: 'intake' }); - core.info('check ' + (isPull ? 'PR' : 'issue') + ' #' + item.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); - - if (res.ok) { - if (hasLabel) { - await removeLabel(github, context, item.number); - await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: 'Thanks, this follows the format now.' }); - } - return; - } - if (context.payload.action === 'edited' && !hasLabel) return; // edits only matter for items already flagged - if (hasLabel) return; // one note only - await ensureLabel(github, context); - await github.rest.issues.addLabels({ owner, repo, issue_number: item.number, labels: [LABEL] }); - await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.intakeComment(isPull, res.missing) }); -} - -// issue_comment created, body starts with /reopen -async function reopen({ github, context, core }) { - const { owner, repo } = context.repo; - const comment = context.payload.comment; - const issue = context.payload.issue; - if (!/^\s*\/reopen\b/.test(comment.body || '')) return; - if (comment.user.type === 'Bot') return; - const isAuthor = comment.user.login === issue.user.login; - const isMaint = MAINTAINER.has(comment.author_association); - if (!isAuthor && !isMaint) { - core.info('ignored /reopen from ' + comment.user.login + ' (not the author or a maintainer)'); - return; - } - const isPull = Boolean(issue.pull_request); - const say = (body) => github.rest.issues.createComment({ owner, repo, issue_number: issue.number, body }); - const labels = labelNames(issue); - const wasOpen = issue.state === 'open'; - - if (labels.some((l) => BLOCK_LABELS.has(l.toLowerCase())) && !isMaint) { - await say('This one was closed on purpose (' + labels.filter((l) => BLOCK_LABELS.has(l.toLowerCase())).join(', ') + '). Please add your new evidence in a comment and a maintainer will decide.'); - return; - } - if (wasOpen && !labels.includes(LABEL)) { - core.info('already open, nothing to do'); - return; - } - - // The bot reads the live item, not the possibly stale event copy. - const live = (await github.rest.issues.get({ owner, repo, issue_number: issue.number })).data; - const res = check.checkItem({ isPull, title: live.title, body: live.body, labels: labelNames(live), mode: 'reopen' }); - core.info('reopen check #' + live.number + ': ' + (res.ok ? 'ok' : res.missing.join(' | '))); - - if (!res.ok) { - await say(check.reopenMissingComment(isPull, res.missing)); - return; - } - if (!wasOpen) { - try { - await github.rest.issues.update({ owner, repo, issue_number: live.number, state: 'open' }); - } catch (e) { - await say('The check passed, but GitHub would not reopen it (' + (e.message || e.status) + '). ' + (isPull ? 'If the branch was deleted, restore it or open a new pull request and link this one.' : 'Please open a new issue and link this one.')); - return; - } - } - await removeLabel(github, context, live.number); - let extra = ''; - if (isPull) { - try { - const pr = (await github.rest.pulls.get({ owner, repo, pull_number: live.number })).data; - if (pr.mergeable_state === 'dirty') extra = '\n\nIt has conflicts with main now: please rebase it.'; - } catch (e) { /* best effort */ } - } - await say(check.reopenOkComment(isPull) + extra); -} - -async function labelTime(github, owner, repo, number, fallback) { - const events = await github.paginate(github.rest.issues.listEvents, { owner, repo, issue_number: number, per_page: 100 }); - let t = null; - for (const e of events) { - if (e.event === 'labeled' && e.label && e.label.name === LABEL) t = e.created_at; - } - return t || fallback; -} - -// scheduled: close items that kept the needs-format label for more than 5 days -async function sweep({ github, context, core }) { - const { owner, repo } = context.repo; - const cutoff = Date.now() - STALE_DAYS * 86400 * 1000; - const items = await github.paginate(github.rest.issues.listForRepo, { owner, repo, state: 'open', labels: LABEL, per_page: 100 }); - core.info(items.length + ' open items with ' + LABEL); - for (const item of items) { - const since = new Date(await labelTime(github, owner, repo, item.number, item.created_at)).getTime(); - if (since > cutoff) continue; - const isPull = Boolean(item.pull_request); - // Re-check first: an edit that fixed it should have cleared the label already; do not close good items. - const res = check.checkItem({ isPull, title: item.title, body: item.body, labels: labelNames(item), mode: 'intake' }); - if (res.ok) { - await removeLabel(github, context, item.number); - continue; - } - await github.rest.issues.createComment({ owner, repo, issue_number: item.number, body: check.staleComment(isPull) }); - await github.rest.issues.update({ owner, repo, issue_number: item.number, state: 'closed', state_reason: 'not_planned' }); - core.info('closed #' + item.number); - } -} - -module.exports = { intake, reopen, sweep, LABEL, STALE_DAYS }; diff --git a/engine/strata/.github/workflows/docker-images.yml b/engine/strata/.github/workflows/docker-images.yml deleted file mode 100644 index e72c8e99..00000000 --- a/engine/strata/.github/workflows/docker-images.yml +++ /dev/null @@ -1,114 +0,0 @@ -name: Docker images - -# Builds the Strata container images of one release from its engine packages and pushes them to ghcr.io. -# Run by hand only (Actions tab -> Docker images -> Run workflow). Nothing starts it on its own. -# -# For each flavor the job downloads the engine package from the release and checks it against the signed update feed -# (docker/fetch-engines.py: the feed's Ed25519 signature, the archive's SHA-256, the manifest hash, the package signature, -# every file's hash), builds the image with docker/build.sh and, only when "push" is on, pushes -# ghcr.io/niko1221/strata:- and ghcr.io/niko1221/strata:latest- -# The first run with "push" off builds everything without publishing it (a dry run). - -on: - workflow_dispatch: - inputs: - release_tag: - description: 'Release tag whose engine packages go into the images (for example v0.2.3)' - required: true - type: string - flavors: - description: 'Flavors to build, comma separated (empty: every flavor the release has a package for)' - required: false - default: '' - type: string - push: - description: 'Push the images to ghcr.io (off: build only, nothing is published)' - required: true - default: false - type: boolean - latest: - description: 'Also move the latest- tags (turn off for a pre-release or a test)' - required: true - default: true - type: boolean - source_ref: - description: 'Git ref of the Dockerfile and the Terminal sources (empty: the release tag)' - required: false - default: '' - type: string - -permissions: - contents: read - -env: - IMAGE: ghcr.io/niko1221/strata - -jobs: - plan: - runs-on: ubuntu-24.04 - outputs: - flavors: ${{ steps.list.outputs.flavors }} - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ inputs.source_ref || inputs.release_tag }} - - name: Which flavors does the release have a package for - id: list - env: - WANT: ${{ inputs.flavors }} - TAG: ${{ inputs.release_tag }} - run: | - set -eu - args="--release-tag $TAG --list --skip-missing" - [ -n "$WANT" ] && args="$args --flavors $WANT" - python3 docker/fetch-engines.py $args > list.tsv - cat list.tsv - flavors=$(awk -F'\t' '$3 != "SKIP" {printf "%s\"%s\"", (n++ ? "," : ""), $1}' list.tsv) - [ -n "$flavors" ] || { echo "the release has no engine package for any requested flavor"; exit 1; } - echo "flavors=[$flavors]" >> "$GITHUB_OUTPUT" - - image: - needs: plan - runs-on: ubuntu-24.04 - timeout-minutes: 120 - permissions: - contents: read - packages: write - strategy: - fail-fast: false - max-parallel: 3 - matrix: - flavor: ${{ fromJSON(needs.plan.outputs.flavors) }} - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ inputs.source_ref || inputs.release_tag }} - - name: Free disk space (the runner has about 14 GB; a package plus its image needs about 10 GB) - run: | - sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL || true - docker system prune -af >/dev/null 2>&1 || true - df -h / - - name: Log in to ghcr.io - if: ${{ inputs.push }} - env: - REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }} - REGISTRY_USER: ${{ github.actor }} - run: printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io -u "$REGISTRY_USER" --password-stdin - - name: Fetch, verify, build (and push when push is on) - env: - TAG: ${{ inputs.release_tag }} - FLAVOR: ${{ matrix.flavor }} - PUSH: ${{ inputs.push && '--push' || '' }} - LATEST: ${{ !inputs.latest && '--no-latest' || '' }} - run: | - docker/publish.sh --release-tag "$TAG" --flavors "$FLAVOR" --image "$IMAGE" $PUSH $LATEST - - name: Summary - if: ${{ always() }} - run: | - { - echo "### ${{ matrix.flavor }}" - echo "- release: ${{ inputs.release_tag }}, pushed: ${{ inputs.push }}" - echo "- image: \`$IMAGE:${INPUT_TAG#v}-${{ matrix.flavor }}\`" - } >> "$GITHUB_STEP_SUMMARY" - env: - INPUT_TAG: ${{ inputs.release_tag }} diff --git a/engine/strata/.github/workflows/intake.yml b/engine/strata/.github/workflows/intake.yml deleted file mode 100644 index 326a0d92..00000000 --- a/engine/strata/.github/workflows/intake.yml +++ /dev/null @@ -1,58 +0,0 @@ -name: Intake - -# New issues and pull requests that do not follow CONTRIBUTING.md get the needs-format label and one friendly note. -# Items that keep the label for 5 days are closed by the daily sweep, with a note on how to /reopen. -# -# pull_request_target is used instead of pull_request on purpose: a pull request from a fork gets a read-only -# GITHUB_TOKEN under pull_request, so it could not be labelled or commented on. It is safe here because this -# workflow never checks out or runs the pull request's code. It checks out the default branch only (the bot -# scripts) and reads the title and description from the event payload and the REST API. - -on: - issues: - types: [opened, edited] - pull_request_target: - types: [opened, edited] - schedule: - - cron: '17 4 * * *' - workflow_dispatch: - -permissions: - contents: read - issues: write - pull-requests: write - -concurrency: - group: intake-${{ github.event.issue.number || github.event.pull_request.number || 'sweep' }} - cancel-in-progress: false - -jobs: - check: - if: github.event_name == 'issues' || github.event_name == 'pull_request_target' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - sparse-checkout: .github/scripts - persist-credentials: false - - uses: actions/github-script@v7 - with: - script: | - const bot = require('./.github/scripts/reset-bot.js'); - await bot.intake({ github, context, core }); - - sweep: - if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - sparse-checkout: .github/scripts - persist-credentials: false - - uses: actions/github-script@v7 - with: - script: | - const bot = require('./.github/scripts/reset-bot.js'); - await bot.sweep({ github, context, core }); diff --git a/engine/strata/.github/workflows/metal-build.yml b/engine/strata/.github/workflows/metal-build.yml deleted file mode 100644 index 7a69696f..00000000 --- a/engine/strata/.github/workflows/metal-build.yml +++ /dev/null @@ -1,51 +0,0 @@ -name: Metal build - -# Compile and link the Metal engine on a macOS runner (no GPU needed: the kernels are compiled at run time). The shared host files -# (src/core/verify.cpp, src/prefill, src/program/generate.cpp) call kernel entry points that exist only for CUDA / HIP until Metal gets a -# stub or an implementation; a missing one is a link error here, not on a user's Mac (owner round 9, G6). - -on: - pull_request: - paths: - - 'src/**' - - 'include/**' - - 'metal/**' - - 'third_party/**' - - 'CMakeLists.txt' - - '.github/workflows/metal-build.yml' - workflow_dispatch: - -permissions: - contents: read - -jobs: - metal-link: - runs-on: macos-14 - timeout-minutes: 45 - env: - # setup.py's LLAMA_CPP_COMMIT and metal/setup_mac.py's metal-cpp pin - LLAMA_CPP_COMMIT: 3cf03257f219afbe7334045ff7c6a06ac68c627d - METAL_CPP_URL: https://developer.apple.com/metal/cpp/files/metal-cpp_26.zip - METAL_CPP_SHA256: 4df3c078b9aadcb516212e9cb03004cbc5ce9a3e9c068fa3144d021db585a3a4 - steps: - - uses: actions/checkout@v4 - - name: Tools - run: brew install ninja - - name: metal-cpp - run: | - curl -fsSL "$METAL_CPP_URL" -o metal-cpp.zip - echo "$METAL_CPP_SHA256 metal-cpp.zip" | shasum -a 256 -c - - unzip -q metal-cpp.zip -d _mcpp - - name: llama.cpp (ggml) at the pinned commit - run: | - mkdir llama.cpp && cd llama.cpp - git init -q - git remote add origin https://github.com/ggml-org/llama.cpp.git - git fetch -q --depth 1 origin "$LLAMA_CPP_COMMIT" - git checkout -q FETCH_HEAD - - name: Configure - run: | - cmake -S metal -B build-metal -G Ninja -DCMAKE_BUILD_TYPE=Release \ - -DMETAL_CPP_DIR="$PWD/_mcpp/metal-cpp" -DSTRATA_GGML_DIR="$PWD/llama.cpp" - - name: Build and link the engine - run: cmake --build build-metal --target strata diff --git a/engine/strata/.github/workflows/reopen.yml b/engine/strata/.github/workflows/reopen.yml deleted file mode 100644 index ff7c10f9..00000000 --- a/engine/strata/.github/workflows/reopen.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Reopen - -# An author comments /reopen on their closed issue or pull request. The check runs and the item is reopened, -# or the bot replies with what is still missing. GitHub does not let authors reopen items a maintainer closed, -# so this workflow does it for them. -# -# issue_comment always runs the workflow file from the default branch with a write-capable token, which is what -# we need for fork authors too. It never checks out or executes the pull request's code: it reads the live -# title and description through the REST API. Only the author of the item or a maintainer can trigger it. - -on: - issue_comment: - types: [created] - -permissions: - contents: read - issues: write - pull-requests: write - -concurrency: - group: reopen-${{ github.event.issue.number }} - cancel-in-progress: false - -jobs: - reopen: - if: startsWith(github.event.comment.body, '/reopen') && github.event.comment.user.type != 'Bot' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - ref: ${{ github.event.repository.default_branch }} - sparse-checkout: .github/scripts - persist-credentials: false - - uses: actions/github-script@v7 - with: - script: | - const bot = require('./.github/scripts/reset-bot.js'); - await bot.reopen({ github, context, core }); diff --git a/engine/strata/.github/workflows/scripts-test.yml b/engine/strata/.github/workflows/scripts-test.yml deleted file mode 100644 index 97b5de9c..00000000 --- a/engine/strata/.github/workflows/scripts-test.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Scripts test - -on: - pull_request: - paths: - - '.github/scripts/**' - - '.github/workflows/intake.yml' - - '.github/workflows/reopen.yml' - -permissions: - contents: read - -jobs: - node-test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 22 - - run: node --test .github/scripts/item-check.test.js diff --git a/engine/strata/.github/workflows/terminal-minimal-server.yml b/engine/strata/.github/workflows/terminal-minimal-server.yml deleted file mode 100644 index e2c75316..00000000 --- a/engine/strata/.github/workflows/terminal-minimal-server.yml +++ /dev/null @@ -1,65 +0,0 @@ -name: Minimal serving runtime - -on: - push: - paths: - - .github/workflows/terminal-minimal-server.yml - - requirements.txt - - strata.py - - strata_cli/** - - strata_control/** - - serve/** - - tests/terminal/test_runtime.py - - tools/minimal_server_smoke.py - - tools/strata_tokenizer.py - pull_request: - paths: - - .github/workflows/terminal-minimal-server.yml - - requirements.txt - - strata.py - - strata_cli/** - - strata_control/** - - serve/** - - tests/terminal/test_runtime.py - - tools/minimal_server_smoke.py - - tools/strata_tokenizer.py - workflow_dispatch: - -permissions: - contents: read - -jobs: - fake-engine: - name: Linux / runtime requirements only - runs-on: ubuntu-latest - timeout-minutes: 20 - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - - uses: actions/setup-python@v7 - with: - python-version: '3.11' - - name: Install only pinned runtime requirements - shell: bash - run: | - python -m venv "$RUNNER_TEMP/strata-runtime-venv" - "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m pip install -r requirements.txt - - name: Check fake-engine serving without terminal packages - shell: bash - run: | - python - <<'PY' - import os - import subprocess - from pathlib import Path - - report = Path(os.environ['RUNNER_TEMP']) / 'minimal-server-smoke.json' - python = str(Path(os.environ['RUNNER_TEMP']) / 'strata-runtime-venv' / 'bin' / 'python') - subprocess.run([python, 'tools/minimal_server_smoke.py', - '--report', str(report)], check=True) - print(report.read_text()) - PY - - name: Run full server suite without terminal packages - shell: bash - run: | - "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m unittest discover -s serve -p 'test_*.py' diff --git a/engine/strata/.github/workflows/terminal-portable-monitor.yml b/engine/strata/.github/workflows/terminal-portable-monitor.yml deleted file mode 100644 index 905e7c40..00000000 --- a/engine/strata/.github/workflows/terminal-portable-monitor.yml +++ /dev/null @@ -1,115 +0,0 @@ -name: Portable monitor client - -on: - push: - paths: - - .github/workflows/terminal-portable-monitor.yml - - packaging/monitor_bundle.py - - strata.py - - strata_cli/** - - strata_control/** - - tools/minimal_cli_smoke.py - - tools/portable_monitor_smoke.py - - tools/portable_monitor_pty_smoke.py - - requirements-monitor.txt - - LICENSE - pull_request: - paths: - - .github/workflows/terminal-portable-monitor.yml - - packaging/monitor_bundle.py - - strata.py - - strata_cli/** - - strata_control/** - - tools/minimal_cli_smoke.py - - tools/portable_monitor_smoke.py - - tools/portable_monitor_pty_smoke.py - - requirements-monitor.txt - - LICENSE - workflow_dispatch: - -permissions: - contents: read - -jobs: - client: - name: ${{ matrix.os }} / Python ${{ matrix.python }} - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest] - python: ['3.10', '3.11'] - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - - uses: actions/setup-python@v7 - with: - python-version: ${{ matrix.python }} - - name: Check source CLI without optional packages - shell: bash - run: | - python - <<'PY' - import os - import subprocess - import sys - from pathlib import Path - - report = Path(os.environ['RUNNER_TEMP']) / 'minimal-cli-smoke.json' - subprocess.run([sys.executable, 'tools/minimal_cli_smoke.py', - '--report', str(report)], check=True) - print(report.read_text()) - PY - - name: Build and smoke test without site packages - shell: bash - run: | - python - <<'PY' - import os - import subprocess - import sys - from pathlib import Path - - bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' - report = bundle.with_name('monitor-stdlib-smoke.json') - subprocess.run([sys.executable, 'packaging/monitor_bundle.py', - 'build', str(bundle)], check=True) - subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', - '--bundle', str(bundle), '--report', str(report)], check=True) - print(report.read_text()) - PY - - name: Install optional Textual dependency - if: matrix.python == '3.11' - run: python -m pip install -r requirements-monitor.txt - - name: Smoke test packaged interactive Overview - if: matrix.python == '3.11' - shell: bash - run: | - python - <<'PY' - import os - import subprocess - import sys - from pathlib import Path - - bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' - report = bundle.with_name('monitor-interactive-smoke.json') - subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py', - '--bundle', str(bundle), '--interactive', - '--report', str(report)], check=True) - print(report.read_text()) - PY - - name: Check POSIX terminal restoration - if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11' - shell: bash - run: | - python - <<'PY' - import os - import subprocess - import sys - from pathlib import Path - - bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz' - report = bundle.with_name('monitor-pty-smoke.json') - subprocess.run([sys.executable, 'tools/portable_monitor_pty_smoke.py', - '--bundle', str(bundle), '--report', str(report)], check=True) - print(report.read_text()) - PY diff --git a/engine/strata/.github/workflows/title-area.yml b/engine/strata/.github/workflows/title-area.yml deleted file mode 100644 index 6c5779f0..00000000 --- a/engine/strata/.github/workflows/title-area.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Title area - -# Checks that a pull request or issue title starts with its area: [Engine], [GUI], [TUI], [Benchmark], [Docs] or [Other]. -# It reads the title only: no checkout, no labels, no comments, no write access. - -on: - pull_request: - types: [opened, edited, reopened, synchronize] - issues: - types: [opened, edited, reopened] - -permissions: {} - -jobs: - title: - runs-on: ubuntu-latest - steps: - - name: Check the title - env: - TITLE: ${{ github.event.pull_request.title || github.event.issue.title }} - run: | - case "$TITLE" in - "[Engine] "?*|"[GUI] "?*|"[TUI] "?*|"[Benchmark] "?*|"[Docs] "?*|"[Other] "?*) - echo "Title OK: $TITLE" ;; - *) - echo "::error::The title must start with its area and then a short description. Allowed areas: [Engine], [GUI], [TUI], [Benchmark], [Docs], [Other]. Example: \"[Engine] fix decode stop on long prompts\". Your title: $TITLE" - exit 1 ;; - esac diff --git a/engine/strata/.gitignore b/engine/strata/.gitignore deleted file mode 100644 index c6cfb336..00000000 --- a/engine/strata/.gitignore +++ /dev/null @@ -1,87 +0,0 @@ -# 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 -/build-strata-cuda12.bat -/build-cuda12/ -/.strata-mcp/ - -# image encoder (setup.py --vision): build output and the generated build script -build-vision*/ -build-vision.bat -build-vision-cuda12.bat - -# setup.py outputs (engine, downloads) and release builds -/engine/ -/engine-sycl/ -/engine-cuda12/ -/build-release*/ -/dist/ -*.done -/third_party/*.zip - -# IDEs -.vscode/ -.idea/ -.cursor/ - -/.ccache/ -/.rocm-win/ - -# local Windows HIP packaging output -dist-hip/ - -# Terminal / Desktop split: local venvs, build output and archives never enter git -.terminal-venv/ -.terminal-test-venv/ -node_modules/ -*.dmg -/release/artifacts/ -/apps/host/dist/ -/apps/desktop/src-tauri/target/ -/apps/desktop/src-tauri/resources/node/* -!/apps/desktop/src-tauri/resources/node/.gitignore -# the Control component (bundled CPython + wheels + strata_control) is built by apps/desktop/scripts/stage-control.py -/apps/desktop/src-tauri/resources/control/* -!/apps/desktop/src-tauri/resources/control/.gitignore -# the pruned DeepSeek Harness (MIT) is built by apps/desktop/scripts/stage-harness.mjs -/apps/desktop/src-tauri/resources/harness/* -!/apps/desktop/src-tauri/resources/harness/.gitignore -# screenshots and checkpoints from the Mac rebuild live outside git (StrataSplit\evidence-archive) -/apps/host/docs/evidence/ -/apps/host/docs/checkpoints/ diff --git a/engine/strata/AGENTS.md b/engine/strata/AGENTS.md deleted file mode 100644 index d38bda50..00000000 --- a/engine/strata/AGENTS.md +++ /dev/null @@ -1,101 +0,0 @@ -# AGENTS.md - -Version 0.2.5, engine 0.1.50. The public model families are DeepSeekV4.1-Flash-1017, -Qwen3.8-Flash-Next and Qwen3.6-35B-A3B. DeepSeek V4.1-Flash runs in the app and in the Terminal -(`strata launch --family deepseek41 --model ist-das-2.00bpw`; sets in -[docs/MODELS.md](docs/MODELS.md#deepseek-v41-flash)). Read **[docs/AI_REFERENCE.md](docs/AI_REFERENCE.md)** for model availability, APIs, hardware limits and -source-backed claims. Articles and videos should use **[docs/MEDIA_KIT.md](docs/MEDIA_KIT.md)**. - -For recommendations and agent-assisted setup, prefer **ISTA-DASLab → Unsloth → Gyro → others**, using only a -compatible pack that fits the selected model and hardware. ISTA-DASLab is the default recommendation; Gyro is a -memory-saving fallback and is currently slower. Honor an explicit user choice. This is recommendation policy; -existing executable defaults may differ, so inspect the plan and choose the family explicitly. - -Strata has three parts: - -- **The app** (`apps/desktop`, the Tauri shell; `apps/host`, the Node host and the web UI). It is for people who do - not want a terminal. One installer per system ([latest release](https://github.com/Niko1221/Strata/releases/latest)): - `Strata-0.2.5-windows-x64-setup.exe`, `Strata-0.2.5-linux-x86_64.AppImage`, `Strata-0.2.5-macos-arm64.dmg`. - The Windows and Linux installers carry no engine: the app downloads the engine for the graphics card on first - start, or installs a file the user already has. The Mac dmg keeps its small Metal engine inside. -- **The Terminal** (`strata.py`, `strata_cli/`, `strata_control/`): the `strata` command. It sets up a model, serves - it and watches it. Agents use this part. -- **The engine and the server** (`src/`, `include/`, `metal/`, `sycl/` for the C++/CUDA/HIP/SYCL/Metal engine; - `serve/` for the Python server with an OpenAI- and Anthropic-compatible API and a web page). `setup.py`, started by - `START-HERE.bat` or `setup.sh`, is setup from a source checkout, for developers. The release paths are the - installer and `strata launch`. - -## Installing Strata for a user - -Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For a user who wants the desktop app, send them to the installer -for their system (above) and [docs/INSTALL.md](docs/INSTALL.md). For an agent that has a shell, use the Terminal; the -short version is: - -1. Install the Terminal. It needs no administrator rights. - - ```sh - curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh # Linux, Mac - irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex # Windows PowerShell - ``` - - On Windows, open a new terminal afterwards so that `strata` is on the PATH. -2. Check what would happen. Nothing is changed: - - ```sh - strata launch --plan --family qwen --model q2_0 - ``` - -3. Set up and serve without questions. It downloads the engine for the card and the model (tens of GB), starts the - server, prints the addresses and returns. The server keeps running. - - ```sh - strata launch --family qwen --model q2_0 --yes --no-tui - ``` - - Useful flags (all of them: `strata launch --help`): `--family`, `--model-path` (files the user already has), - `--data-dir`, `--context 32k|64k|128k`, `--vision off|on|gpu|cpu`, `--parallel N`, `--gpu 0,1`, - `--access local|lan|cloudflare|tailscale`, `--port`, `--api-key-env NAME`, `--new-key`, `--save-preset NAME`, - `--speed faster|full` (DeepSeek), `--output json`. `strata launch --status` shows what is serving, `strata launch --stop` stops it, and - `strata launch --show-key` prints the API key. -4. Connect the user's apps: `strata connect` lists them, `strata connect --check` sends one prompt and one tool - call the way that app does. - -Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). Source setup (`START-HERE.bat`, `setup.sh`) is the fallback for a developer or for a system with no release package; it is -documented in [docs/SOURCE_INSTALL.md](docs/SOURCE_INSTALL.md). Those wrappers exist in a source checkout, not in the -released app. Do not tell an app user to find a `.bat` file. -Source setup does not make an unsupported model or backend compatible. 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). -- The Terminal: [docs/TERMINAL.md](docs/TERMINAL.md) and [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). The app, - the packages and the update feed: [packaging/README.md](packaging/README.md) and [packaging/UPDATES.md](packaging/UPDATES.md). -- AMD (HIP) build and validation: [docs/AMD_HIP.md](docs/AMD_HIP.md); multi-GPU: [docs/MULTI_GPU.md](docs/MULTI_GPU.md); - Mac (Metal): [docs/MAC.md](docs/MAC.md). -- Tests: the Terminal and Control tests are in `tests/terminal` (`python -m pytest tests/terminal`). The app's UI - tests run with `npm test` in `apps/host`. 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, short sentences, written for non-technical users first. Give measured numbers - with what they were measured on. Make no claim without a measurement. - -## Contributing a change or report - -The rules are in **[CONTRIBUTING.md](CONTRIBUTING.md)**. Read it before you open an issue or a pull request, and -follow it whether a person or an agent writes the text. The short version: - -- Start every issue and pull request title with its area: `[Engine]`, `[GUI]`, `[TUI]`, `[Benchmark]`, `[Docs]` or - `[Other]`, for example `[Engine] fix …`. A check on GitHub fails a pull request whose title has no area. -- Search the open and closed issues and pull requests first, and add to a thread that already covers your point. -- Agree the scope in an issue before a large feature, a refactor or a change to a default. -- One problem per pull request. Lead with the problem and the result, then the approach, then the validation - (passed, failed and not run, kept apart) and the limits. -- A new feature is opt-in, and the default path stays byte-identical to the last release. Say how you checked. -- Build every backend a file touches (CUDA, HIP, SYCL) before asking for review. -- Change a default only where you measured it faster, and show the numbers with what they were measured on. -- Never submit measurements, logs or reproduction steps you did not produce. Mark a finding from reading code as - unconfirmed static analysis. -- A report from hardware the maintainers do not have is welcome. Follow - [docs/COMMUNITY_BENCHMARKS.md](docs/COMMUNITY_BENCHMARKS.md), compare against a same-day run of the build you are - testing, and say what you did not test. -- Open test requests and the hardware that is wanted are listed in [docs/TEST_REQUESTS.md](docs/TEST_REQUESTS.md). diff --git a/engine/strata/BENCH.bat b/engine/strata/BENCH.bat deleted file mode 100644 index f54bc90d..00000000 --- a/engine/strata/BENCH.bat +++ /dev/null @@ -1,19 +0,0 @@ -@echo off -rem Benchmark this Strata install the way it is used and write a report you can share (docs/COMMUNITY_BENCHMARKS.md). -rem It starts the model with your settings (or uses the one already running), takes about 10 minutes and changes nothing. -rem Options: --clients 4 (several requests at once), --long (a 32K prompt), --compare . -rem This is the quick speed check. The standard benchmark (docs/BENCHMARK_PROTOCOL.md), whose results other people can compare with, is `strata bench run`. -setlocal -title Strata - benchmark -cd /d "%~dp0" -if not exist ".venv\Scripts\python.exe" ( - echo Strata is not set up here yet: run START-HERE.bat first. - pause - exit /b 1 -) -echo Quick speed check. For results other people can compare with (the standard benchmark, a few minutes), run: .venv\Scripts\python.exe strata.py bench run -echo. -".venv\Scripts\python.exe" tools\strata_bench.py %* -set "RC=%ERRORLEVEL%" -pause -exit /b %RC% diff --git a/engine/strata/CMakeLists.txt b/engine/strata/CMakeLists.txt deleted file mode 100644 index ef1a1aec..00000000 --- a/engine/strata/CMakeLists.txt +++ /dev/null @@ -1,2490 +0,0 @@ -# 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.50 LANGUAGES CXX) -# EXPERIMENTAL: the Intel Arc engine, the SYCL port in sycl/ (PR #423; icpx + oneMKL, docs/INTEL_ARC.md). It is its -# own project that takes the unported sources from src/; with this on, nothing below is configured. -option(STRATA_ENABLE_SYCL "EXPERIMENTAL: build the Intel Arc (SYCL) engine from sycl/ - docs/INTEL_ARC.md" OFF) -if(STRATA_ENABLE_SYCL) - if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) - message(FATAL_ERROR "STRATA_ENABLE_SYCL is a separate backend; leave STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP off") - endif() - message(WARNING "STRATA_ENABLE_SYCL: the Intel Arc engine is experimental (community port, docs/INTEL_ARC.md)") - add_subdirectory(sycl) - return() -endif() -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) -# EXPERIMENTAL, opt-in: an engine for CPUs without AVX2 (#394, #595, #623), compiled on that PC. ggml-cpu, which then -# computes every CPU expert row, is built for this floor instead of AVX2 or the build host: "avx" (Sandy/Ivy Bridge: -# AVX, no FMA/F16C/AVX2) or "none" (SSE4.2 + POPCNT: Nehalem/Westmere). Strata's own AVX2/AVX-512 kernels stay in the -# binary behind their CPU checks; the router lookahead gets an AVX1 kernel. Empty (the default) changes nothing. -set(STRATA_ISA_FLOOR "" CACHE STRING "experimental older-CPU build: empty (default, AVX2 floor), avx, or none (SSE4.2)") -set_property(CACHE STRATA_ISA_FLOOR PROPERTY STRINGS "" avx none) -if(NOT STRATA_ISA_FLOOR STREQUAL "" AND NOT STRATA_ISA_FLOOR STREQUAL "avx" AND NOT STRATA_ISA_FLOOR STREQUAL "none") - message(FATAL_ERROR "STRATA_ISA_FLOOR must be empty, avx or none (got '${STRATA_ISA_FLOOR}')") -endif() -if(STRATA_ISA_FLOOR AND STRATA_PORTABLE) - message(FATAL_ERROR "STRATA_ISA_FLOOR (an older-CPU build) and STRATA_PORTABLE (the AVX2 release build) exclude each other") -endif() -if(STRATA_PORTABLE AND MSVC) - set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") -endif() - -# #3202: Windows hands a program its command line in the system's ANSI code page (cp1251 / cp866 on a Russian Windows, cp1252 on an -# English one), but the engine reads every path as UTF-8 (the run configs and the server write UTF-8). A model folder with -# Cyrillic letters arrived as other bytes, or as "?" where the page has no such letter, and the model did not open. This manifest -# makes the process's ANSI code page UTF-8 (Windows 10 1903 and newer; older Windows ignores it and nothing changes), so the -# command line, fopen and std::ifstream all take UTF-8. -function(strata_utf8_manifest target) - if(MSVC) - target_sources(${target} PRIVATE ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/cmake/strata-utf8.manifest) - endif() -endfunction() - -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) -# AMD gfx906 (MI50, wave64): the same .cu sources compiled as HIP through the gfx906 compat layer. The CUDA runtime and -# cuBLAS names are mapped by the headers in include/strata/platform/hip_compat/, which go first on the include path, -# and CUDA::cudart / CUDA::cublas become aliases of HIP's targets, so every CUDA target below stays as it is. This is -# separate from STRATA_ENABLE_HIP (the wave32 RDNA backend): with it on, STRATA_ENABLE_CUDA is on and -# STRATA_ENABLE_HIP stays off, so every "CUDA" branch of the tree is the one taken. -option(STRATA_HIP_GFX906 "Build the CUDA targets for AMD gfx906 through HIP (wave64 compat layer)" OFF) -if(STRATA_HIP_GFX906) - if(STRATA_ENABLE_HIP) - message(FATAL_ERROR "STRATA_HIP_GFX906 and STRATA_ENABLE_HIP are separate backends; enable only one") - endif() - set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE) -endif() -option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/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 STRATA_HIP_GFX906 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) -# MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K (Unsloth's UD-Q4/Q5/Q6_K_XL experts; on HIP also the dense GGUF -# projections, STRATA_DENSE_MMQ). On by default since MODEL-UPDATE Phase 1: on CUDA they are their own library -# (strata_kq, loaded only for a model with these formats: the engine loads every kernel of its own binary at start, -# CUDA_MODULE_LOADING=EAGER, and these took ~3.8 MB of VRAM - 3 IQ3_XXS expert slots on a P100 - from every model); on -# HIP a code object loads on first use, so they cost other models nothing there (R9700: the same slots). Used at run -# time with STRATA_MMQ_KQ=1 (opt-in: it changes the prompt's rounding against the FP16 path). -option(STRATA_MMQ_TQ_OVERLAY "Gyro trellis MMQ prompt kernels on an upstream llama.cpp: an overlay of its ggml-cuda headers written at configure time (cmake/strata_ggml_tq_overlay.cmake)" ON) -option(STRATA_MMQ_KQUANTS "Build the MMQ prompt kernels for Q4_K / Q5_K / Q5_1 / Q6_K: the experts of Unsloth's K-quant files, and on HIP the dense GGUF projections (STRATA_DENSE_MMQ)" ON) -# Q6_K gate/up in the grouped expert kernels (Unsloth's UD-Q6_K_XL, and layer 2 of UD-Q5_K_XL; docs/QUANTS.md). On by -# default since MODEL-UPDATE Phase 1: one more instance per grouped kernel in iq_kernels.cu, +19 KB of sm_60 code, -# measured to leave every expert-cache slot count as it was (P100, R9700). -DSTRATA_Q6K_EXPERTS=OFF drops it. -option(STRATA_Q6K_EXPERTS "Build the Q6_K gate/up grouped expert kernels (UD-Q6_K_XL, UD-Q5_K_XL)" ON) -if(STRATA_Q6K_EXPERTS) - add_compile_definitions(STRATA_Q6K_EXPERTS=1) -endif() -option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) -# CUDA: the pointer-table MMQ behind STRATA_MMQ_DIRECT=1 (the prompt path's MMQ reads resident experts in their cache -# slots through a Strata-side copy of llama.cpp's MMQ scheduler, src/prefill/moe_mmq_tab.cuh). Off by default, like -# the K-quant options above: the engine loads every kernel when it starts (CUDA_MODULE_LOADING=EAGER), and these nine -# instances (+15 MB of binary) take 36-38 MiB of VRAM per GPU on sm_86 - expert slots every model would lose, with -# STRATA_MMQ_DIRECT unset too. They also add ~70% of the upstream MMQ instances' compile time per CUDA arch (175 s -# of CPU for the nine at sm_86 alone). Off, the build's device code is byte for byte the one without this feature. CUDA -# only (not HIP, not gfx906); switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy -# was verified against. -option(STRATA_MMQ_TAB "Build the pointer-table prompt MMQ for STRATA_MMQ_DIRECT=1 (CUDA; ~37 MiB VRAM per GPU)" 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 AND NOT STRATA_HIP_GFX906) - 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) -# #2027: defined here, before the GPU section reads it to register the native-expert tests (it was defined at the -# native-experts section far below, so a first configure registered four tests fewer than the second) -option(STRATA_NATIVE_EXPERTS "Native (IQ) expert support through ggml-cpu" ON) - -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_split_failure_test src/core/conversation_split_failure_test.cpp) - target_include_directories(conversation_split_failure_test PRIVATE include) - add_test(NAME conversation_split_failure_test COMMAND conversation_split_failure_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) - add_executable(conversation_file_test src/core/conversation_file_test.cpp src/core/conversation_file.cpp) - target_include_directories(conversation_file_test PRIVATE include) - add_test(NAME conversation_file_test COMMAND conversation_file_test) - add_executable(session_save_reclaim_test src/core/session_save_reclaim_test.cpp src/core/conversation_file.cpp) - target_include_directories(session_save_reclaim_test PRIVATE include) - add_test(NAME session_save_reclaim_test COMMAND session_save_reclaim_test) -endif() - -if(STRATA_HIP_GFX906) - if(NOT DEFINED CMAKE_HIP_ARCHITECTURES) - set(CMAKE_HIP_ARCHITECTURES gfx906 CACHE STRING "HIP architectures" FORCE) - endif() - enable_language(HIP) - find_package(hip REQUIRED) - find_package(hipblas REQUIRED) - add_library(CUDA::cudart INTERFACE IMPORTED) - target_link_libraries(CUDA::cudart INTERFACE hip::host) - target_compile_definitions(CUDA::cudart INTERFACE STRATA_HIP_GFX906=1 __HIP_PLATFORM_AMD__=1) - target_include_directories(CUDA::cudart BEFORE INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - add_library(CUDA::cublas INTERFACE IMPORTED) - target_link_libraries(CUDA::cublas INTERFACE roc::hipblas CUDA::cudart) - set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) - add_compile_definitions(STRATA_HIP_GFX906=1) - message(STATUS "Strata: HIP (gfx906 compat) enabled, arch ${CMAKE_HIP_ARCHITECTURES}") - set(_strata_gpu_runtime_target CUDA::cudart) - set(_strata_gpu_blas_target CUDA::cublas) - set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) -elseif(STRATA_ENABLE_CUDA) - # #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the - # DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with - # LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The - # ready-made engine (CUDA 13, no STRATA_EXPERIMENTAL_SM60) is unchanged; -DCMAKE_CUDA_RUNTIME_LIBRARY overrides. - if(MSVC AND STRATA_EXPERIMENTAL_SM60 AND NOT DEFINED CMAKE_CUDA_RUNTIME_LIBRARY) - set(CMAKE_CUDA_RUNTIME_LIBRARY Shared) - endif() - 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() - if(STRATA_EXPERIMENTAL_SM60) - # every target sees it: the Pascal / Volta code paths (the Volta prompt attention, PR #600) are compiled into this - # build only, so the ready-made engine (sm_75+) keeps exactly the code it had - add_compile_definitions(STRATA_EXPERIMENTAL_SM60=1) - endif() - 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 ${STRATA_HIP_BLAS_TARGETS}) - 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) - add_executable(batch_telemetry_test src/core/batch_telemetry_test.cpp) - target_include_directories(batch_telemetry_test PRIVATE include) - add_test(NAME batch_telemetry_test COMMAND batch_telemetry_test) - add_executable(logit_bias_test src/core/logit_bias_test.cpp) - target_include_directories(logit_bias_test PRIVATE include) - add_test(NAME logit_bias_test COMMAND logit_bias_test) - # 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) - # the model families (qwen4exp, qwen35moe): the guards, the geometry from metadata, the layout tables (synthetic) - add_executable(model_family_test tests/core/model_family_test.cpp) - target_link_libraries(model_family_test PRIVATE strata_artifact) - add_test(NAME model_family_test COMMAND model_family_test) - # how --batch cuts a prompt read into pieces (a layer split with no slot decoding must still reach a BYIELD) - add_executable(batch_read_test tests/program/batch_read_test.cpp) - target_include_directories(batch_read_test PRIVATE include) - add_test(NAME batch_read_test COMMAND batch_read_test) - # the model's geometry from its metadata, and the check against the kernels' compiled shape (synthetic) - add_executable(gguf_geometry_test tests/core/gguf_geometry_test.cpp) - target_link_libraries(gguf_geometry_test PRIVATE strata_artifact) - add_test(NAME gguf_geometry_test COMMAND gguf_geometry_test) - - # the hipBLASLt tuning header's architecture gate: RDNA4 siblings share solution IDs, RDNA3 siblings share - # theirs, cross-family pairs and version mismatches stay rejected (synthetic tables: no model, no GPU) - add_executable(tuning_header_arch_family_test tests/prefill/tuning_header_arch_family_test.cpp) - target_include_directories(tuning_header_arch_family_test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") - add_test(NAME tuning_header_arch_family_test COMMAND tuning_header_arch_family_test) - - # the auto layer split's minimum stage size (#1616): header-only rule, no GPU - add_executable(split_rules_test tests/program/split_rules_test.cpp) - target_include_directories(split_rules_test PRIVATE include) - add_test(NAME split_rules_test COMMAND split_rules_test) - - # the prompt planner's host-memory model (#2824): header-only, no GPU - add_executable(prefill_plan_test tests/program/prefill_plan_test.cpp) - target_include_directories(prefill_plan_test PRIVATE include) - add_test(NAME prefill_plan_test COMMAND prefill_plan_test) - - # the default CPU prefill share is not armed when every expert is resident (#1595): header-only rule, no GPU - add_executable(share_rules_test tests/prefill/share_rules_test.cpp) - target_include_directories(share_rules_test PRIVATE include) - add_test(NAME share_rules_test COMMAND share_rules_test) - - # the Windows HIP auto prefill chunk cap (#1630) and the commit-limit verdict (#1607): header-only, no GPU - add_executable(host_limits_test tests/platform/host_limits_test.cpp) - target_include_directories(host_limits_test PRIVATE include) - add_test(NAME host_limits_test COMMAND host_limits_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) - # the DFlash2 drafter (src/core/dflash2.cpp, src/kernels/cuda/dflash2.cu) exists in the CUDA and HIP builds; the Metal and SYCL builds compile without it - target_compile_definitions(strata_core PUBLIC STRATA_HAVE_DFLASH2=1) - 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/s_gemv_pair.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/route_prior.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/dflash2.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() - # Exact gfx1100 prompt scorer (PR1825 method port): optional standalone test, - # also available where the published source omits tests/. - option(STRATA_PARITY_GFX1100_QSA_SCORES "Build the exact gfx1100 QSA score/ID check" OFF) - if(STRATA_ENABLE_HIP AND (STRATA_BUILD_TESTS OR STRATA_PARITY_GFX1100_QSA_SCORES)) - set_source_files_properties(src/kernels/cuda/qsa_scores_gfx1100_test.cu - src/kernels/qsa_scores_gfx1100_parity.cpp PROPERTIES LANGUAGE HIP) - add_executable(qsa_scores_gfx1100_parity src/kernels/qsa_scores_gfx1100_parity.cpp - src/kernels/cuda/qsa_scores_gfx1100_test.cu) - target_include_directories(qsa_scores_gfx1100_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(qsa_scores_gfx1100_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - enable_testing() - add_test(NAME qsa_scores_gfx1100_parity COMMAND qsa_scores_gfx1100_parity --full) - set_tests_properties(qsa_scores_gfx1100_parity PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 180 - ENVIRONMENT "STRATA_SCORES_THREAD=1;STRATA_SCORES_THREAD_TRACE=1") - 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() - # PR #600: the Volta (sm_70) prompt attention's latency pipeline against the FP32 kernel it replaces. Only in the - # experimental sm_60/sm_70 build, where prompt_attn_v70_kernel is compiled in. - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND STRATA_EXPERIMENTAL_SM60) - add_executable(qsa_prompt_attn_sm70_bench bench/qsa_prompt_attn_sm70_bench.cpp) - target_include_directories(qsa_prompt_attn_sm70_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_prompt_attn_sm70_bench PRIVATE strata_kernels CUDA::cudart) - endif() - # #512: the top-k's active-block bound (Turing's dispatch, forced on any card by STRATA_TOPK_ACTIVE_ANY) against - # the capacity rule, selected ids bitwise - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - add_executable(qsa_topk_active_parity src/kernels/qsa_topk_active_parity.cpp) - target_include_directories(qsa_topk_active_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_topk_active_parity PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_topk_active_parity COMMAND qsa_topk_active_parity) - set_tests_properties(qsa_topk_active_parity PROPERTIES SKIP_RETURN_CODE 77) - # STRATA_QSA_SLOTS: a batch window's scores, top-k and attention as one launch over rows of different slots - # against one call per row, bitwise (synthetic, no model) - add_executable(qsa_slots_parity src/kernels/qsa_slots_parity.cpp) - target_include_directories(qsa_slots_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_slots_parity PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_slots_parity COMMAND qsa_slots_parity) - add_test(NAME qsa_slots_parity_lanecell COMMAND qsa_slots_parity) - set_tests_properties(qsa_slots_parity qsa_slots_parity_lanecell PROPERTIES SKIP_RETURN_CODE 77) - set_tests_properties(qsa_slots_parity_lanecell PROPERTIES ENVIRONMENT "STRATA_ATTN_LANECELL=1") - # fork: the Daily's decode attention (STRATA_ATTN_DAILY=1: PR #540's chunk kernel on every card and the bounded - # merge) against upstream's kernels, bitwise; the production entries checked with the variable off and on - add_executable(qsa_merge_daily_parity src/kernels/qsa_merge_daily_parity.cpp) - target_include_directories(qsa_merge_daily_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_merge_daily_parity PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_merge_daily_parity_default COMMAND qsa_merge_daily_parity) - add_test(NAME qsa_merge_daily_parity_daily COMMAND qsa_merge_daily_parity) - set_tests_properties(qsa_merge_daily_parity_default PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=0" - SKIP_RETURN_CODE 77) - set_tests_properties(qsa_merge_daily_parity_daily PROPERTIES ENVIRONMENT "STRATA_ATTN_DAILY=1" - SKIP_RETURN_CODE 77) - # the prompt path's block scores on the thread-per-head kernel (Turing) against the warp kernel, bitwise - add_executable(qsa_scores_parity src/kernels/qsa_scores_parity.cpp) - target_include_directories(qsa_scores_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_scores_parity PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_scores_parity COMMAND qsa_scores_parity) - set_tests_properties(qsa_scores_parity PROPERTIES SKIP_RETURN_CODE 77 ENVIRONMENT "STRATA_SCORES_THREAD=1") - endif() - # QSAROWS (docs/QSAROWS.md): what the T rows of a verification window cost in a QSA layer's decode kernels at a long - # context (block scores, top-k, attention over each row's selection, indexer append), row by row; GPU, synthetic, no - # model. Not in the default build: `cmake --build --target qsa_rows_bench`. - if(STRATA_ENABLE_CUDA) - add_executable(qsa_rows_bench EXCLUDE_FROM_ALL src/kernels/qsa_rows_bench.cpp) - target_include_directories(qsa_rows_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_rows_bench PRIVATE strata_kernels CUDA::cudart) - 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) - # the FP32 tiled scorer (STRATA_SELECT_SIMT=1) on HIP: FP64 gate and selections against the warp kernel at 131K - add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144) - set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_SELECT_SIMT=1") - endif() - # the same on CUDA: the tensor-core scorer (sm_80+) or the FP32 tiled one (below sm_80, and forced on any card by - # STRATA_QSA_WARP=1 in the second test) against the warp kernel and FP64, at 32K and 131K - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - add_executable(qsa_select_bench src/kernels/qsa_select_bench.cpp) - target_include_directories(qsa_select_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(qsa_select_bench PRIVATE strata_kernels CUDA::cudart) - add_test(NAME qsa_select_bench COMMAND qsa_select_bench 32768 256 3 262144) - add_test(NAME qsa_select_bench_fp32_tiled COMMAND qsa_select_bench 131072 256 3 262144) - set_tests_properties(qsa_select_bench_fp32_tiled PROPERTIES ENVIRONMENT "STRATA_QSA_WARP=1;STRATA_SELECT_SIMT=1") - endif() - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # the prompt attention on a recorded selection (STRATA_QSA_DUMP) - add_executable(pa_bench tests/cuda/pa_bench.cpp) - target_include_directories(pa_bench PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) - target_link_libraries(pa_bench PRIVATE strata_kernels CUDA::cudart) - 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/remote_expert_opt.cu - 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/dflash2.cpp - src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp - src/core/arch_defaults.cpp src/core/nv_defaults.cpp src/core/vmm.cpp src/core/conversation_file.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}) - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) - add_executable(host_graph_launch_test tests/core/host_graph_launch_test.cu) - target_include_directories(host_graph_launch_test PRIVATE include) - target_link_libraries(host_graph_launch_test PRIVATE CUDA::cudart Threads::Threads) - add_test(NAME host_graph_launch_test COMMAND host_graph_launch_test) - set_tests_properties(host_graph_launch_test PROPERTIES TIMEOUT 30) - endif() - if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp") - add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp) - target_include_directories(exchange_storage_test PRIVATE include) - target_link_libraries(exchange_storage_test PRIVATE Threads::Threads) - add_test(NAME exchange_storage_test COMMAND exchange_storage_test) - set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60) - endif() - - # available_host_bytes(): MemAvailable, cgroup limits and the operator's --memory-limit-mib cap on fixture directories - # - no GPU, no CUDA - if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/memory_guard_test.cpp") - add_executable(memory_guard_test tests/core/memory_guard_test.cpp src/core/conversation_memory.cpp) - target_include_directories(memory_guard_test PRIVATE include) - add_test(NAME memory_guard_test COMMAND memory_guard_test) - set_tests_properties(memory_guard_test PROPERTIES TIMEOUT 60) - endif() - - 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) - add_executable(vmm_test tests/core/vmm_test.cpp) - target_link_libraries(vmm_test PRIVATE strata_engine) - add_test(NAME vmm_test COMMAND vmm_test) - set_tests_properties(vmm_test PROPERTIES TIMEOUT 60) - # The resident RAM mode with a layer split: the copy keeps each stage's lend region, and the experts the - # prompt path borrows are served from RAM (the file source reads none of them). The device calls are - # wrapped - conversation_transfer_test's pattern - and `pin = false` keeps the copy pageable, so this - # runs on a CPU-only PC. - if(NOT STRATA_ENABLE_HIP AND UNIX AND NOT APPLE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") - add_executable(split_lend_complement_test tests/core/split_lend_complement_test.cpp) - target_link_libraries(split_lend_complement_test PRIVATE strata_engine) - target_link_options(split_lend_complement_test PRIVATE - -Wl,--wrap=cudaMalloc -Wl,--wrap=cudaFree -Wl,--wrap=cudaMemset -Wl,--wrap=cudaMemcpy - -Wl,--wrap=cudaMemcpyAsync -Wl,--wrap=cudaStreamSynchronize -Wl,--wrap=cudaDeviceSynchronize - -Wl,--wrap=cudaGetLastError -Wl,--wrap=cudaGetDevice -Wl,--wrap=cudaSetDevice - -Wl,--wrap=cudaMemGetInfo -Wl,--wrap=cudaHostAlloc -Wl,--wrap=cudaFreeHost) - add_test(NAME split_lend_complement_test COMMAND split_lend_complement_test) - set_tests_properties(split_lend_complement_test PROPERTIES ENVIRONMENT "CUDA_VISIBLE_DEVICES=-1" TIMEOUT 120) - endif() - endif() - # #477: the learned expert profile (--expert-profile-save): its order and make_profile.py's file format (CPU only) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_save_test.cpp") - enable_testing() - add_executable(expert_profile_save_test tests/core/expert_profile_save_test.cpp) - target_link_libraries(expert_profile_save_test PRIVATE strata_engine) - add_test(NAME expert_profile_save_test COMMAND expert_profile_save_test) - set_tests_properties(expert_profile_save_test PROPERTIES TIMEOUT 60) - endif() - # the profile header's version is enforced: a version other than 1 is refused by its number (CPU only) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/expert_profile_version_test.cpp") - enable_testing() - add_executable(expert_profile_version_test tests/core/expert_profile_version_test.cpp) - target_link_libraries(expert_profile_version_test PRIVATE strata_engine) - add_test(NAME expert_profile_version_test COMMAND expert_profile_version_test) - set_tests_properties(expert_profile_version_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) - add_executable(expert_cache_segmented_test tests/core/expert_cache_segmented_test.cpp) - target_link_libraries(expert_cache_segmented_test PRIVATE strata_engine) - add_test(NAME expert_cache_segmented_test COMMAND expert_cache_segmented_test) - set_tests_properties(expert_cache_segmented_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) - # STRATA_MMQ_DIRECT: slot_guard / slot_room / slot_tail on the uniform and the sized cache, and the default - # (no guard) sized layout unchanged - add_executable(expert_cache_slot_guard_test tests/core/expert_cache_slot_guard_test.cpp) - target_link_libraries(expert_cache_slot_guard_test PRIVATE strata_engine) - add_test(NAME expert_cache_slot_guard_test COMMAND expert_cache_slot_guard_test) - set_tests_properties(expert_cache_slot_guard_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=cudaMemcpyAsync -Wl,--wrap=cudaStreamSynchronize - -Wl,--wrap=cudaGetDevice -Wl,--wrap=cudaStreamCreateWithFlags - -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) - if(STRATA_ENABLE_HIP) - # #313: the RDNA3 WMMA GEMMs include hip_runtime.h: AMD builds only (a CUDA build never sees this file) - target_sources(strata_prefill PRIVATE src/prefill/wmma_gemm.cu) - endif() - 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_CUDA) - # v100/gdn-chunk: the chunked Volta GDN prompt recurrence. The dispatch (src/prefill/kernels.cu) is - # Volta-only (cc 7.0) and gated on STRATA_EXPERIMENTAL_SM60; the path itself stays opt-in (STRATA_GDN_CHUNK). - target_sources(strata_prefill PRIVATE src/prefill/gdn_chunk.cu) - endif() - 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() - if(STRATA_ENABLE_HIP AND STRATA_ROCBLAS_AVAILABLE) - # the prompt path's rocBLAS solution table (STRATA_ROCBLAS_TUNING; tools/hip/tune_rocblas makes one) - target_compile_definitions(strata_prefill PRIVATE STRATA_ROCBLAS_AVAILABLE=1) - target_link_libraries(strata_prefill PRIVATE roc::rocblas) - - add_executable(tune_rocblas tools/hip/tune_rocblas.cpp) - target_link_libraries(tune_rocblas PRIVATE hip::host roc::rocblas) - endif() - - # DFlash2 drafter tools (not built by default: cmake --build --target dflash2_parity dflash2_gemm_bench dflash2_attn_bench): the drafter against - # the torch port on a synthetic case (needs the pack and a case file, tools/dflash2/mk_parity_case.py), and the timing of its Q8 GEMM and attention - add_executable(dflash2_parity EXCLUDE_FROM_ALL src/core/dflash2_parity.cpp) - target_include_directories(dflash2_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_parity PRIVATE strata_engine strata_kernels ${_strata_gpu_runtime_target}) - add_executable(dflash2_gemm_bench EXCLUDE_FROM_ALL src/core/dflash2_gemm_bench.cpp) - target_include_directories(dflash2_gemm_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_gemm_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_executable(dflash2_launch_bench EXCLUDE_FROM_ALL src/core/dflash2_launch_bench.cu) - target_include_directories(dflash2_launch_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_launch_bench PRIVATE ${_strata_gpu_runtime_target}) - add_executable(dflash2_bw_bench EXCLUDE_FROM_ALL src/core/dflash2_bw_bench.cu) - target_include_directories(dflash2_bw_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_bw_bench PRIVATE ${_strata_gpu_runtime_target}) - add_executable(dflash2_small_bench EXCLUDE_FROM_ALL src/core/dflash2_small_bench.cpp) - target_include_directories(dflash2_small_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_small_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_executable(dflash2_attn_bench EXCLUDE_FROM_ALL src/core/dflash2_attn_bench.cpp) - target_include_directories(dflash2_attn_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dflash2_attn_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - - add_executable(strata src/program/generate.cpp) - strata_utf8_manifest(strata) - 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(WIN32 AND STRATA_ENABLE_HIP) - # 0.2.1.2: the ROCm math libraries live in \rocm\bin, which is on PATH only when the launcher starts the engine; load them on first - # use (main() adds that folder to the DLL search first) so `strata.exe --version` works from the package folder. amdhip64_7.dll and the - # C++ runtime sit beside the exe (tools/hip/package_windows.py) and stay normal imports. - target_link_libraries(strata PRIVATE delayimp) - target_link_options(strata PRIVATE "LINKER:/DELAYLOAD:hipblas.dll" "LINKER:/DELAYLOAD:libhipblaslt.dll" "LINKER:/DELAYLOAD:rocblas.dll") - endif() - - # NEW-MODELS-PLAN.md T1: Qwen3.6-35B-A3B's reference path (one GPU, the model resident, plain kernels), checked - # against llama.cpp by tools/qwen35/; the engine itself does not run the family yet - add_executable(strata-q36ref src/qwen35/q36ref.cu) - target_include_directories(strata-q36ref PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(strata-q36ref PRIVATE strata_kernels strata_warnings ${_strata_gpu_runtime_target}) - # the engine path for the same family (serve protocol, prompt chunks, decode graph): src/qwen35/q36_engine.cu, a - # library that `strata` switches to for a qwen35moe model (the family switch at the top of its main) and that - # strata-q36 wraps on its own. Not on gfx906 (#3172, #3271): it calls cuBLAS entry points the wave64 compat layer does - # not map (cublasSgemm, cublasGemmStridedBatchedEx) and its kernels assume 32-lane warps; main() guards every use with - # STRATA_HAVE_QWEN35, so a gfx906 build links and runs the Qwen3.8 family, and `strata --families` says so - if(NOT STRATA_HIP_GFX906) - add_library(strata_qwen35 STATIC src/qwen35/q36_engine.cu) - target_include_directories(strata_qwen35 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(strata_qwen35 PRIVATE strata_prefill strata_kernels strata_warnings ${_strata_gpu_runtime_target}) - if(STRATA_NATIVE_EXPERTS) - # the hybrid mode (experts that do not all fit in VRAM): the CPU expert pool on ggml-cpu's arithmetic - target_link_libraries(strata_qwen35 PRIVATE strata_kernels_cpu) - target_compile_definitions(strata_qwen35 PRIVATE STRATA_Q36_CPU_POOL=1) - endif() - add_executable(strata-q36 src/qwen35/q36_main.cpp) - strata_utf8_manifest(strata-q36) - target_link_libraries(strata-q36 PRIVATE strata_qwen35 ${_strata_gpu_runtime_target}) - target_link_libraries(strata PRIVATE strata_qwen35) - target_compile_definitions(strata PRIVATE STRATA_HAVE_QWEN35=1) - endif() - - # DeepSeek-V4.1-Flash: the third engine path (src/dsv41, from Project Maya's maya-ds4, MIT, third_party/project-maya). - # Its own executable for now (strata-dsv41); a family switch in `strata` comes after first light. OFF by default: it - # changes no existing target (the vendored kernels live in strata::dsv41k, so no symbol is shared with strata_kernels). - option(STRATA_BUILD_DSV41 "Build the DeepSeek-V4.1 engine path (strata-dsv41)" OFF) - if(STRATA_BUILD_DSV41 AND NOT STRATA_HIP_GFX906) - add_library(strata_dsv41_kernels STATIC src/dsv41/vendor/exl3.cu src/dsv41/vendor/sampler.cu src/dsv41/vendor/moe_win.cu - src/dsv41/vendor/exl3_cpu.cpp) - if(NOT STRATA_ENABLE_HIP) # (the pre-sm_80 NVIDIA decode kernels exl3.cu dispatches to) - target_sources(strata_dsv41_kernels PRIVATE src/dsv41/vendor/exl3_legacy.cu) - endif() - target_include_directories(strata_dsv41_kernels PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories}) - target_link_libraries(strata_dsv41_kernels PUBLIC ${_strata_gpu_runtime_target}) - add_executable(strata-dsv41 src/dsv41/ds4_main.cpp src/dsv41/ds4_model.cu src/dsv41/ds4_kernels.cu src/dsv41/ds4_vision.cu - src/dsv41/ds4_gguf.cu src/dsv41/ds4_gguf_cpu.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp - src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_packinfo.cpp) - # the commit the binary was built from, readable with --version (set -DSTRATA_BUILD_ID=... for a tree without .git) - if(NOT STRATA_BUILD_ID AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID) # (a git archive has no .git: the packer writes the commit here) - file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/BUILD_ID STRATA_BUILD_ID LIMIT_COUNT 1) - endif() - if(NOT STRATA_BUILD_ID) - execute_process(COMMAND git -C ${CMAKE_CURRENT_SOURCE_DIR} rev-parse --short=9 HEAD OUTPUT_VARIABLE STRATA_BUILD_ID - OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET) - endif() - if(NOT STRATA_BUILD_ID) - set(STRATA_BUILD_ID unknown) - endif() - set_source_files_properties(src/dsv41/ds4_main.cpp PROPERTIES COMPILE_DEFINITIONS "DS4_BUILD_ID=\"${STRATA_BUILD_ID}\"") - target_include_directories(strata-dsv41 PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) - target_link_libraries(strata-dsv41 PRIVATE strata_dsv41_kernels ${_strata_gpu_runtime_target} ${_strata_gpu_blas_target}) - find_package(Threads REQUIRED) - target_link_libraries(strata-dsv41 PRIVATE Threads::Threads) - if(WIN32 AND STRATA_ENABLE_HIP) # cudaMemGetInfo is the DXGI-budgeted hip_compat::mem_get_info (src/core/device.cu): on a Strix Halo the - # carve-out is not all the GPU may use, and the engine sizes its expert tiers by what the budget says is free - target_link_libraries(strata-dsv41 PRIVATE strata_core) - endif() - if(STRATA_NATIVE_EXPERTS) # Strata's CPU trellis kernels (tq_cpu.hpp) for the trellis experts on the CPU lane - target_link_libraries(strata-dsv41 PRIVATE strata_kernels_cpu) - target_compile_definitions(strata-dsv41 PRIVATE STRATA_DSV41_TQ_CPU=1) - endif() - if(STRATA_NATIVE_EXPERTS) - # the CPU lane's ggml-type rows: ggml-cpu's dots against Strata's AVX2 i-quant rows (bits and GB/s); no GPU, no model - add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) - target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) - target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) - target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) - endif() - if(STRATA_NATIVE_EXPERTS) - # the trellis experts (device kernels ds4_tq.cu, CPU lane ds4_tq_cpu.cpp) against a double reference; needs a GPU, no model - # both test .cpp files launch kernels, so they compile as HIP on the AMD backend and as CUDA on the NVIDIA one - if(STRATA_ENABLE_HIP) - set(_ds4_test_lang HIP) - elseif(STRATA_ENABLE_CUDA) - set(_ds4_test_lang CUDA) - else() - set(_ds4_test_lang CXX) - endif() - set_source_files_properties(tests/dsv41/tq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) - add_executable(ds4_tq_test tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp - src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) - target_include_directories(ds4_tq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) - target_link_libraries(ds4_tq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) - target_compile_definitions(ds4_tq_test PRIVATE STRATA_DSV41_TQ_CPU=1) - # the same with the plain-FMA tile instead of the gfx12 WMMA one (what CUDA and gfx11 builds run) - add_executable(ds4_tq_test_portable tests/dsv41/tq_expert_test.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_iq.cu src/dsv41/ds4_tq_cpu.cpp - src/dsv41/ds4_iq_cpu.cpp src/dsv41/ds4_gg_cpu.cpp tools/trellis/tqenc.cpp) - target_include_directories(ds4_tq_test_portable PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) - target_link_libraries(ds4_tq_test_portable PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) - target_compile_definitions(ds4_tq_test_portable PRIVATE STRATA_DSV41_TQ_CPU=1 DS4_TQ_PORTABLE=1) - if(STRATA_ENABLE_HIP) - target_compile_options(ds4_tq_test_portable PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") - endif() - if(STRATA_ENABLE_HIP) - target_compile_options(ds4_tq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") - endif() - # the i-quant experts (ds4_iq.cu) against ggml's own decode of the same blocks + a double reference, device and CPU - # lane, for every type the device takes: the gate a new type (IQ2_XS ..) has to pass before the engine uses it - set_source_files_properties(tests/dsv41/iq_expert_test.cpp PROPERTIES LANGUAGE ${_ds4_test_lang}) - add_executable(ds4_iq_test tests/dsv41/iq_expert_test.cpp src/dsv41/ds4_iq.cu src/dsv41/ds4_iq_cpu.cpp - src/dsv41/ds4_gg_cpu.cpp src/dsv41/ds4_tq.cu src/dsv41/ds4_tq_cpu.cpp) - target_include_directories(ds4_iq_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${_strata_gpu_include_directories} - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml ${CMAKE_CURRENT_SOURCE_DIR}/src/kernels/cpu) - target_link_libraries(ds4_iq_test PRIVATE strata_kernels_cpu ${_strata_gpu_runtime_target} Threads::Threads) - target_compile_definitions(ds4_iq_test PRIVATE STRATA_DSV41_TQ_CPU=1) - if(STRATA_ENABLE_HIP) - target_compile_options(ds4_iq_test PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") - endif() - # the kept conversations' .meta file and prefix matching (ds4_slotmeta.hpp): no GPU, no model - add_executable(ds4_slot_test tests/dsv41/slot_test.cpp) - target_include_directories(ds4_slot_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) - target_compile_features(ds4_slot_test PRIVATE cxx_std_17) - add_executable(ds4_experts_rule_test tests/dsv41/experts_rule_test.cpp) - target_include_directories(ds4_experts_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) - target_compile_features(ds4_experts_rule_test PRIVATE cxx_std_17) - add_executable(ds4_pick_rule_test tests/dsv41/pick_rule_test.cpp) - target_include_directories(ds4_pick_rule_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41) - target_compile_features(ds4_pick_rule_test PRIVATE cxx_std_17) - endif() - if(STRATA_ENABLE_HIP) - foreach(_t strata_dsv41_kernels strata-dsv41) - target_compile_options(${_t} PRIVATE "$<$:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/dsv41/hip_extra.h>") - endforeach() - endif() - endif() - - if(STRATA_ENABLE_HIP) - enable_testing() - set(_strata_hip_tests) - add_executable(hip_prefill_gemm tests/hip/prefill_gemm.cpp) - target_link_libraries(hip_prefill_gemm PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_prefill_gemm COMMAND hip_prefill_gemm) - list(APPEND _strata_hip_tests hip_prefill_gemm) - add_executable(hip_gemm_f16_io_parity tests/hip/gemm_f16_io_parity.cpp) - target_link_libraries(hip_gemm_f16_io_parity PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_gemm_f16_io_parity COMMAND hip_gemm_f16_io_parity) - list(APPEND _strata_hip_tests hip_gemm_f16_io_parity) - add_executable(hip_q2_zero tests/hip/q2_zero.cpp) - target_link_libraries(hip_q2_zero PRIVATE strata_kernels strata_hip_runtime) - add_test(NAME hip_q2_zero COMMAND hip_q2_zero) - list(APPEND _strata_hip_tests hip_q2_zero) - 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() - # Aurora: the prompt GDN recurrence's per-head kernel against the column-split + norm kernels, bitwise - add_executable(hip_gdn_rec_head tests/hip/gdn_rec_head.cpp) - target_link_libraries(hip_gdn_rec_head PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_gdn_rec_head COMMAND hip_gdn_rec_head) - list(APPEND _strata_hip_tests hip_gdn_rec_head) - add_executable(hip_gdn_chunked tests/hip/gdn_chunked.cpp) - target_link_libraries(hip_gdn_chunked PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_gdn_chunked COMMAND hip_gdn_chunked) - add_test(NAME hip_gdn_chunked_off COMMAND hip_gdn_chunked --off) - add_test(NAME hip_gdn_chunked_default COMMAND hip_gdn_chunked --default) - list(APPEND _strata_hip_tests hip_gdn_chunked hip_gdn_chunked_off hip_gdn_chunked_default) - # #313: the RDNA3 / RDNA3.5 WMMA dense GEMMs (opt-in STRATA_WMMA_GEMM=1) against a reference - add_executable(hip_prefill_wmma_gemm_parity tests/hip/prefill_wmma_gemm_parity.cpp) - target_include_directories(hip_prefill_wmma_gemm_parity PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") - target_link_libraries(hip_prefill_wmma_gemm_parity PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_prefill_wmma_gemm_parity COMMAND hip_prefill_wmma_gemm_parity) - set_tests_properties(hip_prefill_wmma_gemm_parity PROPERTIES SKIP_RETURN_CODE 77) # no matrix cores: skipped - list(APPEND _strata_hip_tests hip_prefill_wmma_gemm_parity) - # S (STRATA_HCD_EXACT): the exact HC down kernel against hipBLASLt solution 1176 / 1177 (needs STRATA_HIPBLASLT_TUNING; exit 77 else) - add_executable(hip_prefill_hcd_exact_parity tests/hip/prefill_hcd_exact_parity.cpp) - target_link_libraries(hip_prefill_hcd_exact_parity PRIVATE strata_prefill strata_hip_runtime) - add_test(NAME hip_prefill_hcd_exact_parity COMMAND hip_prefill_hcd_exact_parity) - set_tests_properties(hip_prefill_hcd_exact_parity PROPERTIES SKIP_RETURN_CODE 77) - list(APPEND _strata_hip_tests hip_prefill_hcd_exact_parity) - # the HC write-back kernel timed at the prompt path's shapes with an output checksum (not a ctest; STRATA_GRW_V picks a variant) - add_executable(hip_prefill_gr_write_bench tests/hip/prefill_gr_write_bench.cpp) - target_link_libraries(hip_prefill_gr_write_bench PRIVATE strata_prefill strata_hip_runtime) - # 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_ROCBLAS_AVAILABLE) - # the rocBLAS solution table of the FP16-out prompt GEMMs (gfx103x): opt-in, skips without STRATA_ROCBLAS_TUNING - add_executable(hip_prefill_rocblas_gemm tests/hip/prefill_rocblas_gemm.cpp) - target_include_directories(hip_prefill_rocblas_gemm PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/prefill") - target_link_libraries(hip_prefill_rocblas_gemm PRIVATE strata_prefill strata_hip_runtime roc::rocblas roc::hipblas) - add_test(NAME hip_prefill_rocblas_gemm COMMAND hip_prefill_rocblas_gemm) - set_tests_properties(hip_prefill_rocblas_gemm PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) - list(APPEND _strata_hip_tests hip_prefill_rocblas_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() - if(TARGET hip_prefill_rocblas_gemm) - set_tests_properties(hip_prefill_rocblas_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) - if(STRATA_HIP_GFX906) # the CUDA layout, where the negative control has power (the wave64 one is exact at every T) - add_test(NAME mmvq_multi_parity_cuda_layout COMMAND mmvq_multi_parity) - set_tests_properties(mmvq_multi_parity_cuda_layout PROPERTIES ENVIRONMENT "STRATA_MMVQ_WAVE=0") - endif() - endif() - if(STRATA_ENABLE_CUDA) - # fork F4: the 2-4 column dense projections from the interleaved q8_1 copy, bitwise vs native_mmvq (GPU, synthetic) - add_executable(mmvq_il_parity src/kernels/mmvq_il_parity.cpp) - target_include_directories(mmvq_il_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(mmvq_il_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME mmvq_il_parity COMMAND mmvq_il_parity) - # the wide dequant kernels (a thread per 8 values; sm_61's default), bitwise vs the per-group ones (GPU, synthetic, - # no model; --bench adds old/new timings) - add_executable(dequant_wide_parity src/kernels/dequant_wide_parity.cpp) - target_include_directories(dequant_wide_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(dequant_wide_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME dequant_wide_parity COMMAND dequant_wide_parity) - endif() - # programmatic dependent launch (pdl.hpp) in a captured verify-shaped chain: bitwise vs ordinary launches over - # replays with poisoned buffers, and only kernel-to-kernel programmatic edges (GPU, synthetic, no model; the edges - # are only made on sm_90+, elsewhere it checks that there are none). NVIDIA only: PDL is a CUDA feature. - if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) - add_executable(pdl_parity src/kernels/pdl_parity.cpp) - target_include_directories(pdl_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(pdl_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME pdl_parity COMMAND pdl_parity) - # PDL is opt-in (STRATA_DF_PDL); the test checks the opted-in path, whose PDL capture forces programmatic launches - set_tests_properties(pdl_parity PROPERTIES ENVIRONMENT "STRATA_DF_PDL=1") - 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) - # the Gyro trellis decode kernels (TQ2_T / TQK6 / TQK7) on synthetic blocks: decode-once vs per-column bitwise, output - # checksums to compare two builds byte for byte, --bench for timings (GPU, no model) - add_executable(tq_pascal_bench src/kernels/tq_pascal_bench.cpp) - target_include_directories(tq_pascal_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(tq_pascal_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME tq_pascal_bench COMMAND tq_pascal_bench) - set_tests_properties(iq_multi_parity PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1") # the Q4_K / Q5_K / Q8_0 Split path against the old kernels - # the same Split path on the other routes it can meet: the generic multi kernels (no V2K) and the fused gate/up + SwiGLU kernel, and the sub-16-row - # gate/up route switched off (a K-quant row has 160 dots, not the 80 the sub-16 rows assume: STRATA_KQ_SPLIT=1 must stay bitwise on all of them) - add_test(NAME iq_multi_parity_kq_nov2k COMMAND iq_multi_parity) - set_tests_properties(iq_multi_parity_kq_nov2k PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_EXPERT_V2K=0") - add_test(NAME iq_multi_parity_kq_swiglu COMMAND iq_multi_parity) - set_tests_properties(iq_multi_parity_kq_swiglu PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_GU_SWIGLU=1") - add_test(NAME iq_multi_parity_kq_nosub16 COMMAND iq_multi_parity) - set_tests_properties(iq_multi_parity_kq_nosub16 PROPERTIES ENVIRONMENT "STRATA_KQ_SPLIT=1;STRATA_NO_SUB16_GU=1") - # the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU, - # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) - if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) - # Independent pinned expert uploads: byte parity and stream/event ordering. - add_executable(dma_batch_parity tests/core/dma_batch_parity.cu) - target_include_directories(dma_batch_parity PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_link_libraries(dma_batch_parity PRIVATE ${_strata_gpu_runtime_target}) - add_test(NAME dma_batch_parity COMMAND dma_batch_parity) - set_tests_properties(dma_batch_parity PROPERTIES TIMEOUT 120) - if(WIN32) - add_test(NAME dma_batch_registered_parity COMMAND dma_batch_parity --registered) - set_tests_properties(dma_batch_registered_parity PROPERTIES TIMEOUT 120) - endif() - add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) - target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) - add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity) - # the prompt path's BF16 products against cuBLAS's own BF16 GEMM, within fp32 rounding (sm_7x runs them on the - # FP16 tensor cores; GPU, synthetic, no model; --bench adds timings) - add_executable(gemm_bf16_parity src/prefill/gemm_bf16_parity.cu) - target_link_libraries(gemm_bf16_parity PRIVATE strata_prefill ) - add_test(NAME gemm_bf16_parity COMMAND gemm_bf16_parity) - # Pascal, opt-in STRATA_DENSE_F32=1: the dense projections' FP16 GEMMs as cublasSgemm on FP32 copies, bitwise vs - # the cuBLAS FP16 call over a sweep of chunk sizes (GPU, synthetic, no model; --full sweeps every size, --bench - # adds timings). Not a ctest: whether the two agree is a property of the cuBLAS build, which this checks. - add_executable(gemm_f32_parity src/prefill/gemm_f32_parity.cu) - target_link_libraries(gemm_f32_parity PRIVATE strata_prefill ) - # the hyper-connection read's fused up projection + mix (gr_upmix, STRATA_HC_UPMIX) against cuBLAS + gr_mix_r, - # bitwise where cuBLAS sums K in the same order, else within FP32 rounding and as close to FP64 (GPU, synthetic, - # no model; --bench adds timings) - add_executable(gr_upmix_parity src/prefill/gr_upmix_parity.cu) - target_link_libraries(gr_upmix_parity PRIVATE strata_prefill ) - add_test(NAME gr_upmix_parity COMMAND gr_upmix_parity) - set_tests_properties(gr_upmix_parity PROPERTIES SKIP_RETURN_CODE 77) - endif() - # native_expert_grouped's group stride and fused SwiGLU + q8_1, bitwise vs the launches before them (GPU, synthetic, - # no model; --bench adds v1/new timings of a window's 48 calls in a graph) - add_executable(native_grouped_parity src/kernels/native_grouped_parity.cpp) - target_include_directories(native_grouped_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_grouped_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME native_grouped_parity COMMAND native_grouped_parity) - add_executable(mmvf_rows_parity src/kernels/mmvf_rows_parity.cpp) - target_include_directories(mmvf_rows_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(mmvf_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME mmvf_rows_parity COMMAND mmvf_rows_parity) - set_tests_properties(mmvf_rows_parity PROPERTIES ENVIRONMENT "STRATA_MMVF_ROWS=1" TIMEOUT 120) - if(STRATA_HIP_GFX906) - add_test(NAME native_grouped_fused_parity COMMAND native_grouped_parity) - set_tests_properties(native_grouped_fused_parity PROPERTIES - ENVIRONMENT "STRATA_HIP_SWIGLU_FUSED=1;STRATA_EXP_MODE=7" TIMEOUT 120) - add_executable(gfx906_gdn_rec_head tests/hip/gdn_rec_head.cpp) - target_include_directories(gfx906_gdn_rec_head PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(gfx906_gdn_rec_head PRIVATE strata_prefill ${_strata_gpu_runtime_target}) - add_test(NAME gfx906_gdn_rec_head COMMAND gfx906_gdn_rec_head) - set_tests_properties(gfx906_gdn_rec_head PROPERTIES TIMEOUT 120) - endif() - if(STRATA_ENABLE_CUDA) - # the Volta prompt experts (gemm_iq_f16_grouped, STRATA_PF_WMMA) against a double reference; skipped below sm_70 - add_executable(pf_wmma_parity src/kernels/pf_wmma_parity.cpp) - target_include_directories(pf_wmma_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(pf_wmma_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME pf_wmma_parity COMMAND pf_wmma_parity) - set_tests_properties(pf_wmma_parity PROPERTIES SKIP_RETURN_CODE 77) - endif() - 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) - # the split / batched verify-window kernels (from eddoursul's fork), bitwise vs the kernels they replace; CUDA only - if(STRATA_ENABLE_CUDA) - add_executable(verify_parity src/kernels/verify_parity.cpp) - target_include_directories(verify_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME verify_parity COMMAND verify_parity --selftest) - endif() - add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) - target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_executable(router_chain_bench src/kernels/router_chain_bench.cpp) - target_include_directories(router_chain_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(router_chain_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - # B6: the dense projections' time per verify row at the model's shapes, default vs STRATA_B6_MMVQ_ROWS, bitwise - if(STRATA_ENABLE_CUDA) - add_executable(b6_mmvq_bench src/kernels/b6_mmvq_bench.cpp) - target_include_directories(b6_mmvq_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(b6_mmvq_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() - 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) - - # v100/gdn-chunk: the chunked GDN prompt recurrence vs the token recurrence and a host reference (GPU, - # synthetic, no model). The chunked path changes the summation order - FP32-level, not bit-exact - so the - # test asserts measured error bounds, and --selftest pins them. - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - add_executable(gdn_chunk_parity src/kernels/gdn_chunk_parity.cpp) - target_include_directories(gdn_chunk_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(gdn_chunk_parity PRIVATE strata_prefill ${_strata_gpu_runtime_target}) - add_test(NAME gdn_chunk_parity COMMAND gdn_chunk_parity --selftest) - set_tests_properties(gdn_chunk_parity PROPERTIES SKIP_RETURN_CODE 77) - - # v100/gdn-chunk: the micro benchmark (CUDA events, real GDN shapes): chunked vs recurrent prompt path. - add_executable(gdn_chunk_bench bench/gdn_chunk_bench.cpp) - target_include_directories(gdn_chunk_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(gdn_chunk_bench PRIVATE strata_prefill ${_strata_gpu_runtime_target}) - endif() - - 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 GPU verifier of probabilistic draft acceptance against the host reference (STRATA_SPEC_PROB) - add_executable(spec_verify_parity src/kernels/spec_verify_parity.cpp) - target_include_directories(spec_verify_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(spec_verify_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME spec_verify_parity COMMAND spec_verify_parity) - set_tests_properties(spec_verify_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") - # S19: the decode QSA top-k and the greedy argmax on thread-block clusters (sm_90+) vs the one-CTA kernels, bitwise, - # captured in a graph too (GPU, synthetic, no model; skips below sm_90); --bench: per-call times - if(STRATA_ENABLE_CUDA) - add_executable(decode_cluster_parity src/kernels/decode_cluster_parity.cpp) - target_include_directories(decode_cluster_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(decode_cluster_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME decode_cluster_parity COMMAND decode_cluster_parity --selftest) - endif() - - 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) - - # the verify window's routing in one multi-column BF16 projection + one top-k, bitwise the per-token calls - add_executable(route_window_parity src/kernels/route_window_parity.cpp) - target_include_directories(route_window_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(route_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME route_window_parity COMMAND route_window_parity) - - # STRATA_ROUTE_RESIDENT's swap: the warp-per-token kernel against a scalar reference of the same semantics, - # bitwise on the ids, the weights and the four counters (GPU, synthetic, no model) - add_executable(route_resident_parity src/kernels/route_resident_parity.cu) - target_include_directories(route_resident_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(route_resident_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME route_resident_parity COMMAND route_resident_parity) - set_tests_properties(route_resident_parity PROPERTIES TIMEOUT 120) - - 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) - # #783 PR-c: the multi-token router and the k = 10 float4 combine, bitwise against the single-token contracts - add_executable(native_multi_parity src/kernels/native_multi_parity.cpp) - target_include_directories(native_multi_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME native_multi_parity COMMAND native_multi_parity) - # #783 PR-d: the batched K/V append (INT8, Q4_0, the hybrid fold) against the per-cell appends, memcmp - add_executable(kv_steps_parity src/kernels/kv_steps_parity.cpp) - target_include_directories(kv_steps_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_steps_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_steps_parity COMMAND kv_steps_parity) - # #783 PR-e: the device-built expert plan (parallel grouping + prefix scan) against a host replay of its contract - add_executable(resident_plan_parity src/kernels/resident_plan_parity.cpp) - target_include_directories(resident_plan_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(resident_plan_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME resident_plan_parity COMMAND resident_plan_parity) - # #783 PR-g: the multi-token hyper-connection read/write (exact-T projections under them) against the single-token calls - add_executable(gr_multi_parity src/kernels/gr_multi_parity.cpp) - target_include_directories(gr_multi_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(gr_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME gr_multi_parity COMMAND gr_multi_parity) - # STRATA_HC_PERSIST=1: the persistent hyper-connection read against the default multi read (bounded, two runs bitwise), - # and with the variable unset it never runs (a skip where the card cannot hold its 80 blocks, and on CUDA) - add_executable(hc_persist_parity src/kernels/hc_persist_parity.cpp) - target_include_directories(hc_persist_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(hc_persist_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME hc_persist_parity COMMAND hc_persist_parity) - add_test(NAME hc_persist_default_off COMMAND hc_persist_parity --off) - if(STRATA_HIP_GFX906) - # the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64 - add_executable(hip_router_fast tests/hip/router_fast.cpp) - target_include_directories(hip_router_fast PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(hip_router_fast PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() - - 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) - - # the V100 fusion work: every fused kernel against its unfused pipeline, bitwise, and the before/after - # CUDA-event timings at decode shapes (`--bench`). It is a .cu because it carries the unfused reference - # kernels it compares against. - if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) - add_executable(fusions_parity bench/micro/fusions_parity.cu) - target_include_directories(fusions_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(fusions_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME fusions_parity COMMAND fusions_parity) - endif() - - 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) - - # the QSA top-k the engine dispatches against the original kernel: identical ids on both sides of the register - # kernel's reach, with tied and with equal scores (synthetic, no model) - add_executable(qsa_topk_parity src/kernels/qsa_topk_parity.cpp) - target_include_directories(qsa_topk_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(qsa_topk_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME qsa_topk_parity COMMAND qsa_topk_parity --selftest) - # the register kernel from the smallest prompt batch (the line gfx1151 moves to 4096 blocks): same ids at every case - add_test(NAME qsa_topk_parity_reg_always COMMAND qsa_topk_parity --selftest) - set_tests_properties(qsa_topk_parity_reg_always PROPERTIES ENVIRONMENT "STRATA_TOPK_REG_MIN_BLOCKS=0") - - # ---- 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) - - # #2403: the verify window's KV calls on a streamed layer and on a ring (steps appends with the host copy, batched - # resolve + attention, plain launches and graph replays), q4_0 / int8 / K8V4 (GPU, synthetic, no model). - add_executable(kv_window_parity src/kernels/kv_window_parity.cpp) - target_include_directories(kv_window_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(kv_window_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME kv_window_parity COMMAND kv_window_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) - # the verify window's one-launch forms (hyper-connection write, PLE post-ops with the commit's - # history snapshots) vs the per-token launches they replace, bitwise (GPU, synthetic, no model) - add_executable(verify_batch_parity src/kernels/verify_batch_parity.cpp) - target_include_directories(verify_batch_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(verify_batch_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME verify_batch_parity COMMAND verify_batch_parity) - # #2234: the batch window's one-launch-for-all-rows kernels vs the per-row launches, bitwise (GPU, synthetic) - add_executable(batch_rows_parity src/kernels/batch_rows_parity.cpp) - target_include_directories(batch_rows_parity PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(batch_rows_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - add_test(NAME batch_rows_parity COMMAND batch_rows_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) - - # The pinned-memory headroom (pin_budget.hpp) against a simulated ceiling; skips without a GPU. - add_executable(pin_budget_test src/core/pin_budget_test.cpp) - target_link_libraries(pin_budget_test PRIVATE strata_core ${_strata_gpu_runtime_target}) - add_test(NAME pin_budget_test COMMAND pin_budget_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 - src/spec/draft_source.cpp) -target_include_directories(strata_spec PUBLIC include) -if(STRATA_BUILD_TESTS) - add_executable(arch_defaults_test src/core/arch_defaults_test.cpp src/core/arch_defaults.cpp) - target_include_directories(arch_defaults_test PRIVATE include) - add_test(NAME arch_defaults_test COMMAND arch_defaults_test) - add_executable(adapt_async_default_test src/core/adapt_async_default_test.cpp) - target_include_directories(adapt_async_default_test PRIVATE include) - add_test(NAME adapt_async_default_test COMMAND adapt_async_default_test) - add_executable(uma_cache_test src/core/uma_cache_test.cpp) - target_include_directories(uma_cache_test PRIVATE include) - add_test(NAME uma_cache_test COMMAND uma_cache_test) - 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) - add_executable(spec_start_test src/spec/spec_start_test.cpp) - target_include_directories(spec_start_test PRIVATE include) - add_test(NAME spec_start_test COMMAND spec_start_test) -endif() -if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS) - add_executable(message_boundary_test src/program/message_boundary_test.cpp) - target_include_directories(message_boundary_test PRIVATE include) - add_test(NAME message_boundary_test COMMAND message_boundary_test) - # a layer split's ring override and the lend slots sized with it: the RAM copy must keep every borrowed slot (CPU) - add_executable(split_ring_test src/program/split_ring_test.cpp) - target_include_directories(split_ring_test PRIVATE include) - add_test(NAME split_ring_test COMMAND split_ring_test) - # 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) - # which path computes the draft layer's prompt K/V, and STRATA_SPLIT_MTP_BATCH's parsing (header-only, CPU) - add_executable(draft_kv_plan_test src/program/draft_kv_plan_test.cpp) - target_include_directories(draft_kv_plan_test PRIVATE include) - add_test(NAME draft_kv_plan_test COMMAND draft_kv_plan_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) - # probabilistic draft acceptance (STRATA_SPEC_PROB): rejection sampling preserves p - chi-square over 2M trials per case (CPU) - add_executable(spec_prob_test src/core/spec_prob_test.cpp) - target_include_directories(spec_prob_test PRIVATE include) - add_test(NAME spec_prob_test COMMAND spec_prob_test) - # the per-card window cap of --draft dflash2 (header-only, CPU) - add_executable(draft_cap_test src/core/draft_cap_test.cpp) - target_include_directories(draft_cap_test PRIVATE include) - add_test(NAME draft_cap_test COMMAND draft_cap_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) - # the batch window's row layout (a slot's group of proposed rows, the layer split's hand-off capacity; header-only, CPU) - add_executable(batch_rows_test tests/core/batch_rows_test.cpp) - target_include_directories(batch_rows_test PRIVATE include) - add_test(NAME batch_rows_test COMMAND batch_rows_test) - # how many pipelined slot groups --batch runs with: the 0.1.41 default, and --batch-mtp keeping it serial (header-only, CPU) - add_executable(batch_groups_test src/program/batch_groups_test.cpp) - target_include_directories(batch_groups_test PRIVATE include) - add_test(NAME batch_groups_test COMMAND batch_groups_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 src/kernels/cpu/hadamard.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() -# AVX-VNNI (Alder Lake, Sapphire Rapids and later): the AVX-2 expert kernels' vpdpwssd / vpdpbusd copies (q2_avx2.cpp, -# iq_avx2.cpp; *_rows.inl), taken at run time where cpu_avxvnni_ok(). GCC and Clang compile only those functions with -# target("avxvnni") - never -mavxvnni on a file, which would let the compiler use it anywhere - and MSVC takes the -# intrinsics under /arch:AVX2. A compiler without them (GCC < 11, Clang < 12) builds the files without the copies. -include(CheckCXXSourceCompiles) -if(MSVC) - set(CMAKE_REQUIRED_FLAGS "/arch:AVX2") -else() - set(CMAKE_REQUIRED_FLAGS "-mavx2 -mfma -mf16c") -endif() -check_cxx_source_compiles([=[ -#include -#if defined(__GNUC__) || defined(__clang__) -__attribute__((target("avxvnni"))) -#endif -static __m256i dots(__m256i a, __m256i b) { return _mm256_dpbusd_avx_epi32(_mm256_dpwssd_avx_epi32(a, a, b), a, b); } -int main() { - volatile int x = 1; - return _mm256_extract_epi32(dots(_mm256_set1_epi32(x), _mm256_set1_epi32(x)), 0) == 0; -} -]=] STRATA_HAVE_AVXVNNI_INTRINSICS) -unset(CMAKE_REQUIRED_FLAGS) -if(STRATA_HAVE_AVXVNNI_INTRINSICS) - set(_strata_avxvnni STRATA_AVXVNNI=1) -else() - set(_strata_avxvnni STRATA_AVXVNNI=0) -endif() -set_property(SOURCE src/kernels/cpu/q2_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni}) -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). -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() - # The DeepSeek engine (STRATA_BUILD_DSV41) builds ggml-cpu with BMI2 OFF: ggml's IQ1_S / IQ1_M dots use _pdep_u64 with it, and AMD - # Zen 1/2 run PDEP in microcode (EPYC 7452, IQ1_M one-token dot 1.8 GB/s against 32 GB/s without it; IQ1_S 2.3 against 37). The - # results are bit-identical either way (ds4_gg_bench --dump, types 19 and 29, 1-16 tokens). Other engines keep BMI2 until their - # next rebuild is looked at: no Qwen package changes with this commit. - if(STRATA_BUILD_DSV41) - set(GGML_BMI2 OFF CACHE BOOL "" FORCE) - endif() - elseif(STRATA_ISA_FLOOR) - # the experimental older-CPU build (STRATA_ISA_FLOOR above): one ggml-cpu for the floor, ggml's "sandybridge" - # feature set (SSE4.2 + AVX) or SSE4.2 alone - not the build host's, which may be newer than the PC it runs on. - # From the Strata_Dirigo fork (rwkeyes). ggml's defaults turn the rest on when GGML_NATIVE is off: all off here. - set(GGML_NATIVE OFF CACHE BOOL "" FORCE) - set(GGML_CPU_ALL_VARIANTS OFF CACHE BOOL "" FORCE) - set(GGML_SSE42 ON CACHE BOOL "" FORCE) - if(STRATA_ISA_FLOOR STREQUAL "avx") - set(GGML_AVX ON CACHE BOOL "" FORCE) - else() - set(GGML_AVX OFF CACHE BOOL "" FORCE) - endif() - foreach(_f GGML_AVX2 GGML_FMA GGML_F16C GGML_BMI2 GGML_AVX_VNNI GGML_AVX512 GGML_AVX512_VBMI GGML_AVX512_VNNI - GGML_AVX512_BF16 GGML_AMX_TILE GGML_AMX_INT8 GGML_AMX_BF16) - set(${_f} OFF 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 - src/kernels/cpu/kq_avx1.cpp src/kernels/cpu/q2_avx1.cpp src/kernels/cpu/iq_avx1.cpp - src/kernels/cpu/nvfp4_avx512.cpp src/kernels/cpu/nvfp4_avx2.cpp - src/kernels/cpu/tq_cpu.cpp src/kernels/cpu/tq_avx2.cpp src/kernels/cpu/tq_avx512.cpp) - target_include_directories(strata_kernels_cpu PRIVATE third_party/ggml) - if(MSVC) - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_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") - set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") - set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2") - set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512") - # the router lookahead's AVX1 dot (older CPUs; called behind cpu_avx1_ok): no FMA, no 256-bit integer ops - set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") - # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): 128-bit integer lanes, - # no FMA/F16C, its own #error guard; called only behind cpu_avx1_ok() && !cpu_avx2_ok() - set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") - # the older CPUs' i-quant expert rows (iq_avx1.hpp): 128-bit SSSE3/SSE2 integer, SSE2 float, no FMA/F16C - set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX") - else() - set_source_files_properties(src/kernels/cpu/iq_avx512.cpp src/kernels/cpu/nvfp4_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx512vbmi;-mavx512vpopcntdq;-mbmi2;-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") - set_source_files_properties(src/kernels/cpu/nvfp4_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") - # the trellis kernels: AVX2 + FMA, and AVX-512 F/BW/VL/VBMI/VNNI (exactly what cpu_avx512_ok() checks) - set_source_files_properties(src/kernels/cpu/tq_avx2.cpp PROPERTIES COMPILE_OPTIONS "-mavx2;-mfma;-mf16c") - set_source_files_properties(src/kernels/cpu/tq_avx512.cpp PROPERTIES COMPILE_OPTIONS - "-mavx512f;-mavx512bw;-mavx512vl;-mavx512vnni;-mavx512vbmi;-mavx2;-mfma;-mf16c") - set_source_files_properties(src/kernels/cpu/kq_avx1.cpp PROPERTIES COMPILE_OPTIONS "-mavx") - # the older CPUs' Q2_0 rows and activation quantizer (q2_avx1.cpp, issue #1699): SSE4.2 + AVX with - # AVX2/FMA/F16C explicitly off, so a -march=native build host cannot leak AVX2 code into the file that - # runs on a Sandy Bridge Xeon - set_source_files_properties(src/kernels/cpu/q2_avx1.cpp PROPERTIES COMPILE_OPTIONS - "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") - # the older CPUs' i-quant expert rows (iq_avx1.hpp): SSE4.2 + AVX with AVX2/FMA/F16C explicitly off, so a - # -march=native build host cannot leak AVX2 code into the file that runs on a Sandy Bridge Xeon - set_source_files_properties(src/kernels/cpu/iq_avx1.cpp PROPERTIES COMPILE_OPTIONS - "-msse4.2;-mavx;-mno-avx2;-mno-fma;-mno-f16c") - endif() - set_property(SOURCE src/kernels/cpu/iq_avx2.cpp APPEND PROPERTY COMPILE_DEFINITIONS ${_strata_avxvnni}) - if(STRATA_ISA_FLOOR STREQUAL "avx") - target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_AVX=1) - elseif(STRATA_ISA_FLOOR STREQUAL "none") - target_compile_definitions(strata_kernels_cpu PRIVATE STRATA_ISA_FLOOR_NONE=1) - endif() - target_link_libraries(strata_kernels_cpu PUBLIC ggml-cpu ggml-base) - target_compile_definitions(strata_kernels_cpu PUBLIC STRATA_NATIVE_EXPERTS=1) - if(STRATA_BUILD_TESTS) - # the Q5_1 block dequantizer (a Q5_1 PLE table) against ggml's, synthetic blocks: no model, no GPU - add_executable(dequant_q5_1_test tests/core/dequant_q5_1_test.cpp) - target_link_libraries(dequant_q5_1_test PRIVATE strata_artifact ggml-base) - add_test(NAME dequant_q5_1_test COMMAND dequant_q5_1_test) - endif() - # the router lookahead's dot on each rung this CPU has (AVX2, the older CPUs' AVX1) against a double reference - add_executable(router_dot_parity src/kernels/cpu/router_dot_parity.cpp) - target_link_libraries(router_dot_parity PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_executable(pool_tasks_test src/kernels/cpu/pool_tasks_test.cpp) - target_link_libraries(pool_tasks_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_tasks_test COMMAND pool_tasks_test) - set_tests_properties(pool_tasks_test PROPERTIES TIMEOUT 180) - add_test(NAME router_dot_parity COMMAND router_dot_parity) - add_test(NAME router_dot_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) - endif() - # the AVX-2 expert kernels' variants (iq_avx2.cpp, q2_avx2.cpp) bit for bit against each other at 1..8 tokens and - # against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM - add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp) - target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu) - # the 512-bit i-quant rows against ggml-cpu's dot: the exact rows bit for bit at 1-4 tokens, the engine's multi-token rows to float - # rounding, with the grid lookups as scalar loads and as gathers (SKIP without AVX-512) - add_executable(iq512_gather_parity src/kernels/cpu/iq512_gather_parity.cpp) - target_link_libraries(iq512_gather_parity PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_test(NAME iq512_gather_parity_scalar COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=0 $) - add_test(NAME iq512_gather_parity_gather COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=1 $) - endif() - # MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test) - add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp) - target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity) - add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $) - endif() - # the older CPUs' AVX1 expert rows (iq_avx1.cpp) against ggml-cpu's dots and against their own one-token - # rows at every width; --bench: ms per expert, the weights streamed from DRAM. Runs on any AVX CPU: - # on an AVX2 machine it checks the older-CPU path as an AVX-only machine would run it. - add_executable(iq_avx1_parity src/kernels/cpu/iq_avx1_parity.cpp) - target_link_libraries(iq_avx1_parity PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_test(NAME iq_avx1_parity COMMAND iq_avx1_parity) - endif() - # the AVX-2 Q8_K activation quantizer against ggml's, byte for byte (--bench: its time) - add_executable(q8k_quant_parity src/kernels/cpu/q8k_quant_parity.cpp) - target_link_libraries(q8k_quant_parity PRIVATE strata_kernels_cpu) - if(STRATA_BUILD_TESTS) - add_test(NAME q8k_quant_parity COMMAND q8k_quant_parity) - add_test(NAME q8k_quant_parity_avx COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_ISA=avx $) - endif() - set(_strata_mmq_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) - # APR: the agention llama.cpp fork has MMQ instances for its trellis expert types (f62fdead0); any other ggml - # tree leaves them to the FP16 prompt path - if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/template-instances/mmq-instance-tqk6.cu") - list(APPEND _strata_mmq_types tq2_t tqk6 tqk7) - set(_strata_mmq_tq ON) - elseif(STRATA_MMQ_TQ_OVERLAY AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)) - # an upstream llama.cpp: the trellis MMQ instances come from an overlay of the pinned ggml-cuda headers written at - # configure time (cmake/strata_ggml_tq_overlay.cmake); off with a message if the llama.cpp tree is not the pinned one - if(STRATA_GGML_DIR) - set(_strata_tq_llama "${STRATA_GGML_DIR}") - else() - set(_strata_tq_llama "${strata_llamacpp_SOURCE_DIR}") - endif() - include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/strata_ggml_tq_overlay.cmake) - set(_strata_tq_overlay_dir "${CMAKE_BINARY_DIR}/ggml-tq-overlay") - strata_ggml_tq_overlay("${_strata_tq_llama}" "${_strata_tq_overlay_dir}") - if(STRATA_TQ_OVERLAY_OK) - configure_file(third_party/ggml/ggml-common-tq.h "${_strata_tq_overlay_dir}/ggml-common-tq.h" COPYONLY) - configure_file(src/kernels/cuda/tq_lut_i8.cuh "${_strata_tq_overlay_dir}/tq_lut_i8.cuh" COPYONLY) - set(_strata_mmq_tq ON) - set(_strata_mmq_tq_overlay ON) - message(STATUS "trellis MMQ (Gyro prompts): overlay on the pinned ggml-cuda in ${_strata_tq_overlay_dir}") - if(STRATA_BUILD_TESTS) - add_test(NAME ggml_tq_overlay COMMAND ${CMAKE_COMMAND} -DLLAMA=${_strata_tq_llama} - -DOUT=${CMAKE_BINARY_DIR}/ggml-tq-overlay-test -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/ggml_tq_overlay_test.cmake) - endif() - endif() - endif() - # #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) - set(_strata_quantize_cu ${_strata_mmq}/quantize.cu) # the overlay's copy when the trellis overlay is on: it includes mmq.cuh - if(_strata_mmq_tq_overlay) - set(_strata_quantize_cu ${_strata_tq_overlay_dir}/quantize.cu) - endif() - # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA - # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable) - add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu - src/prefill/mmq_nvfp4_w4a8.cu - src/prefill/ggml_cuda_host.cu ${_strata_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 q6_k, the experts of Unsloth's UD-Q4/Q5/Q6_K_XL (docs/QUANTS.md; the dispatch - # follows eddoursul/Strata 7706c1b). MODEL-UPDATE Phase 1: on CUDA they are a library of their own, strata_kq - # (below), loaded only for a model with these experts: the engine loads every kernel of its own binary at start - # (CUDA_MODULE_LOADING=EAGER), and these four took ~3.8 MB of VRAM (3 expert slots of IQ3_XXS on a P100) from every - # model. gfx906 (HIP: code objects load on first use) keeps them in strata_mmq. - set(_strata_mmq_cuda_types ${_strata_mmq_types}) - set(_strata_kq_types q4_k q5_k q5_1 q6_k) - set(_strata_kq_dso OFF) - if(STRATA_MMQ_KQUANTS AND STRATA_HIP_GFX906) - list(APPEND _strata_mmq_cuda_types ${_strata_kq_types}) - elseif(STRATA_MMQ_KQUANTS) - set(_strata_kq_dso ON) - endif() - foreach(_t IN LISTS _strata_mmq_cuda_types) - target_sources(strata_mmq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) - endforeach() - if(_strata_mmq_tq_overlay) - foreach(_t tq2_t tqk6 tqk7) - target_sources(strata_mmq PRIVATE ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) - endforeach() - # first on the include path: the patched mmq.cuh / ggml.h shadow the pinned ones for this target only - target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) - endif() - # NVFP4: W4A8 (default) in mmq_nvfp4_w4a8.cu with the plain architectures; the opt-in W4A4 needs RTX 50's FP4 MMA, - # which exists only in the arch-specific target, so its one unit alone is built with 12x -> 12xa (the default - # binary is unchanged and runs on sm_121; a card without that image falls back to W4A8 at run time) - set(_strata_w4a4_archs ${CMAKE_CUDA_ARCHITECTURES}) - # (two steps: CMake before 3.29 rejects a \2 whose optional group did not match, "120" alone) - list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])$" "\\1a") - list(TRANSFORM _strata_w4a4_archs REPLACE "^(12[0-9])-(real|virtual)$" "\\1a-\\2") - add_library(strata_mmq_w4a4 STATIC src/prefill/mmq_nvfp4_w4a4.cu) - set_target_properties(strata_mmq_w4a4 PROPERTIES CUDA_ARCHITECTURES "${_strata_w4a4_archs}") - target_include_directories(strata_mmq_w4a4 PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}) - target_compile_options(strata_mmq_w4a4 PRIVATE $<$:--extended-lambda -use_fast_math>) - if(MSVC) - target_compile_options(strata_mmq_w4a4 PRIVATE $<$:-Xcompiler=/bigobj>) - endif() - target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target}) - target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4) - # STRATA_MMQ_TAB: the pointer-table copy of MMQ's scheduler mirrors mmq.cuh from mul_mat_q_process_tile through - # mul_mat_q_case (struct mmq_args included). A fingerprint of that text instead of a compile probe: nothing is - # compiled at configure time, and a llama.cpp tree with another scheduler turns the feature off instead of - # failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the - # fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh). - set(_strata_mmq_tab_on OFF) - if(STRATA_MMQ_TAB AND NOT STRATA_HIP_GFX906) # gfx906 compiles no .cu from here (its HIP glob): no tab at all - set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0) - set(_strata_mmq_tab_hash "") - if(EXISTS ${_strata_mmq}/mmq.cuh) - file(READ ${_strata_mmq}/mmq.cuh _strata_mmq_src) - string(REPLACE "\r\n" "\n" _strata_mmq_src "${_strata_mmq_src}") - string(FIND "${_strata_mmq_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _strata_tab_a) - string(FIND "${_strata_mmq_src}" "#define DECL_MMQ_CASE" _strata_tab_b) - if(_strata_tab_a GREATER -1 AND _strata_tab_b GREATER _strata_tab_a) - math(EXPR _strata_tab_len "${_strata_tab_b} - ${_strata_tab_a}") - string(SUBSTRING "${_strata_mmq_src}" ${_strata_tab_a} ${_strata_tab_len} _strata_tab_region) - string(SHA256 _strata_mmq_tab_hash "${_strata_tab_region}") - endif() - unset(_strata_mmq_src) - unset(_strata_tab_region) - endif() - if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known) - set(_strata_mmq_tab_on ON) - else() - message(STATUS "STRATA_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_mmq_tab_hash})") - endif() - endif() - if(_strata_mmq_tab_on) - set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh) - # the native packs' nine types, the ones prefill_mmq_tab_test checks bit for bit; the optional Q5_0 / K-quant - # instances (STRATA_ORCA_Q4KS_MMQ, STRATA_MMQ_KQUANTS) get no pointer table and keep the gather - set(_strata_mmq_tab_types q2_0 iq2_xxs iq2_xs iq2_s iq3_xxs iq3_s iq4_nl iq4_xs q8_0) - foreach(_t IN LISTS _strata_mmq_tab_types) - string(TOUPPER ${_t} _strata_tab_T) - configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY) - target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu) - endforeach() - target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1) - message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_tab_types}") - endif() - 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() - # GGML's CUDA error reporting calls cuGetErrorString from the driver API. - target_link_libraries(strata_mmq PUBLIC ggml-base ${_strata_gpu_runtime_target}) - if(TARGET CUDA::cuda_driver) # not in the HIP (gfx906) build, whose CUDA::cudart is a stand-in - target_link_libraries(strata_mmq PUBLIC CUDA::cuda_driver) - endif() - if(STRATA_MMQ_KQUANTS) - target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_KQUANTS=1) - endif() - if(_strata_kq_dso) - # strata_kq: the K-quant MMQ instances with their own copy of ggml_cuda_host.cu's symbols and the static CUDA - # runtime, next to the engine (libstrata_kq.so / strata_kq.dll); moe_mmq.cu opens it when a model asks for one - # of these formats (STRATA_MMQ_KQ=1). Without the file the engine runs them on the FP16 prompt path, as before. - target_compile_definitions(strata_mmq PRIVATE STRATA_KQ_DSO=1) - target_sources(strata_mmq PRIVATE src/prefill/mmq_kq_loader.cpp) - if(NOT WIN32) - target_link_libraries(strata_mmq PUBLIC ${CMAKE_DL_LIBS}) - endif() - add_library(strata_kq SHARED src/prefill/mmq_kq_lib.cu src/prefill/ggml_cuda_host.cu) - foreach(_t IN LISTS _strata_kq_types) - target_sources(strata_kq PRIVATE ${_strata_mmq}/template-instances/mmq-instance-${_t}.cu) - endforeach() - target_include_directories(strata_kq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} - ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_compile_options(strata_kq PRIVATE $<$:--extended-lambda -use_fast_math>) - if(MSVC) - target_compile_options(strata_kq PRIVATE $<$:-Xcompiler=/bigobj>) - endif() - set_target_properties(strata_kq PROPERTIES CUDA_RUNTIME_LIBRARY Static POSITION_INDEPENDENT_CODE ON - CXX_VISIBILITY_PRESET hidden CUDA_VISIBILITY_PRESET hidden) - # ggml-base is static: position-independent so a shared library can hold it (the same code otherwise) - set_target_properties(ggml-base PROPERTIES POSITION_INDEPENDENT_CODE ON) - target_link_libraries(strata_kq PRIVATE ggml-base) - if(TARGET CUDA::cuda_driver) - target_link_libraries(strata_kq PRIVATE CUDA::cuda_driver) - endif() - add_dependencies(strata_mmq strata_kq) - endif() - if(STRATA_ORCA_Q4KS_MMQ) - target_compile_definitions(strata_mmq PRIVATE STRATA_ORCA_Q4KS_MMQ=1) - endif() - if(_strata_mmq_tq) - target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=1) - endif() - target_link_libraries(strata_prefill PUBLIC strata_mmq) - target_compile_definitions(strata_prefill PUBLIC STRATA_PREFILL_MMQ=1 STRATA_PREFILL_FUSED=1) - if(STRATA_BUILD_TESTS) - # #136: the fused int8 experts against a double-precision reference and the MMQ path (exit 77 below sm_80) - add_executable(prefill_fused_moe_test tests/cuda/prefill_fused_moe_test.cpp) - target_link_libraries(prefill_fused_moe_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_fused_moe_test COMMAND prefill_fused_moe_test) - set_tests_properties(prefill_fused_moe_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - # #136: the same for the native packs' formats (IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL) - add_executable(prefill_fused_iq_test tests/cuda/prefill_fused_iq_test.cpp) - target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) - set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) - # the MoE input quantized per token and scattered to its rows (mmq::quantize_scatter) against the per-row - # gather: the same q8_1 bytes for every MMQ layout (--bench: both at 2K, 8K and 32K tokens) - add_executable(prefill_mmq_scatter_test tests/cuda/prefill_mmq_scatter_test.cpp) - target_link_libraries(prefill_mmq_scatter_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_mmq_scatter_test COMMAND prefill_mmq_scatter_test) - set_tests_properties(prefill_mmq_scatter_test PROPERTIES TIMEOUT 120) - endif() - if(STRATA_BUILD_TESTS AND _strata_mmq_tab_on) - # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) - add_executable(prefill_mmq_tab_test tests/cuda/prefill_mmq_tab_test.cu) - target_link_libraries(prefill_mmq_tab_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) - add_test(NAME prefill_mmq_tab_test COMMAND prefill_mmq_tab_test) - set_tests_properties(prefill_mmq_tab_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) - endif() - 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) - # the K-quant MMQ is opt-in at run time (STRATA_MMQ_KQ=1), and on CUDA it is strata_kq next to the test - set_tests_properties(prefill_mmq_kquant_test PROPERTIES TIMEOUT 120 ENVIRONMENT STRATA_MMQ_KQ=1) - endif() - # the NVFP4 expert products (w4a8 / w4a4, STRATA_PREFILL_NVFP4) against a double-precision reference - add_executable(mmq_nvfp4_parity src/prefill/mmq_nvfp4_parity.cpp) - target_link_libraries(mmq_nvfp4_parity PRIVATE strata_mmq ggml-base CUDA::cudart) - if(NOT MSVC) # its FP16 rounding helper uses the F16C intrinsics (GCC/Clang need the target flag) - target_compile_options(mmq_nvfp4_parity PRIVATE $<$:-mf16c>) - endif() - # the routed-expert products (MMQ) timed at the prompt path's shapes (16 experts a launch) - add_executable(mmq_expert_bench src/prefill/mmq_expert_bench.cpp) - target_link_libraries(mmq_expert_bench PRIVATE strata_mmq ggml-base CUDA::cudart) - 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") - set(_strata_quantize_cu "${_strata_mmq}/quantize.cu") # the overlay's copy when the trellis overlay is on: it includes mmq.cuh - if(_strata_mmq_tq_overlay) - set(_strata_quantize_cu "${_strata_tq_overlay_dir}/quantize.cu") - endif() - 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() - # Aurora: moe_fused.cu's gfx11 and moe_fused_iq.cu's gfx11 / gfx12 WMMA kernels for the prompt experts (opt-in STRATA_PF_FUSED=1) - set(_strata_mmq_sources - src/prefill/moe_mmq.cu - src/prefill/moe_fused.cu - src/prefill/moe_fused_iq.cu - src/prefill/moe_f16_kq.cu - src/prefill/ggml_cuda_host.cu - "${_strata_quantize_cu}") - if(STRATA_MMQ_KQUANTS) - # the same K-quant instances as the CUDA branch: on HIP they serve the dense GGUF projections - # of Gemm::native (STRATA_DENSE_MMQ=1), the mixed-quant packs' attention/PLE tensors - list(APPEND _strata_mmq_types q4_k q5_k q5_1 q6_k) - endif() - foreach(_t IN LISTS _strata_mmq_types) - list(APPEND _strata_mmq_sources "${_strata_mmq}/template-instances/mmq-instance-${_t}.cu") - endforeach() - if(_strata_mmq_tq_overlay) - foreach(_t tq2_t tqk6 tqk7) - list(APPEND _strata_mmq_sources "${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu") - endforeach() - endif() - set_source_files_properties(${_strata_mmq_sources} PROPERTIES LANGUAGE HIP) - # moe_fused.cu is Strata's own CUDA-shaped source: it takes the HIP compat headers, ggml's MMQ sources do not - set_source_files_properties(src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu src/prefill/moe_f16_kq.cu - PROPERTIES INCLUDE_DIRECTORIES "${STRATA_HIP_COMPAT_INCLUDE_DIR}") - 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) - if(_strata_mmq_tq_overlay) - target_include_directories(strata_mmq BEFORE PRIVATE ${_strata_tq_overlay_dir} ${_strata_tq_overlay_dir}/include) - endif() - target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP=1) - 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() - if(_strata_mmq_tq) - target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TQ=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 STRATA_PREFILL_FUSED=1) - # Aurora: the gfx11 fused experts against the FP64 reference and MMQ (tests/cuda's test; exit 77 off gfx11) - add_executable(hip_prefill_fused_moe tests/cuda/prefill_fused_moe_test.cpp) - target_include_directories(hip_prefill_fused_moe PRIVATE "${_strata_gg}/include") - target_link_libraries(hip_prefill_fused_moe PRIVATE strata_mmq ggml-base strata_hip_runtime) - add_test(NAME hip_prefill_fused_moe COMMAND hip_prefill_fused_moe) - set_tests_properties(hip_prefill_fused_moe PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) - list(APPEND _strata_hip_tests hip_prefill_fused_moe) - add_executable(hip_prefill_fused_iq tests/cuda/prefill_fused_iq_test.cpp) - target_include_directories(hip_prefill_fused_iq PRIVATE "${_strata_gg}/include") - target_link_libraries(hip_prefill_fused_iq PRIVATE strata_mmq ggml-base strata_hip_runtime) - add_test(NAME hip_prefill_fused_iq COMMAND hip_prefill_fused_iq) - set_tests_properties(hip_prefill_fused_iq PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) - # the same binary on F16 weights (gfx11: the covered formats take moe_f16_kq.cu / native_f16_kernel; elsewhere it is the default run again) - add_test(NAME hip_prefill_fused_iq_f16 COMMAND hip_prefill_fused_iq) - set_tests_properties(hip_prefill_fused_iq_f16 PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600 ENVIRONMENT "STRATA_PF_F16=1;STRATA_PF_F16_KQ=1") - list(APPEND _strata_hip_tests hip_prefill_fused_iq) - - # 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() - # the NVFP4 AVX-512 and AVX2 rows vs ggml-cpu's vec_dot, and their speed (CPU only; optional arg: a pack's experts.bin) - add_executable(nvfp4_avx512_parity src/kernels/cpu/nvfp4_avx512_parity.cpp) - target_link_libraries(nvfp4_avx512_parity PRIVATE strata_kernels_cpu) - add_test(NAME nvfp4_cpu_parity COMMAND nvfp4_avx512_parity) # random blocks; the AVX2 rows bit-equal to ggml's - set_tests_properties(nvfp4_cpu_parity PROPERTIES TIMEOUT 120) - if(STRATA_ENABLE_CUDA) # the NVFP4 decode kernels vs ggml's reference - add_executable(nvfp4_expert_gpu_parity src/kernels/nvfp4_expert_gpu_parity.cpp) - target_link_libraries(nvfp4_expert_gpu_parity PRIVATE strata_kernels ggml-base CUDA::cudart) - # the decode experts' weight bandwidth on random blobs of a format pair, and an output hash (bit-for-bit checks) - add_executable(nvfp4_decode_bench src/kernels/nvfp4_decode_bench.cpp) - target_link_libraries(nvfp4_decode_bench PRIVATE strata_kernels CUDA::cudart) - 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}) - # strata_engine: the --load-check mode runs the engine's start-up checks (NativeDense, check_experts_gguf) - target_link_libraries(native_expert_parity PRIVATE strata_engine strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) - add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) - target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) - # MODEL-UPDATE: the dense Q8_0 GEMVs at the engine's shapes against the memory bandwidth (a benchmark, no test) - add_executable(q8_gemv_bench src/kernels/q8_gemv_bench.cpp) - target_include_directories(q8_gemv_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(q8_gemv_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - if(STRATA_ENABLE_CUDA) - # EXPDEC (docs/EXPERTDEC.md): the grouped experts' default kernels against STRATA_EXPDEC=1 at T = 1..4, bit for bit - # and in microseconds, on synthetic blobs read cold from DRAM - add_executable(expdec_bench EXCLUDE_FROM_ALL src/kernels/expdec_bench.cpp) - target_include_directories(expdec_bench PRIVATE ${_strata_gpu_include_directories}) - target_link_libraries(expdec_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) - endif() - 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. - # q4_K/q5_0 and q5_0/q8_0: a plain llama-quantize "_M" tier GGUF (not Unsloth's dynamic method) commonly - # puts Q5_0 on down-projections (sometimes gate/up too) where this model's native_experts.txt had no GPU - # kernel for it before; q5_0/q5_0 (both roles Q5_0) is left out of this list since stacking the same - # lower-precision format on both roles pushes the GPU path over this test's 3% threshold (quantization - # noise, not a kernel bug -- see the PR). - # q4_0/q4_0 and q4_0/q4_1: a plain llama-quantize Q4_0 file (bartowski's Qwen3.8-Flash-Next-Q4_0: gate/up Q4_0, - # down Q4_0 on 42 layers and Q4_1 on 6) - # q6_K/q8_0: Unsloth UD-Q6_K_XL gate/up Q6_K with Q8_0 down (docs/UNSLOTH_Q6.md). Layer 2 is q8_0/q8_0, already listed. - set(_strata_parity_pairs q4_K/q5_1 q4_K/q8_0 q5_K/q8_0 q8_0/q8_0 q4_K/q5_0 q5_0/q8_0 q4_0/q4_0 q4_0/q4_1) - if(STRATA_Q6K_EXPERTS) - list(APPEND _strata_parity_pairs q6_K/q8_0) - else() # 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() - foreach(_pair ${_strata_parity_pairs}) - 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) - # APR: the trellis expert types and the Hadamard activation rotation, when ggml comes from the agention fork - # (the only tree with these types; marked by its ggml-cuda/tq.cuh) - if(STRATA_GGML_DIR AND EXISTS "${STRATA_GGML_DIR}/ggml/src/ggml-cuda/tq.cuh") - foreach(_pair tqk6/tqk7 tq2_t/tq2_t) - string(REPLACE "/" "_" _name "${_pair}") - add_test(NAME native_expert_parity_${_name} COMMAND native_expert_parity --synthetic ${_pair}) - add_test(NAME native_expert_parity_hadamard_${_name} COMMAND native_expert_parity --synthetic-hadamard ${_pair}) - set_tests_properties(native_expert_parity_${_name} native_expert_parity_hadamard_${_name} PROPERTIES TIMEOUT 300) - endforeach() - endif() - # #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) - 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) - if(WIN32) - add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_test.cpp) - target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_affinity_test COMMAND pool_affinity_test) - elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") - add_executable(pool_affinity_test src/kernels/cpu/pool_affinity_linux_test.cpp) - target_link_libraries(pool_affinity_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_affinity_test COMMAND pool_affinity_test) - endif() - # 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) - set_tests_properties(expert_multi_test PROPERTIES SKIP_RETURN_CODE 77) # no AVX-512: skipped - - # PR #706: the opt-in AVX-2 Q2_0 bit-plane kernel (STRATA_Q2_BITPLANE=1) against the legacy one, bitwise alone/window - if(STRATA_BUILD_TESTS AND CMAKE_SYSTEM_PROCESSOR MATCHES "AMD64|x86_64|x64|X86") - add_executable(q2_bitplane_parity src/kernels/cpu/q2_bitplane_parity.cpp) - target_link_libraries(q2_bitplane_parity PRIVATE strata_kernels_cpu) - add_test(NAME q2_bitplane_parity COMMAND q2_bitplane_parity) - set_tests_properties(q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") - endif() - - if(STRATA_NATIVE_EXPERTS) - # APR port: a Hadamard-folded trellis expert (TQ2_T / TQK6 / TQK7) on the CPU path vs llama.cpp's graph for the - # same weights (synthetic; needs STRATA_GGML_DIR = a ggml with the trellis types, else it reports and fails) - add_executable(native_hadamard_test src/kernels/cpu/native_hadamard_test.cpp) - target_link_libraries(native_hadamard_test PRIVATE strata_kernels_cpu strata_artifact) - add_test(NAME native_hadamard_test COMMAND native_hadamard_test) - set_tests_properties(native_hadamard_test PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) - # the CPU trellis kernels (tq_cpu.hpp): AVX2 / AVX-512 vs the scalar kernel bit for bit, vs ggml-cpu's vec_dot - # and to_float, plain and with the Hadamard rotation; `tq_cpu_parity --bench` is the micro-benchmark - add_executable(tq_cpu_parity src/kernels/cpu/tq_cpu_parity.cpp) - target_link_libraries(tq_cpu_parity PRIVATE strata_kernels_cpu) - add_test(NAME tq_cpu_parity COMMAND tq_cpu_parity) - add_test(NAME tq_cpu_parity_avx2 COMMAND ${CMAKE_COMMAND} -E env STRATA_FORCE_AVX2=1 $) - set_tests_properties(tq_cpu_parity tq_cpu_parity_avx2 PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) - endif() - - 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}) - # where the workers are placed (one per physical core by default) and --pool-cores (real pools, no model) - add_executable(pool_cores_test src/kernels/cpu/pool_cores_test.cpp) - target_link_libraries(pool_cores_test PRIVATE strata_kernels_cpu) - add_test(NAME pool_cores_test COMMAND pool_cores_test) - # the default CPU expert worker count on mock CPUs (8c/16t, 16c/32t, 64c/128t, 2-socket 128c/256t, ...) - add_executable(pool_plan_test src/kernels/cpu/pool_plan_test.cpp) - target_include_directories(pool_plan_test PRIVATE include) - add_test(NAME pool_plan_test COMMAND pool_plan_test) - # 0.2.2: when the pool splits per NUMA node by itself (a fake sysfs node folder, mock cores; STRATA_NUMA_POOL=0, one node = unchanged) - add_executable(numa_pool_test src/kernels/cpu/numa_pool_test.cpp) - target_include_directories(numa_pool_test PRIVATE include) - target_compile_features(numa_pool_test PRIVATE cxx_std_17) - add_test(NAME numa_pool_test COMMAND numa_pool_test) - # #3204: when the HIP start-up warm-up of hipBLAS may run (pure policy, no GPU) - add_executable(warm_policy_test src/prefill/warm_policy_test.cpp) - target_include_directories(warm_policy_test PRIVATE include) - add_test(NAME warm_policy_test COMMAND warm_policy_test) - # 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) - - # #795: nothing an AVX2-only CPU can reach may hold AVX-512 / AVX-VNNI-class instructions. (1) the linked test binary - # (every CPU kernel file plus ggml-cpu; on Linux, the kernel library) is disassembled and any function with such instructions must be a kernel of - # a wide-ISA file, not a weak / COMDAT copy and not a probe or helper that every CPU runs; (2) with -DSTRATA_SDE= - # (Intel SDE) the CPU tests run on an emulated AVX2-only Haswell and on an Alder Lake (AVX-VNNI, no AVX-512): SDE stops - # at the first instruction the chip does not have. - if(TARGET iq_avx2_parity) - find_package(Python3 QUIET COMPONENTS Interpreter) - if(Python3_Interpreter_FOUND) - if(MSVC) - target_link_options(iq_avx2_parity PRIVATE /MAP) - add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py - $ --map $/iq_avx2_parity.map) - else() - # the library, not the binary: a Linux source build compiles ggml-cpu for the build machine on purpose - add_test(NAME isa_guard_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/check_isa_guard.py - $) - endif() - set_tests_properties(isa_guard_check PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) - endif() - endif() - set(STRATA_SDE "" CACHE FILEPATH "Intel SDE (sde / sde64): also run the CPU tests on an emulated AVX2-only and an AVX-VNNI-only CPU") - if(STRATA_SDE AND TARGET iq_avx2_parity) - foreach(_chip hsw adl) - foreach(_t iq_avx2_parity q8k_quant_parity router_dot_parity pool_tasks_test q2_bitplane_parity) - if(TARGET ${_t}) - add_test(NAME sde_${_chip}_${_t} COMMAND ${STRATA_SDE} -${_chip} -- $) - set_tests_properties(sde_${_chip}_${_t} PROPERTIES TIMEOUT 900) - endif() - endforeach() - if(TARGET q2_bitplane_parity) - set_tests_properties(sde_${_chip}_q2_bitplane_parity PROPERTIES ENVIRONMENT "STRATA_Q2_BITPLANE=1") - endif() - endforeach() - endif() - - 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() - # --aux-cpus: the CPU-set derivation (pure) and the placement of live threads; header-only, no GPU - add_executable(aux_cpus_test tests/platform/aux_cpus_test.cpp) - target_include_directories(aux_cpus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) - target_link_libraries(aux_cpus_test PRIVATE Threads::Threads) - add_test(NAME aux_cpus_test COMMAND aux_cpus_test) -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() - -# ---- HIP gfx906: every CUDA source of the tree (and the ggml-cuda MMQ sources) is compiled as HIP ---- -if(STRATA_HIP_GFX906) - file(GLOB_RECURSE _strata_cu CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/*.cu - ${CMAKE_CURRENT_SOURCE_DIR}/tools/vision/*.cu) - if(_strata_mmq) - file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu) - list(APPEND _strata_cu ${_strata_mmq_cu}) - target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP) - # #3172: strata_mmq_w4a4 is built from llama.cpp's headers too; without GGML_USE_HIP its common.cuh took the CUDA vendor header - # (cuda.h, cuda_bf16.h: not found). Here it only reports that W4A4 (RTX 50's FP4 MMA) is not available. - if(TARGET strata_mmq_w4a4) - target_compile_definitions(strata_mmq_w4a4 PRIVATE GGML_USE_HIP) - endif() - # #3271: three more link errors of a 0.1.44+ gfx906 build, all sources that strata_mmq lists but the glob above never saw: - # the trellis overlay's quantize.cu and instances (they are generated into the build tree, so the glob missed them: CMake drops a - # .cu source whose language is not enabled) and moe_f16_kq.cu, which moe_fused_iq.cu calls (a stub here: no gfx11 device code, so - # f16kq::covers() answers false and the int8 kernels run, as on every other card) - if(_strata_mmq_tq_overlay) - set(_strata_tq_hip ${_strata_tq_overlay_dir}/quantize.cu) - foreach(_t tq2_t tqk6 tqk7) - list(APPEND _strata_tq_hip ${_strata_tq_overlay_dir}/template-instances/mmq-instance-${_t}.cu) - endforeach() - list(APPEND _strata_cu ${_strata_tq_hip}) - endif() - target_sources(strata_mmq PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_f16_kq.cu) - endif() - set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) -endif() - -if(STRATA_HIP_GFX906) - add_executable(gfx906_qsa_query_swizzle_probe bench/gfx906_qsa_query_swizzle_probe.cpp) - target_link_libraries(gfx906_qsa_query_swizzle_probe PRIVATE strata_kernels ${_strata_gpu_runtime_target}) -endif() - -# ---- DeepSeek-V4.1 on a box with no GPU toolkit ------------------------------------------------ -# The whole DSV41 block above lives inside if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP), so with neither backend on -# -DSTRATA_BUILD_DSV41=ON was silently unused and the host-side benchmark could not be built at all (found on p1004, -# 2026-10-23: the CPU lane is exactly what a box without a usable GPU needs to measure). This branch builds the one target -# that has no device code, so the CPU-lane A/B runs anywhere. -if(STRATA_BUILD_DSV41 AND NOT STRATA_ENABLE_CUDA AND NOT STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) - message(STATUS "STRATA_BUILD_DSV41: no GPU backend, building the host-side benchmark only (ds4_gg_bench)") - if(STRATA_NATIVE_EXPERTS) - add_executable(ds4_gg_bench tests/dsv41/gg_dot_bench.cpp src/dsv41/ds4_gg_cpu.cpp) - target_include_directories(ds4_gg_bench PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src/dsv41 - ${CMAKE_CURRENT_SOURCE_DIR}/third_party/ggml) - target_link_libraries(ds4_gg_bench PRIVATE strata_kernels_cpu Threads::Threads) - target_compile_definitions(ds4_gg_bench PRIVATE STRATA_DSV41_TQ_CPU=1) - endif() -endif() diff --git a/engine/strata/CONTRIBUTING.md b/engine/strata/CONTRIBUTING.md deleted file mode 100644 index 4efd7dd6..00000000 --- a/engine/strata/CONTRIBUTING.md +++ /dev/null @@ -1,122 +0,0 @@ -# Contributing to Strata - -**AI assistance is welcome. The contributor is responsible for understanding the change and supplying real evidence.** - -These rules apply to issues, pull requests, benchmark reports, and the agents helping prepare them. -You should be able to explain every changed line and answer review questions about it. - -## Before starting - -1. Search [issues](https://github.com/Niko1221/Strata/issues) and - [pull requests](https://github.com/Niko1221/Strata/pulls), including closed discussions. Add new evidence to an - existing thread when it covers your problem. -2. Read [AGENTS.md](AGENTS.md) and the documentation for the component you want to change. -3. Get maintainer agreement on scope before substantial features, refactors, architecture changes, or changes to - defaults. Describe the user problem, proposed behavior, and tradeoffs in an issue first. Agreement on scope - does not guarantee a merge. Focused fixes and benchmark reports can go straight to a PR. -4. Keep one problem per PR. Update that PR after feedback; do not open competing attempts for the same change. - -Do not resubmit a declined proposal under a different title or through another agent. If new evidence changes -the situation, bring it to the original discussion and let a maintainer decide whether to reopen it. - -## Report a problem people can investigate - -Use the matching [issue form](https://github.com/Niko1221/Strata/issues/new/choose). A bug report should include: - -- The smallest steps or command that reproduce the problem, and the expected and actual behavior. -- Strata version or commit, OS, GPU and VRAM, and relevant model, quantization, and configuration. -- The exact error and relevant logs, with credentials and private content removed. -- Whether you reproduced it yourself. Label a finding based only on reading code or a scanner as - **unconfirmed static analysis**, and explain the suspected path without presenting it as an observed failure. - -Do not invent reproduction steps, errors, affected hardware, or severity. If you cannot reproduce something, -say what you inspected and what would verify the hypothesis. Feature requests should explain a concrete user -need and the current workaround. Questions should say what you tried and where you got stuck. - -Example structure, with placeholders to replace with actual observations: - -```text -Problem: -Environment: -Reproduce: -Expected: -Actual: -Evidence: -Reproduction status: -``` - -## Titles - -Every issue and pull request title starts with its area in square brackets, then a short description: `[Engine]`, `[GUI]`, `[TUI]`, -`[Benchmark]`, `[Docs]` or `[Other]`. For example `[Engine] fix decode stop on long prompts` or `[GUI] keep the model list after a tab -switch`. The issue forms ask for the area and a check on the title fails when the prefix is missing. - -## Prepare a focused pull request - -Lead with the problem and resulting behavior. Explain why the approach is needed, the important limits, and -any compatibility effects. Link the issue and scope agreement when applicable. A file-by-file narration or -an AI-generated summary of the diff is not a substitute for this explanation. - -- Keep unrelated formatting, cleanup, dependency changes, and speculative abstractions out of the PR. -- Add documentation where it changes what a user or developer needs to know. Avoid repeated summaries, - speculative roadmaps, and generated documentation with no actionable information. -- Preserve existing behavior outside the intended change. New features are opt-in; follow the default-path - and performance requirements in [AGENTS.md](AGENTS.md). -- Read the complete diff, including generated files, before submitting. Remove debugging output, secrets, - private paths, and accidental files. -- Prefer a small relevant regression check over tests that only restate the implementation. Documentation-only - changes need link, example, and consistency checks; they do not require GPU builds. - -## Show the validation you actually performed - -List exact commands, the revision and environment tested, and observed outcomes. Keep **passed**, **failed**, -and **not run** separate. Include relevant output or a log attachment. A command you suggest running is not -evidence that it passed; a CI run on a different revision is not validation of the submitted code. - -Build every backend a code change touches, including CUDA, HIP, and SYCL where applicable, before requesting -review. For changes that need hardware execution, report that execution separately from compilation. A mock, -static check, or successful build does not establish hardware correctness. If you lack a required environment, -keep the PR as a draft, identify the missing checks, and ask for targeted help in the same thread. Do not claim -compatibility you have not tested. - -Performance claims need before/after runs on the same hardware and workload, with every changed setting -identified. Preserve the individual runs, failures, and variability. Follow the -[community measurement guide](docs/COMMUNITY_BENCHMARKS.md); standard submissions will use the -[benchmark protocol](docs/BENCHMARK_PROTOCOL.md) once it is activated. One fast run does not justify changing a -default or claiming a speedup for other machines. - -Example PR body; placeholders are not test results: - -```text -Problem and result: -Related discussion: -Approach: -Validation: - Passed: - Failed: - Not run: -Limits: -``` - -## Rules for AI-assisted work - -Use agents to help investigate, implement, and explain work that you can review. Before submitting, verify -their claims against the source, actual command output, or a cited primary reference. - -Never submit fabricated measurements, invented test results, fake logs, or copied claims you have not checked. -Do not turn a repository scan into a batch of speculative issues or PRs. Consolidate related findings, establish -their effect, and submit the useful evidence. Do not present an agent's confidence or another model's approval -as validation. Keep review replies concise and address the requested change or evidence directly. - -Maintainers may request a smaller change, return a PR to draft, or close a submission that lacks evidence, -duplicates existing work, or ignores agreed scope. A smaller, understandable contribution with honest limits -is easier to review and maintain. - -## Share a benchmark - -A results-only PR should contain the human report, raw measurements, sanitized configuration, and supporting -logs. Keep it separate from engine changes and include poor results and failed requests. - -The [current community benchmark guide](docs/COMMUNITY_BENCHMARKS.md) remains available for measurements made -with today's tools. The [new protocol](docs/BENCHMARK_PROTOCOL.md) defines the draft standard and future approval -workflow. Its draft status must remain visible: existing reports are not automatically standard or approved. diff --git a/engine/strata/Dockerfile b/engine/strata/Dockerfile deleted file mode 100644 index 82f096cf..00000000 --- a/engine/strata/Dockerfile +++ /dev/null @@ -1,110 +0,0 @@ -# Strata, built FROM SOURCE (NVIDIA CUDA 13). The engine is compiled here, packaged as an engine component package and then -# installed into the same runtime image as the ready-made ones (docker/Dockerfile): same Terminal, same entrypoint, same /data volume. -# -# Most people want the ready-made images instead (nothing compiled): docs/DOCKER.md. -# -# docker build -t strata:src . # RTX 20/30/40/50 (compiles for each, ~25 min) -# docker build -t strata:src --build-arg CUDA_ARCHITECTURES=86 . # one card only (faster); 86 = RTX 30, 89 = RTX 40, 120 = RTX 50 -# docker build -t strata:src-cuda12 --build-arg CUDA_IMAGE=nvidia/cuda:12.9.1-devel-ubuntu24.04 \ -# --build-arg CUDA_ARCHITECTURES="60;61;70;75;80;86;89" --build-arg BUILD_VISION=0 . # GTX 10 / P100 / V100 (driver 575+) -# docker run --rm --gpus all -p 127.0.0.1:8080:8080 --ulimit memlock=-1 --shm-size 2g --stop-timeout 120 \ -# -v strata-data:/data -e MODEL=IQ3_XXS -e API_KEY=change-me-please-123 strata:src -# -# docker build has no GPU, so the CUDA architectures are given here instead of read from nvidia-smi. The engine is a fat binary with -# a machine-code part per listed architecture (plus PTX for the newest, which later cards can JIT), and the runtime picks the one -# matching your card. Narrow CUDA_ARCHITECTURES to your card for a faster build. Native code for the CPU that builds the image is NOT -# used (STRATA_PORTABLE=ON), so the image runs on any x86-64 CPU with AVX2. -# -# Plain legacy-builder features only (no heredocs, no --mount). AMD (HIP) and Intel (SYCL) source builds: docs/AMD_HIP.md, docs/INTEL.md. - -ARG CUDA_IMAGE=nvidia/cuda:13.0.0-devel-ubuntu24.04 -ARG RUNTIME_BASE=ubuntu:24.04 - -# ---- 1. compile the engine and make its component package -FROM ${CUDA_IMAGE} AS engine-build -ENV DEBIAN_FRONTEND=noninteractive PYTHONUNBUFFERED=1 PATH=/venv/bin:$PATH -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential ca-certificates git libgomp1 libatomic1 python3 python3-pip python3-venv unzip \ - && rm -rf /var/lib/apt/lists/* -WORKDIR /src -COPY . . -ARG CUDA_ARCHITECTURES="75;80;86;89;120" -ARG BUILD_VISION=1 -ARG ENGINE_VERSION= -RUN python3 -m venv /venv && /venv/bin/pip install --no-cache-dir -r requirements.txt -r requirements-build.txt -# llama.cpp at the pinned commit (ggml for the engine, mtmd for pictures), exactly as setup.py fetches it -RUN /venv/bin/python -c "import setup; print(setup.get_llama_cpp())" -RUN set -e; \ - real=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do real="$real;${a}-real"; done; real=${real#;}; \ - last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ - sm60=OFF; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do if [ "$a" -lt 75 ]; then sm60=ON; fi; done; \ - /venv/bin/cmake -G Ninja -S . -B build -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_CUDA=ON -DSTRATA_BUILD_TESTS=OFF \ - -DSTRATA_EXPERIMENTAL_SM60=$sm60 \ - -DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_PORTABLE=ON -DSTRATA_Q6K_EXPERTS=ON -DSTRATA_MMQ_KQUANTS=ON \ - "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual" -DSTRATA_GGML_DIR=/src/third_party/llama.cpp; \ - /venv/bin/cmake --build build --target strata strata_kq -j "$(nproc)"; \ - if [ "$BUILD_VISION" = "1" ]; then \ - /venv/bin/cmake -G Ninja -S tools/vision -B build-vision -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=/src/third_party/llama.cpp \ - -DSTRATA_VISION_CUDA=ON -DSTRATA_PORTABLE=ON -DGGML_CUDA_NCCL=OFF "-DCMAKE_CUDA_ARCHITECTURES=${real};${last}-virtual"; \ - /venv/bin/cmake --build build-vision --target strata-vision -j "$(nproc)"; \ - fi -RUN set -e; \ - mkdir -p /stage /engine; \ - cp build/strata /stage/; \ - [ -f build/libstrata_kq.so ] && cp build/libstrata_kq.so /stage/ || true; \ - [ -f build-vision/bin/strata-vision ] && cp build-vision/bin/strata-vision /stage/ || true; \ - ver="${ENGINE_VERSION:-$(sed -n 's/^[[:space:]]*project([^)]*VERSION[[:space:]]*\([0-9][0-9.]*\).*/\1/p' CMakeLists.txt | head -1)}"; \ - cudafull=$(nvcc --version | sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' | head -1); cudamajor=${cudafull%%.*}; \ - if [ "$cudamajor" = 13 ]; then mindriver=580.65; else mindriver=575.51; fi; \ - vision_archs=""; [ -f /stage/strata-vision ] && vision_archs=", \"vision_archs\": \"$CUDA_ARCHITECTURES\""; \ - echo "{\"version\": \"$ver\", \"source\": \"docker build\", \"archs\": \"$CUDA_ARCHITECTURES\", \"cuda\": \"$cudafull\", \"portable\": true${vision_archs}}" > /stage/BUILD.json; \ - python3 packaging/collect_libs.py --binary build/strata --search /usr/local/cuda/lib64 --out /stage --also 'libcublasLt.so*'; \ - archs=""; for a in $(echo "$CUDA_ARCHITECTURES" | tr ';,' ' '); do archs="$archs --arch sm_$a"; done; \ - last=$(echo "$CUDA_ARCHITECTURES" | tr ';,' ' ' | awk '{print $NF}'); \ - python3 packaging/package_engine.py --src /stage --backend cuda --version "$ver" --out /engine $archs --arch "compute_$last" \ - --min-driver nvidia=$mindriver --variant cuda$cudamajor --platform linux-x86_64 --build-id "docker-source-${ver}-cuda${cudafull}" --include SYSTEM-LIBS.txt --include 'libstrata_kq*' \ - --include strata-vision; \ - for d in /engine/*/; do python3 packaging/package_engine.py --verify "$d"; python3 packaging/binary_deps.py "$d"; done - -# ---- 2. the Terminal (the release archive, built here) -FROM ${RUNTIME_BASE} AS terminal -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && apt-get install -y --no-install-recommends python3 ca-certificates git && rm -rf /var/lib/apt/lists/* -COPY . /src/ -RUN python3 /src/packaging/package_terminal.py --out /out --cache /cache \ - && mkdir -p /opt/strata \ - && tar -xzf /out/strata-terminal-*-linux-x86_64.tar.gz -C /opt/strata \ - && mv /opt/strata/strata-terminal-* /opt/strata/terminal \ - && /opt/strata/terminal/bin/strata --version -# llama.cpp at the commit setup.py pins: fetched here, so the first start does not depend on GitHub. Only gguf-py (the model preparation -# tools) and the file setup.py looks for (ggml/CMakeLists.txt) are kept: 170 MB become a few -RUN cd /opt/strata/terminal && STRATA_CONTROL_INSTALL=1 STRATA_INSTALL_DIR=/opt/strata/seed PYTHONNOUSERSITE=1 \ - /opt/strata/terminal/python/bin/python3 -c "import setup; print(setup.get_llama_cpp())" \ - && rm -rf /opt/strata/seed/third_party/*.zip* \ - && cd /opt/strata/seed/third_party/llama.cpp \ - && find . -mindepth 1 -maxdepth 1 ! -name gguf-py ! -name ggml ! -name 'LICENSE*' -exec rm -rf {} + \ - && find ggml -mindepth 1 -depth ! -type d ! -name CMakeLists.txt -delete && find ggml -mindepth 1 -type d -empty -delete \ - && du -sh /opt/strata/seed - -# ---- 3. the runtime image (the same as docker/Dockerfile's, FLAVOR=cuda) -FROM ${RUNTIME_BASE} -ARG STRATA_VERSION=dev -ENV DEBIAN_FRONTEND=noninteractive -RUN apt-get update && apt-get install -y --no-install-recommends tini ca-certificates libgomp1 libatomic1 libnuma1 zlib1g \ - && rm -rf /var/lib/apt/lists/* /var/cache/apt/* -COPY --from=terminal /opt/strata/terminal /opt/strata/terminal -COPY --from=terminal /opt/strata/seed /opt/strata/seed -COPY --from=engine-build /engine/ /opt/strata/components/engine/ -COPY docker/entrypoint.sh docker/healthcheck.sh /opt/strata/ -COPY docker/strata-wrapper.sh /usr/local/bin/strata -RUN chmod 0755 /opt/strata/entrypoint.sh /opt/strata/healthcheck.sh /usr/local/bin/strata -ENV STRATA_COMPONENTS_DIR=/opt/strata/components STRATA_INSTALL_DIR=/data/install XDG_STATE_HOME=/data/state \ - XDG_CONFIG_HOME=/data/config HOME=/data/home PORT=8080 LANG=C.UTF-8 PYTHONUNBUFFERED=1 PYTHONNOUSERSITE=1 STRATA_IN_DOCKER=1 \ - NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility -VOLUME ["/data"] -EXPOSE 8080 -LABEL org.opencontainers.image.title="Strata" com.strata.flavor="cuda" com.strata.build="from-source" org.opencontainers.image.version="${STRATA_VERSION}" -HEALTHCHECK --interval=30s --timeout=8s --start-period=2h --retries=3 CMD ["/opt/strata/healthcheck.sh"] -STOPSIGNAL SIGTERM -ENTRYPOINT ["/usr/bin/tini", "--", "/opt/strata/entrypoint.sh"] -CMD ["run"] diff --git a/engine/strata/README.de.md b/engine/strata/README.de.md deleted file mode 100644 index 070c03f3..00000000 --- a/engine/strata/README.de.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

Leistungsstarke KI auf deinem eigenen Computer.

-

Chatten, programmieren und mit Bildern arbeiten, lokal.

- -

- Modelle · Installation · - Hardware · Tools · - Hilfe · Unterstützen -

- -

- Strata herunterladen - MIT-Lizenz - Strata auf Buy Me a Coffee unterstützen -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**Kostenlos, Open Source und ganz in deiner Hand.** Nutze Strata auf dem Desktop oder mit deinen liebsten Coding-Tools. Kein Konto nötig. - -## Modelle - -Wir empfehlen **zuerst ISTA-DASLab**, danach **Unsloth** und andere Anbieter, soweit ein passendes Modell in deinen Speicher passt. - -
-  Qwen3.8-Flash-Next - -| Anbieter | Auswahl | -| --- | --- | -| **ISTA-DASLab · empfohlen** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) zum Programmieren. | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Geringerer Speicherbedarf, aber langsamer. | -| **Weitere Optionen** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[Größen, Speicherbedarf und Kompatibilität vergleichen](docs/MODELS.md). - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Das sind die derzeit dokumentierten Pakete für dieses Modell. - -[Modellanleitung und Kompatibilität](docs/QWEN36.md). - -
- -
-  DeepSeekV4.1-Flash-1017 - -In der **Desktop-App** und im **Terminal**. Was nicht in den Arbeitsspeicher passt, wird von deiner SSD gelesen. Darum brauchst du viel freien Speicherplatz. - -| Set (IST-DAS) | Download | Freier Speicherplatz nötig | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | etwa 245 GB | -| 2.00 bpw | 257 GB | etwa 265 GB | -| 2.25 bpw | 274 GB | etwa 280 GB | - -Läuft auf NVIDIA RTX 30, 40 und 50 (Windows und Linux) und auf AMD Radeon AI PRO R9700 (Linux). Das Setup lädt die Dateien und die DeepSeek-Engine herunter und startet dann das Modell. - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Gemessen mit dem 2.00-bpw-Set auf Strata 0.2.5. „Ausgabe“ ist das Tempo der Antwort, „Prompt“ zeigt, wie schnell Strata deine Eingabe liest. - -| Hardware | Ausgabe | Prompt | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB RAM | 4 bis 6 Token/s | etwa 110 Token/s (4K) | -| RTX 3060 12 GB, 46 GB RAM | 9 bis 11 Token/s | etwa 155 Token/s (4K) | -| 1x Radeon AI PRO R9700, 251 GB RAM | 21 bis 25 Token/s | 320 bis 360 Token/s (8K) | -| 4x Radeon AI PRO R9700 | 74 bis 77 Token/s | 400 bis 450 Token/s (8K) | - -[Speicher, Festplatte und Details](docs/DEEPSEEK41.md) · [Versionshinweise](https://github.com/Niko1221/Strata/releases) - -
- - - -Unsicher, was passt? [Wähle ein Modell für deinen Computer](docs/MODELS.md#pick-by-memory). - -## Installation - - - -### Desktop-App - -**[Strata für Windows, Linux oder Mac herunterladen →](https://github.com/Niko1221/Strata/releases/latest)** - -Installiere die App, wähle ein Modell und leg mit dem Chat los. Es gibt einen Installer pro System. Beim ersten Start lädt die App die Engine für deine Grafikkarte herunter. [Hilfe zum Installer](docs/INSTALL.md#the-app). - -Dateien: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Strata-Desktop-App mit Chat und Live-Codevorschau nebeneinander -
Chat, Dateien und Live-Vorschau in einem Fenster. -

- - - -### Terminal-App - -Lieber im Terminal? Installiere Strata und starte dann **`strata launch`**. - -
-Installationsbefehle - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -Öffne unter Windows danach ein neues Terminal. Dann: - -```sh -strata launch -``` - -Folge den Anweisungen, um ein Modell herunterzuladen und zu starten. [Terminal-Anleitung](docs/TERMINAL_LAUNCH.md). - -
- -

- Strata-Terminal-App mit Modellaktivität, Tempo, Speicher und letzten Anfragen -
Behalte Modell und Hardware im Blick, während es läuft. -

- - - -[Aus dem Quellcode bauen](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Vollständige Installationsanleitung](docs/INSTALL.md) - - - -## Hardware - -| Unterstützte Hardware | Anleitung | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [NVIDIA-Setup](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD-Setup](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · experimentell** | [RX-6000-Setup](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Intel-Setup](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 oder neuer** | [Mac-Setup](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Strix-Halo-Setup](docs/STRIX_HALO.md) | - - - -## Tools - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, und weitere über die OpenAI- und Anthropic-kompatiblen APIs. - -Führe **`strata connect`** aus, um die Einrichtung für dein Tool zu sehen. [Verbindungsanleitung](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). - - - - - - -## Hilfe - -[Alle Anleitungen](docs) · [Fehlerbehebung](docs/TROUBLESHOOTING.md) · [Fehler melden](https://github.com/Niko1221/Strata/issues/new/choose) · -[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [So funktioniert es](docs/HOW_IT_WORKS.md) · [Mitmachen](CONTRIBUTING.md) - -## Strata unterstützen - -**Hilf mit, lokale KI für alle offen zu halten.** Ein Kaffee hilft, Entwicklung und Tests auf mehr Hardware zu finanzieren. - -Buy Me a Coffee: Strata unterstützen - -[MIT-Lizenz](LICENSE) · [Danksagung und Modelllizenzen](docs/HOW_IT_WORKS.md#credits) · [Datenschutz](docs/SAFETY.md) - - - -Für KI-Tools und automatische Leser: technische Referenz · Setup-Anleitung. - -**Sponsoring, Hardware-Partnerschaften oder Zusammenarbeit:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.es.md b/engine/strata/README.es.md deleted file mode 100644 index e9efd723..00000000 --- a/engine/strata/README.es.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

IA potente en tu propio ordenador.

-

Chatea, programa y trabaja con imágenes, en local.

- -

- Modelos · Instalación · - Hardware · Herramientas · - Ayuda · Apoyar -

- -

- Descargar Strata - Licencia MIT - Apoya Strata en Buy Me a Coffee -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**Gratis, de código abierto y tuyo para ejecutar.** Usa Strata en tu escritorio o con tus herramientas de programación favoritas. No necesitas cuenta. - -## Modelos - -Recomendamos **primero ISTA-DASLab**, después **Unsloth** y otros proveedores, siempre que haya un modelo compatible que quepa en tu memoria. - -
-  Qwen3.8-Flash-Next - -| Proveedor | Opciones | -| --- | --- | -| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memoria, pero es más lento. | -| **Otras opciones** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[Compara tamaños, necesidades de memoria y compatibilidad](docs/MODELS.md). - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Son los paquetes documentados actualmente para este modelo. - -[Guía del modelo y compatibilidad](docs/QWEN36.md). - -
- -
-  DeepSeekV4.1-Flash-1017 - -En la **aplicación de escritorio** y en el **Terminal**. Lo que no cabe en la memoria se lee desde tu SSD, así que hace falta mucho espacio libre en disco. - -| Conjunto (IST-DAS) | Descarga | Espacio libre necesario | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | unos 245 GB | -| 2.00 bpw | 257 GB | unos 265 GB | -| 2.25 bpw | 274 GB | unos 280 GB | - -Funciona en NVIDIA RTX 30, 40 y 50 (Windows y Linux) y en AMD Radeon AI PRO R9700 (Linux). La instalación descarga los archivos y el motor de DeepSeek, y después inicia el modelo. - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Medido con el conjunto de 2.00 bpw en Strata 0.2.5. «Salida» es la velocidad de la respuesta; «Prompt» es la rapidez con la que Strata lee tu texto. - -| Hardware | Salida | Prompt | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | unos 110 tokens/s (4K) | -| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | unos 155 tokens/s (4K) | -| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | -| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | - -[Memoria, disco y detalles](docs/DEEPSEEK41.md) · [Notas de la versión](https://github.com/Niko1221/Strata/releases) - -
- - - -¿No sabes qué cabe? [Elige un modelo para tu ordenador](docs/MODELS.md#pick-by-memory). - -## Instalación - - - -### Aplicación de escritorio - -**[Descargar Strata para Windows, Linux o Mac →](https://github.com/Niko1221/Strata/releases/latest)** - -Instala la aplicación, elige un modelo y empieza a chatear. Hay un instalador por sistema. En el primer arranque, la aplicación descarga el motor para tu tarjeta gráfica. [Ayuda con el instalador](docs/INSTALL.md#the-app). - -Archivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Aplicación de escritorio de Strata con un chat y una vista previa del código en vivo, una junto a otra -
Chat, archivos y vista previa en vivo en una sola ventana. -

- - - -### Aplicación de Terminal - -¿Prefieres la terminal? Instala Strata y ejecuta **`strata launch`**. - -
-Comandos de instalación - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -En Windows, abre una terminal nueva después. Luego: - -```sh -strata launch -``` - -Sigue las indicaciones para descargar e iniciar un modelo. [Guía del Terminal](docs/TERMINAL_LAUNCH.md). - -
- -

- Aplicación de Terminal de Strata con la actividad del modelo, la velocidad, la memoria y las peticiones recientes -
Observa tu modelo y tu hardware mientras se ejecuta. -

- - - -[Compilar desde el código fuente](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guía de instalación completa](docs/INSTALL.md) - - - -## Hardware - -| Hardware compatible | Guía | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalación en NVIDIA](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalación en AMD](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalación en RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Instalación en Intel](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 o posterior** | [Instalación en Mac](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Instalación en Strix Halo](docs/STRIX_HALO.md) | - - - -## Herramientas - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, y más, mediante las API compatibles con OpenAI y Anthropic. - -Ejecuta **`strata connect`** para ver las instrucciones de tu herramienta. [Guía de conexión](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). - - - - - - -## Ayuda - -[Todas las guías](docs) · [Solución de problemas](docs/TROUBLESHOOTING.md) · [Informar de un error](https://github.com/Niko1221/Strata/issues/new/choose) · -[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Cómo funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) - -## Apoya Strata - -**Ayuda a mantener la IA local abierta a todos.** Un café ayuda a financiar el desarrollo y las pruebas en más hardware. - -Buy Me a Coffee: apoya Strata - -[Licencia MIT](LICENSE) · [Créditos y licencias de los modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidad](docs/SAFETY.md) - - - -Para herramientas de IA y lectores automáticos: referencia técnica · instrucciones de instalación. - -**Patrocinios, alianzas de hardware o colaboraciones:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.fr.md b/engine/strata/README.fr.md deleted file mode 100644 index eb4e6723..00000000 --- a/engine/strata/README.fr.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

Une IA puissante sur votre propre ordinateur.

-

Discutez, programmez et travaillez avec des images, en local.

- -

- Modèles · Installation · - Matériel · Outils · - Aide · Soutenir -

- -

- Télécharger Strata - Licence MIT - Soutenir Strata sur Buy Me a Coffee -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**Gratuit, open source, et à vous de l'exécuter.** Utilisez Strata sur votre bureau ou avec vos outils de programmation préférés. Aucun compte nécessaire. - -## Modèles - -Nous recommandons **d'abord ISTA-DASLab**, puis **Unsloth** et d'autres fournisseurs, lorsqu'un modèle compatible tient en mémoire. - -
-  Qwen3.8-Flash-Next - -| Fournisseur | Choix | -| --- | --- | -| **ISTA-DASLab · recommandé** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder : IQ1\_M](docs/MODELS.md#coder) pour programmer. | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Utilise moins de mémoire, mais plus lent. | -| **Autres options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[Comparer les tailles, la mémoire nécessaire et la compatibilité](docs/MODELS.md). - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Ce sont les paquets actuellement documentés pour ce modèle. - -[Guide du modèle et compatibilité](docs/QWEN36.md). - -
- -
-  DeepSeekV4.1-Flash-1017 - -Dans l'**application de bureau** et dans le **Terminal**. Ce qui ne tient pas en mémoire est lu depuis votre SSD : il faut donc beaucoup d'espace disque libre. - -| Jeu (IST-DAS) | Téléchargement | Espace disque libre nécessaire | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | environ 245 GB | -| 2.00 bpw | 257 GB | environ 265 GB | -| 2.25 bpw | 274 GB | environ 280 GB | - -Fonctionne sur les NVIDIA RTX 30, 40 et 50 (Windows et Linux) et sur l'AMD Radeon AI PRO R9700 (Linux). L'installation télécharge les fichiers et le moteur DeepSeek, puis démarre le modèle. - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Mesuré avec le jeu 2.00 bpw sur Strata 0.2.5. « Sortie » est la vitesse de la réponse, « Prompt » la vitesse à laquelle Strata lit votre texte. - -| Matériel | Sortie | Prompt | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB de RAM | 4 à 6 tokens/s | environ 110 tokens/s (4K) | -| RTX 3060 12 GB, 46 GB de RAM | 9 à 11 tokens/s | environ 155 tokens/s (4K) | -| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 à 25 tokens/s | 320 à 360 tokens/s (8K) | -| 4x Radeon AI PRO R9700 | 74 à 77 tokens/s | 400 à 450 tokens/s (8K) | - -[Mémoire, disque et détails](docs/DEEPSEEK41.md) · [Notes de version](https://github.com/Niko1221/Strata/releases) - -
- - - -Vous ne savez pas ce qui tient ? [Choisir un modèle pour votre ordinateur](docs/MODELS.md#pick-by-memory). - -## Installation - - - -### Application de bureau - -**[Télécharger Strata pour Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** - -Installez l'application, choisissez un modèle et commencez à discuter. Il y a un seul installateur par système. Au premier lancement, l'application télécharge le moteur de votre carte graphique. [Aide pour l'installateur](docs/INSTALL.md#the-app). - -Fichiers: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Application de bureau Strata avec une discussion et un aperçu du code en direct côte à côte -
Discussion, fichiers et aperçu en direct dans une seule fenêtre. -

- - - -### Application Terminal - -Vous préférez le terminal ? Installez Strata, puis lancez **`strata launch`**. - -
-Commandes d'installation - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -Sous Windows, ouvrez ensuite un nouveau terminal. Puis : - -```sh -strata launch -``` - -Suivez les invites pour télécharger et démarrer un modèle. [Guide du Terminal](docs/TERMINAL_LAUNCH.md). - -
- -

- Application Terminal de Strata affichant l'activité du modèle, la vitesse, la mémoire et les requêtes récentes -
Suivez votre modèle et votre matériel pendant qu'il tourne. -

- - - -[Compiler depuis les sources](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guide d'installation complet](docs/INSTALL.md) - - - -## Matériel - -| Matériel pris en charge | Guide | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Installation NVIDIA](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Installation AMD](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · expérimental** | [Installation RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Installation Intel](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 ou plus récent** | [Installation sur Mac](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Installation Strix Halo](docs/STRIX_HALO.md) | - - - -## Outils - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, et d'autres via les API compatibles OpenAI et Anthropic. - -Lancez **`strata connect`** pour voir la configuration de votre outil. [Guide de connexion](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). - - - - - - -## Aide - -[Tous les guides](docs) · [Dépannage](docs/TROUBLESHOOTING.md) · [Signaler un bogue](https://github.com/Niko1221/Strata/issues/new/choose) · -[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Comment ça marche](docs/HOW_IT_WORKS.md) · [Contribuer](CONTRIBUTING.md) - -## Soutenir Strata - -**Aidez à garder l'IA locale ouverte à tous.** Un café aide à financer le développement et les tests sur davantage de matériel. - -Buy Me a Coffee : soutenir Strata - -[Licence MIT](LICENSE) · [Crédits et licences des modèles](docs/HOW_IT_WORKS.md#credits) · [Confidentialité](docs/SAFETY.md) - - - -Pour les outils d'IA et les lecteurs automatiques : référence technique · instructions d'installation. - -**Parrainages, partenariats matériel ou collaborations :** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.ja.md b/engine/strata/README.ja.md deleted file mode 100644 index 4a180076..00000000 --- a/engine/strata/README.ja.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

あなた自身のパソコンで、高性能な AI を。

-

チャット、コーディング、画像の処理を、すべてローカルで。

- -

- モデル · インストール · - ハードウェア · ツール · - ヘルプ · 支援 -

- -

- Strata をダウンロード - MIT ライセンス - Buy Me a Coffee で Strata を支援する -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**無料でオープンソース。自分の環境で動かせます。** デスクトップで、またはお好みのコーディングツールと一緒に Strata を使えます。アカウントは不要です。 - -## モデル - -まず **ISTA-DASLab** をおすすめします。次に **Unsloth** などの提供元です。メモリに収まる互換モデルがある場合に選べます。 - -
-  Qwen3.8-Flash-Next - -| 提供元 | 選択肢 | -| --- | --- | -| **ISTA-DASLab · おすすめ** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder: IQ1\_M](docs/MODELS.md#coder)(コーディング向け)。 | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。メモリ使用量は少ないですが、動作は遅くなります。 | -| **その他の選択肢** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[サイズ、必要なメモリ、互換性を比べる](docs/MODELS.md)。 - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。現在、このモデルで文書化されているパックです。 - -[モデルガイドと互換性](docs/QWEN36.md)。 - -
- -
-  DeepSeekV4.1-Flash-1017 - -**デスクトップアプリ**と**ターミナル**で使えます。メモリに収まらない分は SSD から読み込むため、空きディスク容量がたくさん必要です。 - -| セット(IST-DAS) | ダウンロード | 必要な空き容量 | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | 約245 GB | -| 2.00 bpw | 257 GB | 約265 GB | -| 2.25 bpw | 274 GB | 約280 GB | - -NVIDIA RTX 30・40・50 シリーズ(Windows と Linux)と、AMD Radeon AI PRO R9700(Linux)で動きます。セットアップがファイルと DeepSeek エンジンをダウンロードし、モデルを起動します。 - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Strata 0.2.5 で 2.00 bpw のセットを使って測定しました。「出力」は回答の速さ、「プロンプト」は Strata が入力を読み込む速さです。 - -| ハードウェア | 出力 | プロンプト | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB RAM | 4〜6 トークン/秒 | 約 110 トークン/秒 (4K) | -| RTX 3060 12 GB, 46 GB RAM | 9〜11 トークン/秒 | 約 155 トークン/秒 (4K) | -| 1x Radeon AI PRO R9700, 251 GB RAM | 21〜25 トークン/秒 | 320〜360 トークン/秒 (8K) | -| 4x Radeon AI PRO R9700 | 74〜77 トークン/秒 | 400〜450 トークン/秒 (8K) | - -[メモリ、ディスク、詳細](docs/DEEPSEEK41.md) · [リリースノート](https://github.com/Niko1221/Strata/releases) - -
- - - -どれが動くかわからない場合は、[お使いのパソコンに合うモデルを選ぶ](docs/MODELS.md#pick-by-memory)。 - -## インストール - - - -### デスクトップアプリ - -**[Windows、Linux、Mac 用の Strata をダウンロード →](https://github.com/Niko1221/Strata/releases/latest)** - -アプリをインストールし、モデルを選んで、チャットを始めましょう。インストーラーはシステムごとに1つです。初回起動時に、アプリがお使いのグラフィックスカード用のエンジンをダウンロードします。[インストーラーのヘルプ](docs/INSTALL.md#the-app)。 - -ファイル: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- チャットとライブのコードプレビューを並べて表示した Strata デスクトップアプリ -
チャット、ファイル、ライブプレビューを1つのウィンドウで。 -

- - - -### ターミナルアプリ - -ターミナルのほうが好みですか? Strata をインストールして、**`strata launch`** を実行します。 - -
-インストールコマンド - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -Windows では、インストール後に新しいターミナルを開きます。そのあと: - -```sh -strata launch -``` - -画面の案内に従って、モデルをダウンロードして起動します。[ターミナルガイド](docs/TERMINAL_LAUNCH.md)。 - -
- -

- モデルの動作、速度、メモリ、最近のリクエストを表示する Strata ターミナルアプリ -
動作中のモデルとハードウェアの状態を確認できます。 -

- - - -[ソースからビルド](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [インストールガイド(全文)](docs/INSTALL.md) - - - -## ハードウェア - -| 対応ハードウェア | ガイド | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 シリーズ** | [NVIDIA のセットアップ](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD のセットアップ](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · 試験的** | [RX 6000 のセットアップ](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Intel のセットアップ](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 以降** | [Mac のセットアップ](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo のセットアップ](docs/STRIX_HALO.md) | - - - -## ツール - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**。OpenAI 互換と Anthropic 互換の API を通じて、ほかのツールも使えます。 - -**`strata connect`** を実行すると、お使いのツールの設定方法が表示されます。[接続ガイド](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 - - - - - - -## ヘルプ - -[すべてのガイド](docs) · [トラブルシューティング](docs/TROUBLESHOOTING.md) · [不具合を報告](https://github.com/Niko1221/Strata/issues/new/choose) · -[ベンチマーク](docs/COMMUNITY_BENCHMARKS.md) · [仕組み](docs/HOW_IT_WORKS.md) · [貢献する](CONTRIBUTING.md) - -## Strata を支援する - -**ローカル AI をみんなに開かれたものに。** コーヒー1杯が、開発と、より多くのハードウェアでのテストの支えになります。 - -Buy Me a Coffee: Strata を支援する - -[MIT ライセンス](LICENSE) · [クレジットとモデルのライセンス](docs/HOW_IT_WORKS.md#credits) · [プライバシー](docs/SAFETY.md) - - - -AI ツールと自動リーダー向け: 技術リファレンス · セットアップ手順 - -**スポンサー、ハードウェア提携、共同開発のご相談:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.md b/engine/strata/README.md deleted file mode 100644 index 0c9be0d1..00000000 --- a/engine/strata/README.md +++ /dev/null @@ -1,191 +0,0 @@ -

- - - Strata - -

- -

Run powerful AI on your own computer.

-

Chat, code and work with images, locally.

- -

- Models · Install · - Hardware · Tools · - Help · Support -

- -

- Download Strata - MIT license - Support Strata on Buy Me a Coffee -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**Free, open source, and yours to run.** Use Strata on your desktop or with your favorite coding tools. No account needed. - -## Models - -We recommend **ISTA-DASLab first**, then **Unsloth** and other providers, where a compatible model fits. - -
-  Qwen3.8-Flash-Next - -| Provider | Choices | -| --- | --- | -| **ISTA-DASLab · recommended** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) for coding. | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Lower memory use but slower. | -| **Other options** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[Compare sizes, memory needs and compatibility](docs/MODELS.md). - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. These are the currently documented packs for this model. - -[Model guide and compatibility](docs/QWEN36.md). - -
- -
-  DeepSeekV4.1-Flash-1017 - -In the **desktop app** and the **Terminal**. What does not fit in memory is read from your SSD, so it needs a lot of free -disk space. - -| Set (IST-DAS) | Download | Free disk needed | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | about 245 GB | -| 2.00 bpw | 257 GB | about 265 GB | -| 2.25 bpw | 274 GB | about 280 GB | - -Runs on NVIDIA RTX 30, 40 and 50 series (Windows and Linux) and AMD Radeon AI PRO R9700 (Linux). Setup downloads the -files and the DeepSeek engine, then starts the model. - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Measured with the 2.00 bpw set on Strata 0.2.5. Output is the speed of the answer, prompt is how fast Strata reads your input. - -| Hardware | Output | Prompt | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB RAM | 4 to 6 tokens/s | about 110 tokens/s (4K) | -| RTX 3060 12 GB, 46 GB RAM | 9 to 11 tokens/s | about 155 tokens/s (4K) | -| 1x Radeon AI PRO R9700, 251 GB RAM | 21 to 25 tokens/s | 320 to 360 tokens/s (8K) | -| 4x Radeon AI PRO R9700 | 74 to 77 tokens/s | 400 to 450 tokens/s (8K) | - -[Memory, disk and details](docs/DEEPSEEK41.md) · [Release notes](https://github.com/Niko1221/Strata/releases) - -
- - - -Not sure what fits? [Choose a model for your computer](docs/MODELS.md#pick-by-memory). - -## Install - - - -### Desktop app - -**[Download Strata for Windows, Linux or Mac →](https://github.com/Niko1221/Strata/releases/latest)** - -Install the app, choose a model, and start chatting. There is one installer for each system. On first start the app -downloads the engine for your graphics card. [Help with the installer](docs/INSTALL.md#the-app). - -Files: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Strata desktop app with a chat and live code preview side by side -
Chat, files and a live preview in one window. -

- - - -### Terminal app - -Prefer the terminal? Install Strata, then run **`strata launch`**. - -
-Install commands - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -On Windows, open a new terminal afterwards. Then: - -```sh -strata launch -``` - -Follow the prompts to download and start a model. [Terminal guide](docs/TERMINAL_LAUNCH.md). - -
- -

- Strata terminal app showing model activity, speed, memory and recent requests -
Watch your model and hardware while it runs. -

- - - -[Build from source](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Full install guide](docs/INSTALL.md) - - - -## Hardware - -| Supported hardware | Guide | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 series** | [NVIDIA setup](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [AMD setup](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · experimental** | [RX 6000 setup](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Intel setup](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 or newer** | [Mac setup](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo setup](docs/STRIX_HALO.md) | - - - -## Tools - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, and more through the OpenAI- and Anthropic-compatible APIs. - -Run **`strata connect`** to see setup instructions for your tool. [Connection guide](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). - - - - - - -## Help - -[All guides](docs) · [Troubleshooting](docs/TROUBLESHOOTING.md) · [Report a bug](https://github.com/Niko1221/Strata/issues/new/choose) · -[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [How it works](docs/HOW_IT_WORKS.md) · [Contribute](CONTRIBUTING.md) - -## Support Strata - -**Help keep local AI open to everyone.** A coffee helps fund development and testing on more hardware. - -Buy Me a Coffee: support Strata - -[MIT license](LICENSE) · [Credits and model licenses](docs/HOW_IT_WORKS.md#credits) · [Privacy](docs/SAFETY.md) - - - -For AI tools and automated readers: technical reference · setup instructions. - -**Sponsorships, hardware partnerships or collaborations:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.pt-BR.md b/engine/strata/README.pt-BR.md deleted file mode 100644 index f268b29a..00000000 --- a/engine/strata/README.pt-BR.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

IA poderosa no seu próprio computador.

-

Converse, programe e trabalhe com imagens, localmente.

- -

- Modelos · Instalação · - Hardware · Ferramentas · - Ajuda · Apoiar -

- -

- Baixar o Strata - Licença MIT - Apoie o Strata no Buy Me a Coffee -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**Gratuito, de código aberto e seu para executar.** Use o Strata no desktop ou com suas ferramentas de programação favoritas. Não precisa de conta. - -## Modelos - -Recomendamos **primeiro a ISTA-DASLab**, depois a **Unsloth** e outros provedores, quando um modelo compatível cabe na memória. - -
-  Qwen3.8-Flash-Next - -| Provedor | Opções | -| --- | --- | -| **ISTA-DASLab · recomendado** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S. [Coder: IQ1\_M](docs/MODELS.md#coder) para programar. | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF). Usa menos memória, mas é mais lento. | -| **Outras opções** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[Compare tamanhos, necessidades de memória e compatibilidade](docs/MODELS.md). - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0. Esses são os pacotes documentados atualmente para este modelo. - -[Guia do modelo e compatibilidade](docs/QWEN36.md). - -
- -
-  DeepSeekV4.1-Flash-1017 - -No **aplicativo de desktop** e no **Terminal**. O que não cabe na memória é lido do seu SSD, por isso é preciso muito espaço livre em disco. - -| Conjunto (IST-DAS) | Download | Espaço livre necessário | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | cerca de 245 GB | -| 2.00 bpw | 257 GB | cerca de 265 GB | -| 2.25 bpw | 274 GB | cerca de 280 GB | - -Roda em NVIDIA RTX 30, 40 e 50 (Windows e Linux) e em AMD Radeon AI PRO R9700 (Linux). A instalação baixa os arquivos e o motor do DeepSeek e depois inicia o modelo. - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -Medido com o conjunto de 2.00 bpw no Strata 0.2.5. “Saída” é a velocidade da resposta; “Prompt” é a rapidez com que o Strata lê o seu texto. - -| Hardware | Saída | Prompt | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB de RAM | 4 a 6 tokens/s | cerca de 110 tokens/s (4K) | -| RTX 3060 12 GB, 46 GB de RAM | 9 a 11 tokens/s | cerca de 155 tokens/s (4K) | -| 1x Radeon AI PRO R9700, 251 GB de RAM | 21 a 25 tokens/s | 320 a 360 tokens/s (8K) | -| 4x Radeon AI PRO R9700 | 74 a 77 tokens/s | 400 a 450 tokens/s (8K) | - -[Memória, disco e detalhes](docs/DEEPSEEK41.md) · [Notas da versão](https://github.com/Niko1221/Strata/releases) - -
- - - -Não sabe o que cabe? [Escolha um modelo para o seu computador](docs/MODELS.md#pick-by-memory). - -## Instalação - - - -### Aplicativo de desktop - -**[Baixar o Strata para Windows, Linux ou Mac →](https://github.com/Niko1221/Strata/releases/latest)** - -Instale o aplicativo, escolha um modelo e comece a conversar. Há um instalador por sistema. Na primeira vez que abre, o aplicativo baixa o motor da sua placa de vídeo. [Ajuda com o instalador](docs/INSTALL.md#the-app). - -Arquivos: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Aplicativo de desktop do Strata com um chat e uma prévia do código ao vivo lado a lado -
Chat, arquivos e prévia ao vivo em uma só janela. -

- - - -### Aplicativo de Terminal - -Prefere o terminal? Instale o Strata e execute **`strata launch`**. - -
-Comandos de instalação - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -No Windows, abra um novo terminal depois. Em seguida: - -```sh -strata launch -``` - -Siga as instruções para baixar e iniciar um modelo. [Guia do Terminal](docs/TERMINAL_LAUNCH.md). - -
- -

- Aplicativo de Terminal do Strata mostrando a atividade do modelo, a velocidade, a memória e as solicitações recentes -
Acompanhe seu modelo e seu hardware enquanto ele roda. -

- - - -[Compilar a partir do código-fonte](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [Guia de instalação completo](docs/INSTALL.md) - - - -## Hardware - -| Hardware compatível | Guia | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50** | [Instalação para NVIDIA](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900, RX 9060 / 9070, AI PRO R9700** | [Instalação para AMD](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · experimental** | [Instalação para RX 6000](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Instalação para Intel](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 ou mais novo** | [Instalação para Mac](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Instalação para Strix Halo](docs/STRIX_HALO.md) | - - - -## Ferramentas - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**, e outras, pelas APIs compatíveis com OpenAI e Anthropic. - -Execute **`strata connect`** para ver as instruções da sua ferramenta. [Guia de conexão](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect). - - - - - - -## Ajuda - -[Todos os guias](docs) · [Solução de problemas](docs/TROUBLESHOOTING.md) · [Relatar um bug](https://github.com/Niko1221/Strata/issues/new/choose) · -[Benchmarks](docs/COMMUNITY_BENCHMARKS.md) · [Como funciona](docs/HOW_IT_WORKS.md) · [Contribuir](CONTRIBUTING.md) - -## Apoie o Strata - -**Ajude a manter a IA local aberta para todos.** Um café ajuda a financiar o desenvolvimento e os testes em mais hardware. - -Buy Me a Coffee: apoie o Strata - -[Licença MIT](LICENSE) · [Créditos e licenças dos modelos](docs/HOW_IT_WORKS.md#credits) · [Privacidade](docs/SAFETY.md) - - - -Para ferramentas de IA e leitores automáticos: referência técnica · instruções de instalação. - -**Patrocínios, parcerias de hardware ou colaborações:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/README.zh-CN.md b/engine/strata/README.zh-CN.md deleted file mode 100644 index 43abda7b..00000000 --- a/engine/strata/README.zh-CN.md +++ /dev/null @@ -1,188 +0,0 @@ -

- - - Strata - -

- -

在你自己的电脑上运行强大的 AI。

-

本地聊天、写代码、处理图片。

- -

- 模型 · 安装 · - 硬件 · 工具 · - 帮助 · 支持 -

- -

- 下载 Strata - MIT 许可证 - 在 Buy Me a Coffee 上支持 Strata -

- -

English · 简体中文 · 日本語 · Deutsch · Français · Español · Português

- -**免费、开源,由你自己运行。** 在桌面上使用 Strata,或搭配你喜欢的编程工具。无需账号。 - -## 模型 - -我们**首先推荐 ISTA-DASLab**,其次是 **Unsloth** 和其他提供方,前提是有内存放得下的兼容模型。 - -
-  Qwen3.8-Flash-Next - -| 提供方 | 可选项 | -| --- | --- | -| **ISTA-DASLab · 推荐** | Q2\_0, IQ2\_XS, IQ3\_XXS, IQ3\_S。[Coder:IQ1\_M](docs/MODELS.md#coder),适合写代码。 | -| **Unsloth** | UD-IQ4\_XS, UD-Q4\_K\_XL, UD-Q5\_K\_XL, UD-Q6\_K\_XL, Q8\_0 | -| **Gyro · agentionai** | [Gyro-S, Gyro-M](https://huggingface.co/agentionai/Qwen3.8-Flash-Next-Gyro-GGUF)。占用内存更少,但速度更慢。 | -| **其他选项** | [Swift 1.5](docs/MODELS.md#swift-15), [NVFP4](docs/NVFP4.md), [OrcaRouter](docs/ORCA.md) | - -[比较大小、内存需求和兼容性](docs/MODELS.md)。 - -
- -
-  Qwen3.6-35B-A3B - -**Unsloth:** UD-Q4_K_XL, UD-Q6_K_XL, Q8_0。这些是目前文档中收录的该模型的版本。 - -[模型指南和兼容性](docs/QWEN36.md)。 - -
- -
-  DeepSeekV4.1-Flash-1017 - -可在**桌面应用**和**终端**中使用。内存放不下的部分会从 SSD 读取,所以需要大量空闲磁盘空间。 - -| 版本(IST-DAS) | 下载大小 | 所需空闲磁盘 | -| --- | ---: | ---: | -| 1.75 bpw | 239 GB | 约245 GB | -| 2.00 bpw | 257 GB | 约265 GB | -| 2.25 bpw | 274 GB | 约280 GB | - -支持 NVIDIA RTX 30、40 和 50 系列(Windows 和 Linux),以及 AMD Radeon AI PRO R9700(Linux)。安装程序会下载模型文件和 DeepSeek 引擎,然后启动模型。 - -```sh -strata launch --family deepseek41 --model ist-das-2.00bpw --plan -``` - -以下为 Strata 0.2.5 上 2.00 bpw 版本的实测结果。“输出”是回答的速度,“提示词”是 Strata 读取你输入内容的速度。 - -| 硬件 | 输出 | 提示词 | -| --- | ---: | ---: | -| RTX 5070 12 GB, 64 GB 内存 | 4 到 6 tokens/s | 约 110 tokens/s(4K) | -| RTX 3060 12 GB, 46 GB 内存 | 9 到 11 tokens/s | 约 155 tokens/s(4K) | -| 1x Radeon AI PRO R9700, 251 GB 内存 | 21 到 25 tokens/s | 320 到 360 tokens/s (8K) | -| 4x Radeon AI PRO R9700 | 74 到 77 tokens/s | 400 到 450 tokens/s (8K) | - -[内存、磁盘和详细信息](docs/DEEPSEEK41.md) · [发行说明](https://github.com/Niko1221/Strata/releases) - -
- - - -不确定哪个放得下?[为你的电脑选择模型](docs/MODELS.md#pick-by-memory)。 - -## 安装 - - - -### 桌面应用 - -**[下载适用于 Windows、Linux 或 Mac 的 Strata →](https://github.com/Niko1221/Strata/releases/latest)** - -安装应用,选择模型,就可以开始聊天。每个系统只有一个安装程序。首次启动时,应用会下载适合你显卡的引擎。[安装程序帮助](docs/INSTALL.md#the-app)。 - -文件: `Strata-0.2.5-windows-x64-setup.exe` · `Strata-0.2.5-linux-x86_64.AppImage` · `Strata-0.2.5-macos-arm64.dmg` - -

- Strata 桌面应用,聊天和实时代码预览并排显示 -
聊天、文件和实时预览都在一个窗口里。 -

- - - -### 终端应用 - -更喜欢终端?安装 Strata,然后运行 **`strata launch`**。 - -
-安装命令 - -**Linux / Mac** - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -``` - -**Windows PowerShell** - -```powershell -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -在 Windows 上,安装后请打开一个新的终端。然后运行: - -```sh -strata launch -``` - -按提示下载并启动模型。[终端指南](docs/TERMINAL_LAUNCH.md)。 - -
- -

- Strata 终端应用,显示模型活动、速度、内存和最近的请求 -
模型运行时,随时查看模型和硬件状态。 -

- - - -[从源码构建](docs/SOURCE_INSTALL.md) · [Docker](docs/DOCKER.md) · [完整安装指南](docs/INSTALL.md) - - - -## 硬件 - -| 支持的硬件 | 指南 | -| --- | --- | -| **NVIDIA GeForce RTX 20 / 30 / 40 / 50 系列** | [NVIDIA 安装](docs/INSTALL.md#what-you-need) | -| **AMD Radeon RX 7700 / 7800 / 7900、RX 9060 / 9070、AI PRO R9700** | [AMD 安装](docs/AMD_HIP.md) | -| **AMD Radeon RX 6800 / 6900 · 实验性** | [RX 6000 安装](docs/AMD_HIP.md#rdna2-gfx1030) | -| **Intel Arc · Linux** | [Intel 安装](docs/INTEL_ARC.md) | -| **Apple Silicon · M1 或更新** | [Mac 安装](docs/MAC.md) | -| **AMD Ryzen AI Max · Strix Halo** | [Strix Halo 安装](docs/STRIX_HALO.md) | - - - -## 工具 - -**Claude Code · Codex CLI · OpenCode · oh-my-pi · pi.dev · Hermes Agent · OpenClaw**,也可以通过兼容 OpenAI 和 Anthropic 的 API 使用更多工具。 - -运行 **`strata connect`**,查看你所用工具的设置方法。[连接指南](docs/TERMINAL_LAUNCH.md#connect-your-apps-strata-connect)。 - - - - - - -## 帮助 - -[全部指南](docs) · [故障排查](docs/TROUBLESHOOTING.md) · [报告问题](https://github.com/Niko1221/Strata/issues/new/choose) · -[基准测试](docs/COMMUNITY_BENCHMARKS.md) · [工作原理](docs/HOW_IT_WORKS.md) · [参与贡献](CONTRIBUTING.md) - -## 支持 Strata - -**帮助本地 AI 保持开放。** 一杯咖啡能帮助我们在更多硬件上开发和测试。 - -Buy Me a Coffee:支持 Strata - -[MIT 许可证](LICENSE) · [致谢和模型许可证](docs/HOW_IT_WORKS.md#credits) · [隐私](docs/SAFETY.md) - - - -面向 AI 工具和自动阅读器: 技术参考 · 安装说明 - -**赞助、硬件合作或其他合作:** [niko.veit@outlook.com](mailto:niko.veit@outlook.com). diff --git a/engine/strata/SECURITY.md b/engine/strata/SECURITY.md deleted file mode 100644 index 8bd61c84..00000000 --- a/engine/strata/SECURITY.md +++ /dev/null @@ -1,95 +0,0 @@ -# Security - -## Reporting a vulnerability - -Please report anything that should not be public until it is fixed **privately**, through GitHub's private -vulnerability reporting: the repository's **Security** tab, **Report a vulnerability** -([direct link](https://github.com/Niko1221/Strata/security/advisories/new)). Say what you found, how to reproduce it -(the request, the config keys involved, the Strata version), and what an attacker gains. We answer there, fix it in -a release, and credit you in the advisory unless you ask us not to. - -Ordinary hardening ideas and findings that are safe to discuss in public are welcome as an -[issue](https://github.com/Niko1221/Strata/issues) (#544 collects audit findings) or as a pull request, which we -review like our own code. - -Supported: the latest release. Fixes go into the next release, not into older ones. - -## What the server exposes - -Strata runs a model on your PC and serves it over HTTP (`serve/server.py`). Out of the box it is reachable from -this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAILS.md) ("From other devices", -"Host names", "Web pages without an API key", "Tools from MCP servers"). - -- **Where it listens.** `127.0.0.1` by default. `--host 0.0.0.0` (or `"host"` in `strata-.json`) opens it to - your network, and the server then warns when no API key is set. -- **API key.** `"api_key"` in the run config (or `STRATA_API_KEY`) is required on `/v1/*` and on every endpoint - that shows the model's state, requests or answers (`/status`, `/metrics`, `/settings`, `/mcp`, `/props`, `/slots`, - `/api/requests`, `/config`) and on every `POST`. It is compared in constant time. Set one before you open the - server to your network or put a tunnel in front of it. -- **Host check (DNS rebinding, 0.1.38).** Without an API key the server answers only requests whose `Host` is a name - it knows (`localhost`, an IP address, the address it listens on and, when it listens beyond this PC, this PC's - name). Others get 403. `"allowed_hosts"` adds names; with an API key the key decides. -- **Origin check (0.1.38).** Without an API key, a browser `POST` to `/v1/*` from another web site's page (it carries - an `Origin` header) gets 403 unless that origin is Strata's own page, `localhost`, an allowed host, or listed in - `"trusted_origins"` / `"cors_origins"`. Changing settings (`/settings`, and `/config`: the few run config keys the - page's Model settings may change - never the network, key, MCP or program keys), `/load` and `/unload` and the - MCP tools are accepted only as JSON from Strata's own page (or `"trusted_origins"`), so a page elsewhere cannot - change settings or run tools. -- **CORS** is off unless `"cors_origins"` lists origins, and then only for `/v1/*`. -- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own page - that ask for them. They run with your user's rights, and the model decides when to call them. -- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless - `"api_monitor": true` is set. Apart from it, the server keeps in its process memory the text and tokens of its - last few prompts, whatever `"api_monitor"` says, to encode the next turn faster; no endpoint shows them, and they - are gone when the server stops. - -## The desktop app and the Terminal - -Strata comes in three parts that share one engine: the **desktop app**, the **Terminal** (`strata`) and the **engine** that runs -the model. The section above is about the engine's HTTP server. This is what the other two add. - -- **The app's host listens on this PC only.** The app serves its page from a local host process on `127.0.0.1` (port 8791 unless - changed). A request to its `/api/` endpoints that carries a browser `Origin` from any other site gets 403. The app shell holds a - random secret (32 characters or more, compared in constant time) that is needed to quit the host or tell it which window is open, - and the host gives its own helper processes a second random secret. By default the models the app starts are served on this PC only. -- **Sharing is a separate, key-protected listener.** "Share with other devices" (and the Cloudflare tunnel) will not start until an - API key is set. It opens a different listener that answers only `/v1/models`, `/v1/chat/completions` and `/v1/messages`, never the - app's page or its host endpoints. -- **App and Terminal talk through an owner channel.** One owner process per installation starts and ends the engine, and a second - client (the Terminal) attaches to it. On macOS and Linux that is a private Unix socket in a folder only you can open. On Windows it - is a TCP listener on `127.0.0.1` that answers only requests carrying a 256-bit token kept in an owner-only folder. That is a weaker - guarantee than a socket other users cannot open: on Windows the token is what protects it, as with any loopback service that has a - token (`strata_control/owner_transport.py`). The bridge between the app shell and the host (used for the app update) is also loopback and protected by a token. -- **Starting a model and serving never download anything.** Downloads and updates are one explicit step: `strata update`, or "Update - engine" and "Update Strata" in the app's Settings. Models and saved tuning are never replaced by an update. -- **Updates come from a signed feed.** The release publishes `strata-feed.json` and `strata-feed.json.sig` (Ed25519). An installed - Strata checks the signature against the public key it carries (`strata_control/update_keys.json`), refuses a feed older than the last - one it accepted (a replayed old feed) or expired, and checks every engine package against its SHA-256, its signed manifest and the - card in your PC before it test-starts it and switches to it. Any failure keeps the engine you had. The app installer itself is signed - with a separate key (Tauri's minisign key) that the app and the Terminal both check. The private keys are kept offline by the owner. - See [packaging/UPDATES.md](packaging/UPDATES.md). - -### How far to trust `curl | sh` and `irm | iex` - -The Terminal installs with one line: - -```sh -curl -fsSL https://github.com/Niko1221/Strata/releases/latest/download/install.sh -o install.sh && sh install.sh -irm https://github.com/Niko1221/Strata/releases/latest/download/install.ps1 | iex -``` - -Piping a script into a shell runs whatever the server sends, so it deserves the same care as running any downloaded program. -What the script does is short and written at its top: it fetches the Terminal archive named in the release's `install-manifest.txt`, -checks its SHA-256, unpacks it into your home folder (no administrator rights, nothing outside your home), checks the release's signed feed -with the Terminal it just unpacked and removes it again if that fails, and puts `strata` on your PATH. - -Those checks have a limit. The checksum comes from the same release as the archive, and the public key that checks the feed arrives inside -that archive, so for the first install all trust rests on HTTPS and on the `Niko1221/Strata` GitHub release itself. The checks catch a -damaged or half-finished download and a feed that was not signed by the release key; they do not protect you if the release has been replaced -by someone who controls it. Later updates are checked against the key already on your PC, which is a stronger position. - -If that is not enough: save the script (`curl -fsSLO https://github.com/Niko1221/Strata/releases/latest/download/install.sh`), read it, and -run it from the file; or install the desktop app or build from source instead and check the code you build. - -Strata has not had an outside security audit yet. -What Strata downloads, when it uses the internet, what stays on your PC and how downloads are checked is written up in [docs/SAFETY.md](docs/SAFETY.md). diff --git a/engine/strata/SETUP.bat b/engine/strata/SETUP.bat deleted file mode 100644 index d2e6541c..00000000 --- a/engine/strata/SETUP.bat +++ /dev/null @@ -1,3 +0,0 @@ -@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 deleted file mode 100644 index 5f255c07..00000000 --- a/engine/strata/START-HERE.bat +++ /dev/null @@ -1,65 +0,0 @@ -@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 -rem Python reads and writes text as UTF-8, not in the Windows code page (cp1251, cp866, ...): a folder or user name with Cyrillic or other letters stays intact (#3202). -set "PYTHONUTF8=1" -title Strata -cd /d "%~dp0" -rem A bundled Python runtime (the python\ folder of the terminal archive) is used when it is there: nothing to find, -rem install or download. SETUP.bat and UPDATE.bat run this file, so they use it too. -if exist "python\python.exe" goto bundled -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 - -:bundled -set "PYTHONNOUSERSITE=1" -set "PYTHONHOME=" -set "PYTHONPATH=" -"python\python.exe" setup.py %* -if errorlevel 1 pause -exit /b - -: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/UPDATE.bat b/engine/strata/UPDATE.bat deleted file mode 100644 index c0fd78a1..00000000 --- a/engine/strata/UPDATE.bat +++ /dev/null @@ -1,82 +0,0 @@ -@echo off -rem Update Strata without starting the model (#475): the newest code (git pull, when this folder is a git clone), then -rem what START-HERE.bat does before a start - the engine (a new one when this version needs it), the Python packages, -rem each installed model's settings and draft subset. The model files are not touched. Start the model later with -rem START-HERE.bat. Options are passed on to setup.py. The bundled Python (python\ beside this file) is used when -rem there is one: START-HERE.bat, which this file runs, picks it. -setlocal -title Strata - update -cd /d "%~dp0" -rem All of it in one block: cmd reads a .bat file while it runs it, and the git pull can change this very file. -( - if exist ".git" ( - where git >nul 2>nul || ( - echo This folder is a git clone, but git is not on PATH: install Git for Windows ^(winget install Git.Git^) - echo or run "git pull" here yourself, then run UPDATE.bat again. - pause - exit /b 1 - ) - echo Getting the newest Strata ^(git pull^) ... - git pull --ff-only - if errorlevel 1 ( - rem The history was rewritten on 2026-10-06, see #1276: a clone from before has no commit in common with origin/main. - set "REWR=" - git merge-base HEAD origin/main >nul 2>nul - if errorlevel 1 set "REWR=1" - git rev-parse --is-shallow-repository 2>nul | findstr /x true >nul && set "REWR=" - if defined REWR ( - echo. - echo This clone is on the repository's old history ^(cleaned up on 2026-10-06^): it has no commit in common - echo with origin/main, so it cannot be updated by git pull. - set "DIRTY=" - for /f "delims=" %%i in ('git status --porcelain --untracked-files^=no') do set "DIRTY=1" - if defined DIRTY ( - echo You have local changes to tracked files here, so nothing was touched. To move to the new history - echo yourself ^(your untracked files, models and settings stay where they are^): - echo git branch pre-cleanup-backup - echo git stash push - echo git checkout -B main origin/main - echo then run UPDATE.bat again. - pause - exit /b 1 - ) - set "BK=pre-cleanup-backup" - git rev-parse --verify -q refs/heads/pre-cleanup-backup >nul 2>nul && set "BK=pre-cleanup-backup-%RANDOM%" - set "BR=main" - for /f "delims=" %%i in ('git symbolic-ref --short -q HEAD 2^>nul') do set "BR=%%i" - call git branch %%BK%% HEAD - if errorlevel 1 ( - echo Could not make the backup branch: nothing was updated. - pause - exit /b 1 - ) - call git checkout -q -B %%BR%% origin/main - if errorlevel 1 ( - call git branch -D %%BK%% >nul 2>nul - echo. - echo Could not move to the new history ^(the reason is above^): nothing was updated. By hand: - echo git checkout -B main origin/main - pause - exit /b 1 - ) - call echo Moved to the new history. Your old commits are kept in the branch %%BK%%. - echo Untracked files ^(models, settings, the engine^) were not touched. - ) else ( - echo. - echo git pull did not succeed ^(the reason is above^): nothing was updated. Files you changed here can stop it: - echo "git status" lists them. - pause - exit /b 1 - ) - ) - ) else ( - echo This copy of Strata was not made with git, so it cannot fetch new files itself. Download the newest one: - echo https://github.com/Niko1221/Strata/archive/refs/heads/main.zip - echo unzip it anywhere and run START-HERE.bat ^(or UPDATE.bat^) in it: it finds the model files in Strata-data - echo and sets itself up the same way - nothing big is downloaded again. - echo Checking this copy's engine and settings meanwhile ... - ) - call "%~dp0START-HERE.bat" --update %* - if not errorlevel 1 pause - exit /b -) diff --git a/engine/strata/apps/desktop/package-lock.json b/engine/strata/apps/desktop/package-lock.json deleted file mode 100644 index 448060e1..00000000 --- a/engine/strata/apps/desktop/package-lock.json +++ /dev/null @@ -1,232 +0,0 @@ -{ - "name": "strata-desktop", - "version": "0.1.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "strata-desktop", - "version": "0.1.0", - "devDependencies": { - "@tauri-apps/cli": "2.12.3" - } - }, - "node_modules/@tauri-apps/cli": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz", - "integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==", - "dev": true, - "license": "Apache-2.0 OR MIT", - "bin": { - "tauri": "tauri.js" - }, - "engines": { - "node": ">= 10" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/tauri" - }, - "optionalDependencies": { - "@tauri-apps/cli-darwin-arm64": "2.12.3", - "@tauri-apps/cli-darwin-x64": "2.12.3", - "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3", - "@tauri-apps/cli-linux-arm64-gnu": "2.12.3", - "@tauri-apps/cli-linux-arm64-musl": "2.12.3", - "@tauri-apps/cli-linux-riscv64-gnu": "2.12.3", - "@tauri-apps/cli-linux-x64-gnu": "2.12.3", - "@tauri-apps/cli-linux-x64-musl": "2.12.3", - "@tauri-apps/cli-win32-arm64-msvc": "2.12.3", - "@tauri-apps/cli-win32-ia32-msvc": "2.12.3", - "@tauri-apps/cli-win32-x64-msvc": "2.12.3" - } - }, - "node_modules/@tauri-apps/cli-darwin-arm64": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz", - "integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-darwin-x64": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz", - "integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz", - "integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm64-gnu": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz", - "integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-arm64-musl": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz", - "integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz", - "integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-x64-gnu": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz", - "integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-linux-x64-musl": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz", - "integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-arm64-msvc": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz", - "integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-ia32-msvc": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz", - "integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@tauri-apps/cli-win32-x64-msvc": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz", - "integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "Apache-2.0 OR MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - } - } -} diff --git a/engine/strata/apps/desktop/package.json b/engine/strata/apps/desktop/package.json deleted file mode 100644 index e66e5fbc..00000000 --- a/engine/strata/apps/desktop/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "strata-desktop", - "productName": "Strata", - "version": "0.2.5", - "private": true, - "description": "Strata Desktop - local AI, tuned to one model.", - "scripts": { - "build:ui": "npm --prefix ../host run build", - "typecheck:ui": "npm --prefix ../host run typecheck", - "test:ui": "npm --prefix ../host test", - "tauri": "tauri", - "dev": "npm run build:ui && tauri dev", - "build": "npm run build:ui && tauri build", - "build:app": "npm run build:ui && tauri build --bundles app", - "dmg": "npm run build:ui && tauri build --bundles dmg" - }, - "devDependencies": { - "@tauri-apps/cli": "2.12.3" - } -} diff --git a/engine/strata/apps/desktop/scripts/app-close-matrix.py b/engine/strata/apps/desktop/scripts/app-close-matrix.py deleted file mode 100644 index 31e65b98..00000000 --- a/engine/strata/apps/desktop/scripts/app-close-matrix.py +++ /dev/null @@ -1,361 +0,0 @@ -#!/usr/bin/env python3 -"""The installed Windows app, closed every way, with a stub engine: nothing may be left running. - - python apps/desktop/scripts/app-close-matrix.py --install [--scenarios all] [--report out.json] - -For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API -(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app, -the host, Control, the owner host, the server, the engine), ends the app one way, and asserts: - * no process of the tree is left, the engine's port is free, the runtime lease can be taken again; - * the engine got the clean stop where the way of closing allows one (normal close, window X); - * the next load of the same slot works (a lost owner's state is cleaned, not a blocker). -It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both. -Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs. -""" -from __future__ import annotations - -import argparse -import ctypes -import json -import os -import subprocess -import sys -import tempfile -import time -import urllib.error -import urllib.request -from ctypes import wintypes -from pathlib import Path - -ROOT = Path(__file__).resolve().parents[3] -sys.path.insert(0, str(ROOT)) - -import psutil # noqa: E402 - -from strata_control import procs, runtime # noqa: E402 -from tests.terminal.lifecycle_matrix import install_fake_engine, port_open # noqa: E402 - -if os.name != "nt": - raise SystemExit("this matrix drives the Windows installer's app") - -user32 = ctypes.WinDLL("user32", use_last_error=True) -WM_CLOSE = 0x0010 - - -def main_window(pid: int) -> int | None: - found = [] - - @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) - def visit(hwnd, _): - owner = wintypes.DWORD() - user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner)) - if owner.value == pid and user32.IsWindowVisible(hwnd): - buf = ctypes.create_unicode_buffer(256) - user32.GetWindowTextW(hwnd, buf, 256) - if buf.value.strip() == "Strata": - found.append(hwnd) - return True - user32.EnumWindows(visit, 0) - return found[0] if found else None - - -class Scratch: - def __init__(self, root: Path, install: Path): - self.root, self.install = root, install - self.components = root / "components" - self.models = root / "models" - self.mark = root / "mark" - for d in (self.components, self.models, self.mark, root / "local", root / "home", root / "appdata", root / "webview"): - d.mkdir(parents=True, exist_ok=True) - install_fake_engine(self.components) - from tools.strata_tokenizer import BYTE_TO_UNICODE - tok = self.models / "tokenizer" - tok.mkdir() - tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"] - (tok / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)})) - (tok / "merges.txt").write_text("a b") - (tok / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3])) - for name in ("stub", "stub2"): - (self.models / f"strata-{name}.json").write_text(json.dumps({ - "exe": "component:strata-engine", "backend": "cuda", "tokenizer": str(tok), "args": [], "cwd": str(root), - "model_name": name, "host": "127.0.0.1", "port": 0})) - self.env = {**os.environ, "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_PROFILE_DIR": str(root / "profiles"), - "STRATA_RUNTIME_DIR": str(root / "runtime"), "STRATA_INSTALL_DIR": str(self.models), - "STRATA_MODELS_DIR": str(root / "models-unused"), "STRATA_ENGINE_BACKEND": "cuda", - "STRATA_HOME": str(root / "home"), "APPDATA": str(root / "appdata"), "LOCALAPPDATA": str(root / "local"), - "WEBVIEW2_USER_DATA_FOLDER": str(root / "webview"), "FAKE_ENGINE_MARK": str(self.mark), - "FAKE_ENGINE_SLOW_STEPS": "0", "PYTHONDONTWRITEBYTECODE": "1"} - self.env.pop("STRATA_API_KEY", None) - for key in ("STRATA_COMPONENTS_DIR", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "STRATA_ENGINE_BACKEND", - "STRATA_NO_ACQUIRE", "FAKE_ENGINE_MARK"): - os.environ[key] = self.env.get(key, "1") # this process reads the same runtime and records folders - - -class App: - def __init__(self, scratch: Scratch): - self.s = scratch - self.proc = subprocess.Popen([str(scratch.install / "strata-desktop.exe")], cwd=scratch.install, env=scratch.env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - self.base = None - - def host(self): - for child in psutil.Process(self.proc.pid).children(recursive=True): - if child.name().lower() == "node.exe": - return child - return None - - def wait_up(self, seconds=90): - deadline = time.monotonic() + seconds - while time.monotonic() < deadline: - if self.proc.poll() is not None: - raise RuntimeError(f"the app exited with {self.proc.returncode}") - try: - host = self.host() - if host: - for c in host.net_connections(kind="tcp"): - if c.status == "LISTEN" and c.laddr.ip == "127.0.0.1": - base = f"http://127.0.0.1:{c.laddr.port}" - try: - if urllib.request.urlopen(base + "/api/health", timeout=2).status == 200 and main_window(self.proc.pid): - self.base = base - return - except OSError: - pass - except psutil.Error: - pass - time.sleep(0.5) - raise RuntimeError("the app did not come up") - - def call(self, path, method="GET", body=None): - req = urllib.request.Request(self.base + path, method=method, data=None if body is None else json.dumps(body).encode(), - headers={"content-type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=120) as r: - return json.loads(r.read() or b"null") - except urllib.error.HTTPError as exc: - raise RuntimeError(f"{method} {path} -> {exc.code} {exc.read()[:300]!r}") from None - - def load(self, model, multiple=False): - self.call("/api/native?refresh=1") - started = self.call("/api/native/operations", "POST", {"kind": "load", "args": {"model": model, **({"multiple": True} if multiple else {})}}) - deadline = time.monotonic() + 180 - while time.monotonic() < deadline: - state = self.call("/api/native") - job = next((j for j in state["jobs"] if j["id"] == started["id"]), None) - if job and job["state"] != "running": - if job["state"] != "done": - raise RuntimeError(f"load {model}: {job['state']} {job.get('error')}") - return state - time.sleep(0.3) - raise RuntimeError("load did not finish") - - -def tree_of(app: App, slots=("app-1",)) -> tuple[list[procs.Ident], list[int]]: - idents, ports = [], [] - members = [psutil.Process(app.proc.pid), *psutil.Process(app.proc.pid).children(recursive=True)] - pids = {p.pid for p in members} - for slot in slots: - state = runtime._read_state(slot) - if state: - pids.add(state["host_pid"]) - for r in procs.records(): - if r.get("profile") in slots: # the app's own slots; a Terminal service is not part of the app's tree - pids.add(r["pid"]) - for pid in pids: - token = procs.start_token(pid) - if token: - idents.append(procs.Ident(pid, token, tuple(procs.command_line(pid) or []))) - return idents, ports - - -def survivors(idents): - return [f"{i.pid} {' '.join(i.cmd)[:80]}" for i in idents if procs.start_token(i.pid) == i.token] - - -def wait_gone(idents, seconds): - deadline = time.monotonic() + seconds - left = survivors(idents) - while left and time.monotonic() < deadline: - time.sleep(0.25) - left = survivors(idents) - return left - - -def lease_free() -> bool: - try: - fd = runtime.acquire_activity_lease(shared=False) - except Exception: # noqa: BLE001 - return False - runtime._unlock_file(fd) - os.close(fd) - return True - - -def control(scratch: Scratch, *argv: str, timeout: int = 300) -> dict: - py = scratch.install / "control" / "python" / "python.exe" - out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), *argv, "--output", "json"], - env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, - capture_output=True, text=True, timeout=timeout) - try: - return json.loads(out.stdout) - except ValueError: - return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]} - - -def stop_cli(scratch: Scratch, slot: str) -> dict: - py = scratch.install / "control" / "python" / "python.exe" - out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), "runtime", "stop", "--profile", slot, "--wait", "30", - "--output", "json"], env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"}, - capture_output=True, text=True, timeout=120) - try: - return json.loads(out.stdout) - except ValueError: - return {"state": "?", "raw": out.stdout[-200:] + out.stderr[-200:]} - - -def case(name: str, install: Path, how: str) -> dict: - with tempfile.TemporaryDirectory(prefix="strata-app-matrix-", ignore_cleanup_errors=True) as tmp: - saved = dict(os.environ) - scratch = Scratch(Path(tmp), install) - app = App(scratch) - problems, note = [], "" - try: - app.wait_up() - slots = ("app-1", "app-2") if how == "two-engines" else ("app-1",) - terminal = None - if how == "window-x-terminal-engine": - # an engine the Terminal started (its own profile, no tie to the app) must survive the app's close - control(scratch, "profile", "create", "terminal-1", "--from-config", str(scratch.models / "strata-stub2.json")) - terminal = control(scratch, "runtime", "start", "--profile", "terminal-1", "--wait", "60") - if terminal.get("state") != "ready": - raise RuntimeError(f"the Terminal's service did not start: {terminal}") - terminal_pids = {r["pid"] for r in procs.records(profile="terminal-1")} | {runtime._read_state("terminal-1")["host_pid"]} - state = app.load("stub") - if how == "two-engines": - state = app.load("stub2", multiple=True) - engine_ports = [i["port"] for i in state["instances"]] - idents, _ = tree_of(app, slots) - kinds = sorted({("engine" if "engine" in " ".join(i.cmd) else "server" if "serve.server" in " ".join(i.cmd) else - "owner" if "strata_control.runtime" in " ".join(i.cmd) else "app" if "strata-desktop" in i.cmd[0].lower() - else "host" if "node" in i.cmd[0].lower() else "other") for i in idents}) - note = f"tree {len(idents)} processes: {', '.join(kinds)}; engine ports {engine_ports}" - t0 = time.monotonic() - if how == "normal-close": - subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) - elif how in ("window-x", "two-engines", "window-x-terminal-engine"): - hwnd = main_window(app.proc.pid) - if not hwnd: - raise RuntimeError("no main window") - user32.PostMessageW(hwnd, WM_CLOSE, 0, 0) - elif how == "kill-app": - subprocess.run(["taskkill", "/F", "/PID", str(app.proc.pid)], capture_output=True) - elif how == "host-crash": - host = app.host() - subprocess.run(["taskkill", "/F", "/PID", str(host.pid)], capture_output=True) - elif how == "second-launch": - second = subprocess.Popen([str(install / "strata-desktop.exe")], cwd=install, env=scratch.env, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - try: - code = second.wait(timeout=30) - except subprocess.TimeoutExpired: - second.kill() - problems.append("the second launch did not exit") - code = None - time.sleep(2) - hosts = [p for p in psutil.process_iter(["name", "pid"]) if p.info["name"].lower() == "node.exe" - and (p.parent() and p.parent().pid == app.proc.pid)] - apps = [p for p in psutil.process_iter(["name"]) if p.info["name"].lower() == "strata-desktop.exe"] - if app.proc.poll() is not None: - problems.append("the first app went away") - if len(apps) != 1: - problems.append(f"{len(apps)} app processes (want 1)") - if len(hosts) != 1: - problems.append(f"{len(hosts)} hosts under the first app (want 1)") - after, _ = tree_of(app, slots) - new = [i for i in after if i.pid not in {x.pid for x in idents}] - if new: - problems.append(f"the second launch started: {[' '.join(i.cmd)[:60] for i in new]}") - note += f"; second launch exit code {code}, app processes {len(apps)}, hosts {len(hosts)}" - subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) - if how == "host-crash": - # the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and - # the engine must not - idents = [i for i in idents if any(k in " ".join(i.cmd) for k in ("strata_control.runtime", "serve.server", "engine", "node.exe"))] - left = wait_gone(idents, 90) - if left: - problems.append(f"processes left: {left}") - for port in engine_ports: - deadline = time.monotonic() + 10 - while port_open(port) and time.monotonic() < deadline: - time.sleep(0.2) - if port_open(port): - problems.append(f"engine port {port} still open") - if terminal is None and not lease_free(): - problems.append("lease still held") - marks = sorted(p.name for p in scratch.mark.iterdir()) - if terminal is not None: - status = control(scratch, "runtime", "status", "--profile", "terminal-1") - alive_pids = [p for p in terminal_pids if procs.start_token(p)] - if status.get("state") != "ready" or len(alive_pids) != len(terminal_pids): - problems.append(f"closing the app disturbed the Terminal's service: {status.get('state')}, alive {alive_pids} of {sorted(terminal_pids)}") - note += f"; the Terminal's service is {status.get('state')} after the app closed" - stopped = control(scratch, "runtime", "stop", "--profile", "terminal-1", "--wait", "30") - if stopped.get("state") != "stopped" or [p for p in terminal_pids if procs.start_token(p)]: - problems.append(f"the Terminal's service did not stop on request: {stopped}") - time.sleep(1) - if not lease_free(): - problems.append("lease still held after the Terminal's service stopped") - if how in ("normal-close", "window-x", "two-engines", "second-launch", "window-x-terminal-engine") and not ({"quit", "eof"} & set(marks)): - problems.append(f"the engine was not stopped the clean way (marks {marks})") - seconds = round(time.monotonic() - t0, 1) - if how == "host-crash": - subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True) - note += "; the app shell stays open after a host crash (by design today)" - # the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load - for slot in slots: - res = stop_cli(scratch, slot) - already = "not managed or is stopped" in json.dumps(res) # nothing was left to stop: the clean outcome - if res.get("state") not in ("stopped",) and not already: - problems.append(f"runtime stop {slot} after the close: {res}") - if runtime._read_state(slot) is not None: - problems.append(f"state of {slot} left behind") - return {"name": f"app-{how}", "ok": not problems, "problems": problems, "seconds": seconds, "marks": marks, "note": note} - except Exception as exc: # noqa: BLE001 - return {"name": f"app-{how}", "ok": False, "problems": [f"{type(exc).__name__}: {exc}"] + problems, "note": note} - finally: - for p in psutil.process_iter(["name", "exe"]): - try: - if (p.info["exe"] or "").lower().startswith(str(install).lower()): - p.kill() - except psutil.Error: - pass - for r in procs.records(): - try: - psutil.Process(r["pid"]).kill() - except psutil.Error: - pass - os.environ.clear(); os.environ.update(saved) - - -SCENARIOS = ["normal-close", "window-x", "window-x-terminal-engine", "kill-app", "host-crash", "second-launch", "two-engines"] - - -def main() -> int: - ap = argparse.ArgumentParser() - ap.add_argument("--install", required=True) - ap.add_argument("--scenarios", default="all") - ap.add_argument("--report") - a = ap.parse_args() - names = SCENARIOS if a.scenarios == "all" else a.scenarios.split(",") - results = [] - for how in names: - r = case(how, Path(a.install), how) - results.append(r) - print(("PASS " if r["ok"] else "FAIL ") + r["name"], r.get("seconds", ""), r.get("problems") or "", r.get("note", ""), flush=True) - if a.report: - Path(a.report).write_text(json.dumps({"platform": "windows", "engine": "fake", "results": results}, indent=1), encoding="utf-8") - return 0 if all(r["ok"] for r in results) else 1 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/engine/strata/apps/desktop/scripts/cards-e2e.mjs b/engine/strata/apps/desktop/scripts/cards-e2e.mjs deleted file mode 100644 index fe31a7f4..00000000 --- a/engine/strata/apps/desktop/scripts/cards-e2e.mjs +++ /dev/null @@ -1,110 +0,0 @@ -#!/usr/bin/env node -/** - * The Graphics cards choice of the app, end to end on a box with two cards, through the installed app layout (packaged host + bundled Control + a real - * engine component): the model list carries the options (one rule, strata_control/gpu_fit.py), a model that fits one card recommends that card, then - * load with ONE card -> answers, only that card holds the model; load with BOTH cards (the layer split) -> answers, both cards hold the model. - * - * node cards-e2e.mjs --install --components > --work \ - * --family qwen --model IQ3_XXS --data [--smi "nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits"] - */ -import { spawn, spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readdirSync } from 'node:fs'; -import { createServer } from 'node:net'; -import { join, resolve } from 'node:path'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); -for (const need of ['install', 'components', 'work', 'model']) if (!args[need]) { console.error('missing --' + need); process.exit(2); } -const install = resolve(args.install), work = resolve(args.work), components = resolve(args.components), family = String(args.family ?? 'qwen'), modelId = String(args.model); -const node = join(install, 'node', 'node'), hostEntry = join(install, 'host', 'server', 'index.mjs'); -const dirs = { models: join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home'), xdg: join(work, 'xdg'), appdata: join(work, 'appdata') }; -for (const d of [dirs.models, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); -const delay = ms => new Promise(r => setTimeout(r, ms)); -let failed = false; -const record = (name, ok, detail = '') => { if (!ok) failed = true; console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 500) : ''}`); }; -const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; -const env = { ...process.env, STRATA_COMPONENTS_DIR: components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.models, - STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models-unused'), APPDATA: dirs.appdata, XDG_CONFIG_HOME: dirs.xdg, PYTHONDONTWRITEBYTECODE: '1' }; -delete env.STRATA_API_KEY; -const port = await freePort(); -const base = `http://127.0.0.1:${port}`; -const host = spawn(node, [hostEntry], { cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], - env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', - STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } }); -let hostLog = ''; -host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); -const call = async (path, method = 'GET', body) => { - const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); - return { status: response.status, body: await response.json().catch(() => null) }; -}; -async function waitJob(id, seconds) { - let last = ''; - for (let i = 0; i < seconds * 2; i++) { - const state = (await call('/api/native')).body; - const job = state.jobs.find(j => j.id === id); - if (job && job.summary !== last) { last = job.summary; console.log(' ... ' + String(last).slice(0, 120)); } - if (job && job.state !== 'running') return { job, state }; - await delay(500); - } - throw new Error('operation did not finish'); -} -const smi = () => { - const cmd = String(args.smi ?? 'nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits').split(' '); - const r = spawnSync(cmd[0], cmd.slice(1), { encoding: 'utf8' }); - return (r.stdout ?? '').split('\n').map(s => Number(s.trim())).filter(Number.isFinite); -}; -async function chatPong(instance) { - const chat = await call('/v1/chat/completions', 'POST', { model: instance?.apiModelId ?? modelId.toLowerCase(), max_tokens: 400, stream: false, temperature: 0, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }] }); - const m = chat.body?.choices?.[0]?.message ?? {}; - return { ok: chat.status === 200 && /pong/i.test(`${m.content ?? ''}`), text: `${m.content ?? ''}`.slice(0, 60), status: chat.status }; -} -async function main() { - let up = false; - for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { /* not yet */ } if (!up) await delay(150); } - record('host healthy', up, up ? base : hostLog.slice(-500)); - if (!up) return; - const packages = existsSync(join(components, 'engine')) ? readdirSync(join(components, 'engine')) : []; - record('an engine component is installed', packages.length > 0, packages.join(', ')); - - // ---- the model list carries the choice - const native = (await call('/api/native?refresh=1')).body; - const gpus = native.hardware?.gpus ?? []; - record('the host sees two or more graphics cards', gpus.filter(g => g.usable !== false).length >= 2, JSON.stringify(gpus.map(g => ({ i: g.index, n: g.name, gb: g.vram_gb })))); - const size = native.catalog?.families?.find(f => f.family === family)?.sizes.find(s => s.model === modelId); - const opt = size?.gpu_options; - record('the model list offers the cards choice for this model', !!opt && opt.options.length >= 2, JSON.stringify(opt?.options?.map(o => ({ key: o.key, cards: o.cards, verdict: o.verdict, rec: o.recommended })))); - record('a model that fits one card recommends the single largest card (the split is offered, not forced)', opt?.recommended === 'single' && opt.options.find(o => o.key === 'split'), `recommended=${opt?.recommended}`); - const single = opt?.options.find(o => o.key === 'single')?.cards ?? [0]; - const both = opt?.options.find(o => o.key === 'split')?.cards ?? [0, 1]; - - // ---- Download and prepare with the recommended card - const values = { family, model: modelId, context: 32768, vision: 'no', gpu: single[0], ...(args.data ? { data_dir: resolve(args.data) } : {}) }; - const started = await call('/api/native/operations', 'POST', { kind: 'install', args: values }); - record('the install operation starts', started.status === 200 || started.status === 202, JSON.stringify(started.body).slice(0, 160)); - const done = await waitJob(started.body.id, 3600); - record('Download and prepare finishes', done.job.state === 'done', `${done.job.state} ${done.job.error ?? done.job.summary}`); - const installed = (await call('/api/native?refresh=1')).body.installed?.models?.find(m => String(m.model).toLowerCase() === modelId.toLowerCase()); - const model = installed?.model ?? modelId.toLowerCase(); - - for (const [label, cards] of [['ONE card', single], ['BOTH cards (layer split)', both]]) { - const before = smi(); - const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model, gpus: cards } }); - const loaded = await waitJob(load.body.id, 900); - const instance = loaded.state.instances[0]; - record(`load with ${label} starts the engine`, loaded.job.state === 'done' && instance?.status === 'ready', `${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}; gpus=${JSON.stringify(instance?.gpus)}`); - record(`the instance runs on exactly the chosen card(s)`, JSON.stringify([...(instance?.gpus ?? [])].sort()) === JSON.stringify([...cards].sort()), `want ${JSON.stringify(cards)} got ${JSON.stringify(instance?.gpus)}`); - await delay(3000); - const used = smi(); - const holding = used.map((mb, i) => (mb - (before[i] ?? 0)) > 1000 ? i : -1).filter(i => i >= 0); - record(`only the chosen card(s) hold the model (graphics memory in use: ${used.join(', ')} MiB)`, JSON.stringify(holding) === JSON.stringify([...cards].sort()), `holding ${JSON.stringify(holding)}`); - const pong = await chatPong(instance); - record(`it answers (${label})`, pong.ok, `${pong.status} ${JSON.stringify(pong.text)}`); - const unloaded = await call(`/api/native/instances/${instance?.id}/unload`, 'POST', {}); - record(`unload (${label})`, unloaded.status === 200, unloaded.status); - await delay(4000); - } -} -try { await main(); } catch (e) { record('run', false, e.stack ?? e); } -host.kill(); -await delay(1500); -console.log(failed ? 'CARDS-E2E FAIL' : 'CARDS-E2E PASS'); -process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/fetch-node.ps1 b/engine/strata/apps/desktop/scripts/fetch-node.ps1 deleted file mode 100644 index 2d833a9b..00000000 --- a/engine/strata/apps/desktop/scripts/fetch-node.ps1 +++ /dev/null @@ -1,72 +0,0 @@ -# Fetch and verify the private Node runtime the Windows desktop bundle ships (win-x64). -# -# The PowerShell twin of fetch-node.sh: same pinned version, same SHA-256 pin, same refusal to -# install anything whose digest does not match. Not committed output: node.exe is a ~90 MB binary. -# -# Usage: -# powershell -NoProfile -ExecutionPolicy Bypass -File apps\desktop\scripts\fetch-node.ps1 -# ... -File fetch-node.ps1 -Check # verify what is already installed -# ... -File fetch-node.ps1 -FromFile node.zip # verify and install a zip you already have (offline) -# -# The Node version must satisfy the App Host's own engines.node (>= 24.12.0). -[CmdletBinding()] -param( - [switch]$Check, - [string]$FromFile = '', - [string]$Dest = '' -) -$ErrorActionPreference = 'Stop' - -$NodeVersion = if ($env:STRATA_NODE_VERSION) { $env:STRATA_NODE_VERSION } else { '24.12.0' } -$Target = 'win-x64' -# SHA-256 of node-v24.12.0-win-x64.zip from nodejs.org's SHASUMS256.txt; keep equal to fetch-node.sh. -$Expected = '9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812' -if (-not $Dest) { $Dest = Join-Path $PSScriptRoot '..\src-tauri\resources\node' } -$Installed = Join-Path $Dest 'node.exe' - -function Fail([string]$Message) { [Console]::Error.WriteLine("fetch-node: $Message"); exit 1 } - -if ($Check) { - if (-not (Test-Path -LiteralPath $Installed)) { Fail "not installed at $Installed" } - $got = (& $Installed --version).Trim() - Write-Output "fetch-node: $Installed is $got" - if ($got -ne "v$NodeVersion") { Fail "expected v$NodeVersion" } - exit 0 -} - -$Archive = "node-v$NodeVersion-$Target.zip" -$Work = Join-Path ([IO.Path]::GetTempPath()) ("strata-node-" + [Guid]::NewGuid().ToString('N')) -New-Item -ItemType Directory -Path $Work | Out-Null -try { - $Zip = Join-Path $Work $Archive - if ($FromFile) { - Copy-Item -LiteralPath $FromFile -Destination $Zip - } else { - $Url = "https://nodejs.org/dist/v$NodeVersion/$Archive" - Write-Output "fetch-node: $Url" - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - $ProgressPreference = 'SilentlyContinue' - Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Zip - } - $Actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $Zip).Hash.ToLowerInvariant() - if ($NodeVersion -ne '24.12.0') { - # another version has no recorded digest: say so rather than implying a verification - [Console]::Error.WriteLine("fetch-node: WARNING - no recorded digest for v$NodeVersion; this download is NOT authenticated.") - [Console]::Error.WriteLine("fetch-node: computed sha256 $Actual - record it in this script and fetch-node.sh.") - } elseif ($Actual -ne $Expected) { - Fail "REFUSING - $Archive hashes $Actual, expected $Expected" - } else { - Write-Output 'fetch-node: sha256 verified against the recorded digest' - } - Add-Type -AssemblyName System.IO.Compression.FileSystem - $zipFile = [IO.Compression.ZipFile]::OpenRead($Zip) - try { - $entry = $zipFile.GetEntry("node-v$NodeVersion-$Target/node.exe") - if (-not $entry) { Fail "node.exe is not inside $Archive" } - New-Item -ItemType Directory -Force -Path $Dest | Out-Null - [IO.Compression.ZipFileExtensions]::ExtractToFile($entry, $Installed, $true) - } finally { $zipFile.Dispose() } - Write-Output "fetch-node: installed at $Installed" -} finally { - Remove-Item -LiteralPath $Work -Recurse -Force -ErrorAction SilentlyContinue -} diff --git a/engine/strata/apps/desktop/scripts/fetch-node.sh b/engine/strata/apps/desktop/scripts/fetch-node.sh deleted file mode 100755 index 3a363233..00000000 --- a/engine/strata/apps/desktop/scripts/fetch-node.sh +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env bash -# Fetch and verify the private Node runtime the desktop bundle ships. -# -# The App Host is an ordinary Node program, and the packaging requirement is that an end user -# supplies no runtime of their own. The desktop bundle therefore carries a pinned standalone Node -# beside the host. -# -# It is NOT committed. It is a ~117 MB platform binary: committing it would bloat every clone, it -# cannot be reviewed in a diff, and it is not source. This script is the reproducible substitute — -# it downloads the official build for the target and refuses to install anything whose SHA-256 does -# not match the recorded digest. -# -# Usage: -# apps/desktop/scripts/fetch-node.sh # host platform -# apps/desktop/scripts/fetch-node.sh --target linux-x64 -# apps/desktop/scripts/fetch-node.sh --check # verify what is already installed -# -# The Node version must satisfy the App Host's own `engines.node` (>= 24.12.0). -set -euo pipefail - -NODE_VERSION="${STRATA_NODE_VERSION:-24.12.0}" -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DEST="$HERE/../src-tauri/resources/node" - -# Published SHA-256 of each official nodejs.org archive, recorded so a tampered or truncated -# download is refused rather than shipped. Add a row when bumping the version. -# Taken from nodejs.org's own SHASUMS256.txt for v24.12.0, which is published over HTTPS beside -# the archives. Recorded here so the fetch is verified against a value that does not come from the -# same response as the payload. -digest_for() { - case "$1" in - darwin-arm64) echo "319f221adc5e44ff0ed57e8a441b2284f02b8dc6fc87b8eb92a6a93643fd8080" ;; - linux-x64) echo "6159227e0af7d7c3c6bb2fa900452b04a6cb8841a702a79acc613209d70b04d0" ;; - linux-arm64) echo "9b2a2eeb98a8eb37361224e2a1d060300ad2dd143af58dfdb16de785df0f1228" ;; - win-x64) echo "9c125f61ae947b52e779095830f9cac267846a043ef7192183c84016aaad2812" ;; - *) echo "" ;; - esac -} - -target() { - if [ "${1:-}" = "--target" ]; then echo "${2:?--target needs a value}"; return; fi - case "$(uname -s)-$(uname -m)" in - Darwin-arm64) echo darwin-arm64 ;; - Linux-x86_64) echo linux-x64 ;; - Linux-aarch64) echo linux-arm64 ;; - MINGW*|MSYS*|CYGWIN*) echo win-x64 ;; - *) echo "unsupported host: $(uname -s)-$(uname -m)" >&2; exit 2 ;; - esac -} - -TARGET="$(target "$@")" -EXE="node" -case "$TARGET" in win-*) EXE="node.exe" ;; esac -INSTALLED="$DEST/$EXE" - -if [ "${1:-}" = "--check" ]; then - if [ ! -x "$INSTALLED" ]; then echo "fetch-node: not installed at $INSTALLED" >&2; exit 1; fi - got="$("$INSTALLED" --version)" - echo "fetch-node: $INSTALLED is $got" - case "$got" in "v$NODE_VERSION") exit 0 ;; *) echo "fetch-node: expected v$NODE_VERSION" >&2; exit 1 ;; esac -fi - -# The official archive for this target. -case "$TARGET" in - darwin-arm64) ARCHIVE="node-v$NODE_VERSION-darwin-arm64.tar.gz" ;; - darwin-x64) ARCHIVE="node-v$NODE_VERSION-darwin-x64.tar.gz" ;; - linux-x64) ARCHIVE="node-v$NODE_VERSION-linux-x64.tar.gz" ;; - linux-arm64) ARCHIVE="node-v$NODE_VERSION-linux-arm64.tar.gz" ;; - win-x64) ARCHIVE="node-v$NODE_VERSION-win-x64.zip" ;; - *) echo "fetch-node: no archive known for $TARGET" >&2; exit 2 ;; -esac -URL="https://nodejs.org/dist/v$NODE_VERSION/$ARCHIVE" - -EXPECTED="$(digest_for "$TARGET")" -WORK="$(mktemp -d "${TMPDIR:-/tmp}/strata-node.XXXXXX")" # GNU mktemp needs the X template; BSD accepts it too -trap 'rm -rf "$WORK"' EXIT - -echo "fetch-node: $URL" -curl -fsSL -o "$WORK/$ARCHIVE" "$URL" - -ACTUAL="$(shasum -a 256 "$WORK/$ARCHIVE" 2>/dev/null | cut -d' ' -f1 || sha256sum "$WORK/$ARCHIVE" | cut -d' ' -f1)" -if [ -n "$EXPECTED" ]; then - if [ "$ACTUAL" != "$EXPECTED" ]; then - echo "fetch-node: REFUSING — $ARCHIVE hashes $ACTUAL, expected $EXPECTED" >&2 - exit 1 - fi - echo "fetch-node: sha256 verified against the recorded digest" -else - # Without a recorded digest the download cannot be authenticated. Say so loudly and keep the - # computed value so it can be recorded, rather than implying a verification that did not happen. - echo "fetch-node: WARNING — no recorded digest for $TARGET; this download is NOT authenticated." >&2 - echo "fetch-node: computed sha256 $ACTUAL — record it in $(basename "${BASH_SOURCE[0]}") to enable verification." >&2 -fi - -mkdir -p "$DEST" -case "$ARCHIVE" in - *.zip) unzip -q -j "$WORK/$ARCHIVE" "node-v$NODE_VERSION-win-x64/node.exe" -d "$DEST" ;; - *) tar xzf "$WORK/$ARCHIVE" -C "$WORK" - cp "$WORK/node-v$NODE_VERSION-$TARGET/bin/node" "$DEST/node" ;; -esac -chmod +x "$DEST/$EXE" - -echo "fetch-node: installed $("$DEST/$EXE" --version) at $DEST/$EXE" diff --git a/engine/strata/apps/desktop/scripts/first-run-ui.mjs b/engine/strata/apps/desktop/scripts/first-run-ui.mjs deleted file mode 100644 index 757905cd..00000000 --- a/engine/strata/apps/desktop/scripts/first-run-ui.mjs +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env node -/** - * The first run of the installed app, headless: the host as the Tauri shell starts it (STRATA_PACKAGED=1, STRATA_NO_ACQUIRE=1, - * the staged Control, nothing installed, nothing in the per-user folders) and Chrome on its onboarding. - * - * node apps/desktop/scripts/first-run-ui.mjs [--control ] [--node ] [--work ] [--shots ] - * - * Checks, one line each (exit 1 if any fails): - * the host answers; /api/native has a real catalog (families with sizes), a recommendation and the GPUs of this PC - * (from Control's bundled installer on Control's Python); the page shows "Let's get started", and after it the model - * list with sizes (no "couldn't show this screen"); no page error; the install plan for the recommended model is a - * plan (nothing is downloaded or started: a plan changes nothing); the spy sees no pip/git/compiler/engine fetch. - * Per-user folders (STRATA_HOME, APPDATA, LOCALAPPDATA, the components and install folders) are all under --work. - * No model is downloaded and no engine runs. - */ -import { spawn } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:net'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') ? true : all[i + 1]]] : acc), [])); -const here = dirname(fileURLToPath(import.meta.url)); -const repoHost = resolve(here, '../../host'); -const staged = resolve(here, '../src-tauri/resources'); -const control = resolve(args.control ?? join(staged, 'control')); -const nodeExe = resolve(args.node ?? join(staged, 'node', process.platform === 'win32' ? 'node.exe' : 'node')); -const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-first-run-'))); -const shots = resolve(args.shots ?? join(work, 'shots')); -mkdirSync(work, { recursive: true }); mkdirSync(shots, { recursive: true }); -const spy = pathToFileURL(join(repoHost, 'tests/helpers/acquire-spy.mjs')).href; -const spyLog = join(work, 'spy.log'); writeFileSync(spyLog, ''); - -const { chromium } = await import(pathToFileURL(join(repoHost, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); -const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'].find(existsSync); - -let failed = false; -const check = (ok, label, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${detail ? ' ' + detail : ''}`); if (!ok) failed = true; }; -const delay = ms => new Promise(r => setTimeout(r, ms)); -const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; - -for (const need of [nodeExe, join(control, 'strata.py'), join(repoHost, 'dist', 'index.html')]) if (!existsSync(need)) { console.error(`missing ${need} (run stage-control.py, fetch-node and "npm run build" in apps/host first)`); process.exit(2); } - -const dirs = { home: join(work, 'home'), appdata: join(work, 'appdata'), local: join(work, 'local'), components: join(work, 'local', 'Strata', 'components') }; -for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true }); -const port = await freePort(); -const env = { - ...process.env, - STRATA_PORT: String(port), STRATA_DIST: join(repoHost, 'dist'), STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', - STRATA_CONTROL_DIR: control, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(work, 'models'), STRATA_COMPONENTS_DIR: dirs.components, - APPDATA: dirs.appdata, LOCALAPPDATA: dirs.local, XDG_CONFIG_HOME: join(work, 'xdg'), XDG_DATA_HOME: join(work, 'xdgdata'), - STRATA_PROFILE_DIR: join(work, 'profiles'), STRATA_RUNTIME_DIR: join(work, 'runtime'), ACQUIRE_SPY_LOG: spyLog, -}; -delete env.STRATA_INSTALL_DIR; -mkdirSync(env.STRATA_MODELS_DIR, { recursive: true }); -const host = spawn(nodeExe, [...(args['no-spy'] === undefined ? ['--import', spy] : []), join(repoHost, 'server', 'index.mjs')], { cwd: repoHost, env, stdio: ['ignore', 'pipe', 'pipe'] }); -let hostLog = ''; -host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); -const base = `http://127.0.0.1:${port}`; -const api = async (path, init) => { const r = await fetch(base + path, init); return { status: r.status, body: await r.json().catch(() => null) }; }; - -let browser; -try { - let up = false; - for (let i = 0; i < 150 && !up; i++) { try { up = (await api('/api/health')).status === 200; } catch { await delay(200); } } - check(up, 'the packaged host starts', `port ${port}`); - if (!up) throw new Error(hostLog.slice(-2000)); - - const native = await api('/api/native?refresh=1'); - const state = native.body; - check(native.status === 200 && state?.available === true, 'the host reads Control', state?.error ?? ''); - const sizes = (state?.catalog?.families ?? []).reduce((n, f) => n + (f.sizes?.length ?? 0), 0); - check((state?.catalog?.families?.length ?? 0) > 0 && sizes >= 3, 'the catalog has real families and sizes', `${state?.catalog?.families?.length} families, ${sizes} sizes`); - check(!!state?.catalog?.recommendation, 'the catalog has a recommendation', JSON.stringify(state?.catalog?.recommendation ?? null).slice(0, 120)); - check(Array.isArray(state?.hardware?.gpus), 'the hardware lists GPUs', (state?.hardware?.gpus ?? []).map(g => `${g.name} ${g.vram_gb} GB`).join('; ') || 'none on this PC'); - check(state?.installDir && realpathSync.native(state.installDir).toLowerCase().startsWith(realpathSync.native(work).toLowerCase()), 'models go to a writable per-user folder, not the bundle', state?.installDir); - const hw = (await api('/api/hardware')).body; - console.log('info host hardware probe:', JSON.stringify((hw?.gpus ?? []).map(g => ({ name: g.name, backend: g.backend, vramGb: g.vramGb, unified: g.unified })))); - check(!state?.installerError, 'the bundled installer answers', state?.installerError ?? ''); - - browser = await chromium.launch({ executablePath: CHROME, headless: true }); - const page = await browser.newPage({ viewport: { width: 1400, height: 950 } }); - const problems = []; - page.on('pageerror', e => problems.push(`pageerror: ${e.message}`)); - await page.goto(base, { waitUntil: 'domcontentloaded' }); - await page.waitForSelector('text=/Let.s get started|Choose a version|Connect your Strata/i', { timeout: 30000 }).catch(() => {}); - await page.screenshot({ path: join(shots, '1-welcome.png') }); - const broken = await page.locator('text=/couldn.t show this screen/i').count(); - check(broken === 0, 'the first screen renders (not "Strata couldn\'t show this screen")'); - const start = page.getByRole('button', { name: /get started/i }); - check(await start.count() > 0, 'the welcome step offers "Let\'s get started"'); - if (await start.count()) await start.first().click(); - await page.waitForSelector('text=/Choose a version/i', { timeout: 30000 }).catch(() => {}); - await delay(1200); - await page.screenshot({ path: join(shots, '2-models.png') }); - check(await page.locator('text=/couldn.t show this screen/i').count() === 0, 'the model step renders'); - check(await page.getByText(/Choose a version/i).count() > 0, 'the model step lists the versions'); - const labels = await page.locator('[role=radio]').allInnerTexts(); - check(labels.length >= 3, 'the versions are the real catalog\'s sizes', labels.map(l => l.replace(/\s+/g, ' ').slice(0, 40)).join(' | ')); - check(labels.some(l => /\d+\.\d\s*GB/.test(l)), 'each version shows its download size'); - check(problems.length === 0, 'no page error', problems.join('; ')); - - const recommended = state?.catalog?.recommendation; - if (recommended?.model) { - const plan = await api('/api/native/plan', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ family: recommended.family, model: recommended.model, context: recommended.context, data_dir: join(work, 'Strata-data') }) }); - check(plan.status === 200 && !!plan.body?.plan, 'the install plan for the recommended model is a plan (nothing downloaded)', plan.body?.summary?.slice(0, 100) ?? JSON.stringify(plan.body).slice(0, 150)); - check(!existsSync(join(work, 'Strata-data', 'models')), 'a plan wrote no model files'); - } -} catch (error) { - check(false, 'the run', String(error?.message ?? error).slice(0, 600)); -} finally { - await browser?.close().catch(() => {}); - host.kill(); - await new Promise(r => host.once('exit', r)); // only the PID this script started - const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); - check(attempts.length === 0, 'the spy saw no pip, git, compiler, engine or internet access', attempts.slice(0, 3).join(' ')); - console.log(`shots in ${shots}`); - if (!args.work) rmSync(work, { recursive: true, force: true, maxRetries: 3 }); -} -process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs b/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs deleted file mode 100644 index 403d4df2..00000000 --- a/engine/strata/apps/desktop/scripts/flatten-pnpm.mjs +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Turn a pnpm "isolated" node_modules (a virtual store in `.pnpm` full of links) into an ordinary hoisted tree of real folders. - * - * Why: the installer copies the Harness folder file by file. pnpm's layout is thousands of links (junctions on Windows); a copy - * that follows them duplicates every package once per dependent and one that does not breaks on the first dangling link. A hoisted - * tree has each package once (nested only where two versions of the same name are needed), no links, and Node resolves it - * exactly as it resolves any npm install. - * - * Algorithm (the one npm uses, in short): the packages the root names come first, at the top. Then, walking each placed package's - * own dependencies: look the name up from the package's own folder upwards; if the same instance is already visible, nothing to - * do; if a DIFFERENT instance of that name is visible, nest this one inside the dependent; if none is visible, hoist it to the top. - * - * @param {string} out folder holding `node_modules` - * @param {{skip?: RegExp}} [options] package names never copied (the caller removes them anyway) - * @returns {{packages:number, copied:number, nested:number}} - */ -import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from 'node:fs'; -import { dirname, join, relative, sep } from 'node:path'; - -export function flattenPnpm(out, { skip = null } = {}) { - const nm = join(out, 'node_modules'); - const store = join(nm, '.pnpm'); - const flatRoot = join(out, 'node_modules.flat'); - rmSync(flatRoot, { recursive: true, force: true }); - mkdirSync(join(flatRoot, 'node_modules'), { recursive: true }); - - const manifest = dir => { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { return null; } }; - const nameOf = dir => manifest(dir)?.name ?? null; - /** - * What makes two instances "the same package": name and version. pnpm keeps one copy per set of peer packages (the same workspace - * package under many hashed folders); in one hoisted tree they are one package. - */ - const identity = dir => { const m = manifest(dir); return m ? `${m.name}@${m.version}` : dir; }; - /** The sibling links of a store instance: its dependencies, by name -> real instance folder. */ - function storeDeps(instance, name) { - const container = name.startsWith('@') ? dirname(dirname(instance)) : dirname(instance); - const found = new Map(); - for (const e of readdirSync(container, { withFileTypes: true })) { - if (e.name === '.bin') continue; - const entries = e.name.startsWith('@') ? readdirSync(join(container, e.name), { withFileTypes: true }).map(x => [`${e.name}/${x.name}`, join(container, e.name, x.name)]) : [[e.name, join(container, e.name)]]; - for (const [dep, p] of entries) { - if (dep === name) continue; - try { if (lstatSync(p).isSymbolicLink() || existsSync(p)) found.set(dep, realpathSync(p)); } catch { /* a dangling link: the package was removed on purpose */ } - } - } - return found; - } - /** Every instance in the store by package name, for packages that arrived without a store entry (copied peers). */ - const byName = new Map(); - if (existsSync(store)) { - for (const id of readdirSync(store, { withFileTypes: true })) { - if (!id.isDirectory()) continue; - const container = join(store, id.name, 'node_modules'); - if (!existsSync(container)) continue; - for (const e of readdirSync(container, { withFileTypes: true })) { - if (e.name === '.bin') continue; - const dirs = e.name.startsWith('@') ? readdirSync(join(container, e.name)).map(x => join(container, e.name, x)) : [join(container, e.name)]; - for (const d of dirs) { - let real; try { real = realpathSync(d); } catch { continue; } - if (!real.startsWith(store)) continue; // a link to a workspace package outside the store is handled through the instance table - const n = nameOf(real); - if (n && !byName.has(n)) byName.set(n, real); - } - } - } - } - - const placed = new Map(); // folder (in the flat tree) -> real instance folder it holds - let copied = 0, nested = 0; - - const visibleFrom = (chain, name) => { - for (const dir of chain) { - const slot = join(dir, 'node_modules', ...name.split('/')); - if (placed.has(slot)) return { slot, instance: placed.get(slot) }; - } - return null; - }; - const copyInto = (slot, instance) => { - mkdirSync(dirname(slot), { recursive: true }); - cpSync(instance, slot, { recursive: true, dereference: true, filter: f => !relative(instance, f).split(sep).includes('node_modules') }); - placed.set(slot, identity(instance)); - copied++; - }; - - const queue = []; // { slotDir (folder of the placed package), chain (folders searched upwards), instance, name } - const rootChain = [flatRoot]; - const place = (name, instance, chain, forceHere) => { - if (skip?.test(name)) return; - const seen = visibleFrom(chain, name); - if (seen && seen.instance === identity(instance)) return; - const hoist = !seen && !forceHere; - const base = hoist ? flatRoot : chain[0]; - const slot = join(base, 'node_modules', ...name.split('/')); - if (placed.has(slot)) return; // another instance already sits where this one would go (it nests below, handled by the caller's chain) - copyInto(slot, instance); - if (!hoist && base !== flatRoot) nested++; - queue.push({ slotDir: slot, chain: [slot, ...(hoist ? rootChain : chain)], instance, name }); - }; - - // 1. the packages the root names - const rootEntries = []; - for (const e of readdirSync(nm, { withFileTypes: true })) { - if (e.name === '.pnpm' || e.name === '.bin' || e.name.startsWith('.')) continue; - const entries = e.name.startsWith('@') ? readdirSync(join(nm, e.name)).map(x => [`${e.name}/${x}`, join(nm, e.name, x)]) : [[e.name, join(nm, e.name)]]; - for (const [name, p] of entries) rootEntries.push([name, p]); - } - for (const [name, p] of rootEntries) { - let real; try { real = realpathSync(p); } catch { continue; } - place(name, real, rootChain, true); - } - // 2. their dependencies, breadth first - while (queue.length) { - const { slotDir, chain, instance, name } = queue.shift(); - let wants; - if (instance.startsWith(store)) wants = storeDeps(instance, name); - else { - // a package copied in without a store entry: its declared requirements, taken from the store by name when not visible yet - const m = manifest(instance) ?? {}; - wants = new Map(); - for (const dep of [...Object.keys(m.dependencies ?? {}), ...Object.keys(m.peerDependencies ?? {}), ...Object.keys(m.optionalDependencies ?? {})]) { - if (visibleFrom(chain, dep)) continue; - const real = byName.get(dep); - if (real) wants.set(dep, real); - } - } - for (const [dep, real] of wants) place(dep, real, chain, false); - } - - rmSync(nm, { recursive: true, force: true }); - renameSync(join(flatRoot, 'node_modules'), nm); - rmSync(flatRoot, { recursive: true, force: true }); - return { packages: placed.size, copied, nested }; -} diff --git a/engine/strata/apps/desktop/scripts/harness-prune.mjs b/engine/strata/apps/desktop/scripts/harness-prune.mjs deleted file mode 100644 index 35b81124..00000000 --- a/engine/strata/apps/desktop/scripts/harness-prune.mjs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Which files and folders of the staged Harness are dropped, and the check that nothing the Harness imports is gone. - * - * The 2026-10-17 tester report: on Linux and Mac every agent chat failed ("session/create ... waiting for workflowEngine"). - * Cause: the old rule "drop any folder named after another operating system" also removed the Harness's own JavaScript package - * `@deepseek-ai/dsh-win32-process`. It is plain JS (no binary), and `dsh-subprocess-local` and `dsh-sandbox-local` import it by - * name on every platform, so those two plugins failed to load, and everything waiting on them (shell, subprocess, ptcRuntime, - * workflowEngine) never started. Windows kept it (the rule differs there), so the Windows tests passed. - */ -import { existsSync, readFileSync, readdirSync } from 'node:fs'; -import { join, sep } from 'node:path'; - -export const OTHER_OS = { - win32: /(^|[\\/._-])(darwin|linux|android|freebsd|musl)([\\/._-]|$)/i, - darwin: /(^|[\\/._-])(win32|linux|android|freebsd|musl)([\\/._-]|$)/i, - // Linux: the AppImage bundler (linuxdeploy) resolves the libraries of every ELF file under resources and stops on one it - // cannot satisfy (koffi's musl build wants libc.musl). The app is glibc x86_64, so musl and other-CPU builds are dropped. - linux: /(^|[\\/._-])(win32|darwin|android|freebsd|musl|arm64|aarch64|armv7|arm|ia32|riscv64|ppc64|s390x|loong64)([\\/._-]|$)/i, -}; -const NATIVE_FOLDER = /prebuild|bin|native|platform|-(win32|darwin|linux)/i; - -/** The Harness's own JavaScript packages (`@deepseek-ai/dsh-*`) are code every platform imports by name; never drop one. */ -export function isHarnessCodePackage(path) { - const parts = path.split(sep); - const i = parts.lastIndexOf('@deepseek-ai'); - return i >= 0 && i === parts.length - 2 && parts[i + 1].startsWith('dsh-'); -} - -/** True when the folder `path` (a directory named `name`) is another operating system's prebuilt binary and can go. */ -export function isOtherOsBinaryFolder(platform, name, path) { - const rule = OTHER_OS[platform] ?? OTHER_OS.linux; - if (isHarnessCodePackage(path)) return false; - return rule.test(name) && NATIVE_FOLDER.test(path); -} - -/** Imports the Windows copy (which works) is also without: browser-side or dev-only bundles, and the document converter the app drops on purpose. */ -const KNOWN_ABSENT = new Set([ - '@deepseek-ai/libreoffice-kit', '@deepseek-ai/dsh-client-ui-dockkit', '@deepseek-ai/dsh-client-web', - '@deepseek-ai/dsh-experimental-webworker-runtime', '@deepseek-ai/dsh-remote-mock', '@deepseek-ai/dsh-client-test-runtime', -]); - -function jsFiles(dir, out = []) { - for (const e of readdirSync(dir, { withFileTypes: true })) { - const p = join(dir, e.name); - if (e.isSymbolicLink()) continue; - if (e.isDirectory()) jsFiles(p, out); - else if (/\.(m?js|cjs)$/.test(e.name)) out.push(p); - } - return out; -} - -/** - * Every bare `@deepseek-ai/` the staged Harness's own packages import (static `from "x"` and `import("x")`) must exist - * in the staged node_modules. Returns the list of `{from, missing}` problems (empty = good). Plugins that are only loaded on - * another platform still count: Node resolves a static import whether or not the code runs. - */ -export function missingHarnessImports(harnessDir) { - const scope = join(harnessDir, 'node_modules', '@deepseek-ai'); - if (!existsSync(scope)) return [{ from: scope, missing: '@deepseek-ai (no installed packages)' }]; - const problems = []; - const seen = new Set(); - const re = /(?:from|import)\s*\(?\s*["'](@deepseek-ai\/[^"'/]+)(?:\/[^"']*)?["']/g; - for (const pkg of readdirSync(scope)) { - const lib = join(scope, pkg, 'lib'); - if (!existsSync(lib)) continue; - for (const file of jsFiles(lib)) { - const text = readFileSync(file, 'utf8'); - for (const m of text.matchAll(re)) { - const name = m[1]; - const key = `${pkg}>${name}`; - if (seen.has(key) || KNOWN_ABSENT.has(name)) continue; - seen.add(key); - if (!existsSync(join(harnessDir, 'node_modules', ...name.split('/'))) - && !existsSync(join(scope, pkg, 'node_modules', ...name.split('/')))) problems.push({ from: `${pkg}`, missing: name }); - } - } - } - return problems; -} diff --git a/engine/strata/apps/desktop/scripts/installed-flow.mjs b/engine/strata/apps/desktop/scripts/installed-flow.mjs deleted file mode 100644 index 7816b5c2..00000000 --- a/engine/strata/apps/desktop/scripts/installed-flow.mjs +++ /dev/null @@ -1,310 +0,0 @@ -#!/usr/bin/env node -/** - * Prove the INSTALLED app layout can start and stop an engine with nothing acquired, using a stub engine. - * - * node apps/desktop/scripts/installed-flow.mjs --install [--work ] [--spy ] - * - * It starts the installed host with the installed node.exe exactly as the Tauri shell does (STRATA_PACKAGED=1, - * STRATA_NO_ACQUIRE=1; Control found beside the host), against a scratch component folder holding a fake engine - * package and a scratch install folder holding one run config. Everything per-user (profiles, runtime state, host data, - * components) lives under --work, so the real profile of whoever runs this is never read or written. - * - * Steps (each one printed, the run exits 1 if any fails): - * host health, Control status (engine usable, acquiring forbidden), models from Control, load through the host - * (profile + `runtime start` under the owner runtime), a chat answer from the stub engine, a second client attaches to - * the same owner/instance, unload stops it, no engine for this PC is a notice with nothing started, the Tauri-style - * clean shutdown stops the engines the host started, a hard-killed host takes its engine with it. - * With --spy the host runs under tests/helpers/acquire-spy.mjs and the run fails on any attempt to reach the internet or - * run an installer. - * - * REAL mode (a test box with a GPU): --components > --models .json - * whose engine is "component:strata-engine"> --model [--backend cuda]. The same host and Control, a real engine and a - * real model: load, a real answer, ownership, unload, the missing-engine notice, load again, clean shutdown. The stub-only - * steps (the marker file, the hard-kill report) are left out. - */ -import { spawn, spawnSync } from 'node:child_process'; -import { createHash, randomBytes } from 'node:crypto'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync, chmodSync } from 'node:fs'; -import { createServer } from 'node:net'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { pathToFileURL } from 'node:url'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]?.startsWith('--') || all[i + 1] === undefined ? true : all[i + 1]]] : acc), [])); -if (!args.install) { console.error('usage: installed-flow.mjs --install [--work ] [--spy ]'); process.exit(2); } -const install = resolve(args.install); -const isWin = process.platform === 'win32'; -const node = join(install, 'node', isWin ? 'node.exe' : 'node'); -const hostEntry = join(install, 'host', 'server', 'index.mjs'); -const controlDir = join(install, 'control'); -const python = isWin ? join(controlDir, 'python', 'python.exe') : join(controlDir, 'python', 'bin', 'python3'); -const real = !!args.components; -const modelId = String(args.model ?? 'stub'); -const work = resolve(args.work ?? mkdtempSync(join(tmpdir(), 'strata-installed-flow-'))); -mkdirSync(work, { recursive: true }); -const dirs = { components: real ? resolve(args.components) : join(work, 'components'), models: real ? resolve(args.models) : join(work, 'models'), profiles: join(work, 'profiles'), runtime: join(work, 'runtime'), home: join(work, 'home') }; -// the runtime and profile folders are created by Control itself, with the owner-only ACL it insists on -for (const [name, d] of Object.entries(dirs)) if (!['runtime', 'profiles'].includes(name) && !(real && ['components', 'models'].includes(name))) mkdirSync(d, { recursive: true }); - -const steps = []; -const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + detail : ''}`); }; -const delay = ms => new Promise(r => setTimeout(r, ms)); -const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; -const sha = buf => createHash('sha256').update(buf).digest('hex'); - -// ------------------------------------------------------------------------------ fixtures -const baseEnv = { - ...process.env, - STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, - STRATA_INSTALL_DIR: dirs.models, STRATA_ENGINE_BACKEND: String(args.backend ?? 'cuda'), STRATA_HOME: dirs.home, STRATA_MODELS_DIR: real ? join(work, 'models-unused') : dirs.models, - APPDATA: join(work, 'appdata'), XDG_CONFIG_HOME: join(work, 'xdg'), PYTHONDONTWRITEBYTECODE: '1', -}; -delete baseEnv.STRATA_API_KEY; -mkdirSync(baseEnv.APPDATA, { recursive: true }); -const mark = join(work, 'engine-ran.json'); - -const FAKE_ENGINE = `import os, sys, json -from pathlib import Path -Path(os.environ['FAKE_ENGINE_MARK']).write_text(json.dumps({'pid': os.getpid(), 'script': os.path.abspath(__file__), 'argv': sys.argv[1:]})) -print('READY 4096 stop', flush=True) -for line in sys.stdin: - if line.strip() == 'QUIT': break - if line.startswith(('GEN ', 'BGEN ')): - slot = int(line.split()[1]) if line.startswith('BGEN ') else None - print('T 97', flush=True) - print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True) - if slot is not None: print(f'BADM {slot} 0', flush=True) -`; - -function installFakeEngine() { - const platform = isWin ? 'windows-x86_64' : 'linux-x86_64'; - const folder = join(dirs.components, 'engine', `0.1.45-${platform}-cuda`); - mkdirSync(folder, { recursive: true }); - writeFileSync(join(folder, 'engine_main.py'), FAKE_ENGINE); - const entry = isWin ? 'engine.cmd' : 'engine'; - writeFileSync(join(folder, entry), isWin - ? `@echo off\r\n"${python}" "%~dp0engine_main.py" %*\r\n` - : `#!/bin/sh\nexec "${python}" "$(dirname "$0")/engine_main.py" "$@"\n`); - if (!isWin) chmodSync(join(folder, entry), 0o755); - const files = [entry, 'engine_main.py'].map(p => { const b = readFileSync(join(folder, p)); return { path: p, sha256: sha(b), bytes: b.length }; }); - writeFileSync(join(folder, 'engine-component.json'), JSON.stringify({ schema_version: 1, id: 'strata-engine', version: '0.1.45', platform, backend: 'cuda', entrypoint: entry, files })); - return folder; -} - -function makeTokenizerAndConfig() { - const tok = join(dirs.models, 'tokenizer'); - mkdirSync(tok, { recursive: true }); - const script = `import json, sys\nfrom tools.strata_tokenizer import BYTE_TO_UNICODE\ntok = sys.argv[1]\ntokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ['ab', '<|im_start|>', '<|im_end|>', '<|endoftext|>']\njson.dump({t: i for i, t in enumerate(tokens)}, open(tok + '/vocab.json', 'w'))\nopen(tok + '/merges.txt', 'w').write('a b')\njson.dump([0] * 257 + [3, 3, 3], open(tok + '/token_type.json', 'w'))\n`; - const done = spawnSync(python, ['-c', script, tok], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1' }, encoding: 'utf8' }); - if (done.status !== 0) throw new Error('tokenizer fixture failed: ' + done.stderr); - writeFileSync(join(dirs.models, 'strata-stub.json'), JSON.stringify({ exe: 'component:strata-engine', backend: 'cuda', tokenizer: tok, args: [], cwd: work, model_name: 'stub', host: '127.0.0.1', port: 0 })); -} - -const control = (...argv) => spawnSync(python, [join(controlDir, 'strata.py'), ...argv, '--output', 'json'], { cwd: controlDir, env: { ...baseEnv, PYTHONNOUSERSITE: '1', STRATA_NO_ACQUIRE: '1', FAKE_ENGINE_MARK: mark }, encoding: 'utf8', timeout: 120000 }); -const controlJson = (...argv) => { const r = control(...argv); let json = null; try { json = JSON.parse(r.stdout.slice(r.stdout.indexOf('{'))); } catch { /* not json */ } return { code: r.status, json, text: r.stdout + r.stderr }; }; -const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } }; - -// ------------------------------------------------------------------------------ the host -let host = null, port = 0, base = '', spyLog = null, shutdownToken = randomBytes(32).toString('hex'); -async function startHost() { - port = await freePort(); base = `http://127.0.0.1:${port}`; - const hostArgs = [...(args.spy ? ['--import', pathToFileURL(resolve(args.spy)).href] : []), hostEntry]; - if (args.spy) { spyLog = join(work, 'acquire-spy.log'); writeFileSync(spyLog, ''); } - host = spawn(node, hostArgs, { - cwd: join(install, 'host'), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, - env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', - STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, FAKE_ENGINE_MARK: mark, STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), - ...(spyLog ? { ACQUIRE_SPY_LOG: spyLog } : {}) }, - }); - let log = ''; - host.stdout.on('data', c => { log += c; }); host.stderr.on('data', c => { log += c; }); - host.hostLog = () => log; - for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return true; } catch { /* not yet */ } await delay(150); } - return false; -} -/** The host started the way the Tauri shell starts it, by a stand-in shell (a node process) that can then be killed hard. */ -async function startHostViaShell() { - port = await freePort(); base = `http://127.0.0.1:${port}`; - const spec = { command: node, args: [hostEntry], options: { - cwd: join(install, 'host'), stdio: 'ignore', windowsHide: true, - env: { ...baseEnv, STRATA_PORT: String(port), STRATA_DIST: join(install, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', - STRATA_NO_ACQUIRE: '1', STRATA_SHUTDOWN_TOKEN: shutdownToken, STRATA_EXIT_WITH_PARENT: '1', FAKE_ENGINE_MARK: mark, - STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()) } } }; - const shell = spawn(node, ['-e', "const s=JSON.parse(process.env.HOST_SPEC);const c=require('node:child_process').spawn(s.command,s.args,s.options);console.log(c.pid);setInterval(()=>{},1000);"], - { env: { ...process.env, HOST_SPEC: JSON.stringify(spec) }, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true }); - const hostPid = await new Promise(r => shell.stdout.once('data', c => r(Number(String(c).trim())))); - for (let i = 0; i < 200; i++) { try { if ((await fetch(base + '/api/health')).ok) return { shell, hostPid }; } catch { /* not yet */ } await delay(150); } - return { shell, hostPid, failed: true }; -} -const call = async (path, method = 'GET', body) => { - const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); - return { status: response.status, body: await response.json().catch(() => null) }; -}; -async function waitJob(id, seconds = 120) { - for (let i = 0; i < seconds * 5; i++) { - const state = (await call('/api/native')).body; - const job = state.jobs.find(j => j.id === id); - if (job && job.state !== 'running') return { job, state }; - await delay(200); - } - throw new Error('operation did not finish'); -} -async function stopHost(hard = false) { - if (!host || host.exitCode !== null) return; - if (hard) { if (isWin) spawnSync('taskkill', ['/PID', String(host.pid), '/T', '/F'], { windowsHide: true }); else host.kill('SIGKILL'); } - else host.kill(); - for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); -} - -async function main() { - for (const need of [node, hostEntry, python, join(controlDir, 'strata.py')]) if (!existsSync(need)) { record('installed layout', false, `missing ${need}`); return; } - record('installed layout', true, install); - if (real) { - const packages = existsSync(join(dirs.components, 'engine')) ? readdirSync(join(dirs.components, 'engine')) : []; - record('fixtures', packages.length > 0 && existsSync(join(dirs.models, `strata-${modelId}.json`)), `engine package(s) ${packages.join(', ')} in ${dirs.components}; run config strata-${modelId}.json in ${dirs.models}`); - } else { - installFakeEngine(); - makeTokenizerAndConfig(); - record('fixtures', true, `stub engine package in ${dirs.components}; run config strata-stub.json`); - } - - if (!(await startHost())) { record('host healthy', false, host.hostLog().slice(-600)); return; } - record('host healthy', true, base); - - const status = (await call('/api/control/status')).body; - record('Control status: bundled, engine usable, acquiring forbidden', status.control?.python?.startsWith(controlDir) && status.engine?.usable === true && status.acquisition?.forbidden === true, - `python=${status.control?.python}; engine=${status.engine?.engine?.version}; forbidden=${status.acquisition?.forbidden}`); - - const native = (await call('/api/native?refresh=1')).body; - const model = native.installed?.models?.find(m => m.model === modelId); - record('models come from Control', native.available && model?.ready === true && native.packaged === true, `available=${native.available}; model ready=${model?.ready}; ${native.summary ?? native.error}`); - - // ---- load - const started = (await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body; - const loaded = await waitJob(started.id, 400); - const instance = loaded.state.instances[0]; - record('load through the host starts the engine under Control', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); - let ran = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; - if (real) { - const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); - ran = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]), script: listed[0].trim().split(/\s+/)[1] } : null; - record('the engine process running is the binary from the component folder', !!ran, listed[0] ? listed[0].trim().slice(0, 160) : 'no engine process under the component folder'); - } else { - record('the engine that ran is the one in the component folder', ran && ran.script.toLowerCase().startsWith(dirs.components.toLowerCase()), ran?.script ?? 'engine never ran'); - } - - const runtime = controlJson('runtime', 'status', '--profile', 'app-1'); - record('a second client sees the same owner and instance (ownership)', runtime.json?.state === 'ready' && !!runtime.json.owner_id && !!runtime.json.instance_id && runtime.json.host_pid !== host.pid, - `state=${runtime.json?.state}; owner=${String(runtime.json?.owner_id).slice(0, 8)}; instance=${String(runtime.json?.instance_id).slice(0, 8)}; owner host pid ${runtime.json?.host_pid} is not the app host (${host.pid})`); - - // ---- answer - const chat = await call('/v1/chat/completions', 'POST', real - ? { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'Reply with exactly one word: pong' }], max_tokens: 200, temperature: 0, reasoning_effort: 'none', stream: false } - : { model: instance?.apiModelId ?? modelId, messages: [{ role: 'user', content: 'hi' }], max_tokens: 4, stream: false }); - const message = chat.body?.choices?.[0]?.message ?? {}; - const answer = `${message.content ?? ''}${message.reasoning_content ?? ''}`; // the stub emits token 97 ("a"); the server files it as reasoning - record(real ? 'the real model answers through the host (the answer text is checked)' : 'the engine answers through the host (the stub token, not an error)', - chat.status === 200 && (real ? /pong/i.test(answer) : answer === 'a'), `status=${chat.status}; answer=${JSON.stringify(answer.slice(0, 200))}${chat.status === 200 ? '' : ' ' + JSON.stringify(chat.body).slice(0, 160)}`); - - // ---- unload - const unloaded = await call(`/api/native/instances/${instance.id}/unload`, 'POST', {}); - await delay(500); - const after = controlJson('runtime', 'status', '--profile', 'app-1'); - for (let i = 0; i < 100 && ran && alive(ran.pid); i++) await delay(100); // a real engine takes a moment to release the GPU - record('unload stops the engine', unloaded.status === 200 && after.json?.state === 'stopped' && (!ran || !alive(ran.pid)), `status=${unloaded.status}; runtime=${after.json?.state}; engine pid ${ran?.pid} alive=${ran ? alive(ran.pid) : 'n/a'}`); - - // ---- no engine for this PC - const hidden = join(dirs.components, real ? 'engine.hidden-by-flow' : 'engine.gone'); - renameSync(join(dirs.components, 'engine'), hidden); - rmSync(mark, { force: true }); - const missing = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id); - record('no engine for this PC is a notice and nothing is started', missing.job.state === 'error' && /No engine for this PC/.test(missing.job.error) && /never downloads/.test(missing.job.error) && !existsSync(mark), - `${missing.job.state}: ${String(missing.job.error).slice(0, 160)}`); - const refused = await waitJob((await call('/api/native/operations', 'POST', { kind: 'install', args: { family: 'qwen', model: 'IQ2_XS' } })).body.id); - record('installing from the app is refused (Terminal only)', refused.job.state === 'error' && /Terminal/.test(refused.job.error), refused.job.error); - const binary = await call('/api/engine/binary', 'POST'); - record('the llama.cpp download route is refused', binary.status === 409 && /never downloads/.test(binary.body?.error ?? ''), `${binary.status} ${binary.body?.error}`); - - // ---- clean shutdown (what the Tauri shell does on exit) - renameSync(hidden, join(dirs.components, 'engine')); - rmSync(mark, { force: true }); - const again = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); - let ran2 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; - if (real) { - const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); - ran2 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; - } - record('load again after the engine package returns', again.job.state === 'done', again.job.error ?? ''); - const wrong = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': 'nope' } }); - record('shutdown without the shell\'s secret is refused', wrong.status === 403, String(wrong.status)); - const exited = new Promise(r => host.once('exit', code => r(code))); - const stopping = await fetch(base + '/api/control/shutdown', { method: 'POST', headers: { 'x-strata-shutdown': shutdownToken } }); - const code = await Promise.race([exited, delay(90000).then(() => 'timeout')]); - for (let i = 0; i < 100 && ran2 && alive(ran2.pid); i++) await delay(100); - const final = controlJson('runtime', 'status', '--profile', 'app-1'); - record('clean shutdown stops the engine the app started and exits', stopping.status === 202 && code === 0 && final.json?.state === 'stopped' && (!ran2 || !alive(ran2.pid)), `status=${stopping.status}; host exit=${code}; runtime=${final.json?.state}; engine alive=${ran2 ? alive(ran2.pid) : 'n/a'}`); - - // ---- hard kill: an engine whose app host dies ends with it (the owner follows the host: runtime start --die-with-pid) - if (!(await startHost())) { record('host restarts', false, host.hostLog().slice(-400)); return; } - await call('/api/native?refresh=1'); - rmSync(mark, { force: true }); - const third = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); - let ran3 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; - if (real) { - const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); - ran3 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; - record('(real) the engine is up before the host is killed', !!ran3, listed[0] ? listed[0].trim().slice(0, 120) : 'no engine process'); - } - await stopHost(true); - for (let i = 0; i < 600 && ran3 && alive(ran3.pid); i++) await delay(100); // the owner notices within a second, drains, stops - const orphan = controlJson('runtime', 'status', '--profile', 'app-1'); - record('a hard-killed app host takes its engine with it', third.job.state === 'done' && (!ran3 || !alive(ran3.pid)), `engine alive=${ran3 ? alive(ran3.pid) : 'n/a'}; runtime=${orphan.json?.state ?? orphan.json?.error?.message}`); - const cleanup = controlJson('runtime', 'stop', '--profile', 'app-1'); - record('nothing is left to stop afterwards', /stopped|not managed/.test(JSON.stringify(cleanup.json)) && controlJson('runtime', 'status', '--profile', 'app-1').json?.state === 'stopped', JSON.stringify(cleanup.json).slice(0, 160)); - - // ---- the shell itself is killed (what the desktop shell's crash or kill looks like to the host): the host leaves, and - // its engine with it, with nothing announced. Windows also has the job object; this is the path that works everywhere. - const started2 = await startHostViaShell(); - if (started2.failed) { record('host starts under a stand-in shell', false, ''); try { started2.shell.kill('SIGKILL'); } catch { /* gone */ } } - else { - await call('/api/native?refresh=1'); - rmSync(mark, { force: true }); - const fourth = await waitJob((await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } })).body.id, 400); - let ran4 = existsSync(mark) ? JSON.parse(readFileSync(mark, 'utf8')) : null; - if (real) { - const listed = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(`${dirs.components}/engine/`) && l.includes('--serve')); - ran4 = listed.length ? { pid: Number(listed[0].trim().split(/\s+/)[0]) } : null; - } - if (isWin) spawnSync('taskkill', ['/PID', String(started2.shell.pid), '/F'], { windowsHide: true }); else started2.shell.kill('SIGKILL'); - for (let i = 0; i < 100 && alive(started2.hostPid); i++) await delay(100); - const hostGone = !alive(started2.hostPid); - for (let i = 0; i < 900 && ran4 && alive(ran4.pid); i++) await delay(100); - const engineGone = !ran4 || !alive(ran4.pid); - record('a killed shell takes the host and its engine with it', fourth.job.state === 'done' && hostGone && engineGone, - `host pid ${started2.hostPid} gone=${hostGone}; engine pid ${ran4?.pid} gone=${engineGone}; runtime=${controlJson('runtime', 'status', '--profile', 'app-1').json?.state}`); - controlJson('runtime', 'stop', '--profile', 'app-1'); - } - - await finishSpy(); -} - -async function finishSpy() { - if (spyLog) { - const attempts = readFileSync(spyLog, 'utf8').split('\n').filter(Boolean); - record('no acquisition attempt by the host during the whole run (spy)', attempts.length === 0, attempts.join(' | ')); - } -} - -try { await main(); } -catch (error) { record('flow', false, error.stack ?? error.message); } -finally { - try { const hid = join(dirs.components, 'engine.hidden-by-flow'); if (real && existsSync(hid) && !existsSync(join(dirs.components, 'engine'))) renameSync(hid, join(dirs.components, 'engine')); } catch { /* reported by the run */ } - await stopHost(true); - controlJson('runtime', 'stop', '--profile', 'app-1'); - controlJson('runtime', 'stop', '--profile', 'app-2'); -} -const failed = steps.filter(s => !s.ok); -writeFileSync(join(work, 'installed-flow.json'), JSON.stringify({ ok: failed.length === 0, install, work, steps }, null, 1)); -console.log(`\n${steps.length - failed.length}/${steps.length} ok; report ${join(work, 'installed-flow.json')}`); -if (!args.keep && !args.work && failed.length === 0) { try { rmSync(work, { recursive: true, force: true }); } catch { /* leave it */ } } -process.exit(failed.length ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/installer-mockups.mjs b/engine/strata/apps/desktop/scripts/installer-mockups.mjs deleted file mode 100644 index cc7a3c8f..00000000 --- a/engine/strata/apps/desktop/scripts/installer-mockups.mjs +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env node -/** - * Mock-ups of the Windows installer in Strata's own look: four screens (welcome, where, installing, done), light and dark, drawn with - * the app's built CSS (apps/host/dist) and brand files, then photographed with Chrome. Nothing here is built or shipped: it is what - * the owner is shown before an installer is chosen. - * - * node apps/desktop/scripts/installer-mockups.mjs [--out ] - */ -import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); -const here = dirname(fileURLToPath(import.meta.url)); -const host = resolve(here, '../../host'); -const out = resolve(args.out ?? join(here, '../installer-mockups')); -mkdirSync(out, { recursive: true }); -const dist = join(host, 'dist'); -const css = readdirSync(join(dist, 'assets')).filter(f => f.endsWith('.css')).map(f => readFileSync(join(dist, 'assets', f), 'utf8')).join('\n'); -const logo = theme => readFileSync(join(dist, 'brand', `strata-lockup-${theme}.svg`), 'utf8'); -const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); -const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); - -const check = ''; -const folder = ''; - -const screens = { - welcome: theme => `
-

State of the art. At home.

Strata runs AI on your own computer.
Setting it up takes a few minutes.

-
${check}Private${check}Fast${check}Easy to use
-
Installs for you only. No administrator needed.
`, - where: theme => `
-

Where should Strata go?

This is the right place for most people.

-
${folder}
Your Strata folderC:\\Users\\Alex\\AppData\\Local\\Strata
-

About 310 MB. Your models and chats are kept somewhere else and are never removed by an update.

-
`, - installing: theme => `
-

Installing Strata…

Copying the app and its engine room. You can keep working meanwhile.

-
-
62% · 190 / 310 MB
About 1 min left
-
Next: choose your first model inside Strata.
`, - done: theme => `
-

Strata is ready.

Open it to pick your first model. Strata downloads it for you and gets it ready.

-
A shortcut was added to your Start menu and desktop.
`, -}; - -const page = (name, theme) => `
Strata setup– ☐ ✕
-
${screens[name](theme)}
`; - -const browser = await chromium.launch({ executablePath: CHROME, headless: true }); -const written = []; -for (const theme of ['light', 'dark']) { - for (const name of Object.keys(screens)) { - const tab = await browser.newPage({ viewport: { width: 860, height: 620 }, deviceScaleFactor: 1 }); - await tab.setContent(page(name, theme)); - await tab.waitForTimeout(250); - const file = join(out, `${name}-${theme}.png`); - await tab.screenshot({ path: file }); - written.push(file); - await tab.close(); - } -} -await browser.close(); -console.log(written.join('\n')); diff --git a/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs b/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs deleted file mode 100644 index 32e49fa7..00000000 --- a/engine/strata/apps/desktop/scripts/local-gguf-e2e.mjs +++ /dev/null @@ -1,126 +0,0 @@ -#!/usr/bin/env node -/** - * "Use your own GGUF" end to end on a box, through the installed app layout (packaged host + bundled Control + a real engine component): - * preview a folder of a supported model, preview an unsupported GGUF (must be refused in plain terms), prepare the supported one - * (pack, from the folder, nothing copied), load it, get a chat answer, unload, shut down, and check nothing is left running. - * - * node local-gguf-e2e.mjs --root /data/ui4-e2e --good /data/141-gyro/models/IQ2_XS --bad /data/ui4-e2e/bad [--context 8192] [--backend cuda|metal] - * (the app folder is /app: node/, host/, control/ ...; /components gets the engine, from /app/engine-bundle when the app carries one) - */ -import { spawn, spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { createServer } from 'node:net'; -import { join, resolve } from 'node:path'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); -const root = resolve(args.root); -const good = args.good, bad = args.bad; -const context = Number(args.context ?? 8192); -const app = join(root, 'app'); -const dirs = { components: join(root, 'components'), install: join(root, 'install'), profiles: join(root, 'profiles'), runtime: join(root, 'runtime'), home: join(root, 'home'), xdg: join(root, 'xdg'), appdata: join(root, 'appdata') }; -for (const d of [dirs.install, dirs.home, dirs.xdg, dirs.appdata]) mkdirSync(d, { recursive: true }); -const delay = ms => new Promise(r => setTimeout(r, ms)); -const steps = []; -let failed = false; -const record = (name, ok, detail = '') => { steps.push({ name, ok: !!ok, detail: String(detail).slice(0, 400) }); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' ' + String(detail).slice(0, 300) : ''}`); if (!ok) failed = true; }; -const freePort = async () => { const s = createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }; - -const env = { ...process.env, STRATA_COMPONENTS_DIR: dirs.components, STRATA_PROFILE_DIR: dirs.profiles, STRATA_RUNTIME_DIR: dirs.runtime, STRATA_INSTALL_DIR: dirs.install, STRATA_HOME: dirs.home, STRATA_MODELS_DIR: join(root, 'Strata-data'), STRATA_ENGINE_BACKEND: args.backend ?? 'cuda', XDG_CONFIG_HOME: dirs.xdg, APPDATA: dirs.appdata, PYTHONDONTWRITEBYTECODE: '1' }; -delete env.STRATA_API_KEY; -const port = await freePort(); -const base = `http://127.0.0.1:${port}`; -const host = spawn(join(app, 'node', 'node'), [join(app, 'host', 'server', 'index.mjs')], { cwd: join(app, 'host'), stdio: ['ignore', 'pipe', 'pipe'], detached: false, - env: { ...env, STRATA_PORT: String(port), STRATA_DIST: join(app, 'host', 'dist'), NODE_ENV: 'production', STRATA_PACKAGED: '1', STRATA_REAL_ENGINE: '1', STRATA_NO_ACQUIRE: '1', STRATA_EXIT_WITH_PARENT: '1', - STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_WORKSPACE: join(root, 'workspace') } }); -mkdirSync(join(root, 'workspace'), { recursive: true }); -let hostLog = ''; host.stdout.on('data', c => { hostLog += c; }); host.stderr.on('data', c => { hostLog += c; }); -const call = async (path, method = 'GET', body) => { const r = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: r.status, body: await r.json().catch(() => null) }; }; -async function waitJob(id, seconds) { - const until = Date.now() + seconds * 1000; - let last = ''; - while (Date.now() < until) { - const state = (await call('/api/native')).body; - const job = state.jobs.find(j => j.id === id); - if (job && job.state !== 'running') return { job, state }; - if (job && job.summary !== last) { last = job.summary; console.log(' ...', String(job.summary).slice(0, 140)); } - await delay(2000); - } - throw new Error('operation did not finish in time'); -} -const engineProcs = () => spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => l.includes(join(dirs.components, 'engine')) && /\/strata( |$)/.test(l)); - -async function main() { - let up = false; - for (let i = 0; i < 200 && !up; i++) { try { up = (await fetch(base + '/api/health')).ok; } catch { await delay(150); } } - record('host healthy', up, up ? base : hostLog.slice(-500)); - if (!up) return; - let status = (await call('/api/control/status')).body; - for (let i = 0; i < 180 && status?.engineSetup; i++) { await delay(1000); status = (await call('/api/control/status')).body; } // the engine that came with the app is copied on the first start - record('Control status: bundled, engine usable', status?.engine?.usable === true, `engine=${status?.engine?.engine?.version} ${status?.engine?.notice ?? ''}`); - await call('/api/native?refresh=1'); - - // ---- the unsupported GGUF: a plain refusal - const badPreview = await call('/api/native/local/preview', 'POST', { path: bad }); - const badIssues = badPreview.body?.preview?.issues ?? badPreview.body?.issues ?? []; - const badStatus = badPreview.body?.preview?.file_set_status; - console.log(' bad preview:', badPreview.status, JSON.stringify(badPreview.body).slice(0, 400)); - record('an unsupported GGUF is refused, nothing adopted', badPreview.status === 200 ? (badStatus !== 'plausible' || !badPreview.body.preview.candidate_selection) : badPreview.status >= 400, `status=${badPreview.status}; file_set_status=${badStatus}; issues=${JSON.stringify(badIssues)}`); - - // ---- the supported folder - const goodPreview = await call('/api/native/local/preview', 'POST', { path: good }); - const selection = goodPreview.body?.preview?.candidate_selection; - console.log(' good preview:', JSON.stringify(goodPreview.body).slice(0, 500)); - record('a folder of a supported model is recognised', goodPreview.status === 200 && goodPreview.body?.preview?.file_set_status === 'plausible' && !!selection, `family=${selection?.family}; model=${selection?.model}; files=${goodPreview.body?.preview?.file_count}`); - if (!selection || args.only === 'preview') return; - - // ---- prepare (what the page's button does): install from the folder, nothing copied or downloaded - const native0 = (await call('/api/native?refresh=1')).body; - const catalogSize = native0.catalog?.families?.find(f => f.family === selection.family)?.sizes.find(s => s.model === selection.model); - record('the catalog lists the recognised version', !!catalogSize, catalogSize ? `id=${catalogSize.id}` : `no ${selection.family}/${selection.model} in the catalog`); - const started = await call('/api/native/operations', 'POST', { kind: 'install', args: { family: selection.family, model: selection.model, gguf_dir: good, context, vision: 'no' } }); - record('prepare starts', started.status < 300 && !!started.body?.id, `status=${started.status} ${JSON.stringify(started.body).slice(0, 200)}`); - if (!started.body?.id) return; - const prepared = await waitJob(started.body.id, 3600); - record('prepare finishes', prepared.job.state === 'done', `${prepared.job.state}: ${prepared.job.error ?? prepared.job.summary}`); - if (prepared.job.state !== 'done') return; - const native1 = (await call('/api/native?refresh=1')).body; - const modelId = catalogSize?.id ?? `${selection.family === 'qwen' ? '' : selection.family + '-'}${String(selection.model).toLowerCase()}`; - const entry = native1.installed?.models?.find(m => m.model === modelId); - record('the model is ready and points at the folder, not a copy', entry?.ready === true, `model=${modelId}; ready=${entry?.ready}; dataFolder=${entry?.dataFolder}`); - if (!entry?.ready) return; - - // ---- load - const load = await call('/api/native/operations', 'POST', { kind: 'load', args: { model: modelId } }); - const loaded = await waitJob(load.body.id, 1800); - const instance = loaded.state.instances[0]; - record('load starts the engine from the component folder', loaded.job.state === 'done' && instance?.status === 'ready', `job=${loaded.job.state} ${loaded.job.error ?? ''}; instance=${instance?.status}`); - if (instance?.status !== 'ready') return; - record('one engine process is running', engineProcs().length === 1, engineProcs().map(l => l.trim().slice(0, 140)).join(' | ')); - - // ---- a chat answer, checked - const chat = await fetch(base + '/api/chat/stream', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: 'e2e-chat', message: 'Reply with exactly one word: pong', history: [], nativeModelId: instance.id, thinking: 'Off', agent: false, workspaceId: null }) }); - let text = '', done = null; - for await (const chunk of chat.body) { - for (const line of Buffer.from(chunk).toString('utf8').split('\n')) { - if (!line.trim()) continue; - try { const f = JSON.parse(line); if (f.type === 'delta') text += f.text ?? ''; if (f.type === 'done') done = f; if (f.type === 'error') text += ` [error: ${f.message}]`; } catch { /* partial line */ } - } - } - record('the model answers through the app (the answer text is checked)', chat.status === 200 && /pong/i.test(text), `status=${chat.status}; answer=${JSON.stringify(text.slice(0, 120))}; tokensOut=${done?.tokensOut}; tps=${done?.tps}`); - - // ---- unload, shutdown, nothing left - const unload = await call(`/api/native/instances/${instance.id}/unload`, 'POST'); - await delay(3000); - record('unload stops the engine', unload.status < 300 && engineProcs().length === 0, `status=${unload.status}; engines left=${engineProcs().length}`); -} - -try { await main(); } catch (e) { record('the flow', false, e?.stack ?? e); } -host.kill(); -for (let i = 0; i < 100 && host.exitCode === null; i++) await delay(100); -if (host.exitCode === null) host.kill('SIGKILL'); -await delay(2000); -const left = spawnSync('ps', ['-eo', 'pid,args'], { encoding: 'utf8' }).stdout.split('\n').filter(l => (l.includes(dirs.install) || l.includes(join(app, 'host'))) && !l.includes('ps -eo')); -record('nothing of this run is left running', left.length === 0, left.join(' | ').slice(0, 300)); -writeFileSync(join(root, 'e2e-result.json'), JSON.stringify({ steps, hostLogTail: hostLog.slice(-2000) }, null, 1)); -console.log(failed ? 'FAILED' : 'ALL OK'); -process.exit(failed ? 1 : 0); diff --git a/engine/strata/apps/desktop/scripts/make-dmg.sh b/engine/strata/apps/desktop/scripts/make-dmg.sh deleted file mode 100755 index 909579f8..00000000 --- a/engine/strata/apps/desktop/scripts/make-dmg.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash -# Build the Strata DMG without a Finder session. -# -# Tauri's default DMG step runs an AppleScript that asks Finder to arrange the window (icon -# positions, background). Finder AppleEvents time out in a non-GUI or sandboxed context — observed -# here as `Finder got an error: AppleEvent timed out. (-1712)` — so the default path cannot be -# relied on for an automated build. The upstream `create-dmg` script already supports exactly this -# case via `--skip-jenkins`, which produces a plain, correct DMG with the app and the Applications -# drop link and no cosmetic arrangement. -# -# Usage: scripts/make-dmg.sh [output.dmg] -set -euo pipefail - -HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -DESKTOP="$(cd "$HERE/.." && pwd)" -BUNDLE="$DESKTOP/src-tauri/target/release/bundle" -APP="$BUNDLE/macos/Strata.app" -VERSION="$(grep -m1 '^version = ' "$DESKTOP/src-tauri/Cargo.toml" | cut -d'"' -f2)" # the one place the app version is written -OUT="${1:-$BUNDLE/dmg/Strata_${VERSION}_aarch64.dmg}" - -if [ ! -d "$APP" ]; then - echo "error: $APP does not exist; run 'cargo tauri build --bundles app' first" >&2 - exit 1 -fi - -WORK="$(mktemp -d -t strata-dmg)" -trap 'rm -rf "$WORK"' EXIT - -# A staging folder is what create-dmg copies into the image: the app, and nothing else. -# -# The Applications drop link is created by `--app-drop-link` below. Adding one here as well makes -# create-dmg fail with "File exists", because it links into the volume it is assembling. -mkdir -p "$WORK/stage" -cp -R "$APP" "$WORK/stage/" - -# Reuse Tauri's vendored create-dmg if the bundler left it behind, otherwise take it from the -# bundle cache. Building it yourself is not necessary and not expected. -SCRIPT="$BUNDLE/dmg/bundle_dmg.sh" -if [ ! -x "$SCRIPT" ]; then - echo "error: $SCRIPT not found; run 'cargo tauri build --bundles dmg' once to vendor it" >&2 - exit 1 -fi - -mkdir -p "$(dirname "$OUT")" -rm -f "$OUT" - -# --skip-jenkins: no Finder AppleScript. Everything else is the same code path Tauri uses. -"$SCRIPT" \ - --volname "Strata $VERSION" \ - --volicon "$BUNDLE/macos/Strata.app/Contents/Resources/Strata.icns" \ - --app-drop-link 400 200 \ - --skip-jenkins \ - --no-internet-enable \ - "$OUT" "$WORK/stage" - -echo -echo "built: $OUT" -ls -lh "$OUT" | awk '{print "size: " $5}' -shasum -a 256 "$OUT" diff --git a/engine/strata/apps/desktop/scripts/make-icons.mjs b/engine/strata/apps/desktop/scripts/make-icons.mjs deleted file mode 100644 index 411e4b97..00000000 --- a/engine/strata/apps/desktop/scripts/make-icons.mjs +++ /dev/null @@ -1,78 +0,0 @@ -#!/usr/bin/env node -/** - * The app and installer icon, refined from the existing Strata mark (apps/host/public/brand/strata-mark-*.svg and the current - * icons/icon.png): the same three rounded bars on the same dark tile, in the same colours. Nothing is redrawn. What changes is - * how it is cut for small sizes: at 16-48 px the bars are snapped to whole pixels and made a little bolder and wider so they - * stay crisp instead of blurring; from 64 px up the geometry is the mark's own proportions. - * - * node apps/desktop/scripts/make-icons.mjs [--out ] writes icon-.png for every size and icon.ico - */ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); -const here = dirname(fileURLToPath(import.meta.url)); -const host = resolve(here, '../../host'); -const out = resolve(args.out ?? join(here, '../src-tauri/icons')); -mkdirSync(out, { recursive: true }); -const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); -const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); - -const TILE = '#161a1d', LIGHT = '#eef1f3', GREEN = '#34d399'; // the colours of the current icon.png - -/** Integer geometry for the small sizes: bars on whole pixels, centred. Returns [{x,y,w,h,fill}]. */ -function hinted(size) { - const bar = Math.max(2, Math.round(size * 0.14)), gap = Math.max(2, Math.round(size * 0.1)), mid = bar + 1; - const total = 2 * bar + mid + 2 * gap, top = Math.floor((size - total) / 2); - const even = w => (w % 2 === size % 2 ? w : w + 1); - const wide = even(Math.round(size * 0.5)), long = even(Math.round(size * 0.76)); - return [ - { x: (size - wide) / 2, y: top, w: wide, h: bar, fill: LIGHT }, - { x: (size - long) / 2, y: top + bar + gap, w: long, h: mid, fill: GREEN }, - { x: (size - wide) / 2, y: top + bar + gap + mid + gap, w: wide, h: bar, fill: LIGHT }, - ]; -} -/** The mark's own proportions (from icon.png at 512): bars 34% / 50% / 34% wide, 9% high, on a tile with 21.5% corners. */ -function proportional(size) { - const k = size / 512; - return [ - { x: 170 * k, y: 156 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, - { x: 128 * k, y: 232 * k, w: 256 * k, h: 48 * k, fill: GREEN }, - { x: 170 * k, y: 309 * k, w: 173 * k, h: 46 * k, fill: LIGHT }, - ]; -} -function svg(size) { - const small = size <= 48; - const bars = (small ? hinted(size) : proportional(size)); - const radius = small ? Math.round(size * 0.22) : size * 0.215; - const rects = bars.map(b => ``).join(''); - return `${rects}`; -} - -const SIZES = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256, 512, 1024]; -const browser = await chromium.launch({ executablePath: CHROME, headless: true }); -const png = {}; -for (const size of SIZES) { - const page = await browser.newPage({ viewport: { width: size, height: size }, deviceScaleFactor: 1 }); - await page.setContent(`${svg(size)}`); - png[size] = await page.screenshot({ omitBackground: true, clip: { x: 0, y: 0, width: size, height: size } }); - await page.close(); - writeFileSync(join(out, `icon-${size}.png`), png[size]); -} -await browser.close(); - -// The .ico: one PNG image per size (16-256), the sizes Windows asks for at 100-250% scaling. -const ICO = [16, 20, 24, 32, 40, 48, 64, 96, 128, 256]; -const head = Buffer.alloc(6); head.writeUInt16LE(0, 0); head.writeUInt16LE(1, 2); head.writeUInt16LE(ICO.length, 4); -let offset = 6 + 16 * ICO.length; -const entries = [], blobs = []; -for (const size of ICO) { - const data = png[size], e = Buffer.alloc(16); - e.writeUInt8(size === 256 ? 0 : size, 0); e.writeUInt8(size === 256 ? 0 : size, 1); e.writeUInt8(0, 2); e.writeUInt8(0, 3); - e.writeUInt16LE(1, 4); e.writeUInt16LE(32, 6); e.writeUInt32LE(data.length, 8); e.writeUInt32LE(offset, 12); - offset += data.length; entries.push(e); blobs.push(data); -} -writeFileSync(join(out, 'icon.ico'), Buffer.concat([head, ...entries, ...blobs])); -writeFileSync(join(out, 'icon.png'), png[512]); -console.log('icons in', out, ICO.join(',')); diff --git a/engine/strata/apps/desktop/scripts/make-installer-images.mjs b/engine/strata/apps/desktop/scripts/make-installer-images.mjs deleted file mode 100644 index f12d6cc1..00000000 --- a/engine/strata/apps/desktop/scripts/make-installer-images.mjs +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env node -/** - * The installer's pictures, drawn from the app's own design: the light surface and ink colours of the app (src/styles tokens), the - * brand lockup and mark files, GT Walsheim Bold for the words (baked into the pictures, because NSIS cannot use a web font). - * - * node apps/desktop/scripts/make-installer-images.mjs [--out ] [--preview ] - * - * Writes sidebar.bmp (164x314, the welcome and finish pages) and header.bmp (150x57, the other pages) as 24-bit BMPs, and with - * --preview the same as PNGs at 3x. - */ -import { spawnSync } from 'node:child_process'; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; -import { tmpdir } from 'node:os'; - -const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), [])); -const here = dirname(fileURLToPath(import.meta.url)); -const host = resolve(here, '../../host'); -const out = resolve(args.out ?? join(here, '../src-tauri/nsis')); -mkdirSync(out, { recursive: true }); -const { chromium } = await import(pathToFileURL(join(host, 'node_modules/playwright-core/index.mjs')).href).catch(() => import('playwright-core')); -const CHROME = process.env.CHROME ?? ['C:/Program Files/Google/Chrome/Application/chrome.exe', '/usr/bin/google-chrome'].find(existsSync); -const font = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Bold.woff2')).href; -const fontMedium = pathToFileURL(join(host, 'public/fonts/GTWalsheimPro-Medium.woff2')).href; -const lockup = readFileSync(join(host, 'public/brand/strata-lockup-light.svg'), 'utf8'); -const mark = readFileSync(join(host, 'public/brand/strata-mark-light.svg'), 'utf8'); - -// the app's light tokens -const SURFACE = '#f9fafb', INK = '#171b1e', MUTED = '#5b646b', ACCENT = '#10b981', LINE = '#e3e8ea'; -const css = `@font-face{font-family:GT;font-weight:700;src:url(${font})}@font-face{font-family:GT;font-weight:500;src:url(${fontMedium})} -*{box-sizing:border-box}body{margin:0;font-family:GT,'Segoe UI',sans-serif;color:${INK};background:${SURFACE}}`; - -const pages = { - sidebar: { w: 164, h: 314, html: `
-
${lockup.replace(' -
-
State of
the art.
At home.
-
AI on your own computer.
Private. Fast. Easy.
-
-
` }, - header: { w: 150, h: 57, html: `
${lockup.replace('` }, -}; - -const browser = await chromium.launch({ executablePath: CHROME, headless: true }); -const work = join(tmpdir(), 'strata-installer-images'); mkdirSync(work, { recursive: true }); -for (const [name, page] of Object.entries(pages)) { - for (const scale of [1, 3]) { - const file = join(work, `${name}.html`); - writeFileSync(file, `${page.html}`); - const tab = await browser.newPage({ viewport: { width: page.w, height: page.h }, deviceScaleFactor: scale }); - await tab.goto(pathToFileURL(file).href); - await tab.evaluate(() => document.fonts.ready); - await tab.waitForTimeout(200); - const png = join(work, `${name}@${scale}.png`); - await tab.screenshot({ path: png, clip: { x: 0, y: 0, width: page.w, height: page.h } }); - await tab.close(); - if (scale === 3 && args.preview) { mkdirSync(resolve(args.preview), { recursive: true }); writeFileSync(join(resolve(args.preview), `${name}.png`), readFileSync(png)); } - } -} -await browser.close(); -// 24-bit BMP, the format NSIS wants: render at 3x, shrink with a good filter -const py = `import sys\nfrom PIL import Image\nfor name in ('sidebar','header'):\n im = Image.open(sys.argv[1] + '/' + name + '@3.png').convert('RGB')\n w, h = im.width // 3, im.height // 3\n im.resize((w, h), Image.LANCZOS).save(sys.argv[2] + '/' + name + '.bmp', 'BMP')\n`; -const done = spawnSync('python', ['-c', py, work, out], { encoding: 'utf8' }); -if (done.status !== 0) { console.error(done.stderr); process.exit(1); } -console.log('wrote', join(out, 'sidebar.bmp'), join(out, 'header.bmp')); diff --git a/engine/strata/apps/desktop/scripts/make-tester-readme.sh b/engine/strata/apps/desktop/scripts/make-tester-readme.sh deleted file mode 100644 index e38103c8..00000000 --- a/engine/strata/apps/desktop/scripts/make-tester-readme.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env bash -# Write a tester's README with the checksums and sizes of the files it names, computed from the files themselves. -# -# apps/desktop/scripts/make-tester-readme.sh