Merge claude/strata-removal: remove the vendored Strata tree, keep LICENSE and the files Rust embeds in third_party/strata (STRA-406)
Rust port / port-typecheck (push) Successful in 1m10s
Rust port / port-linux-tests (push) Failing after 3m0s
Rust port / port-fast (push) Successful in 4m26s
Rust port / port-oracles (push) Successful in 4m28s
Linux / verify (push) Failing after 5m16s
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Product / product (push) Failing after 14m14s

This commit is contained in:
Pavlo Ratushnyi
2026-11-23 21:44:36 +01:00
2994 changed files with 290 additions and 806750 deletions
+8 -8
View File
@@ -4,14 +4,14 @@ models/
captures/
logs/
control-plane/target/
engine/*
!engine/strata/
engine/strata/*
!engine/strata/LICENSE
# prompt.rs embeds the pinned chat template at compile time
!engine/strata/serve/
engine/strata/serve/*
!engine/strata/serve/chat_template.jinja
third_party/*
!third_party/strata/
third_party/strata/*
!third_party/strata/LICENSE
# prompt.rs and server_api.rs embed the pinned chat template at compile time
!third_party/strata/serve/
third_party/strata/serve/*
!third_party/strata/serve/chat_template.jinja
benchmarks/
target/
dist/
+3
View File
@@ -27,3 +27,6 @@ scripts/check-ci-coverage.py text eol=lf
scripts/install-pinned-rustup.sh text eol=lf
scripts/test-cuda-fixed-ptx.sh text eol=lf
.github/workflows/*.yml text eol=lf
# Strata files kept for the shipped product and the Rust tests (third_party/strata/UPSTREAM.md): embedded and hashed byte for byte, never converted.
third_party/strata/** -text
-311
View File
@@ -6,23 +6,6 @@ on:
tags: ['v*']
pull_request:
workflow_dispatch:
inputs:
keyless_gpu:
description: Run synthetic Keyless CUDA tests on the private GPU runner
type: boolean
default: false
hosted_cuda_package:
description: Build actual CUDA package on isolated hosted CPU (no GPU, private artifact)
type: boolean
default: false
hosted_cuda_ple:
description: Build the hosted package with experimental KAR PLE compiled (serving remains explicit and off by default)
type: boolean
default: false
static_cuda_package:
description: Build and audit static CUDA toolkit linkage on the private Linux runner (no inference)
type: boolean
default: false
permissions:
contents: read
@@ -41,296 +24,6 @@ jobs:
- name: GPU-hidden fixed PTX assembly
run: scripts/test-cuda-fixed-ptx.sh
keyless-cuda-gate:
if: gitea.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.select.outputs.enabled }}
steps:
- id: select
env:
KEYLESS_GPU: ${{ gitea.event.inputs.keyless_gpu }}
run: |
case "${KEYLESS_GPU:-false}" in
true) echo 'enabled=true' >> "$GITHUB_OUTPUT" ;;
false|'') echo 'enabled=false' >> "$GITHUB_OUTPUT" ;;
*) echo 'keyless_gpu must be a boolean input' >&2; exit 2 ;;
esac
keyless-cuda:
needs: [verify, keyless-cuda-gate]
if: needs.keyless-cuda-gate.outputs.enabled == 'true'
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- name: Query-routing, streaming and snapshot GPU tests
run: scripts/check-keyless-gpu.sh
- name: Bounded KAR expert component GPU tests
run: scripts/check-kar-expert-gpu.sh
static-cuda-package:
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && gitea.event.inputs.static_cuda_package == 'true' && gitea.event.repository.private
needs: verify
runs-on: [self-hosted, linux, x64, strata-gpu]
steps:
- uses: actions/checkout@v4
- name: Build and audit engine without GPU inference
env:
CUDA_VISIBLE_DEVICES: ''
BUILD_JOBS: '2'
STRATA_BUILD_DIR: ${{ runner.temp }}/strata-static-cuda-${{ github.run_id }}
run: nice -n 10 scripts/build-static-cuda.sh
- name: Install pinned Rust and musl target
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
command -v musl-gcc
- name: Assemble combined private package
run: |
engine="${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/strata"
python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}/BUILD-FEATURES.json" \
--cargo-target-dir "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}" \
--output "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Build compatible private runtime image without GPU inference
run: |
package="${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json" "$package/IMAGE-PROVENANCE.json"
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json > IMAGE-SHA256SUMS)
- name: Publish exact six-file static CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile static-cuda \
--tag "static-cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Static CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only six-file preview. No hosted compiler/license receipt, GPU or model qualification.' \
--directory "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-package-${GITHUB_RUN_ID}"
- name: Remove owned runtime image
if: always()
run: |
receipt="${RUNNER_TEMP}/strata-image-${GITHUB_RUN_ID}.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
rm "$receipt"
fi
- name: Remove private build intermediates
if: always()
run: rm -rf -- "${RUNNER_TEMP}/strata-static-cuda-${GITHUB_RUN_ID}" "${RUNNER_TEMP}/strata-package-build-${GITHUB_RUN_ID}"
hosted-cuda-package:
permissions:
contents: read
releases: write
if: gitea.event_name == 'workflow_dispatch' && (gitea.event.inputs.hosted_cuda_package == 'true' || gitea.event.inputs.hosted_cuda_ple == 'true') && gitea.event.repository.private
needs: verify
runs-on: ubuntu-latest
timeout-minutes: 150
env:
CUDA_VISIBLE_DEVICES: ''
NVIDIA_VISIBLE_DEVICES: void
BUILD_JOBS: '1'
CARGO_BUILD_JOBS: '2'
CUDA_ARCHITECTURES: '120'
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
steps:
- uses: actions/checkout@v4
- name: Install compatible host tools (no drivers)
run: |
echo "CUDACXX=$RUNNER_TEMP/strata-cuda-toolkit/bin/nvcc" >> "$GITHUB_ENV"
echo "CUDAToolkit_ROOT=$RUNNER_TEMP/strata-cuda-toolkit" >> "$GITHUB_ENV"
echo "STRATA_BUILD_DIR=$RUNNER_TEMP/strata-hosted-cuda-engine" >> "$GITHUB_ENV"
apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates musl-tools binutils docker.io python3 time
- name: Actual runtime-image loader boundary without GPU
run: PYTHONDONTWRITEBYTECODE=1 python3 scripts/test-package-loader-container.py
- name: Assemble pinned build-only CUDA components
run: python3 scripts/bootstrap-cuda-toolkit.py --output "$CUDAToolkit_ROOT"
- name: Build pinned GPU-hidden compiler image
env:
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
run: |
context="$RUNNER_TEMP/strata-cuda-builder-context"
mkdir -p "$context"
cp deploy/Dockerfile.cuda-builder "$context/Dockerfile"
cp /etc/ssl/certs/ca-certificates.crt "$context/runner-ca-bundle.crt"
docker build --platform linux/amd64 --build-arg "BUILDER_BASE=$CUDA_BUILDER_BASE" \
--tag "$CUDA_BUILDER_IMAGE" "$context"
docker image inspect --format '{{.Id}}' "$CUDA_BUILDER_IMAGE" > "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
- name: Record actual toolchain
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
CUDA_BUILDER_BASE: ubuntu@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b
run: |
"$CUDACXX" --version
docker run --rm --platform linux/amd64 --network none "$CUDA_BUILDER_IMAGE" g++-13 --version
df -h "$RUNNER_TEMP"
free -h
python3 - <<'PYTOOL'
import json, os, platform, subprocess
from pathlib import Path
info=json.loads((Path(os.environ['CUDAToolkit_ROOT'])/'TOOLKIT-PROVENANCE.json').read_text())
packages=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'dpkg-query','-W','-f=${binary:Package}=${Version}'+chr(10),
'binutils','ca-certificates','cmake','gcc-13','g++-13','git','make','python3'],text=True).splitlines()
gcc=subprocess.check_output(['docker','run','--rm','--platform','linux/amd64','--network','none',
os.environ['CUDA_BUILDER_IMAGE'],'g++-13','--version'],text=True)
info.update(source=os.environ['GITHUB_SHA'], runner_os=platform.platform(),
builder_base=os.environ['CUDA_BUILDER_BASE'],
builder_image_id=Path(os.environ['RUNNER_TEMP'],'CUDA-BUILDER-IMAGE-ID').read_text().strip(),
builder_packages=packages,
gcc=gcc,
nvcc=subprocess.check_output([os.environ['CUDACXX'],'--version'],text=True),
cuda_architectures=os.environ['CUDA_ARCHITECTURES'], driver_tested=False, model_tested=False)
(Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json').write_text(json.dumps(info,indent=2)+'\n')
PYTOOL
- name: Build actual static CUDA engine and audit without GPU
env:
CUDA_BUILDER_IMAGE: leleka-cuda-builder:${{ github.run_id }}
STRATA_KAR_PLE: ${{ inputs.hosted_cuda_ple && '1' || '0' }}
run: |
mkdir -p "$STRATA_BUILD_DIR"
container="leleka-cuda-build-${GITHUB_RUN_ID}"
volume="leleka-cuda-build-${GITHUB_RUN_ID}"
source_archive="$RUNNER_TEMP/strata-cuda-source.tar"
cleanup() {
docker rm -f "$container" >/dev/null 2>&1 || true
docker volume rm "$volume" >/dev/null 2>&1 || true
rm -f -- "$source_archive"
}
trap cleanup EXIT
git -C "$GITHUB_WORKSPACE" archive --format=tar "$GITHUB_SHA" > "$source_archive"
docker volume create "$volume" >/dev/null
docker create --name "$container" --platform linux/amd64 --network bridge --read-only \
--cap-drop ALL --security-opt no-new-privileges \
--tmpfs /tmp:rw,nosuid,size=2g --mount "type=volume,src=$volume,dst=/work" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
"$CUDA_BUILDER_IMAGE" /bin/bash -euc 'sleep infinity' >/dev/null
docker start "$container" >/dev/null
docker exec "$container" mkdir -p /work/workspace /work/toolkit /work/build
docker exec "$container" chmod 0777 /work/build
# Stage tracked source only. docker cp streams the archive from the
# runner container; bind mounts cannot use its path on the daemon host.
docker cp "$source_archive" "$container:/work/source.tar"
docker exec "$container" tar -xf /work/source.tar -C /work/workspace
docker exec "$container" rm /work/source.tar
docker cp "$CUDAToolkit_ROOT/." "$container:/work/toolkit/"
docker exec --user "$(id -u):$(id -g)" \
-e CUDA_VISIBLE_DEVICES= -e NVIDIA_VISIBLE_DEVICES=void \
-e CUDACXX=/work/toolkit/bin/nvcc -e CUDAToolkit_ROOT=/work/toolkit \
-e CC=/usr/bin/gcc-13 -e CXX=/usr/bin/g++-13 -e CUDAHOSTCXX=/usr/bin/g++-13 \
-e BUILD_JOBS="$BUILD_JOBS" -e CUDA_ARCHITECTURES="$CUDA_ARCHITECTURES" \
-e STRATA_KAR_PLE="$STRATA_KAR_PLE" -e STRATA_BUILD_DIR=/work/build \
-e SOURCE_REVISION="$GITHUB_SHA" \
"$container" /bin/bash -euo pipefail -c '
if compgen -G "/dev/nvidia*" >/dev/null; then
echo "NVIDIA devices unexpectedly visible in build container" >&2
exit 1
fi
cd /work/workspace
scripts/build-static-cuda.sh
'
docker cp "$container:/work/build/strata" "$STRATA_BUILD_DIR/strata"
docker cp "$container:/work/build/BUILD-FEATURES.json" "$STRATA_BUILD_DIR/BUILD-FEATURES.json"
- name: Bind compile capability to CUDA toolchain provenance
run: |
python3 - <<'PYFEATURES'
import hashlib, json, os
from pathlib import Path
features_path=Path(os.environ['STRATA_BUILD_DIR'])/'BUILD-FEATURES.json'
features=json.loads(features_path.read_text())
toolchain_path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
info=json.loads(toolchain_path.read_text())
info['build_features']=features['features']
info['build_features_sha256']=hashlib.sha256(features_path.read_bytes()).hexdigest()
toolchain_path.write_text(json.dumps(info,indent=2)+'\n')
PYFEATURES
- name: Install pinned Rust and musl target
run: |
scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --target x86_64-unknown-linux-musl
- name: Assemble actual combined executable and runtime image
run: |
# Keep resource evidence even if the hosted runner terminates this job.
(while sleep 20; do
date -u
free -m
df -m "$RUNNER_TEMP"
test ! -r /sys/fs/cgroup/memory.events || cat /sys/fs/cgroup/memory.events
done) &
resource_sampler=$!
trap 'kill "$resource_sampler" 2>/dev/null || true; wait "$resource_sampler" 2>/dev/null || true' EXIT
engine="$STRATA_BUILD_DIR/strata"
package="$RUNNER_TEMP/strata-hosted-cuda-package"
/usr/bin/time -v python3 scripts/build-linux-package.py --engine "$engine" --probe-in-runtime-image \
--sha256 "$(sha256sum "$engine" | cut -d ' ' -f 1)" --revision "$GITHUB_SHA" \
--build-features "$STRATA_BUILD_DIR/BUILD-FEATURES.json" \
--cargo-target-dir "$RUNNER_TEMP/strata-hosted-package-build" --output "$package"
python3 scripts/build-runtime-image.py --package "$package" \
--receipt-sha256 "$(sha256sum "$package/SHA256SUMS" | cut -d ' ' -f 1)" \
> "$RUNNER_TEMP/strata-hosted-image.json"
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$RUNNER_TEMP/strata-hosted-image.json")"
docker save --output "$package/runtime-image.tar" "$image"
cp "$RUNNER_TEMP/strata-hosted-image.json" "$package/IMAGE-PROVENANCE.json"
python3 - <<'PYBIND'
import hashlib, json, os
from pathlib import Path
package=Path(os.environ['RUNNER_TEMP'])/'strata-hosted-cuda-package'
receipt=json.loads((package/'PROVENANCE.json').read_text())
image=json.loads((package/'IMAGE-PROVENANCE.json').read_text())
path=Path(os.environ['RUNNER_TEMP'])/'CUDA-TOOLCHAIN.json'
toolchain=json.loads(path.read_text())
with (package/'runtime-image.tar').open('rb') as archive:
archive_sha=hashlib.file_digest(archive, 'sha256').hexdigest()
toolchain['docker_builder']={
'source_commit': os.environ['GITHUB_SHA'],
'image_id': toolchain['builder_image_id'],
'engine_sha256': receipt['engine']['sha256'],
'build_features_sha256': receipt['build_features_sha256'],
'runtime_image_id': image['image'],
'runtime_archive_sha256': archive_sha}
path.write_text(json.dumps(toolchain,indent=2)+'\n')
PYBIND
cp "$RUNNER_TEMP/CUDA-TOOLCHAIN.json" "$package/CUDA-TOOLCHAIN.json"
tar -C "$CUDAToolkit_ROOT" -cf "$package/CUDA-LICENSES.tar" licenses
(cd "$package" && sha256sum runtime-image.tar IMAGE-PROVENANCE.json CUDA-TOOLCHAIN.json CUDA-LICENSES.tar > IMAGE-SHA256SUMS)
- name: Publish exact eight-file hosted CUDA preview through Gitea
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
python3 scripts/publish-gitea-release.py --api-url https://git.vezha.io/api/v1 \
--repository "$GITHUB_REPOSITORY" --profile cuda \
--tag "cuda-preview-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" --target "$GITHUB_SHA" \
--title "Hosted CUDA preview ${GITHUB_RUN_ID}.${GITHUB_RUN_ATTEMPT}" \
--notes 'Private build-only preview. GPU-hidden loader identity and help passed; no GPU/model inference or performance qualification.' \
--directory "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove uploaded package copy
if: always()
run: rm -rf -- "$RUNNER_TEMP/strata-hosted-cuda-package"
- name: Remove owned intermediate image and build files
if: always()
run: |
receipt="$RUNNER_TEMP/strata-hosted-image.json"
if test -s "$receipt"; then
image="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["image"])' "$receipt")"
docker image rm "$image"
fi
rm -rf -- "$RUNNER_TEMP/strata-cuda-toolkit" "$RUNNER_TEMP/strata-hosted-cuda-engine" "$RUNNER_TEMP/strata-hosted-package-build"
docker image rm "leleka-cuda-builder:${GITHUB_RUN_ID}" 2>/dev/null || true
rm -rf -- "$RUNNER_TEMP/strata-cuda-builder-context" "$RUNNER_TEMP/CUDA-BUILDER-IMAGE-ID"
linux-static-cli:
permissions:
contents: read
@@ -387,12 +80,8 @@ jobs:
run: python3 scripts/smoke-cuda-memory.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Atomic pinned assets before native serving
run: python3 scripts/smoke-asset-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native GGUF pack preparation against upstream oracle
run: python3 scripts/smoke-native-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native fetch prepare serve and verified offline reuse
run: python3 scripts/smoke-native-bootstrap.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Pinned MTP structural preflight and native bootstrap
run: python3 scripts/smoke-mtp-pack.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native runtime profile metadata admission
run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api
- name: Native systemd unit syntax and path safety
+6 -32
View File
@@ -4,7 +4,8 @@ name: Rust port
# weights or tokens. The existing "Linux" workflow is unchanged; the jobs below add the port-specific gates:
# port-fast fmt, Clippy and tests on the host-buildable crates (scripts/check-local.sh --fast)
# port-typecheck Linux-only crates (cuda-driver with the cuda-driver feature, leleka-runtime) type-checked, not run
# port-oracles CPU oracle differentials against the unmodified Python tools (needs pip and a pinned llama.cpp gguf-py)
# port-oracles the sampler host shim over the checked-in oracle fixtures (the live Python differentials and the oracle
# generators needed the vendored Strata tree, removed in STRA-406)
# port-linux-tests Docker Linux harness (scripts/linux-tests/run.sh); optional until branch claude/port-linux-tests merges
# Type-checking is not execution: nothing here runs the Linux-gated tests or any GPU smoke.
@@ -54,45 +55,18 @@ jobs:
cargo clippy --locked --target x86_64-unknown-linux-gnu --no-deps -p leleka-cuda-model -p leleka-cuda-driver --features cuda-driver -p leleka-engine-qwen35-cuda -p leleka-runtime --all-targets -- -D warnings
port-oracles:
# CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the
# sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by
# port-fast regardless.
# The sampler host shim over the checked-in oracle fixtures. Optional until it has run green on the hosted runner;
# the committed goldens are replayed by port-fast regardless.
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3 python3-venv
run: apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential cmake git python3
- name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy
- name: Oracle Python environment (no model data)
# numpy 2.5.x needs Python >= 3.12 and the runner's distro Python is older, so the numpy pin follows the
# interpreter exactly as engine/strata/requirements.txt does (2.5.4 on 3.12+, 2.4.6 on 3.11, 2.2.6 below).
# The oracle differentials compare against recorded goldens with tolerances, not against a numpy build.
run: |
python3 -m venv "$RUNNER_TEMP/oracle-venv"
cat > "$RUNNER_TEMP/oracle-requirements.txt" <<'EOF'
numpy==2.5.4; python_version >= "3.12"
numpy==2.4.6; python_version == "3.11"
numpy==2.2.6; python_version < "3.11"
PyYAML==6.0.3
tqdm==4.70.1
Jinja2==3.1.6
regex==2026.9.10
EOF
"$RUNNER_TEMP/oracle-venv/bin/python" --version
"$RUNNER_TEMP/oracle-venv/bin/pip" install --disable-pip-version-check -r "$RUNNER_TEMP/oracle-requirements.txt"
- name: Fetch the pinned llama.cpp gguf-py
run: |
commit="$(sed -n 's/^LLAMA_CPP_COMMIT = "\(.*\)"$/\1/p' engine/strata/setup.py)"
test -n "$commit"
git init -q "$RUNNER_TEMP/llama.cpp"
git -C "$RUNNER_TEMP/llama.cpp" fetch --depth 1 https://github.com/ggml-org/llama.cpp "$commit"
git -C "$RUNNER_TEMP/llama.cpp" checkout -q FETCH_HEAD
- name: Port oracles (sampler shim and live Python differentials)
- name: Port oracles (sampler host shim over the checked-in fixtures)
env:
OFFLINE_ORACLE_PYTHON: ${{ runner.temp }}/oracle-venv/bin/python
STRATA_GGUF_PY: ${{ runner.temp }}/llama.cpp/gguf-py
SKIP_LINUX_TYPECHECK: '1'
run: scripts/check-local.sh --port
+1 -1
View File
@@ -2,7 +2,7 @@
Read-only snapshot, 2026-10-12. Audit artifact only; no builds, tests, GPU,
Strata, model or daemon execution. Paths below are relative to this source-port
tree or to the imported `engine/strata/`. Root integration remains mutable.
tree or to the Strata tree that was imported (removed, see `third_party/strata/UPSTREAM.md`). Root integration remains mutable.
This is a bounded core-path ledger, not a whole-project completion certificate.
## Actionable remaining boundaries
+4 -4
View File
@@ -2,8 +2,8 @@
Leleka is a Rust/CUDA inference runtime for coding agents. Release **0.1** serves one model, **Qwen3.8-Flash-Next IQ3_S** (KAR level-2 PLE, MTP speculative
decode), on **one RTX 5090 (32 GB)** at **262,144 tokens of context**, to Codex CLI and other clients over the Responses, Chat Completions and Messages APIs.
It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (reference copy in `engine/strata/`, pinned at
upstream `41cf05a0`, see `engine/upstream.md`). Serving needs no Python and no CUDA toolkit on the host.
It is a Rust/CUDA port of the Original mode17 serve path of [Strata](https://github.com/Niko1221/Strata) (pinned at upstream `41cf05a0`; the vendored copy was removed, see
`third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host.
**Status of 0.1.** It runs real Codex sessions to completion and decodes about 155 tok/s on the 245k-token benchmark of the 5090 server (section "Numbers").
It is **not a formally quality-gated profile**, only the RTX 5090 is supported, and the limits below are real. Release notes: `spec node release/RELEASE-NOTES-5090-v0.1.md`;
@@ -76,7 +76,7 @@ What the service is doing, and why a request was slow or failed, is in its logs;
- `crates/` — the runtime: `engine-qwen35-cuda` (the engine; `leleka-runtime` is its facade), `engine-core` (pure engine domain), `cuda-driver` (CUDA Driver API, sealed PTX), `leleka-memory` (memory governor), `obs` (logging), `deploy` (the `leleka` binary), model-format, tokenizer, sampler and CPU kernels.
- `control-plane/`, `desktop-core/` — the HTTP/Responses gateway (`leleka-api`) and the engine/daemon processes.
- `engine/strata/` — the pinned upstream Strata, the reference (unmodified by Leleka).
- `third_party/strata/` — the Strata MIT licence texts, the pinned chat template and golden, and `UPSTREAM.md` (pin `41cf05a0`, local patches, where the removed vendored tree is in history). The Strata source tree itself is not in the repository.
- `deploy/`, `scripts/` — profiles, service templates, release packager (`scripts/release/`), test and measurement tooling (Python is allowed there, never in serving).
- `PROJECT_CHARTER.md`, the LeaseVibe spec (imported repository documentation) — requirements, provenance, decisions, gates and measurements. Architecture: spec node `architecture/hexagonal.md`.
@@ -92,4 +92,4 @@ scripts/release/package-5090.sh check # the release gates; `package` buil
## Licence
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`engine/strata/LICENSE`).
MIT (`LICENSE`). A commercial licence is available on request. Third-party notices: `spec node release/licence-and-secrets-audit-5090-v0.1.md`; the Strata reference is MIT (`third_party/strata/LICENSE`, printed by `leleka engine license`).
+1 -1
View File
@@ -201,7 +201,7 @@ fn engine_info() -> Result<(), BoxError> {
}
fn engine_license() -> Result<(), BoxError> {
print!("{}", include_str!("../../../engine/strata/LICENSE"));
print!("{}", include_str!("../../../third_party/strata/LICENSE"));
Ok(())
}
+1 -1
View File
@@ -1,5 +1,5 @@
//! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`,
//! `hardware_static`, `history`; `engine/strata/serve/telemetry.py`), built from the engine's telemetry document
//! `hardware_static`, `history`; `Strata 41cf05a0, serve/telemetry.py`), built from the engine's telemetry document
//! (`leleka-memory`'s `telemetry.rs`, copied here by the worker on its health tick).
//!
//! Units follow the Python service: memory in bytes, utilisation and CPU in percent, power in watts, temperature in
+1 -1
View File
@@ -1,5 +1,5 @@
//! MCP (Model Context Protocol) hub: tools from MCP servers, namespaced `<server>__<tool>`, called
//! on behalf of an agent. Port of `engine/strata/serve/mcp.py`.
//! on behalf of an agent. Port of `Strata 41cf05a0, serve/mcp.py`.
//!
//! The operator lists servers in the run config (`mcp_servers`, or Claude Desktop's `mcpServers`
//! block as is, or a separate `mcp_config_file`): a program Strata starts (`command`, `args`,
+2 -2
View File
@@ -8,10 +8,10 @@ use std::{
};
const INDEX_LIMIT: u64 = 64 * 1024;
// engine/strata/include/strata/kernels/cpu/expert.hpp: NE * BLOB.
// Strata 41cf05a0, include/strata/kernels/cpu/expert.hpp: NE * BLOB.
const EXPERT_BYTES: u64 = 512 * 1_382_400;
// Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py.
// Consumer: engine/strata/src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256).
// Consumer: Strata 41cf05a0, src/core/mtp.cpp (N=2560, HC=4, NH=24, HD=256).
const REQUIRED: &[(&str, &str, u64, u64)] = &[
("fc_embedding.weight", "q8_0", 2560, 2560),
("fc_hidden.weight", "q8_0", 2560, 2560),
+6 -6
View File
@@ -236,12 +236,12 @@ fn shards_for(golden: &Golden) -> Vec<Shard> {
#[test]
fn real_golden_expert_tables_are_reproduced() {
let goldens = [
include_str!("../../../engine/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../../engine/strata/tests/data/native_experts/swift-iq2_xs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_s.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq3_xxs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/iq2_xs.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/q2_0.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/coder-iq1_m.txt"),
include_str!("../../../third_party/strata/tests/data/native_experts/swift-iq2_xs.txt"),
];
for text in goldens {
let golden = parse_golden(text);
+1 -1
View File
@@ -1,5 +1,5 @@
//! The API request monitor: `GET /api/requests`, the opt-in inspection of the last requests' prompts and answers of the
//! Python service (`api_monitor` in its config; `engine/strata/serve/server.py` `begin_request` / `request_records`,
//! Python service (`api_monitor` in its config; `Strata 41cf05a0, serve/server.py` `begin_request` / `request_records`,
//! tests in `serve/test_monitor.py`).
//!
//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`,
+2 -2
View File
@@ -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::*;
@@ -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,
-617
View File
@@ -1,617 +0,0 @@
"""Offline golden generator for the control-plane serving surface (Python is allowed for fixtures only).
Runs the REAL Python handlers of the pinned Strata (`engine/strata/serve/*.py`, mock engine, no GPU) over tables
of inputs and records what they answer. The Rust tests in `control-plane/tests/golden_*.rs` and the unit tests of
`crates/serving-policy` compare against these files.
python3 -I control-plane/tests/golden/gen_goldens.py [section ...]
Needs the packages in engine/strata/requirements.txt (jinja2, jsonschema, regex). The scratchpad venv has them.
Sections: gen_lines, shared, props_slots, cors, ...
"""
import json
import os
import queue
import sys
import threading
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.normpath(os.path.join(HERE, "..", "..", ".."))
ENGINE = os.path.join(REPO, "engine", "strata")
sys.path.insert(0, ENGINE)
sys.path.insert(0, os.path.join(ENGINE, "tools"))
OUT_CONTROL = os.path.join(HERE, "..", "fixtures", "golden")
OUT_POLICY = os.path.join(REPO, "crates", "serving-policy", "tests", "fixtures")
def write(name, obj, dest="control"):
out = OUT_POLICY if dest == "policy" else OUT_CONTROL
os.makedirs(out, exist_ok=True)
path = os.path.join(out, name + ".json")
with open(path, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1, ensure_ascii=False, sort_keys=False)
f.write("\n")
print("wrote", os.path.relpath(path, REPO), file=sys.stderr)
# ------------------------------------------------------------------------------------------------ gen_lines
def gen_lines():
from serve.server import StrataEngine
class Pipe:
def __init__(self):
self.sent = []
def write(self, text):
self.sent.append(text)
def flush(self):
pass
def capture(ids, max_new, sampling, embeddings=None):
eng = object.__new__(StrataEngine)
eng.proc = type("P", (), {"stdin": Pipe()})()
eng.lines = queue.Queue()
eng.lines.put("DONE 1 1 1.0 1.0 stop\n")
eng.can_stop = False
eng.progress = None
eng.prefill_tok_s_mean = None
eng.last = {}
list(eng.generate(ids, max_new, sampling, threading.Event(), embeddings=embeddings))
return "".join(eng.proc.stdin.sent)
cases = []
sampling_tables = [
{},
{"temperature": 0.0},
{"temperature": 0.7},
{"temperature": 0.7, "top_p": 0.9},
{"temperature": 1, "top_p": 1.0},
{"temperature": 0.8, "top_k": 40, "min_p": 0.05},
{"temperature": 0.8, "top_k": 0},
{"temperature": 0.8, "top_k": 1000},
{"temperature": 0.6, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
{"repetition_penalty": 1.1},
{"repetition_penalty": 1.1, "penalty_last_n": 256},
{"presence_penalty": 0.5, "frequency_penalty": 0.25},
{"presence_penalty": -0.5},
{"frequency_penalty": 1.5, "penalty_last_n": 0},
{"temperature": 0.7, "seed": 42},
{"temperature": 0.7, "seed": 0},
{"temperature": 0.7, "seed": 18446744073709551615},
{"temperature": 0.9, "top_p": 0.8, "top_k": 33, "min_p": 0.02, "repetition_penalty": 1.05,
"presence_penalty": 0.1, "frequency_penalty": 0.2, "penalty_last_n": 128, "seed": 7},
{"strata_tune": {"pcie_frac": 0.0}},
{"strata_tune": {"pcie_frac": 0.35, "spec_min_p": 0.2}},
{"strata_tune": {"spec_min_p": 1.0}},
{"experimental_speed_projection": True},
{"experimental_speed_projection": False},
{"temperature": 0.5, "strata_tune": {"pcie_frac": 0.5}, "experimental_speed_projection": False},
]
for ids, max_new, emb in (([1, 2, 3], 16, None), ([248045, 872, 198, 9707], 4096, None),
([5, 248056, 248056, 6], 32, "/tmp/req-abc123.sve")):
for sampling in sampling_tables:
cases.append({"token_ids": ids, "max_new": max_new, "embeddings": emb, "sampling": sampling,
"line": capture(ids, max_new, sampling, emb)})
write("gen_lines", {"source": "serve/server.py StrataEngine.generate (real code, fake pipe)", "cases": cases})
# ------------------------------------------------------------------------------------------------ shared
def shared():
from serve.server import clean_shared_defaults, sampling_defaults_from_config
clean_cases = [
None, {}, [], "x", 5,
{"temperature": 0.7}, {"temperature": 1}, {"temperature": 0}, {"temperature": 2}, {"temperature": 2.5},
{"temperature": -0.1}, {"temperature": True}, {"temperature": "0.5"},
{"top_p": 0.9}, {"top_p": 1}, {"top_p": 0}, {"top_p": 1.5}, {"top_p": False},
{"top_k": 40}, {"top_k": 40.0}, {"top_k": 40.5}, {"top_k": 0}, {"top_k": 64}, {"top_k": 65}, {"top_k": "40"},
{"seed": 7}, {"seed": 7.0}, {"seed": 0}, {"seed": -3}, {"seed": 1.5}, {"seed": 18446744073709551615},
{"max_tokens": 512}, {"max_tokens": 0}, {"max_tokens": "10"},
{"reasoning_effort": "none"}, {"reasoning_effort": "low"}, {"reasoning_effort": "medium"},
{"reasoning_effort": "high"}, {"reasoning_effort": "xhigh"}, {"reasoning_effort": 3},
{"experimental_speed_projection": True}, {"experimental_speed_projection": False},
{"experimental_speed_projection": 1},
{"temperature": None, "top_p": "", "top_k": None}, {"unknown": 1}, {"unknown": None}, {"min_p": 0.1},
{"temperature": 0.7, "top_p": 0.9, "top_k": 20, "seed": 11, "max_tokens": 100,
"reasoning_effort": "medium", "experimental_speed_projection": False},
]
clean = []
for case in clean_cases:
try:
clean.append({"input": case, "ok": clean_shared_defaults(case)})
except ValueError as e:
clean.append({"input": case, "error": str(e)})
config_cases = [
None, {}, {"temperature": 0.7}, {"temperature": 0}, {"temperature": -1}, {"temperature": True},
{"top_p": 0.95}, {"top_p": 0}, {"top_p": 1.01}, {"min_p": 0.05}, {"min_p": 0}, {"min_p": 2},
{"top_k": 40}, {"top_k": 0}, {"top_k": 65}, {"top_k": 20.0}, {"top_k": 1.5},
{"presence_penalty": 0.5}, {"presence_penalty": -0.5}, {"frequency_penalty": 0.25},
{"frequency_penalty": -1}, {"repetition_penalty": 1.1}, {"repetition_penalty": 0},
{"penalty_last_n": 128}, {"penalty_last_n": 0}, {"penalty_last_n": -2}, {"penalty_last_n": 1.5},
{"seed": 5}, {"seed": 0}, {"seed": 5.5}, {"seed": "5"},
{"experimental_speed_projection": True}, {"experimental_speed_projection": "yes"},
{"temperature": None, "top_p": None}, {"nonsense": 3}, {"temperature": 0.6, "nonsense": 3},
{"temperature": 0.6, "top_p": 0.9, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.1,
"frequency_penalty": 0.1, "repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 9},
]
import contextlib
import io
config = []
for case in config_cases:
out = io.StringIO()
try:
with contextlib.redirect_stdout(out):
ok = sampling_defaults_from_config({"sampling": case} if case is not None else {})
config.append({"input": case, "ok": ok, "ignored": [ln for ln in out.getvalue().splitlines()
if "unknown key" in ln]})
except SystemExit as e:
config.append({"input": case, "error": str(e)})
write("shared", {"source": "serve/server.py clean_shared_defaults / sampling_defaults_from_config (real code)",
"clean": clean, "config": config}, dest="policy")
# ------------------------------------------------------------------------------------------------ reasoning
def reasoning():
import random
from serve.frontend import OutputParser
from serve.server import Detokenizer, Service, ByteTokenizer
class BytesTok:
"""Token i's bytes are the table's entry; what Detokenizer needs from the real tokenizer."""
def __init__(self, table):
self.table = table
def token_bytes(self, t):
return self.table[t]
pieces = [b"a", b"b", b" so ", b"think", b"</", b"/think>", b"</think>", b"</thi", b"nk>", b"<", b"/", b"\n",
b"\xc3", b"\xa9", "\u65e5".encode()[:1], "\u65e5".encode()[1:], b"\xff", b"\xe2\x82", b"\xac", b"<t",
b"hink>", b"x"]
rng = random.Random(1234)
seqs = [[0, 1, 2, 3], [4, 5], [6, 0, 1], [0, 4, 0, 1], [11, 12, 0, 0, 0], [13, 14, 0, 0], [16, 0, 0], [17, 18, 0],
[3, 4, 5, 3, 3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
for _ in range(120):
seqs.append([rng.randrange(len(pieces)) for _ in range(rng.randrange(1, 14))])
cases = []
for seq in seqs:
row = {"pieces_hex": [pieces[i].hex() for i in seq], "wrap_at": {}}
for budget in (1, 2, 3, 5, 8):
parser = OutputParser(thinking=True, tools=None, stream_tools=True)
detok = Detokenizer(BytesTok(pieces))
thought, wrap_at = 0, None
for i, t in enumerate(seq):
parser.feed(detok.push(t))
if parser.state == "reasoning":
thought += 1
if thought >= budget and not parser.buf and not detok.pending():
wrap_at = i
break
row["wrap_at"][str(budget)] = wrap_at
cases.append(row)
parse = []
svc = Service.__new__(Service)
for req, default in [(None, 0), ({}, 0), ({"reasoning_budget_tokens": 20}, 0), ({"reasoning_budget_tokens": 20.0}, 0),
({"reasoning_budget_tokens": 0}, 50), ({"reasoning_budget_tokens": -1}, 50),
({}, 50), ({"reasoning_budget_tokens": None}, 50), ({"reasoning_budget_tokens": True}, 0),
({"reasoning_budget_tokens": "5"}, 0), ({"reasoning_budget_tokens": 2.5}, 0),
({"reasoning_budget_tokens": [1]}, 0), ({"reasoning_budget_tokens": 10000}, 0)]:
svc.reasoning_budget_tokens = default
try:
parse.append({"request": req, "default": default, "ok": svc.reasoning_budget(req)})
except ValueError as e:
parse.append({"request": req, "default": default, "error": str(e)})
from serve.server import REASONING_WRAP_UP
write("reasoning", {"source": "serve/server.py Service.reasoning_budget + Service.run budget branch (real "
"Detokenizer/OutputParser)", "wrap_up": REASONING_WRAP_UP, "cases": cases,
"parse": parse}, dest="policy")
# ------------------------------------------------------------------------------------------------ http
def http_surface():
"""The operational HTTP surface of the real Python server, scenario by scenario (fake resident engine)."""
import http.client
from pathlib import Path
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, serve
class Resident(StrataEngine):
def __init__(self, tok, loaded, max_context):
self.reply = MockEngine(tok, "Hello.", max_context=max_context)
self.max_context, self.info, self.last = max_context, {"version": "9.9.9"}, {}
self.loaded, self.unloaded, self.progress = loaded, not loaded, None
def alive(self):
return self.loaded
def exit_code(self):
return None
def restart(self):
self.loaded, self.unloaded = True, False
def close(self):
self.loaded = False
def unload(self):
self.close()
self.unloaded = True
def generate(self, *args, **kwargs):
yield from self.reply.generate(*args, **kwargs)
def run(setup, steps):
tok = ByteTokenizer()
engine = Resident(tok, setup.get("loaded", True), setup.get("max_context", 4096))
svc = Service(engine, tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
model_name=setup.get("model", "strata-test"),
sampling_defaults=setup.get("config_sampling") or {})
svc.set_aliases(setup.get("aliases"))
svc.api_key = setup.get("api_key", "")
svc.cors_origins = setup.get("cors_origins", [])
svc.trusted_origins = setup.get("trusted_origins", [])
if setup.get("shared"):
svc.shared = dict(setup["shared"])
svc.idle_unload_s = setup.get("idle_unload_s", 0)
for key, value in (setup.get("status") or {}).items():
svc.status[key] = value
httpd = serve(svc, port=0)
port = httpd.server_address[1]
out = []
try:
for step in steps:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10)
headers = dict(step.get("headers") or {})
body = step.get("body")
if body is not None and not isinstance(body, str):
body = json.dumps(body)
headers.setdefault("Content-Type", "application/json")
if body is not None:
headers.setdefault("Content-Length", str(len(body.encode())))
conn.request(step["method"], step["path"], body=body.encode() if body is not None else None,
headers=headers)
response = conn.getresponse()
raw = response.read().decode()
selected = {k.lower(): v for k, v in response.getheaders()
if k.lower().startswith("access-control-") or k.lower() == "vary"}
try:
parsed = json.loads(raw) if raw else None
except ValueError:
parsed = raw
out.append({"request": {"method": step["method"], "path": step["path"],
"headers": step.get("headers") or {}, "body": step.get("body")},
"status": response.status, "headers": selected, "body": parsed,
"state": {"loaded": engine.loaded, "shared": svc.shared}})
conn.close()
finally:
httpd.shutdown()
httpd.server_close()
return {"setup": setup, "steps": out}
scenarios = {}
# ---- CORS
cors_steps = [
{"method": "OPTIONS", "path": "/v1/chat/completions",
"headers": {"Origin": "https://a.example", "Access-Control-Request-Headers": "authorization,content-type"}},
{"method": "OPTIONS", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
{"method": "OPTIONS", "path": "/v1/models"},
{"method": "OPTIONS", "path": "/health", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://a.example/"}},
{"method": "GET", "path": "/v1/status?x=1", "headers": {"Origin": "https://b.example"}},
{"method": "GET", "path": "/v1/models", "headers": {"Origin": "https://evil.example"}},
{"method": "GET", "path": "/v1/models"},
{"method": "GET", "path": "/health", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/props", "headers": {"Origin": "https://a.example"}},
{"method": "GET", "path": "/v1/nothing", "headers": {"Origin": "https://a.example"}},
]
for name, origins in (("off", []), ("any", ["*"]), ("listed", ["https://a.example", "https://b.example"])):
scenarios[f"cors_{name}"] = run({"cors_origins": origins}, cors_steps)
# (an unknown path answers 404 before authentication in the Python server; the Rust server
# authenticates every path first, so that one step is left out here)
scenarios[f"cors_{name}_with_key"] = run({"cors_origins": origins, "api_key": "k" * 40}, cors_steps[:-1])
# ---- own page
page = {"defaults": {"temperature": 0.5}}
own = [
{"method": "POST", "path": "/settings", "body": page},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "http://127.0.0.1:1"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com/"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://strata.example.com",
"Host": "proxy.internal"}},
{"method": "POST", "path": "/settings", "body": page, "headers": {"Origin": "https://evil.example",
"X-Forwarded-Host": "evil.example",
"CF-Ray": "1"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page), "headers": {"Content-Type": "text/plain"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page),
"headers": {"Content-Type": "application/x-www-form-urlencoded"}},
{"method": "POST", "path": "/settings", "body": json.dumps(page),
"headers": {"Content-Type": "application/json; charset=utf-8"}},
{"method": "GET", "path": "/settings"},
]
scenarios["own_page"] = run({"trusted_origins": ["https://strata.example.com"]}, own)
# ---- settings
settings = [
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.7, "top_k": 40, "seed": 3}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 9}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"nonsense": 1}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_p": 0, "temperature": 1}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"max_tokens": 128, "reasoning_effort": "low",
"experimental_speed_projection": True}}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": [1, 2]},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": {"temperature": 0.5}}},
{"method": "POST", "path": "/settings", "body": {}},
{"method": "GET", "path": "/settings"},
{"method": "POST", "path": "/settings", "body": {"defaults": 5}},
]
scenarios["settings"] = run({}, settings)
scenarios["settings_with_key"] = run({"api_key": "k" * 40}, [
{"method": "GET", "path": "/settings"},
{"method": "GET", "path": "/settings", "headers": {"Authorization": "Bearer " + "k" * 40}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}}},
{"method": "POST", "path": "/settings", "body": {"defaults": {"top_k": 5}},
"headers": {"Authorization": "Bearer " + "k" * 40}},
])
# ---- props, slots, health, status
reads = [
{"method": "GET", "path": "/props"},
{"method": "GET", "path": "/props?model=strata-test"},
{"method": "GET", "path": "/props?model=alias-one"},
{"method": "GET", "path": "/props?model=nope"},
{"method": "GET", "path": "/props?model="},
{"method": "GET", "path": "/slots"},
{"method": "GET", "path": "/api/health"},
{"method": "GET", "path": "/v1/status"},
]
scenarios["reads_loaded"] = run({"aliases": ["alias-one", "alias-two"]}, reads)
scenarios["reads_loaded_with_defaults"] = run(
{"config_sampling": {"temperature": 0.6, "top_p": 0.95, "top_k": 30, "min_p": 0.02, "presence_penalty": 0.2,
"repetition_penalty": 1.05, "penalty_last_n": 64, "seed": 8},
"shared": {"temperature": 0.9, "max_tokens": 256}, "max_context": 32768}, reads)
scenarios["reads_unloaded"] = run({"loaded": False, "aliases": ["alias-one"]}, reads)
scenarios["reads_busy"] = run({"status": {"busy": True, "queued": 2}}, [
{"method": "GET", "path": "/slots"}, {"method": "GET", "path": "/v1/status"}])
scenarios["reads_with_key"] = run({"api_key": "k" * 40}, [
{"method": "GET", "path": "/props"}, {"method": "GET", "path": "/slots"},
{"method": "GET", "path": "/v1/status"}, {"method": "GET", "path": "/api/health"},
{"method": "GET", "path": "/health"}])
# ---- load / unload
lifecycle = [
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/unload"},
{"method": "GET", "path": "/slots"},
{"method": "POST", "path": "/load"},
{"method": "POST", "path": "/load"},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/load", "body": {"model": "other-model"}},
{"method": "POST", "path": "/v1/load", "body": {"model": "strata-test"}},
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/v1/load", "body": "{}", "headers": {"Content-Type": "text/plain"}},
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Origin": "https://other.example"}},
{"method": "POST", "path": "/v1/unload", "body": [1]},
{"method": "POST", "path": "/v1/unload", "body": "not json", "headers": {"Content-Type": "application/json"}},
{"method": "POST", "path": "/v1/unload", "body": {"model": None}},
{"method": "GET", "path": "/props"},
]
scenarios["lifecycle"] = run({}, lifecycle)
scenarios["lifecycle_busy"] = run({"status": {"queued": 1}}, [
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/load"},
])
scenarios["lifecycle_unloaded_then_busy"] = run({"loaded": False, "status": {"busy": True}}, [
{"method": "POST", "path": "/v1/load", "body": {}},
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/load"},
])
scenarios["lifecycle_with_key"] = run({"api_key": "k" * 40}, [
{"method": "POST", "path": "/unload"},
{"method": "POST", "path": "/v1/unload", "body": {}},
{"method": "POST", "path": "/v1/unload", "body": {},
"headers": {"Authorization": "Bearer " + "k" * 40, "Origin": "https://other.example"}},
{"method": "POST", "path": "/v1/unload", "body": {}, "headers": {"Authorization": "Bearer " + "k" * 40}},
{"method": "POST", "path": "/load", "headers": {"x-api-key": "k" * 40}},
])
write("http_surface", {"source": "serve/server.py Handler (real code, resident fake engine)",
"scenarios": scenarios})
# ------------------------------------------------------------------------------------------------ timings
def timings():
from serve.server import ByteTokenizer, MockEngine, Service, request_timings
from serve.frontend import ChatTemplate
from pathlib import Path
cases = []
lasts = [
{"prompt_ms": 250.0, "decode_ms": 1000.0, "generated": 50, "reused": 60},
{"prompt_ms": 0.0, "decode_ms": 0.0, "generated": 0, "reused": 0},
{"prompt_ms": 12.34567, "decode_ms": 98.7654, "generated": 7, "reused": None},
{"prompt_ms": 0.25, "decode_ms": 0.05, "generated": 3},
{"prompt_ms": 2.675, "decode_ms": 1234.55, "generated": 11, "reused": 5, "drafts_offered": 20, "drafts_accepted": 15},
{"prompt_ms": 100.0, "decode_ms": 333.3333, "generated": 0, "reused": 200},
{"prompt_ms": 1e-9, "decode_ms": 5e-5, "generated": 9, "reused": 0, "drafts_offered": 0, "drafts_accepted": 0},
{"prompt_ms": 12345.678, "decode_ms": 87654.321, "generated": 4096, "reused": 1},
]
for last in lasts:
for prompt_tokens, generated in ((300, last.get("generated") or 5), (10, 10), (0, 0), (50, 7)):
cases.append({"last": last, "prompt_tokens": prompt_tokens, "generated": generated,
"timings": request_timings(prompt_tokens, generated, last)})
cases.append({"last": {}, "prompt_tokens": 5, "generated": 5, "timings": request_timings(5, 5, {})})
aliases = []
tok = ByteTokenizer()
for value in (None, [], ["a"], [" a ", "a", "", "m", "b"], "a, b ,a,,m", ["a", 1], 5, {"a": 1}, "", [""]):
svc = Service(MockEngine(tok, "x"), tok, ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja"),
model_name="m")
try:
svc.set_aliases(value)
aliases.append({"input": value, "ok": svc.aliases})
except ValueError as e:
aliases.append({"input": value, "error": str(e)})
write("timings", {"source": "serve/server.py request_timings + Service.set_aliases (real code)",
"timings": cases, "aliases": aliases}, dest="policy")
# ------------------------------------------------------------------------------------------------ vision
def vision():
import base64
import tempfile
from pathlib import Path
from serve.frontend import ChatTemplate, _image_source, images_of, openai_to_messages
from serve.server import IMAGE_PAD, VISION_START, ByteTokenizer, MockEngine, Service, Vision
# base64 as Vision.load decodes data: URLs
b64 = []
for text in ["QQ==", "QUI=", "QUJD", "QU\nJD", "", "QQ", "Q", "QUJDRA==", "QUJDRA=", "QUJDRA", "QU JD", "QQ==QQ==",
"Q=Q=", "!!!!", "QUJD\n", "//8=", "-_8=", "QUJD=", "====", "QUJDREVG", "QUJDREVGRw", "QUJDREVGRw=="]:
try:
b64.append({"text": text, "ok": Vision.load("data:image/png;base64," + text).hex()})
except Exception as e: # binascii.Error and friends
b64.append({"text": text, "error": type(e).__name__ + ": " + str(e)})
sources = [
{"type": "image_url", "image_url": {"url": "https://x/y.png"}}, {"type": "image_url", "image_url": "data:abc"},
{"type": "input_image", "image_url": "file:///a.png"}, {"type": "image_url"}, {"type": "image_url", "image_url": {}},
{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "QQ=="}},
{"type": "image", "source": {"type": "base64", "data": "QQ=="}},
{"type": "image", "source": {"type": "url", "url": "http://u"}}, {"type": "image", "source": {"path": "/p.png"}},
{"type": "image", "source": {"url": "", "path": "/q.png"}}, {"type": "image"}, {"type": "image", "source": None},
]
src = [{"part": part, "source": _image_source(part)} for part in sources]
tok = ByteTokenizer()
class FakeVision:
def __init__(self, counts):
self.counts, self.dir = counts, Path(tempfile.mkdtemp(prefix="strata-golden-"))
def encode(self, source):
path = self.dir / (str(abs(hash(source)) % 10**8) + ".sve")
path.write_bytes(source.encode())
return path, self.counts[source]
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
prepared = []
cases = [
([{"role": "user", "content": "hello"}], {}),
([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "A"}}]}],
{"A": 3}),
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}},
{"type": "image_url", "image_url": {"url": "B"}},
{"type": "text", "text": "compare"}]}], {"A": 2, "B": 5}),
([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "A"}}]},
{"role": "assistant", "content": "ok"},
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": "C"}}]}],
{"A": 1, "C": 4}),
([{"role": "user", "content": [{"type": "text", "text": "literal " + IMAGE_PAD + " in text"},
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
([{"role": "user", "content": "just text " + IMAGE_PAD + " again"}], {}),
([{"role": "user", "content": [{"type": "text", "text": VISION_START + IMAGE_PAD + " fake"},
{"type": "image_url", "image_url": {"url": "A"}}]}], {"A": 2}),
]
for messages, counts in cases:
req = {"messages": messages}
norm, tools, kw = openai_to_messages(req)
prompt = template.render(norm, tools=tools, **kw)
ids_before = tok.encode(prompt, parse_special=True)
svc = Service(MockEngine(tok, "x", max_context=100000), tok, template, vision=FakeVision(counts) if counts else None)
entry = {"messages": messages, "counts": counts, "ids_before": ids_before,
"images": images_of(norm), "pad": tok.encode(IMAGE_PAD, parse_special=True)[0],
"start": tok.encode(VISION_START, parse_special=True)[0],
"literal": tok.encode(IMAGE_PAD, parse_special=False)}
try:
ids, thinking, max_new = svc.prepare(norm, tools, kw, 10)
entry["ids_after"] = ids
entry["combined_hex"] = Path(svc.embeddings.path).read_bytes().hex() if getattr(svc.embeddings, "path", None) else None
except ValueError as e:
entry["error"] = str(e)
prepared.append(entry)
write("vision", {"source": "serve/server.py Service.prepare, Vision.load, frontend._image_source (real code)",
"base64": b64, "sources": src, "prepare": prepared}, dest="policy")
def vision_dialects():
"""Chat and Messages requests that carry pictures, through the real `openai_to_messages` / `anthropic_to_messages`
and the real chat template: the prompt text and the picture sources in prompt order."""
import base64
from pathlib import Path
from serve.frontend import ChatTemplate, anthropic_to_messages, images_of, openai_to_messages
template = ChatTemplate(Path(ENGINE) / "serve" / "chat_template.jinja")
counter = iter(range(1, 250))
def url():
# a PNG signature and one tag byte: the tests find the picture again by its last byte
return "data:image/png;base64," + base64.b64encode(b"\x89PNG\r\n\x1a\n" + bytes([next(counter)])).decode()
def chat(messages):
return {"dialect": "chat", "request": {"messages": messages, "reasoning_effort": "none"}}
def claude(messages, system=None):
request = {"messages": messages, "thinking": {"type": "disabled"}}
if system:
request["system"] = system
return {"dialect": "messages", "request": request}
def b64(media="image/png"):
data = url().split(",", 1)[1]
return {"type": "image", "source": {"type": "base64", "media_type": media, "data": data}}
cases = [
chat([{"role": "user", "content": [{"type": "text", "text": "what is this?"},
{"type": "image_url", "image_url": {"url": url(), "detail": "high"}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": url()}, {"type": "text", "text": "after"}]}]),
chat([{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": url()}},
{"type": "text", "text": "b"}, {"type": "image_url", "image_url": url()},
{"type": "text", "text": "c"}]}]),
chat([{"role": "system", "content": "be brief"},
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "x"}]}]),
chat([{"role": "user", "content": "first"}, {"role": "assistant", "content": "ok"},
{"role": "user", "content": [{"type": "text", "text": "again"}, {"type": "image_url", "image_url": {"url": url()}}]}]),
chat([{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}]},
{"role": "assistant", "content": "a cat"},
{"role": "user", "content": [{"type": "image_url", "image_url": {"url": url()}}, {"type": "text", "text": "and?"}]}]),
chat([{"role": "user", "content": [{"type": "text", "text": "the docs say <|image_pad|> marks an image"},
{"type": "image_url", "image_url": {"url": url()}}]}]),
claude([{"role": "user", "content": [b64(), {"type": "text", "text": "describe"}]}]),
claude([{"role": "user", "content": [{"type": "text", "text": "describe"}, b64("image/jpeg")]}], system="be brief"),
claude([{"role": "user", "content": [b64(), b64(), {"type": "text", "text": "compare"}]}]),
claude([{"role": "user", "content": [{"type": "text", "text": "look"}, {"type": "image", "source": {"type": "url", "url": url()}}]}]),
claude([{"role": "user", "content": [{"type": "image", "source": {"type": "url", "url": url()}}]}]),
claude([{"role": "user", "content": "first"}, {"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
{"role": "user", "content": [b64(), {"type": "text", "text": "now this"}]}]),
]
out = []
for case in cases:
req = case["request"]
if case["dialect"] == "chat":
messages, tools, kw = openai_to_messages(req)
else:
messages, tools, kw = anthropic_to_messages(req)
out.append({**case, "prompt": template.render(messages, tools=tools, **kw), "images": images_of(messages)})
write("vision_dialects", {"source": "serve/frontend.py openai_to_messages / anthropic_to_messages + chat_template.jinja",
"cases": out})
SECTIONS = {"gen_lines": gen_lines, "shared": shared, "reasoning": reasoning, "http": http_surface,
"timings": timings, "vision": vision, "vision_dialects": vision_dialects}
def main(argv):
names = argv or list(SECTIONS)
for name in names:
SECTIONS[name]()
if __name__ == "__main__":
main(sys.argv[1:])
+1 -1
View File
@@ -2,7 +2,7 @@
//! The operational HTTP surface (`/props`, `/slots`, `/settings`, `/load`, `/unload`, `/v1/load`,
//! `/v1/unload`, `/v1/status`, `/api/health`, CORS, own-page guard) against the real Python
//! handlers: every scenario in `tests/fixtures/golden/http_surface.json` was recorded from
//! `engine/strata/serve/server.py` by `tests/golden/gen_goldens.py http`, and is replayed here
//! `Strata 41cf05a0, serve/server.py` 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
+1 -1
View File
@@ -7,7 +7,7 @@ use std::path::PathBuf;
use std::process::{Command, Stdio};
pub(super) fn fake_path() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../engine/strata/serve/mcp_fake_server.py")
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/mcp_hub/mcp_fake_server.py")
}
pub(super) fn python() -> Option<&'static str> {
+3 -3
View File
@@ -1,6 +1,6 @@
//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`,
//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients,
//! paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation.
//! The MCP hub against the Python fake server of the Original (`mcp_fake_server.py` next to this test, from
//! Strata 41cf05a0 `serve/`, standard library only; a test double, not part of serving): stdio and Streamable
//! HTTP clients, paging, namespacing, errors as text, timeouts, the result cap, restart on demand, cancellation.
//! The tests are skipped (with a message) when `python3` is not installed.
mod harness;
+1 -1
View File
@@ -1,5 +1,5 @@
//! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is
//! `engine/strata/tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine.
//! `Strata 41cf05a0, tools/test_mtp_fetch.py` (#327), ported case for case. Nothing leaves the machine.
use std::{
collections::BTreeMap,
fs,
+1 -1
View File
@@ -2,7 +2,7 @@
These unmodified source and header files come from `ggml-org/llama.cpp` commit
`3cf03257f219afbe7334045ff7c6a06ac68c627d`, the same commit pinned by
the imported Strata engine in `engine/strata/third_party/ggml/VERSION.txt`.
the Strata engine pinned in `third_party/strata/UPSTREAM.md` (its `third_party/ggml/VERSION.txt`).
Their original repository paths are under `ggml/src/` or `ggml/include/`;
`ggml-cpu-impl.h` came from `ggml/src/ggml-cpu/`. `SHA256SUMS` records every
vendored file. The upstream MIT license is in `LICENSE`.
+1 -1
View File
@@ -1,6 +1,6 @@
//! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder.
//!
//! Literal port of the Original (pinned Strata under `engine/strata/`):
//! Literal port of the Original (pinned Strata, upstream commit 41cf05a0):
//! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`,
//! `rope_scaling_invalid`, `RopeKernelArgs`),
//! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads),
+1 -1
View File
@@ -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
@@ -1,49 +0,0 @@
// gen_kv_pool_golden.cpp - prints the Original's `kv_pool_bytes` (src/core/layer.cpp, extracted verbatim by
// gen_plan_golden.py into kv_pool_bytes.inc) for every KV format on several shapes. Output: JSON array.
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/qsa.hpp"
#include <cstdint>
#include <cstdio>
using strata::kernels::QsaShapes;
static bool g_without_key = false; // layer.cpp globals the extracted function reads
static bool g_kv_q4 = false;
#include "kv_pool_bytes.inc"
int main() {
struct Shape { int64_t kv, dim, page; };
const Shape shapes[] = {{2, 256, 4}, {4, 128, 1}, {2, 256, 1}, {1, 64, 8}};
const int64_t pages[] = {1, 7, 131072, 262144};
struct Fmt { const char* name; bool without_key, q4, hybrid, int8; };
// the flag combinations qsa_state_bytes passes: kv_pool_bytes(s, slots, g_kv_hybrid, g_kv_int8 || g_kv_hybrid)
const Fmt fmts[] = {{"fp16", false, false, false, false},
{"int8", false, false, false, true},
{"q4_0", false, true, false, false},
{"k8v4", false, false, true, true},
{"int8-keyless", true, false, false, true}};
std::printf("[");
bool first = true;
for (const Shape& sh : shapes) {
QsaShapes s = strata::kernels::qsa_real_shapes();
s.n_head_kv = sh.kv;
s.head_dim = sh.dim;
s.page_size = sh.page;
for (const Fmt& f : fmts) {
g_without_key = f.without_key;
g_kv_q4 = f.q4;
for (int64_t p : pages) {
std::printf("%s\n {\"n_head_kv\": %lld, \"head_dim\": %lld, \"page_size\": %lld, \"format\": \"%s\", "
"\"pages\": %lld, \"bytes\": %llu}",
first ? "" : ",", (long long) sh.kv, (long long) sh.dim, (long long) sh.page, f.name,
(long long) p, (unsigned long long) kv_pool_bytes(s, p, f.hybrid, f.int8));
first = false;
}
}
}
std::printf("\n]\n");
return 0;
}
@@ -1,62 +0,0 @@
#!/usr/bin/env python3
"""Offline fixture generator (Python is allowed for offline tooling, AGENTS.md): builds the Original's
`strata-plan` CLI (header-only) and the `kv_pool_bytes` harness, runs a table of configurations and writes
memory_plan_golden.json. Usage: gen_plan_golden.py <out.json> <engine/strata dir> <work dir>."""
import json, subprocess, sys, os, re
out, strata, work = sys.argv[1:4]
cxx = os.environ.get("CXX", "clang++")
here = os.path.dirname(os.path.abspath(__file__))
flags = ["-std=c++17", "-O2", "-I" + os.path.join(strata, "include"), "-I" + work]
subprocess.check_call([cxx, *flags, os.path.join(strata, "src/plan/plan_main.cpp"), "-o", os.path.join(work, "strata-plan")])
with open(os.path.join(strata, "src/core/layer.cpp")) as f:
src = f.read().split("\n")
start = next(i for i, l in enumerate(src) if l.startswith("uint64_t kv_pool_bytes("))
end = next(i for i in range(start, len(src)) if src[i].startswith("}"))
with open(os.path.join(work, "kv_pool_bytes.inc"), "w") as f:
f.write("\n".join(src[start:end + 1]) + "\n")
subprocess.check_call([cxx, *flags, os.path.join(here, "gen_kv_pool_golden.cpp"), "-o", os.path.join(work, "kvgen")])
kv_pool = json.loads(subprocess.check_output([os.path.join(work, "kvgen")]))
G = 1000 ** 3
GIB = 1024 ** 3
state_default = 36 * (128 * 48 * 128 * 4 + 3 * 10240 * 4)
cases = []
def add(*args): cases.append([str(a) for a in args])
for ctx in (20480, 65536, 131072, 262144, 393216, 524288):
for vram in (12 * G, 16 * G, 24 * G, 32 * G, 32 * GIB, 48 * G):
add("--max-context", ctx, "--vram", vram)
# charter profiles with their state (x2 slots for 2x256K), on 32 GiB with and without resident weights
for (ctx, slots) in ((524288, 1), (524288, 2), (262144, 1), (262144, 2)):
st = state_default * slots
for vram in (16 * G, 24 * G, 32 * GIB):
add("--max-context", ctx, "--vram", vram, "--state", st)
add("--max-context", ctx, "--vram", vram, "--state", st, "--dense", 4 * G, "--embd", 500_000_000, "--workspace", 300_000_000)
# small cards: the planner must refuse
for ctx in (262144, 524288):
for vram in (3 * G, 4 * G, 6 * G, 7 * G):
add("--max-context", ctx, "--vram", vram)
# resident weights larger than the card: derived pool 0 falls back to the default pool
add("--max-context", 4096, "--vram", 5 * G, "--dense", 6 * G)
add("--max-context", 20480) # CLI defaults
add("--pool", 5943000000, "--max-context", 20480)
add("--pool", 3 * G, "--max-context", 100000)
add("--pool", 20 * G, "--max-context", 100000, "--dense", 5 * G, "--embd", G) # --pool still subtracts dense/embd
add("--max-context", 1000, "--vram", 1_000_000) # does not close
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_399) # no room for one slot (default state)
add("--max-context", 1, "--vram", 13056 + 117_669_888 + 1_382_400) # exactly one slot
add("--max-context", 100, "--vram", 10 * G, "--state", 0)
add("--max-context", 100, "--vram", 10 * G, "--workspace", 123456789)
add("--help")
add("--bogus")
add("--max-context")
runs = []
for args in cases:
p = subprocess.run([os.path.join(work, "strata-plan"), *args], capture_output=True, text=True)
runs.append({"args": args, "exit": p.returncode, "stdout": p.stdout, "stderr": p.stderr})
json.dump({"generator": "strata-plan built from engine/strata/src/plan/plan_main.cpp (unmodified) + extracted layer.cpp kv_pool_bytes",
"state_bytes_default": state_default, "cli": runs, "kv_pool": kv_pool}, open(out, "w"), indent=1)
@@ -1,7 +0,0 @@
#!/bin/sh
# Regenerates memory_plan_golden.json from the Original (macOS or Linux, any C++17 compiler + python3).
set -eu
here=$(cd "$(dirname "$0")" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
python3 -I "$here/gen_plan_golden.py" "$here/memory_plan_golden.json" "$here/../../../../engine/strata" "$work"
@@ -1,196 +0,0 @@
// gen_rope_golden.cpp - golden-fixture generator for the Rust rope port (leleka-runtime::rope_scaling).
//
// It links the ORIGINAL host-side code: `include/strata/kernels/rope_scaling.hpp` is included unmodified, and the
// two `build_rope_table` definitions are extracted VERBATIM from `src/kernels/cuda/rope.cu` by `gen_rope_golden.sh`
// into a generated include (`rope_table_original.inc`). Nothing from the Original is re-typed here.
//
// Every double/float is printed as its IEEE bit pattern in hex so the fixture is exact (serde_json's default
// float parser is not guaranteed correctly rounded). Tables are summarised by FNV-1a 64 over the little-endian
// f32 bytes of the whole cos table and of the whole sin table, plus full rows at selected positions.
#include "strata/kernels/rope_scaling.hpp"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
namespace strata::kernels {
// the engine's other definitions live in the .cu next to the extracted functions; only the table builders are needed
void build_rope_table(int n_rot, double theta, int max_pos, float* cos_tab, float* sin_tab);
void build_rope_table(int n_rot, const RopeScaling& sc, int max_pos, float* cos_tab, float* sin_tab);
} // namespace strata::kernels
namespace strata::kernels {
#include "rope_table_original.inc"
} // namespace strata::kernels
using namespace strata::kernels;
static std::string hex64(double d) {
uint64_t u;
std::memcpy(&u, &d, 8);
char b[32];
std::snprintf(b, sizeof b, "0x%016llx", (unsigned long long) u);
return b;
}
static std::string hex32(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
char b[32];
std::snprintf(b, sizeof b, "0x%08x", u);
return b;
}
static uint64_t fnv(const float* p, size_t n) {
uint64_t h = 0xcbf29ce484222325ull;
for (size_t i = 0; i < n; ++i) {
uint32_t u;
std::memcpy(&u, p + i, 4);
for (int k = 0; k < 4; ++k) {
h ^= (uint8_t) (u >> (8 * k));
h *= 0x100000001b3ull;
}
}
return h;
}
struct Case {
const char* name;
const char* desc;
int n_rot;
RopeScaling sc;
bool tables; // build the 524288-position tables (skipped for invalid configs)
};
static RopeScaling mk(RopeScalingType t, double fb, double factor, double fsi, double orig, double ext, double attn,
double bf, double bs) {
RopeScaling s;
s.type = t;
s.freq_base = fb;
s.factor = factor;
s.freq_scale_in = fsi;
s.orig_ctx = orig;
s.ext_factor = ext;
s.attn_factor = attn;
s.beta_fast = bf;
s.beta_slow = bs;
return s;
}
int main() {
using T = RopeScalingType;
const double B = 1e7, O = 262144;
std::vector<Case> cases = {
{"none_default", "default-constructed RopeScaling (today's engine)", 64, RopeScaling{}, true},
{"none_junk_knobs", "type none with every scaling knob set: knobs must be inert", 64,
mk(T::None, B, 4.0, 0.25, 4096, 1.0, 0.5, 20, 2), true},
{"linear_2", "linear factor 2 (512K over 262144)", 64, mk(T::Linear, B, 2.0, 0, O, 0, 1.0, 32, 1), true},
{"linear_1_5", "linear factor 1.5 (393216 over 262144)", 64, mk(T::Linear, B, 1.5, 0, O, 0, 1.0, 32, 1), true},
{"linear_freq_scale_in", "linear with the raw ggml freq_scale 0.25 overriding 1/factor", 64,
mk(T::Linear, B, 2.0, 0.25, O, 0, 1.0, 32, 1), true},
{"linear_attn_factor", "linear with attn_factor 0.9 and no correction: mscale = attn_factor", 64,
mk(T::Linear, B, 2.0, 0, O, 0, 0.9, 32, 1), true},
{"yarn_2", "yarn factor 2 (setup.py default for 512K), ext 1, betas 32/1", 64,
mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1_5", "yarn factor 1.5 (setup.py default for 393216)", 64,
mk(T::YaRN, B, 1.5, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_1", "yarn factor 1 (inside trained range): ramp active, mscale 1", 64,
mk(T::YaRN, B, 1.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_4", "yarn factor 4 (1M context)", 64, mk(T::YaRN, B, 4.0, 0, O, 1.0, 1.0, 32, 1), true},
{"yarn_2_betas", "yarn factor 2 with attn 1.1, betas 16/2", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.1, 16, 2), true},
{"yarn_2_ext_half", "yarn factor 2 with ext_factor 0.5", 64, mk(T::YaRN, B, 2.0, 0, O, 0.5, 1.0, 32, 1), true},
{"yarn_orig_131072", "yarn factor 4 against a 131072 trained context", 64,
mk(T::YaRN, B, 4.0, 0, 131072, 1.0, 1.0, 32, 1), true},
{"yarn_ext0", "yarn type with ext_factor 0: correction off, behaves as linear", 64,
mk(T::YaRN, B, 2.0, 0, O, 0.0, 1.0, 32, 1), true},
{"yarn_n_rot128", "yarn n_rot 128, base 1e6, orig 4096, factor 8", 128,
mk(T::YaRN, 1e6, 8.0, 0, 4096, 1.0, 1.0, 32, 1), true},
{"yarn_n_rot4", "yarn n_rot 4: corr_dims clamps to n_rot-1", 4, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, 1), true},
// invalid (finite) configurations: only the validity message and the scalar resolutions are recorded
{"bad_factor_below_1", "factor 0.5", 64, mk(T::Linear, B, 0.5, 0, O, 0, 1.0, 32, 1), false},
{"bad_freq_base_1", "freq_base 1 (none)", 64, mk(T::None, 1.0, 1.0, 0, O, 0, 1.0, 32, 1), false},
{"bad_orig_ctx_0", "orig_ctx 0", 64, mk(T::YaRN, B, 2.0, 0, 0.0, 1.0, 1.0, 32, 1), false},
{"bad_ext_negative", "ext_factor -1", 64, mk(T::YaRN, B, 2.0, 0, O, -1.0, 1.0, 32, 1), false},
{"bad_attn_0", "attn_factor 0", 64, mk(T::Linear, B, 2.0, 0, O, 0, 0.0, 32, 1), false},
{"bad_beta_fast_0", "beta_fast 0", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 0, 1), false},
{"bad_beta_slow_neg", "beta_slow -1", 64, mk(T::YaRN, B, 2.0, 0, O, 1.0, 1.0, 32, -1), false},
{"bad_freq_scale_in_neg", "freq_scale_in -0.1", 64, mk(T::Linear, B, 2.0, -0.1, O, 0, 1.0, 32, 1), false},
{"bad_mscale_negative", "freq_scale_in 1e6 with ext 1: the log term drives mscale negative", 64,
mk(T::YaRN, B, 2.0, 1e6, O, 1.0, 1.0, 32, 1), false},
};
const int NMAX = 524288;
const int NS[2] = {262144, 524288};
const int SAMPLE_POS[] = {0, 1, 2, 4095, 4096, 65535, 131071, 262143, 262144, 524287};
const int AN_POS[] = {1, 4096, 262143, 524287};
std::printf("{\n \"generator\": \"gen_rope_golden.cpp over rope_scaling.hpp + rope.cu build_rope_table (verbatim)\",\n");
std::printf(" \"cases\": [\n");
std::vector<float> cs, sn;
for (size_t ci = 0; ci < cases.size(); ++ci) {
const Case& c = cases[ci];
const RopeScaling& s = c.sc;
const int half = c.n_rot / 2;
std::printf(" {\n \"name\": \"%s\", \"desc\": \"%s\", \"n_rot\": %d,\n", c.name, c.desc, c.n_rot);
const char* tn = s.type == T::YaRN ? "yarn" : s.type == T::Linear ? "linear" : "none";
std::printf(" \"type\": \"%s\",\n", tn);
std::printf(" \"freq_base\": \"%s\", \"factor\": \"%s\", \"freq_scale_in\": \"%s\", \"orig_ctx\": \"%s\",\n",
hex64(s.freq_base).c_str(), hex64(s.factor).c_str(), hex64(s.freq_scale_in).c_str(),
hex64(s.orig_ctx).c_str());
std::printf(" \"ext_factor\": \"%s\", \"attn_factor\": \"%s\", \"beta_fast\": \"%s\", \"beta_slow\": \"%s\",\n",
hex64(s.ext_factor).c_str(), hex64(s.attn_factor).c_str(), hex64(s.beta_fast).c_str(),
hex64(s.beta_slow).c_str());
const char* bad = rope_scaling_invalid(s);
if (bad) std::printf(" \"invalid\": \"%s\",\n", bad);
else std::printf(" \"invalid\": null,\n");
std::printf(" \"freq_scale\": \"%s\", \"mscale\": \"%s\",\n", hex64(s.freq_scale()).c_str(),
hex64(s.mscale()).c_str());
double cd[2];
s.corr_dims(c.n_rot, cd);
std::printf(" \"corr_dims\": [\"%s\", \"%s\"],\n", hex64(cd[0]).c_str(), hex64(cd[1]).c_str());
const RopeKernelArgs a = s.kernel_args(c.n_rot);
std::printf(" \"kernel_args\": {\"freq_scale\": \"%s\", \"corr_low\": \"%s\", \"corr_high\": \"%s\", "
"\"ext_factor\": \"%s\", \"attn_factor\": \"%s\"},\n",
hex32(a.freq_scale).c_str(), hex32(a.corr_low).c_str(), hex32(a.corr_high).c_str(),
hex32(a.ext_factor).c_str(), hex32(a.attn_factor).c_str());
// analytic path (float32 rope_scaled_angle): theta_extrap = (float)(p * inv_i)
std::printf(" \"analytic\": [");
bool first = true;
const int pairs[] = {0, 1, 7, 15, 16, 31};
for (int pair : pairs) {
if (pair >= half) continue;
for (int p : AN_POS) {
const double inv = std::pow(s.freq_base, -2.0 * (double) pair / (double) c.n_rot);
const float te = (float) ((double) p * inv);
float co, si;
rope_scaled_angle(te, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.attn_factor, pair, co, si);
std::printf("%s\n {\"theta_extrap\": \"%s\", \"pair\": %d, \"cos\": \"%s\", \"sin\": \"%s\"}",
first ? "" : ",", hex32(te).c_str(), pair, hex32(co).c_str(), hex32(si).c_str());
first = false;
}
}
std::printf("\n ]");
if (c.tables) {
cs.assign((size_t) NMAX * half, 0.f);
sn.assign((size_t) NMAX * half, 0.f);
build_rope_table(c.n_rot, s, NMAX, cs.data(), sn.data());
std::printf(",\n \"tables\": [");
for (int k = 0; k < 2; ++k)
std::printf("%s\n {\"n_pos\": %d, \"cos_fnv1a64\": \"0x%016llx\", \"sin_fnv1a64\": \"0x%016llx\"}",
k ? "," : "", NS[k], (unsigned long long) fnv(cs.data(), (size_t) NS[k] * half),
(unsigned long long) fnv(sn.data(), (size_t) NS[k] * half));
std::printf("\n ],\n \"rows\": [");
for (size_t k = 0; k < sizeof SAMPLE_POS / sizeof *SAMPLE_POS; ++k) {
const int p = SAMPLE_POS[k];
std::printf("%s\n {\"pos\": %d, \"cos\": [", k ? "," : "", p);
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(cs[(size_t) p * half + i]).c_str());
std::printf("], \"sin\": [");
for (int i = 0; i < half; ++i) std::printf("%s\"%s\"", i ? "," : "", hex32(sn[(size_t) p * half + i]).c_str());
std::printf("]}");
}
std::printf("\n ]");
}
std::printf("\n }%s\n", ci + 1 < cases.size() ? "," : "");
}
std::printf(" ]\n}\n");
return 0;
}
@@ -1,19 +0,0 @@
#!/bin/sh
# Regenerates rope_golden.json from the Original's host code (macOS or Linux, any C++17 compiler).
# usage: gen_rope_golden.sh [extra compiler flags]
# The committed fixture is built with -O2 -ffp-contract=off (Rust never fuses multiply-adds) and
# -fno-builtin-sinf/-cosf: Apple clang otherwise merges a sinf+cosf pair into __sincosf_stret, whose sinf
# differs from a separate sinf call by 1-2 ULP, and Rust (like the CUDA device code) calls them separately.
# Only the float32 analytic path is affected; the float64 tables are identical either way.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
strata="$here/../../../../engine/strata"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
# extract the two build_rope_table definitions from rope.cu verbatim (up to the next anonymous namespace)
awk '/^void build_rope_table\(int n_rot, double theta/ {on=1} on && /^namespace \{/ {exit} on {print}' \
"$strata/src/kernels/cuda/rope.cu" > "$work/rope_table_original.inc"
test -s "$work/rope_table_original.inc"
${CXX:-clang++} -std=c++17 -O2 -ffp-contract=off -fno-builtin-sinf -fno-builtin-cosf "$@" -I"$strata/include" -I"$work" \
"$here/gen_rope_golden.cpp" -o "$work/gen_rope_golden"
"$work/gen_rope_golden" > "$here/rope_golden.json"
@@ -1,7 +0,0 @@
#!/bin/sh
# Syntax-check ported .cu files without nvcc. Superseded by the unified stub set under scripts/cuda-stubs/ (clang's CUDA
# frontend against stub headers; covers every .cu, not only the ones the host shim can execute). The EXECUTING emulation
# (shim/cuda_host_shim.h, run_shim_oracles.sh) is a different tool and stays.
# usage: check_cu_syntax.sh [file.cu ...] (no argument: every crates/cuda-driver/src/*.cu)
here=$(cd "$(dirname "$0")" && pwd)
exec python3 "$here/../../../scripts/cuda-stubs/check-cu.py" "$@"
@@ -1,463 +0,0 @@
// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp
// (sha256 1d18288208debcf1d26021ed8bdfc2633db6dcbd88d899c76d1f628b57838c91). The code between the VERBATIM markers is copied from that file (lines 1170-1228, 1279-1287, 1692-1743, 1806-1853);
// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer
// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <thread>
#include <string>
#include <vector>
using cudaStream_t = int;
using cudaEvent_t = int;
enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 };
constexpr int STAGE = 8, RING_MAX = 512, DQ = 2;
static std::vector<std::string> g_ops;
static void op(const std::string& s) { g_ops.push_back(s); }
static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; }
static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); }
static std::string src_of_host(const void* p) {
const uintptr_t v = (uintptr_t) p;
if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u);
return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u);
}
static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) {
op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src));
return 0;
}
static std::string ev_name(cudaEvent_t e) {
if (e >= 4000) return "ple_copied " + std::to_string(e - 4000);
if (e >= 3000) return "dma " + std::to_string(e - 3000);
return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000));
}
static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; }
static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; }
struct Clock { struct time_point {}; static time_point now() { return {}; } };
static double ms_since(Clock::time_point) { return 0.0; }
struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } };
namespace strata { namespace kernels { namespace cpu {
using ExpertLayout = ExpertLayoutStub;
inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; }
} } }
struct ModelGeom { int64_t n_expert; int64_t n_layers; };
struct Scenario {
const char* name;
int n_layers, n_expert, lb, le, ring, stager_ring;
int64_t T; // rows of the chunk (stream_all needs T >= 1024)
std::vector<std::vector<int32_t>> orders; // per layer in [lb, le): routed experts, ascending
int resident_mod, resident_rem; // cache-resident when e % mod == rem (mod 0: none)
bool cache_present;
int pinned_mod, transient_mod; // pinned: e % pinned_mod == 0; transient: (e+l) % transient_mod == 0
int chunks;
};
static const Scenario* g_sc = nullptr;
struct Src {
bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e % g_sc->pinned_mod == 0; }
bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) % g_sc->transient_mod == 0; }
const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); }
};
struct Stager {
struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; };
int kRing = 16;
void start(std::vector<Job>&& js) {
if (js.empty()) return; // Stager::start
std::string d = "H stager_start";
for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U";
op(d + " n=" + std::to_string(js.size()));
}
const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j % kRing) * 0x1000u); }
void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j % kRing, copy); }
void finish() { op("H stager_finish"); }
};
struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } };
struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; };
constexpr int64_t N = 2560;
struct PT { void mark(int, cudaStream_t) {} };
enum { kPfWaitCopy = 0, kPfDequant = 1 };
inline int64_t stream_all_min() { return 1024; }
// ---- PLE read-ahead stubs
#include <future>
static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); }
static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) {
(void) dst;
op("K upload ple_emb " + ple_buf_of(src, 0x60000000u));
return 0;
}
static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; }
template <class F> static std::future<bool> shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); }
struct PleTable {
bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; }
};
struct PleState { PleTable* table; };
struct SessionStub { struct { PleTable* table; } ple; };
struct Impl {
Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr;
int ring = STAGE; cudaStream_t cs = 2, copy = 1;
std::unique_ptr<Stager> stager;
uint8_t* stage_dev[RING_MAX] = {};
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
bool stage_live[RING_MAX] = {};
float* ple_emb = nullptr;
float* ple_emb_host[2] = {};
cudaEvent_t ple_copied[2] = {};
std::vector<uint32_t> ple_rows[2];
int64_t T = 0;
};
static void run_scenario(const Scenario& sc) {
g_sc = &sc;
g_ops.clear();
Impl m;
ModelGeom geom{sc.n_expert, sc.n_layers};
const ModelGeom& g = geom;
Src src_obj; Cache cache_obj;
m.src = &src_obj;
m.g = &geom;
m.ring = sc.ring;
m.stager.reset(new Stager());
m.stager->kRing = sc.stager_ring;
for (int i = 0; i < RING_MAX; ++i) {
m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u);
m.copied[i] = 1000 + i; m.used[i] = 2000 + i;
}
std::vector<int32_t> host_res_table((size_t) sc.n_layers * sc.n_expert, -1);
if (sc.cache_present) {
int next_slot = 0;
for (int l = 0; l < sc.n_layers; ++l)
for (int e = 0; e < sc.n_expert; ++e)
if (sc.resident_mod != 0 && e % sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++;
m.host_res = host_res_table.data();
m.cache = &cache_obj;
}
Stats stats_;
PT pt;
cudaStream_t cs = m.cs;
const int64_t LB = sc.lb, LE = sc.le, T = sc.T;
std::string err;
for (int chunk = 0; chunk < sc.chunks; ++chunk) {
op("H chunk " + std::to_string(chunk));
auto chunk_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (sequence, issue_until) ----
const strata::kernels::cpu::ExpertLayout& lay0 = strata::kernels::cpu::expert_layout();
const bool stream_all = m.ring > STAGE && T >= stream_all_min() && m.src != nullptr;
struct StreamEntry { int32_t l, e; const uint8_t* blob; int job; };
std::vector<StreamEntry> seq;
std::vector<size_t> seq_start;
size_t issued = 0, consumed = 0;
if (stream_all) {
seq_start.assign((size_t) g.n_layers + 1, 0);
std::vector<Stager::Job> js;
for (int64_t l = LB; l < LE; ++l) {
seq_start[(size_t) l] = seq.size();
for (int32_t e = 0; e < m.g->n_expert; ++e) {
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
int job = -1;
const uint8_t* b = nullptr;
if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's buffer
job = (int) js.size();
js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
} else {
b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
if (!m.src->pinned(l, e)) {
job = (int) js.size();
js.push_back({b, (size_t) lay0.blob_bytes(l)});
}
}
seq.push_back({(int32_t) l, e, b, job});
}
}
for (int64_t l = LE; l <= g.n_layers; ++l) seq_start[(size_t) l] = seq.size();
m.stager->start(std::move(js));
}
struct StagerDone {
Stager* st;
~StagerDone() { if (st) st->finish(); }
} chunk_stager_done{stream_all ? m.stager.get() : nullptr};
auto issue_until = [&](size_t limit) {
limit = std::min(limit, seq.size());
while (issued < limit) {
const StreamEntry& en = seq[issued];
const int sl = (int) (issued % (size_t) m.ring);
const auto th = Clock::now();
const size_t bytes = (size_t) lay0.blob_bytes(en.l);
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
if (en.job < 0) {
cudaMemcpyAsync(m.stage_dev[sl], en.blob, bytes, cudaMemcpyHostToDevice, m.copy);
++stats_.experts_dma;
} else {
const uint8_t* hb = m.stager->wait(en.job);
cudaMemcpyAsync(m.stage_dev[sl], hb, bytes, cudaMemcpyHostToDevice, m.copy);
m.stager->issued_one(en.job, m.copy);
}
cudaEventRecord(m.copied[sl], m.copy);
m.stage_live[sl] = true;
stats_.ms_experts_host += ms_since(th);
++stats_.experts_streamed;
++issued;
}
};
// ---- end VERBATIM ----
const bool threaded_issue = false;
std::atomic<size_t> a_issued{0}, a_consumed{0};
// ---- VERBATIM prefill.cpp (wait_issued, give_back) ----
// the consumer's side: entry k's copy is on the copy stream (the thread issued it), then k is given back
auto wait_issued = [&](size_t k) {
if (!threaded_issue) return;
while (a_issued.load(std::memory_order_acquire) <= k) std::this_thread::yield();
};
auto give_back = [&](size_t upto) {
if (threaded_issue) a_consumed.store(upto, std::memory_order_release);
else issue_until(upto + (size_t) m.ring);
};
// ---- end VERBATIM ----
if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); }
for (int64_t l = LB; l < LE; ++l) {
const std::vector<int32_t>& order = sc.orders[(size_t) (l - LB)];
op("H layer " + std::to_string(l));
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
// ---- VERBATIM prefill.cpp (staging setup, stage_one) ----
// Stage ahead: the copy stream moves blobs host -> device while the compute stream works.
int stage_next = 0;
std::vector<int> stage_of(order.size(), -1);
// the unpinned ones are copied to pinned buffers by the stager's threads, in this order
std::vector<int> job_of(order.size(), -1);
if (!stream_all) {
std::vector<Stager::Job> js;
for (size_t j = 0; j < order.size(); ++j) {
const int32_t e = order[j];
if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;
if (m.src->pinned(l, e)) continue;
job_of[j] = (int) js.size();
if (m.src->transient(l, e)) { // CS-T: copied by the source
js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});
continue;
}
const uint8_t* b = m.src->blob(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
js.push_back({b, (size_t) lay.blob_bytes(l)});
}
m.stager->start(std::move(js));
}
StagerDone stager_done{stream_all ? nullptr : m.stager.get()};
auto stage_one = [&](size_t j) -> bool {
const int32_t e = order[j];
const bool resident = m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0;
if (resident) return true;
const int sl = stage_next;
stage_next = (stage_next + 1) % STAGE;
const auto th = Clock::now();
const bool pinned = m.src->pinned(l, e); // pinned: never transient
const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }
if (pinned) {
// DMA straight from the page-locked arena: the copy stream only waits for the slot
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
++stats_.experts_dma;
} else {
// copied to a pinned buffer by the stager (waits only if it is behind), then DMA
const uint8_t* hb = m.stager->wait(job_of[j]);
if (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);
cudaMemcpyAsync(m.stage_dev[sl], hb, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);
m.stager->issued_one(job_of[j], m.copy);
}
cudaEventRecord(m.copied[sl], m.copy);
m.stage_live[sl] = true;
stage_of[j] = sl;
stats_.ms_experts_host += ms_since(th);
++stats_.experts_streamed;
return true;
};
// ---- end VERBATIM ----
auto compute = [&](size_t j, const uint8_t*, int slot) -> bool {
op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-")));
if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob
return true;
};
// ---- VERBATIM prefill.cpp (the walks) ----
if (!stream_all) {
size_t staged = 0;
const size_t lookahead = STAGE - 1;
for (size_t j = 0; j < order.size(); ++j) {
while (staged < order.size() && staged <= j + lookahead) {
if (!stage_one(staged)) return false;
++staged;
}
const int32_t e = order[j];
if (stage_of[j] < 0) {
++stats_.experts_resident;
if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
} else {
pt.mark(kPfWaitCopy, cs);
cudaStreamWaitEvent(m.cs, m.copied[stage_of[j]], 0);
if (!compute(j, m.stage_dev[stage_of[j]], stage_of[j])) return false;
}
}
} else {
// the streamed walk: this layer's entries [k, kend) in id order; an entry the routing did not
// pick only gives its slot back
size_t k = seq_start[(size_t) l];
const size_t kend = seq_start[(size_t) l + 1];
auto release_to = [&](int32_t e_stop) {
while (k < kend && seq[k].e < e_stop) {
cudaEventRecord(m.used[k % (size_t) m.ring], m.cs);
consumed = ++k;
give_back(consumed);
}
};
for (size_t j = 0; j < order.size(); ++j) {
const int32_t e = order[j];
release_to(e);
if (k < kend && seq[k].e == e) {
const int sl = (int) (k % (size_t) m.ring);
pt.mark(kPfWaitCopy, cs);
wait_issued(k);
cudaStreamWaitEvent(m.cs, m.copied[sl], 0);
if (!compute(j, m.stage_dev[sl], sl)) return false;
consumed = ++k;
give_back(consumed);
} else {
++stats_.experts_resident;
if (!compute(j, m.cache->device_slot(m.host_res[(size_t) l * m.g->n_expert + e]), -1)) return false;
}
}
release_to(m.g->n_expert);
}
// ---- end VERBATIM ----
op("K combine");
}
return true;
};
if (!chunk_fn()) { std::fprintf(stderr, "scenario %s failed: %s\n", sc.name, err.c_str()); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"p\":{\"n_layers\":%d,\"n_expert\":%d,\"lb\":%d,\"le\":%d,\"ring\":%d,\"stager_ring\":%d,\"rows\":%lld,"
"\"resident_mod\":%d,\"resident_rem\":%d,\"cache_present\":%d,\"pinned_mod\":%d,\"transient_mod\":%d,\"chunks\":%d,\"orders\":[",
sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem,
(int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks);
for (size_t li = 0; li < sc.orders.size(); ++li) {
std::printf("%s[", li ? "," : "");
for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%s%d", k ? "," : "", sc.orders[li][k]);
std::printf("]");
}
std::printf("]},\"stats\":[%lld,%lld,%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; };
static void run_ple_scenario(const PleScenario& sc) {
g_ops.clear();
Impl m;
m.T = sc.T;
PleTable table;
SessionStub ss;
ss.ple.table = &table;
for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); }
m.ple_emb = (float*) 0x70000000u;
Stats stats_;
std::string err;
const int64_t n = sc.n;
const bool ple_on = true, ple_gpu_cache = sc.gpu_cache;
std::string ple_next_err;
std::future<bool> ple_next;
int ple_buf = 0;
auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; };
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
const int64_t T = std::min(m.T, n - c0);
op("H ple_chunk " + std::to_string(c0));
cudaStream_t cs = 2; (void) cs;
auto ple_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ----
if (ple_on) {
const auto tp = Clock::now();
if (ple_gpu_cache) {
if (!ple_gather(c0, 0, err) ||
!ss.ple.table->gather_batch_device(m.ple_rows[0].data(), (size_t) T,
m.ple_emb, m.cs, err)) return false;
} else if (!ple_next.valid()) {
if (!ple_gather(c0, ple_buf, err)) return false;
} else if (!ple_next.get()) {
err = ple_next_err;
return false;
}
if (!ple_gpu_cache) {
cudaMemcpyAsync(m.ple_emb, m.ple_emb_host[ple_buf], (size_t) T * N * 4, cudaMemcpyHostToDevice, m.cs);
cudaEventRecord(m.ple_copied[ple_buf], m.cs);
if (c0 + m.T < n) {
cudaEventSynchronize(m.ple_copied[ple_buf ^ 1]); // the other buffer's upload (a chunk ago) is done
ple_next = shim_async( [&ple_gather, &ple_next_err, c1 = c0 + m.T, b = ple_buf ^ 1] {
return ple_gather(c1, b, ple_next_err);
});
}
ple_buf ^= 1;
}
stats_.ms_ple += ms_since(tp);
}
// ---- end VERBATIM ----
return true;
};
if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
// ---- the GR write fusion decision of one half
namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } }
static bool g_gr_unfused = false;
static bool gr_unfused() { return g_gr_unfused; }
static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) {
g_gr_unfused = unfused;
strata::kernels::cvec().cover = cvec_covers;
const int64_t nl = half == 0 ? l : l + 1;
const bool fuse = !gr_unfused() && nl < LE && !(half == 1 && nl == 1 && ple_on) &&
!(half == 1 && strata::kernels::cvec().covers(l));
return fuse;
}
static std::vector<int32_t> iota_vec(int n, int step = 1, int from = 0) {
std::vector<int32_t> v;
for (int i = from; i < n; i += step) v.push_back(i);
return v;
}
int main() {
std::vector<Scenario> sc;
// fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks
sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024,
{iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2});
sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048,
{iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2});
sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024,
{iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1});
sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096,
{{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2});
sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512,
{iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2});
sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096,
{iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1});
sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100,
{{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1});
std::printf("{\"ring\":[");
for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); }
std::printf("],\n");
std::vector<PleScenario> ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false},
{"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false},
{"ple_exact_multiple", 2048, 1024, false}};
std::printf("\"ple\":[");
for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); }
std::printf("],\n\"fuse\":[");
bool first = true;
for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused)
for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) {
if (l >= le) continue;
std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0));
first = false;
}
std::printf("]}\n");
return 0;
}
@@ -1,321 +0,0 @@
#!/usr/bin/env python3
"""Builds drivers/prefill_ring_trace.cpp by EXTRACTING the expert-stream scheduling code of the Original
engine/strata/src/prefill/prefill.cpp (the sequence builder + issue_until, wait_issued / give_back, the staged
stage_one lambda, and the two per-layer expert walks) verbatim between textual markers, wrapped in a host harness whose
cuda* calls only append to a trace. usage: gen_prefill_ring_trace.py [prefill.cpp] > drivers/prefill_ring_trace.cpp
The trace line format is the golden-fixture format read by original_prefill_schedule.rs."""
import hashlib, os, sys
here = os.path.dirname(os.path.abspath(__file__))
path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, '../../../engine/strata/src/prefill/prefill.cpp')
text = open(path).read()
lines = text.split('\n')
def find(marker, start=0):
for i in range(start, len(lines)):
if marker in lines[i]:
return i
raise SystemExit('marker not found: ' + marker)
def cut(first, last_exclusive, start=0):
a = find(first, start)
b = find(last_exclusive, a + 1)
return '\n'.join(lines[a:b]), a + 1, b
seq_build, a1, b1 = cut('const strata::kernels::cpu::ExpertLayout& lay0', '// D-5: the stream is issued by its own host thread')
consumer, a2, b2 = cut("// the consumer's side:", 'host_setup_ms += ms_since(tsetup);')
staged, a3, b3 = cut('// Stage ahead: the copy stream moves blobs host -> device', "// one expert's products from its blob on the device")
w_first = find('auto compute = [&](size_t j, const uint8_t* blob_dev, int slot) -> bool {')
a4 = find('if (!stream_all) {', w_first)
b4 = find('pt.mark(kPfCombine, cs);', a4)
walks = '\n'.join(lines[a4:b4])
ple_a = find('// ---- the PLE rows of the whole chunk')
ple_first = find('if (ple_on) {', ple_a)
ple_last = find('for (int64_t t = 0; t < T; ++t) { prev[0] = prev[1];', ple_first)
ple_block = '\n'.join(lines[ple_first:ple_last])
assert 'std::async(std::launch::async,' in ple_block
ple_block = ple_block.replace('std::async(std::launch::async,', 'shim_async(') # the one documented edit: deferred, logged
fuse_a = find('const int64_t nl = half == 0 ? l : l + 1;')
fuse_b = find('const core::WeightRef* wnn = nullptr;', fuse_a)
fuse_block = '\n'.join(lines[fuse_a:fuse_b])
digest = hashlib.sha256(text.encode()).hexdigest()
template = r'''// GENERATED by oracle/gen_prefill_ring_trace.py from engine/strata/src/prefill/prefill.cpp
// (sha256 __DIGEST__). The code between the VERBATIM markers is copied from that file (lines __R1__, __R2__, __R3__, __R4__);
// everything else stubs the cuda* calls and records them. Issue is inline (STRATA_PREFILL_ISSUER=0): the threaded issuer
// makes the same copy-stream calls in the same order, gated by the same consumed + ring rule.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <thread>
#include <string>
#include <vector>
using cudaStream_t = int;
using cudaEvent_t = int;
enum { cudaMemcpyHostToDevice = 1, cudaSuccess = 0 };
constexpr int STAGE = 8, RING_MAX = 512, DQ = 2;
static std::vector<std::string> g_ops;
static void op(const std::string& s) { g_ops.push_back(s); }
static const char* sname(cudaStream_t s) { return s == 1 ? "C" : "K"; }
static int slot_of_dev(const void* p) { return (int) (((uintptr_t) p - 0x10000000u) / 0x1000u); }
static std::string src_of_host(const void* p) {
const uintptr_t v = (uintptr_t) p;
if (v >= 0x40000000u) return "stage " + std::to_string((v - 0x40000000u) / 0x1000u);
return "blob " + std::to_string((v - 0x20000000u) / 0x10000u) + " " + std::to_string(((v - 0x20000000u) % 0x10000u) / 0x10u);
}
static int cudaMemcpyAsync(void* dst, const void* src, size_t, int, cudaStream_t s) {
op(std::string(sname(s)) + " h2d " + std::to_string(slot_of_dev(dst)) + " " + src_of_host(src));
return 0;
}
static std::string ev_name(cudaEvent_t e) {
if (e >= 4000) return "ple_copied " + std::to_string(e - 4000);
if (e >= 3000) return "dma " + std::to_string(e - 3000);
return (e >= 2000 ? "used " + std::to_string(e - 2000) : "copied " + std::to_string(e - 1000));
}
static int cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned) { op(std::string(sname(s)) + " wait " + ev_name(e)); return 0; }
static int cudaEventRecord(cudaEvent_t e, cudaStream_t s) { op(std::string(sname(s)) + " record " + ev_name(e)); return 0; }
struct Clock { struct time_point {}; static time_point now() { return {}; } };
static double ms_since(Clock::time_point) { return 0.0; }
struct ExpertLayoutStub { size_t blob_bytes(int64_t) const { return 4096; } };
namespace strata { namespace kernels { namespace cpu {
using ExpertLayout = ExpertLayoutStub;
inline const ExpertLayout& expert_layout() { static ExpertLayout l; return l; }
} } }
struct ModelGeom { int64_t n_expert; int64_t n_layers; };
struct Scenario {
const char* name;
int n_layers, n_expert, lb, le, ring, stager_ring;
int64_t T; // rows of the chunk (stream_all needs T >= 1024)
std::vector<std::vector<int32_t>> orders; // per layer in [lb, le): routed experts, ascending
int resident_mod, resident_rem; // cache-resident when e %% mod == rem (mod 0: none)
bool cache_present;
int pinned_mod, transient_mod; // pinned: e %% pinned_mod == 0; transient: (e+l) %% transient_mod == 0
int chunks;
};
static const Scenario* g_sc = nullptr;
struct Src {
bool pinned(int64_t, int64_t e) const { return g_sc->pinned_mod != 0 && e %% g_sc->pinned_mod == 0; }
bool transient(int64_t l, int64_t e) const { return !pinned(l, e) && g_sc->transient_mod != 0 && (e + l) %% g_sc->transient_mod == 0; }
const uint8_t* blob(int64_t l, int64_t e) const { return (const uint8_t*) (0x20000000u + (uintptr_t) l * 0x10000u + (uintptr_t) e * 0x10u); }
};
struct Stager {
struct Job { const uint8_t* src; size_t bytes; Src* from = nullptr; int32_t l = 0, e = 0; };
int kRing = 16;
void start(std::vector<Job>&& js) {
if (js.empty()) return; // Stager::start
std::string d = "H stager_start";
for (auto& j : js) d += j.from ? " T" + std::to_string(j.l) + "." + std::to_string(j.e) : " U";
op(d + " n=" + std::to_string(js.size()));
}
const uint8_t* wait(int j) { op("H stager_wait " + std::to_string(j)); return (const uint8_t*) (0x40000000u + (uintptr_t) (j %% kRing) * 0x1000u); }
void issued_one(int j, cudaStream_t copy) { cudaEventRecord(3000 + j %% kRing, copy); }
void finish() { op("H stager_finish"); }
};
struct Cache { const uint8_t* device_slot(int s) const { return (const uint8_t*) (0x50000000u + (uintptr_t) s * 0x1000u); } };
struct Stats { int64_t experts_dma = 0, experts_streamed = 0, experts_resident = 0; double ms_experts_host = 0, ms_ple = 0; };
constexpr int64_t N = 2560;
struct PT { void mark(int, cudaStream_t) {} };
enum { kPfWaitCopy = 0, kPfDequant = 1 };
inline int64_t stream_all_min() { return 1024; }
// ---- PLE read-ahead stubs
#include <future>
static std::string ple_buf_of(const void* p, uintptr_t base) { return std::to_string(((uintptr_t) p - base) / 0x1000u); }
static int cudaMemcpyAsync(float* dst, const float* src, size_t, int, cudaStream_t) {
(void) dst;
op("K upload ple_emb " + ple_buf_of(src, 0x60000000u));
return 0;
}
static int cudaEventSynchronize(cudaEvent_t e) { op("H sync ple_copied " + std::to_string(e - 4000)); return 0; }
template <class F> static std::future<bool> shim_async(F f) { op("H ple_async"); return std::async(std::launch::deferred, f); }
struct PleTable {
bool gather_batch_device(const uint32_t*, size_t, float*, cudaStream_t, std::string&) { op("K ple_gather_device"); return true; }
};
struct PleState { PleTable* table; };
struct SessionStub { struct { PleTable* table; } ple; };
struct Impl {
Src* src = nullptr; const Cache* cache = nullptr; const int32_t* host_res = nullptr; const ModelGeom* g = nullptr;
int ring = STAGE; cudaStream_t cs = 2, copy = 1;
std::unique_ptr<Stager> stager;
uint8_t* stage_dev[RING_MAX] = {};
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
bool stage_live[RING_MAX] = {};
float* ple_emb = nullptr;
float* ple_emb_host[2] = {};
cudaEvent_t ple_copied[2] = {};
std::vector<uint32_t> ple_rows[2];
int64_t T = 0;
};
static void run_scenario(const Scenario& sc) {
g_sc = &sc;
g_ops.clear();
Impl m;
ModelGeom geom{sc.n_expert, sc.n_layers};
const ModelGeom& g = geom;
Src src_obj; Cache cache_obj;
m.src = &src_obj;
m.g = &geom;
m.ring = sc.ring;
m.stager.reset(new Stager());
m.stager->kRing = sc.stager_ring;
for (int i = 0; i < RING_MAX; ++i) {
m.stage_dev[i] = (uint8_t*) (0x10000000u + (uintptr_t) i * 0x1000u);
m.copied[i] = 1000 + i; m.used[i] = 2000 + i;
}
std::vector<int32_t> host_res_table((size_t) sc.n_layers * sc.n_expert, -1);
if (sc.cache_present) {
int next_slot = 0;
for (int l = 0; l < sc.n_layers; ++l)
for (int e = 0; e < sc.n_expert; ++e)
if (sc.resident_mod != 0 && e %% sc.resident_mod == sc.resident_rem) host_res_table[(size_t) l * sc.n_expert + e] = next_slot++;
m.host_res = host_res_table.data();
m.cache = &cache_obj;
}
Stats stats_;
PT pt;
cudaStream_t cs = m.cs;
const int64_t LB = sc.lb, LE = sc.le, T = sc.T;
std::string err;
for (int chunk = 0; chunk < sc.chunks; ++chunk) {
op("H chunk " + std::to_string(chunk));
auto chunk_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (sequence, issue_until) ----
__SEQ_BUILD__
// ---- end VERBATIM ----
const bool threaded_issue = false;
std::atomic<size_t> a_issued{0}, a_consumed{0};
// ---- VERBATIM prefill.cpp (wait_issued, give_back) ----
__CONSUMER__
// ---- end VERBATIM ----
if (stream_all) issue_until((size_t) m.ring); // prefill.cpp: else if (stream_all) { issue_until((size_t) m.ring); }
for (int64_t l = LB; l < LE; ++l) {
const std::vector<int32_t>& order = sc.orders[(size_t) (l - LB)];
op("H layer " + std::to_string(l));
const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
// ---- VERBATIM prefill.cpp (staging setup, stage_one) ----
__STAGED__
// ---- end VERBATIM ----
auto compute = [&](size_t j, const uint8_t*, int slot) -> bool {
op("K compute " + std::to_string(order[j]) + " " + (slot >= 0 ? std::to_string(slot) : std::string("-")));
if (slot >= 0) cudaEventRecord(m.used[slot], m.cs); // prefill.cpp: after the gather / dequant read of the blob
return true;
};
// ---- VERBATIM prefill.cpp (the walks) ----
__WALKS__
// ---- end VERBATIM ----
op("K combine");
}
return true;
};
if (!chunk_fn()) { std::fprintf(stderr, "scenario %%s failed: %%s\n", sc.name, err.c_str()); std::exit(2); }
}
std::printf("{\"name\":\"%%s\",\"p\":{\"n_layers\":%%d,\"n_expert\":%%d,\"lb\":%%d,\"le\":%%d,\"ring\":%%d,\"stager_ring\":%%d,\"rows\":%%lld,"
"\"resident_mod\":%%d,\"resident_rem\":%%d,\"cache_present\":%%d,\"pinned_mod\":%%d,\"transient_mod\":%%d,\"chunks\":%%d,\"orders\":[",
sc.name, sc.n_layers, sc.n_expert, sc.lb, sc.le, sc.ring, sc.stager_ring, (long long) T, sc.resident_mod, sc.resident_rem,
(int) sc.cache_present, sc.pinned_mod, sc.transient_mod, sc.chunks);
for (size_t li = 0; li < sc.orders.size(); ++li) {
std::printf("%%s[", li ? "," : "");
for (size_t k = 0; k < sc.orders[li].size(); ++k) std::printf("%%s%%d", k ? "," : "", sc.orders[li][k]);
std::printf("]");
}
std::printf("]},\"stats\":[%%lld,%%lld,%%lld],\"ops\":[", (long long) stats_.experts_dma, (long long) stats_.experts_streamed, (long long) stats_.experts_resident);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%%s\"%%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
struct PleScenario { const char* name; int64_t n, T; bool gpu_cache; };
static void run_ple_scenario(const PleScenario& sc) {
g_ops.clear();
Impl m;
m.T = sc.T;
PleTable table;
SessionStub ss;
ss.ple.table = &table;
for (int b = 0; b < 2; ++b) { m.ple_emb_host[b] = (float*) (0x60000000u + (uintptr_t) b * 0x1000u); m.ple_copied[b] = 4000 + b; m.ple_rows[b].assign(4, 0); }
m.ple_emb = (float*) 0x70000000u;
Stats stats_;
std::string err;
const int64_t n = sc.n;
const bool ple_on = true, ple_gpu_cache = sc.gpu_cache;
std::string ple_next_err;
std::future<bool> ple_next;
int ple_buf = 0;
auto ple_gather = [&](int64_t c0, int buf, std::string&) -> bool { op("H ple_gather " + std::to_string(c0) + " " + std::to_string(buf)); return true; };
for (int64_t c0 = 0; c0 < n; c0 += m.T) {
const int64_t T = std::min(m.T, n - c0);
op("H ple_chunk " + std::to_string(c0));
cudaStream_t cs = 2; (void) cs;
auto ple_fn = [&]() -> bool {
// ---- VERBATIM prefill.cpp (the PLE row read-ahead) ----
__PLE__
// ---- end VERBATIM ----
return true;
};
if (!ple_fn()) { std::fprintf(stderr, "ple scenario failed\n"); std::exit(2); }
}
std::printf("{\"name\":\"%s\",\"ple\":[%lld,%lld,%d],\"ops\":[", sc.name, (long long) sc.n, (long long) sc.T, (int) sc.gpu_cache);
for (size_t i = 0; i < g_ops.size(); ++i) std::printf("%s\"%s\"", i ? "," : "", g_ops[i].c_str());
std::printf("]}");
}
// ---- the GR write fusion decision of one half
namespace strata { namespace kernels { struct CvecStub { bool cover; bool covers(int64_t) const { return cover; } }; inline CvecStub& cvec() { static CvecStub c; return c; } } }
static bool g_gr_unfused = false;
static bool gr_unfused() { return g_gr_unfused; }
static bool fuse_of(int64_t l, int half, int64_t LE, bool ple_on, bool unfused, bool cvec_covers) {
g_gr_unfused = unfused;
strata::kernels::cvec().cover = cvec_covers;
__FUSE__
return fuse;
}
static std::vector<int32_t> iota_vec(int n, int step = 1, int from = 0) {
std::vector<int32_t> v;
for (int i = from; i < n; i += step) v.push_back(i);
return v;
}
int main() {
std::vector<Scenario> sc;
// fields: name, n_layers, n_expert, lb, le, ring, stager_ring, T, orders, resident_mod, resident_rem, cache_present, pinned_mod, transient_mod, chunks
sc.push_back({"stream_basic", 6, 24, 1, 4, 16, 16, 1024,
{iota_vec(24, 2), iota_vec(24, 3, 1), {0, 1, 2, 5, 23}}, 5, 0, true, 3, 4, 2});
sc.push_back({"stream_ring_wrap", 4, 40, 0, 3, 16, 16, 2048,
{iota_vec(40), iota_vec(40), iota_vec(40, 7)}, 0, 0, true, 2, 0, 2});
sc.push_back({"stream_no_cache_all_pinned", 3, 20, 0, 3, 16, 16, 1024,
{iota_vec(20), iota_vec(20, 2), {19}}, 0, 0, false, 1, 0, 1});
sc.push_back({"stream_sparse_release", 5, 40, 1, 4, 16, 4, 4096,
{{39}, {0}, {5, 6, 7, 30}}, 0, 0, true, 5, 3, 2});
sc.push_back({"staged_under_threshold", 4, 32, 0, 3, 384, 16, 512,
{iota_vec(32), iota_vec(32, 3), {2, 4}}, 4, 1, true, 3, 5, 2});
sc.push_back({"staged_ring8", 3, 12, 0, 2, 8, 16, 4096,
{iota_vec(12), iota_vec(12, 2)}, 0, 0, false, 2, 3, 1});
sc.push_back({"staged_few_experts", 3, 10, 0, 2, 16, 16, 100,
{{1, 3, 4}, {9}}, 3, 0, true, 0, 0, 1});
std::printf("{\"ring\":[");
for (size_t i = 0; i < sc.size(); ++i) { if (i) std::printf(",\n"); run_scenario(sc[i]); }
std::printf("],\n");
std::vector<PleScenario> ples = {{"ple_two_chunks_gather", 2000, 1024, false}, {"ple_single_chunk", 100, 256, false},
{"ple_gpu_cache", 3000, 1024, true}, {"ple_four_chunks", 4096, 1024, false},
{"ple_exact_multiple", 2048, 1024, false}};
std::printf("\"ple\":[");
for (size_t i = 0; i < ples.size(); ++i) { if (i) std::printf(",\n"); run_ple_scenario(ples[i]); }
std::printf("],\n\"fuse\":[");
bool first = true;
for (int le : {48, 16}) for (int ple_on = 0; ple_on < 2; ++ple_on) for (int unfused = 0; unfused < 2; ++unfused)
for (int cv = 0; cv < 2; ++cv) for (int l : {0, 1, 2, 14, 15, 46, 47}) for (int half = 0; half < 2; ++half) {
if (l >= le) continue;
std::printf("%s[%d,%d,%d,%d,%d,%d,%d]", first ? "" : ",", le, ple_on, unfused, cv, l, half, (int) fuse_of(l, half, le, ple_on != 0, unfused != 0, cv != 0));
first = false;
}
std::printf("]}\n");
return 0;
}
'''
out = (template.replace('__DIGEST__', digest)
.replace('__R1__', f'{a1}-{b1}').replace('__R2__', f'{a2}-{b2}').replace('__R3__', f'{a3}-{b3}').replace('__R4__', f'{a4+1}-{b4}')
.replace('__SEQ_BUILD__', seq_build).replace('__CONSUMER__', consumer).replace('__STAGED__', staged).replace('__WALKS__', walks).replace('__PLE__', ple_block).replace('__FUSE__', fuse_block))
out = out.replace('%%', '%')
sys.stdout.write(out)
@@ -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;
@@ -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
+1 -1
View File
@@ -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.
@@ -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<TD, SUB_DOWN>`, `engine/strata/.../iq_kernels.cu:2130`), formats 20 and 42.
//! (`native_down_multi_kernel<TD, SUB_DOWN>`, `Strata 41cf05a0, .../iq_kernels.cu:2130`), formats 20 and 42.
//!
//! `sm120_down_sub16.cu` computes the same floats as `window_moe_down_<T>` 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
@@ -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
@@ -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
@@ -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.
@@ -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
@@ -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`),
@@ -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`.
//!
+6 -6
View File
@@ -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<String> {
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<String> {
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()
+1 -1
View File
@@ -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"),
+2 -1
View File
@@ -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}"
+4 -4
View File
@@ -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] = [
@@ -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"
@@ -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 <cstdio>
#include <cstdint>
#include <sstream>
#include <string>
#include <vector>
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<class T> std::string arr(const std::vector<T>& 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<ConversationImageKey>& 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<size_t> 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<size_t> 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<uint64_t> 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<std::string> 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<uint64_t> 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<uint64_t>(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<int32_t> ids;
std::vector<ConversationImageKey> imgs;
std::vector<std::vector<int32_t>> checkpoints;
std::vector<std::vector<ConversationImageKey>> cp_imgs;
size_t gdn = 0;
bool cvec = true;
};
SavedConversation build(const Spec& s) {
SavedConversation img;
img.live.ids = std::vector<int32_t>(s.ids.begin(), s.ids.end());
img.live.imgs = std::vector<ConversationImageKey>(s.imgs.begin(), s.imgs.end());
img.live.gdn = std::vector<uint8_t>(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<int32_t>(s.checkpoints[i].begin(), s.checkpoints[i].end());
c.imgs = std::vector<ConversationImageKey>(s.cp_imgs[i].begin(), s.cp_imgs[i].end());
c.gdn = std::vector<uint8_t>(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<std::vector<int32_t>> roots;
explicit World(Rng& rng) {
for (int r = 0; r < 3; ++r) {
std::vector<int32_t> 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<int32_t> extend(Rng& rng, const std::vector<int32_t>& 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<int32_t> 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<ConversationImageKey> 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<int32_t>(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<ConversationKv> layers;
const size_t n = 1 + rng.below(3);
layers.reserve(n);
std::vector<size_t> 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;
}
@@ -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 <algorithm>
#include <cstdio>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
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<class T> std::string arr(const std::vector<T>& 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<int32_t>& 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<ImgKey>& 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<int32_t>& ids;
const std::vector<ConversationImageKey>& images;
const std::vector<ConversationCheckpoint>& 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<int32_t> live;
std::vector<ImgKey> live_imgs;
bool live_ok = false;
std::vector<ConvCheckpoint> checks;
uint64_t check_clock = 0;
bool cvec_cached = true;
ConversationCache conversations;
int64_t pp_next_check = 0;
std::optional<uint64_t> 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<int32_t>(v.ids.begin(), v.ids.end());
s.live.imgs = std::vector<ImgKey>(v.images.begin(), v.images.end());
s.live.gdn = std::vector<uint8_t>(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<ImgKey> imgs_below(const std::vector<ImgKey>& all, int64_t L) {
std::vector<ImgKey> 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<int32_t>& cur, const std::vector<ImgKey>& 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<uint8_t>(kPayload, 2);
c.used = ++check_clock;
checks.push_back(std::move(c));
while ((int) checks.size() > o.prompt_cache) {
std::vector<uint64_t> 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<int32_t> ids;
std::vector<ImgKey> 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<int32_t> 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>((uint64_t) r.available);
S.validate_fails = r.validate_fails;
const std::vector<int32_t>& ids = r.ids;
const std::vector<ImgKey>& req_imgs = r.imgs;
const int64_t n = (int64_t) ids.size();
auto starts_with = [&](const std::vector<int32_t>& pre, const std::vector<ImgKey>& 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<SavedConversation> 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<ConversationKv>{}, 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<int32_t> 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<int32_t> 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<int32_t> v; for (int i = 0; i < n; ++i) v.push_back(base + i); return v; };
auto cat = [](std::vector<int32_t> a, const std::vector<int32_t>& b) { a.insert(a.end(), b.begin(), b.end()); return a; };
std::vector<int32_t> 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<int32_t> 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<int32_t> 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<std::vector<int32_t>> 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<int32_t> 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);
}
@@ -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 <array>
#include <cstdio>
#include <cstring>
#include <deque>
#include <string>
#include <vector>
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<uint8_t>& 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<uint8_t> 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<std::vector<uint8_t>> blocks;
template<class T> void alloc(T*& p, size_t n) {
if (!n) return;
blocks.emplace_back(n, 0);
p = reinterpret_cast<T*>(blocks.back().data());
}
};
struct Fixture {
ModelGeometry g;
QsaState state;
Storage store;
std::array<void*, 5> sources{};
std::array<size_t, 5> 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<uint8_t*>(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<int64_t, 18>{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<int, 5>{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<int, 5>{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<int32_t> ids(65);
for (size_t i = 0; i < ids.size(); ++i) ids[i] = (int32_t) i + 1;
std::vector<ConversationImageKey> images;
std::vector<ConversationCheckpoint> checkpoints;
auto fill = [&](uint8_t salt) {
main.fill(salt); draft.fill(salt);
for (const auto& [p, n] : std::vector<std::pair<void*, size_t>>{{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);
}
@@ -1,16 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <cstring>
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;
@@ -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('<e',raw[b*18:b*18+2])[0]
qs=raw[b*18+2:b*18+18]
out.extend(struct.unpack('<I',struct.pack('<f',d*CODE[q&15]))[0] for q in qs)
out.extend(struct.unpack('<I',struct.pack('<f',d*CODE[q>>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('<H',s)+bytes(((15-j)<<4)|j for j in range(16)) for s in scales)
decode.append({'name':name,'row_hex':raw.hex(),'expected_f32_words':words(raw)})
source_paths=['engine/strata/src/kernels/ngram.cpp','engine/strata/src/kernels/ple_oracle_vectors.inc','crates/model-format/src/qwen4exp.rs','engine/strata/src/kernels/cuda/ple.cu','engine/strata/src/kernels/cuda/native_ple_postops.cu']
data={'schema':'stra161-independent-reference-v1','provenance':'Original source and preexisting independent PLE literal vectors, no candidate imports','sources':{p:hashlib.sha256((ROOT/p).read_bytes()).hexdigest() for p in source_paths},'multipliers':MULT,'vocab_sizes':VOCAB,'offsets':OFF,'ple_eos':EOS,'tokenizer_eos':248046,'hash_cases':cases,'raw_u64_wrap_case':{'context':[MASK,MASK-1,MASK-2],'mixed2':mixed([MASK,MASK-1]),'mixed3':mixed([MASK,MASK-1,MASK-2]),'scope':'recurrence arithmetic only; invalid token ids must still refuse before read'},'decode_cases':decode,'row_ranges':[{'row':r,'start':90*r,'end':90*(r+1)} for r in [0,1,320001535]],'invalid_token_ids':[-1,248320,4294967295],'invalid_row_ids':[320001536,(1<<64)-1],'float_qualification':'Pending chosen original upstream operation order; no fitted tolerance or CUDA parity claim'}
# CPU-only source-ordered scalar probes. Host libm identity is explicit; these are
# NOT CUDA expf/rsqrt approximations and cannot qualify installed-driver parity.
import ctypes, platform
libm=ctypes.CDLL(None)
for symbol,argc in [('sqrtf',1),('expf',1),('fmaf',3)]:
f=getattr(libm,symbol);f.restype=ctypes.c_float;f.argtypes=[ctypes.c_float]*argc
def f32(v):return struct.unpack('<f',struct.pack('<f',v))[0]
def word(v):return struct.unpack('<I',struct.pack('<f',v))[0]
def sigmoid(v):return f32(1.0/f32(1.0+libm.expf(f32(-v))))
def gate(s):
s=f32(s);mag=libm.sqrtf(max(abs(s),f32(1e-6)))
sign=float((s>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('<f',struct.pack('<I',v<<16))[0]
def xor_reduce(v):
v=list(v)
for off in [16,8,4,2,1]:v=[f32(v[i]+v[i^off]) for i in range(32)]
return v
fp['projection']=[]
for name,entries in [('activation-rounding',[(0,1.+2**-8),(511,1.+3*2**-8),(512,-0.25),(2559,2.)]),('reduction-order',[(0,16777216.),(1,1.),(512,-16777216.),(2559,1.)])]:
x=[0.]*2560
for i,v in entries:x[i]=f32(v)
partial=[]
for t in range(256):
a=0.
for pair in range(t,1280,256):
a=libm.fmaf(1.,x[2*pair],a);a=libm.fmaf(1.,x[2*pair+1],a)
partial.append(a)
reduced=[xor_reduce(partial[j:j+32])[0] for j in range(0,256,32)]
key=xor_reduce(reduced+[0.]*24)[0]
value=f32(sum(from_bf16(bf16(v)) for v in x))
fp['projection'].append({'name':name,'columns':2560,'weights_default_bf16':0x3f80,'activation_default_word':0,'activation_nonzero':[[i,word(v)] for i,v in entries],'key_mmvf_block256_expected_word':word(key),'value_bf16_activation_double_expected_word':word(value)})
data['float_source_probes']=fp
OUT.write_text(json.dumps(data,indent=2)+'\n')
lines=['// Independent original-source literals frozen before STRA161 candidate.','// Generated offline by stra161_reference/reference.py; imports no candidate.','#![allow(dead_code)]','pub struct HashCase { pub name: &\'static str, pub token: u32, pub prev: [i32; 2], pub rows: [u32; 16] }','pub const HASH_CASES: &[HashCase] = &[']
for c in cases:lines.append(' HashCase { name: '+json.dumps(c['name'])+', token: '+str(c['token'])+', prev: '+str(c['prev_oldest_first'])+', rows: '+str(c['rows'])+' },')
lines+= ['];','pub struct DecodeCase { pub name: &\'static str, pub encoded: [u8; 90], pub expected_words: [u32; 160] }','pub const DECODE_CASES: &[DecodeCase] = &[']
for c in decode:lines.append(' DecodeCase { name: '+json.dumps(c['name'])+', encoded: '+str(list(bytes.fromhex(c['row_hex'])))+', expected_words: '+str(c['expected_f32_words'])+' },')
lines += ['];','pub const RAW_WRAP_CONTEXT: [u64; 3] = '+str(data['raw_u64_wrap_case']['context'])+';','pub const RAW_WRAP_MIXED: [u64; 2] = '+str([data['raw_u64_wrap_case']['mixed2'],data['raw_u64_wrap_case']['mixed3']])+';','// Raw wrap fixture is primitive-only: invalid token IDs must still refuse.','// Gate probes: CPU host C libm only; not installed CUDA proof.','pub const GATE_CASES: &[(u32, u32)] = &[']
for c in fp['gate']:lines.append(f" ({c['input_word']}, {c['expected_word']}),")
lines+= ['];','pub const BF16_ROUND_CASES: &[(u32, u16)] = &[']
for c in fp['bf16_round']:lines.append(f" ({c['input_word']}, {c['expected_bf16']}),")
lines += ['];','pub const RESIDUAL_RIVAL: [u32; 5] = '+str(list(fp['residual_rival'].values()))+';']
rs=OUT.parent.parent/'stra161_reference.rs';rs.write_text('\n'.join(lines)+'\n')
import subprocess
subprocess.run(['rustfmt','--edition','2024',str(rs)],check=True)
print(json.dumps({'frozen_hash_cases':len(cases),'independent_original_cases':19,'json_sha':hashlib.sha256(OUT.read_bytes()).hexdigest(),'rust_sha':hashlib.sha256(rs.read_bytes()).hexdigest(),'gate':fp['gate'],'residual_rival':fp['residual_rival']}))
@@ -1,161 +0,0 @@
// Golden fixtures for control-vector loading: `load_control_vectors` of engine/strata/src/program/generate.cpp,
// included VERBATIM (extracted by gen_cvec_golden.sh with awk) and run on synthetic control-vector GGUF files
// written by this harness. `cvec_upload` (CUDA) is replaced by a recorder; the function is otherwise unmodified.
#include "strata/artifact/gguf_reader.hpp"
#include "strata/core/layout.hpp"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <string>
#include <utility>
#include <vector>
// ---- stand-ins for what the extracted function touches
struct Options {
std::vector<std::pair<std::string, float>> cvec_files;
int cvec_first = -1, cvec_last = -1;
int cvec_mode = 1;
int cvec_single = -1;
};
namespace strata::kernels {
struct Recorded { std::vector<float> 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<float>& dir, const std::vector<float>& 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<float> data; uint32_t type = 0; };
std::string gguf(const std::string& arch, const std::vector<T>& 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<float> vec(int n) { std::vector<float> v(n); for (auto& x : v) x = value(); return v; }
struct Case { std::string name; std::vector<std::pair<std::string, float>> files; std::vector<std::string> 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<std::string> 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<float>(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<Case> cases;
auto mk = [&](const std::string& name, std::vector<std::pair<std::string, float>> files, std::vector<std::string> 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;
}
@@ -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"
@@ -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 <separate|fused> (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 <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
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<float> 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<int8_t> rk((size_t) cells * H * D);
std::vector<uint16_t> 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;
}
@@ -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<uint16_t> rk_s\(/ {skip=1; next} skip && /std::vector<float> 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"
@@ -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 <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
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<uint64_t> blobs;
uint64_t blob_bytes(int64_t layer) const { return blobs[(size_t) layer]; }
};
struct Cache {
std::vector<std::pair<int32_t, int32_t>> 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<uint8_t> 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<uint8_t> owned_ = std::vector<uint8_t>(CAP, 0), layers_present_;
std::vector<int32_t> group_of_ = std::vector<int32_t>(CAP, -1), group_id_;
std::vector<unsigned long long> ptr_;
std::vector<int32_t> 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<std::pair<int32_t, int32_t>>& ranked,
const Primary& primary, std::vector<uint8_t>& claimed, std::vector<std::pair<int32_t, int32_t>>& 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 <class T> void arr(const char* name, const std::vector<T>& 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<Tier> tiers;
std::vector<Primary> 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<uint8_t> claimed((size_t) L * E, 0);
for (auto& v : claimed) v = below(6) == 0;
std::vector<std::pair<int32_t, int32_t>> 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<uint8_t> claimed_in = claimed;
std::vector<std::pair<int32_t, int32_t>> 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<int32_t> 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<int32_t> 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<int32_t>(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<int32_t>(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<float> 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<float> 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");
}
@@ -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<std::pair<int32_t, int32_t>> 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"
@@ -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")
@@ -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 <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <vector>
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;
}
@@ -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"
@@ -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
+1 -1
View File
@@ -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`.
+1 -1
View File
@@ -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,
@@ -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::<Vec<_>>().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<String>,
}
/// 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<String> {
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<Body> {
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<String>, 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<String> = 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::<Vec<_>>()
.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"
);
}
@@ -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`.
+2 -2
View File
@@ -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
+1 -1
View File
@@ -21,7 +21,7 @@ struct Case {
}
fn golden() -> Vec<Case> {
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
+1 -1
View File
@@ -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.
@@ -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.
@@ -80,7 +80,7 @@ fn alt_paths(a: &AltArgs) -> Result<AltPaths, String> {
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()
));
}
+1 -1
View File
@@ -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 |
//! |--------------------|------------------------------|-------------------------------------------------------|
+1 -1
View File
@@ -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,
-15
View File
@@ -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"
-507
View File
@@ -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 <cuda_runtime.h>) 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<true>` 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 <cinttypes>
#include <cstddef>
#include <new>
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 <class T> T pick(std::initializer_list<T> 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<float>& 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<int>& 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<int32_t>& v) { put_ints(std::vector<int>(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<int> window_of(const std::vector<int>& 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<int>(hist.end() - hlen, hist.end());
}
bool all_finite(const std::vector<float>& 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<std::pair<int, float>> set;
};
void emit_chain_case(const char* name, const std::vector<float>& logits, const SparseLogits* sparse,
const SamplerParams& p, int row, const std::vector<int>& hist) {
const int nv = (int) logits.size();
const std::vector<int> 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<float> make_logits(Rng& g, int nv, int mode) {
std::vector<float> 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<int>({0, 1, 2, 5, 20, 20, 40, 63, 64, 65, 200, -3});
p.top_p = g.pick<float>({1.0f, 1.0f, 0.95f, 0.9f, 0.5f, 0.2f, 0.0f});
p.min_p = g.pick<float>({0.0f, 0.0f, 0.01f, 0.1f, 0.5f, 1.0f});
p.temperature = g.pick<float>({0.3f, 0.7f, 1.0f, 1.0f, 1.5f, 2.0f});
if (allow_greedy && g.below(6) == 0) p.temperature = g.pick<float>({0.0f, -1.0f});
p.greedy = allow_greedy && g.below(12) == 0;
p.min_keep = g.pick<int>({1, 1, 1, 2, 3});
p.penalty_last_n = g.pick<int>({0, 0, 4, 16, 64, 5000, -2});
p.penalty_repeat = g.pick<float>({1.0f, 1.1f, 1.5f, 2.0f, 0.8f});
p.penalty_freq = g.pick<float>({0.0f, 0.25f, 0.5f});
p.penalty_present = g.pick<float>({0.0f, 0.5f, 1.5f});
p.seed = g.pick<uint64_t>({0ull, 1ull, 42ull, 123456789ull, 0xFFFFFFFFull, 0x1FFFFFFFFull, 0xDEADBEEFCAFEF00Dull,
~0ull});
p.counter = g.pick<uint64_t>({0ull, 1ull, 7ull, 1000ull, (1ull << 32) + 7ull, 0xFFFFFFFFull, ~0ull - 3ull});
return p;
}
std::vector<int> make_history(Rng& g, int nv, int pln) {
int hl = g.pick<int>({0, 8, 32, 80});
if (pln > 0 && hl == 0) hl = 8;
std::vector<int> 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<float> l, const std::vector<int>& sub_to_id, const std::vector<int>& id_to_sub,
int id_vocab, const SamplerParams& params, std::vector<int>& 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<char> 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<int>(), 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<true>: 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<double> 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<std::pair<uint64_t, uint64_t>> 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<float>({1.5f, 2.0f, 3.0f});
p.penalty_freq = g.pick<float>({0.0f, 0.5f, 0.25f});
p.penalty_present = g.pick<float>({0.0f, 1.0f, 0.5f});
p.top_k = 8;
p.top_p = g.pick<float>({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<int> 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<float> 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<int>());
}
// 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<float>({-5.0f, -9.5f, 0.0f});
std::vector<float> 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<int> 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<int>({0, 1, 2, 5, 7, 20});
const int T = 1 + g.below(8);
const int h = g.pick<int>({1, 3, 8, 16});
std::vector<int32_t> 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<int32_t> 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<int>({7, 24, 70, 130});
const bool subset = rep % 3 == 1;
const int id_vocab = subset ? nv * 3 : nv;
std::vector<int> 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<int>({0, 3, 8, 12, 20});
auto l = make_logits(g, nv, rep % 9 == 8 ? 1 : 0);
const int cap = g.pick<int>({16, 32});
const int j = g.below(4);
std::vector<int> 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<int> 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;
}
@@ -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")
@@ -1,38 +0,0 @@
// Host-only stand-in for <cuda_runtime.h> 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 <cstdio>
#include <cstdlib>
#include <cstddef>
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 <class T> 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(); }
+1 -1
View File
@@ -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,
+2 -2
View File
@@ -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`).
//!
+1 -1
View File
@@ -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:
+2 -2
View File
@@ -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).
+1 -1
View File
@@ -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
@@ -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.<layer> 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"
@@ -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 <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <utility>
#include <vector>
#include "strata/artifact/gguf_reader.hpp"
struct Options {
std::vector<std::pair<std::string, float>> 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<float> dir, s; int mode = 0, first = 0, last = 0; bool called = false; };
Captured g_up;
bool cvec_upload(const std::vector<float>& dir, const std::vector<float>& 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<uint64_t> dims; std::vector<float> 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<std::pair<std::string, std::string>>& kv, const std::vector<Tensor>& 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<uint64_t> 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<std::pair<std::string, float>> 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<std::pair<std::string, std::string>> good = {{"general.architecture", "controlvector"}, {"controlvector.model_hint", "qwen4exp"}};
std::vector<std::string> 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<float>(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<float>(N, 0.0f)}, Tensor{"direction.2", 0, {(uint64_t) N}, std::vector<float>(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<Case> 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<std::pair<int, float>> 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;
}
@@ -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 <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#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<Step> steps; };
std::vector<Scenario> 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;
}
@@ -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 <unistd.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#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<int32_t> table;
std::vector<int64_t> row_offset; // float offset into img_rows per token, -1 = none
std::vector<ImgKey> imgs;
};
constexpr int64_t kImagePad = 248056;
static Result run(bool geni, const std::vector<int64_t>& 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<ImgKey> req_imgs;
std::vector<int32_t> 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<float> img_rows;
std::vector<const float*> 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<int64_t> 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<Case> 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;
}
+1 -1
View File
@@ -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
@@ -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
+2 -2
View File
@@ -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
+11 -8
View File
@@ -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"
-3
View File
@@ -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.
-27
View File
@@ -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
-27
View File
@@ -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
-1
View File
@@ -1 +0,0 @@
buy_me_a_coffee: strataengine
-26
View File
@@ -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
-101
View File
@@ -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-<model>.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.
-5
View File
@@ -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.
@@ -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.
-45
View File
@@ -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
-30
View File
@@ -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".**
<!--
Read CONTRIBUTING.md first. Lead with the problem and the result, not a file-by-file list.
Placeholders below are not test results: replace them with what you observed, or write "none".
-->
## Problem and result
<!-- What triggered this change. How it behaves before and after. -->
## Related discussion
<!-- The issue URL and the maintainer's agreement on scope, when the change needs one (features, refactors, defaults). Write "none" if not applicable. -->
## Approach
<!-- Why this fix. Compatibility effects. Keep unrelated cleanup out of the PR. -->
## Validation
<!-- Exact commands, the revision and the environment tested, what you saw. Keep the three lists apart. -->
**Passed:**
<!-- command, revision/environment, observed result, log -->
**Failed:**
<!-- command and failure, or "none observed" -->
**Not run:**
<!-- check, why, and what stays unverified (for example CUDA, HIP, SYCL or Metal builds you could not do) -->
## Limits
<!-- Known limitations or remaining work. -->
-218
View File
@@ -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(/<!--[\s\S]*?-->/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,
};

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