Retire the oracles, generators and scripts that only worked against the vendored Strata tree (STRA-406)

The vendored Strata tree engine/strata is removed for good (owner decision 2026-11-23): Leleka never builds or runs it, the vanilla
benchmark builds from its own checkout, the comparison measurements are finished and the CUDA ports are frozen. Everything below
compiled or read that tree, so it cannot run without it and is retired (the tree stays in git history, see third_party/strata/UPSTREAM.md).
Checked-in fixtures, golden JSON, sealed PTX, seal plans and MANIFEST hashes are untouched and keep being replayed by the cargo tests.

Drift guard
- crates/experimental-ref/tests/literal_port.rs: include_str! of the Original .cu files compared with the checked-in experimental ports.

Oracle generators and builders (they compile or extract from the Strata C++/Python sources; their outputs are the checked-in goldens)
- crates/experimental-ref/oracle/gen_{cvec,kv,remote,stream}_golden.{cpp,sh}, gen_seal_additions.py and the cuda_runtime stub they used
- crates/sampler-ref/oracle/build_oracle.sh, gen_fixtures.cpp, gen_sampling_keys.py, stub/ (run_port_host_tests.sh and the fixtures stay)
- crates/serving-policy/oracle/ (build_oracle.sh, gen_{host,cvec,vision}_fixtures.cpp)
- crates/context/tests/rope_plan_golden/gen_* (plan, rope, kv pool)
- crates/engine-core/src/conversation/golden/gen*.{sh,cpp} and stub/
- crates/cuda-driver/oracle/gen_prefill_ring_trace.py and drivers/prefill_ring_trace.cpp (extracted prefill.cpp), check_cu_syntax.sh
- crates/engine-qwen35-cuda/tests/stra161_reference/reference.py (fixtures.json and the Rust constants stay)
- control-plane/tests/golden/gen_goldens.py, scripts/offline/ (Python differentials and golden generators against the Strata Python tools)

Source-compiling CUDA oracles and builders
- scripts/build-cuda-{projection-family,q5,q6,qsa}-oracle.sh with scripts/cuda-{projection-family,q5,q6,qsa}-oracle/ (include the Original .cu; sha256 pins of them)
- scripts/build-original-verify-ptx.sh, scripts/q8/rebuild_quantizer_ptx.sh, scripts/decode-sm120/make_iq_prefix.py (needs engine/strata/include)
- scripts/cuda-stubs/ (check-cu.py and literal_diff.py need the strata headers and the Original sources; the stub headers served only them)
- tools/chain-probe/build.sh, tools/kernel-ab/{cpp,aa.sh,smoke.sh,time_smoke.sh} (the C++ comparator is built from the Strata CPU kernels; verify_manifest.py stays)
- scripts/e2e/codex/speed/verify-hc-down-kernel-microbench-vs-upstream/ (compiles the upstream kernel from the tree)

Engine builds and Python smokes that need the tree
- scripts/build-cpu.sh, scripts/build-static-cuda.sh, scripts/check-keyless-gpu.sh, scripts/test-static-cuda-profile.py (CMake of engine/strata)
- scripts/compare-real-tokenizer.py, scripts/smoke-mtp-pack.py (reads src/core/mtp.cpp and a bench manifest), scripts/prepare-keyless-routing.py and its test
- scripts/smoke-native-pack.py became scripts/native-pack-fixture.py: the synthetic GGUF fixtures the four other smokes import stay, the iq_pack.py oracle comparison goes

Gates and CI
- scripts/check-local.sh: no live Python oracle differentials, no literal_port note, no check-cu, no build-cpu, no retired test scripts
- .github/workflows/linux.yml: the keyless-cuda, static-cuda-package and hosted-cuda-package jobs (they built the engine from the tree) and their dispatch
  inputs, and the two oracle smoke steps; .github/workflows/port.yml: the Python oracle environment and the llama.cpp fetch of port-oracles
  (the sampler host shim still runs)
- limits.json and scripts/check_limits_test.py exclude third_party/strata/ instead of engine/strata/

Documentation and comments: README.md names third_party/strata and the pin; deploy/README.md marks the retired build and smoke commands; comments
in Rust, Python and Markdown that named engine/strata/... now name "Strata 41cf05a0, ..."; the gpu-bringup scratch-copy test no longer copies the
removed include directories. Stale engine/strata paths in sealed .cu, .ptx, seal-plan and MANIFEST files are left as they are (hashes may depend on the bytes).
This commit is contained in:
Pavlo Ratushnyi
2026-11-23 21:19:11 +01:00
parent b4db01728c
commit 056ab3d689
155 changed files with 156 additions and 13452 deletions
-311
View File
@@ -6,23 +6,6 @@ on:
tags: ['v*'] tags: ['v*']
pull_request: pull_request:
workflow_dispatch: 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: permissions:
contents: read contents: read
@@ -41,296 +24,6 @@ jobs:
- name: GPU-hidden fixed PTX assembly - name: GPU-hidden fixed PTX assembly
run: scripts/test-cuda-fixed-ptx.sh 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: linux-static-cli:
permissions: permissions:
contents: read 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 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 - 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 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 - 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 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 - name: Native runtime profile metadata admission
run: python3 scripts/smoke-runtime-profile.py control-plane/target/x86_64-unknown-linux-musl/release/leleka-api 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 - 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: # 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-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-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 # 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. # 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 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: port-oracles:
# CPU oracle differentials: the Rust side against the UNMODIFIED Python tools and the # The sampler host shim over the checked-in oracle fixtures. Optional until it has run green on the hosted runner;
# sampler host shim. Optional until it has run green on the hosted runner; the committed goldens are replayed by # the committed goldens are replayed by port-fast regardless.
# port-fast regardless.
runs-on: ubuntu-latest runs-on: ubuntu-latest
continue-on-error: true continue-on-error: true
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- name: Install build tools - 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 - name: Install pinned Rust
run: scripts/install-pinned-rustup.sh rustup toolchain install 1.99.0 --profile minimal --component rustfmt --component clippy 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) - name: Port oracles (sampler host shim over the checked-in fixtures)
# 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)
env: env:
OFFLINE_ORACLE_PYTHON: ${{ runner.temp }}/oracle-venv/bin/python
STRATA_GGUF_PY: ${{ runner.temp }}/llama.cpp/gguf-py
SKIP_LINUX_TYPECHECK: '1' SKIP_LINUX_TYPECHECK: '1'
run: scripts/check-local.sh --port 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, 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 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. This is a bounded core-path ledger, not a whole-project completion certificate.
## Actionable remaining boundaries ## 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 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. 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 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
upstream `41cf05a0`, see `third_party/strata/UPSTREAM.md`). Serving needs no Python and no CUDA toolkit on the host. `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"). **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`; 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. - `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. - `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). - `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`. - `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 ## 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
@@ -1,5 +1,5 @@
//! The hardware half of `GET /metrics`, in the member names of the Python service's Monitor (`hardware`, //! 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). //! (`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 //! 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 //! 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` //! 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`, //! 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; 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; const EXPERT_BYTES: u64 = 512 * 1_382_400;
// Shapes from pinned upstream mtp-manifest.json, normalized by tools/mtp_rt.py. // 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)] = &[ const REQUIRED: &[(&str, &str, u64, u64)] = &[
("fc_embedding.weight", "q8_0", 2560, 2560), ("fc_embedding.weight", "q8_0", 2560, 2560),
("fc_hidden.weight", "q8_0", 2560, 2560), ("fc_hidden.weight", "q8_0", 2560, 2560),
+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 //! 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`). //! tests in `serve/test_monitor.py`).
//! //!
//! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`, //! It keeps the last [`RETENTION`] requests of the three generation dialects (`/v1/chat/completions`, `/v1/messages`,
+1 -1
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`, //! 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 //! `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 //! the own-page guard. Behaviour is checked against the real Python handlers in
@@ -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 //! `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, //! 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`, //! 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 //! `/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 //! 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. //! 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 //! Deliberate differences, skipped in the comparison: the chat template text, the build/version
+1 -1
View File
@@ -1,4 +1,4 @@
//! The MCP hub against the Python fake server of the Original (`engine/strata/serve/mcp_fake_server.py`, //! The MCP hub against the Python fake server of the Original (`mcp_fake_server.py` next to this test, from Strata 41cf05a0 `serve/`,
//! standard library only; a test double, not part of serving): stdio and Streamable HTTP clients, //! 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. //! 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. //! The tests are skipped (with a message) when `python3` is not installed.
+1 -1
View File
@@ -1,5 +1,5 @@
//! `mtp_fetch` against a local HTTP mirror of a fake checkpoint: the behavioural spec is //! `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::{ use std::{
collections::BTreeMap, collections::BTreeMap,
fs, fs,
+1 -1
View File
@@ -1,6 +1,6 @@
//! RoPE scaling (none / linear / YaRN) and the host-side cos/sin table builder. //! 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`, //! - `include/strata/kernels/rope_scaling.hpp` (`RopeScaling`, `rope_yarn_ramp`, `rope_scaled_angle`,
//! `rope_scaling_invalid`, `RopeKernelArgs`), //! `rope_scaling_invalid`, `RopeKernelArgs`),
//! - `src/kernels/cuda/rope.cu` (`build_rope_table`, both overloads), //! - `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`] //! 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 //! (`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. //! Physical `MtpDrafter::load` arena contract.
//! //!
//! The order below is the literal `Bump::take` order in //! 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. //! prefix and tail views: those views borrow spans of this one allocation.
use super::{DeviceBuffer, Error, Result, Scratch}; use super::{DeviceBuffer, Error, Result, Scratch};
use crate::ffi::BufferHandle; use crate::ffi::BufferHandle;
@@ -2,7 +2,7 @@
//! //!
//! The Original drafts over the rows of the main native head listed in `rt/draft_vocab.bin` (int32 token ids, 106,299 //! 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 //! 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 //! or
//! `--mtp-draft-vocab FILE`. The English subset (`draft_vocab_en.bin`, 40,525 ids) drops 65,774 head rows from the //! `--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 //! 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 //! 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. //! 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` //! 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, //! every indexed tensor 256-aligned, `experts.bin` 512 routed expert blobs,
//! optional `draft_vocab.bin` int32 token ids. //! 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 //! 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` //! `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 //! (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 //! 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. //! over sealed assets.
//! //!
//! ```text //! ```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 //! 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. //! verify window.
//! //!
//! Each switch replaces kernels of the window by upstream's faster kernels that compute every output byte as the //! 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_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 //! `fused_gdn_step_norm` (state update, readout, per-head RMS norm, ssm_norm weight, sigmoid(z) gate; state in
//! place). //! 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 //! `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 //! `native_gdn = true / fused_gdn = false`) is NOT touched and keeps serving the decomposed path and MTP
//! verification. //! verification.
@@ -5,7 +5,7 @@
//! BF16 alpha / beta GEMMs -> `gdn_gates` -> `gdn_conv` (+history) -> `gdn_l2` //! BF16 alpha / beta GEMMs -> `gdn_gates` -> `gdn_conv` (+history) -> `gdn_l2`
//! -> `gdn_rec_cols_pipe` -> `gdn_out_norm` (f32 `y` and half `y16`) -> native //! -> `gdn_rec_cols_pipe` -> `gdn_out_norm` (f32 `y` and half `y16`) -> native
//! Out GEMM from `y16`. The kernels are the verbatim text of //! 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 //! 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 //! 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 //! 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 //! Closed batched MoE router + shared-expert program of the Strata PREFILL path
//! (STRA-169, option B), whole micro-window of `T` rows per drain. //! (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) //! 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 //! -> `route()` = `route_kernel<16>` (warp per token, plain `expf`) -> ids/weights
//! -> shared expert: native gate / up (dequantized GGUF blocks -> FP16 GEMM from `mixed_h`), //! -> 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` //! 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 //! 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`. //! double buffer, the hyper-connection write fusion rule, the layer-split hand-off double buffer and `ring_slots`.
//! //!
@@ -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 //! 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`). //! 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`. //! * [`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 //! 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::{ use leleka_experimental_ref::{
fwht, kv_q8, 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. //! `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 //! 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` //! 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`. //! replays cases produced by the unmodified Python `Service.run`.
@@ -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. /// (values per block, bytes per block) of each tensor kind.
/// ///
/// Mirrors engine/strata/include/strata/artifact/gguf_reader.hpp at the /// Mirrors Strata 41cf05a0, include/strata/artifact/gguf_reader.hpp at the
/// upstream commit recorded in third_party/strata/UPSTREAM.md, plus the kinds /// upstream commit recorded in third_party/strata/UPSTREAM.md, plus the kinds
/// engine/strata/tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15, /// Strata 41cf05a0, tools/gguf_reader.py BLOCK_GEOMETRY knows beyond it (Q8_K 15,
/// IQ1_S 19, F64 28, MXFP4 39, NVFP4 40). Geometry is only a byte count: a /// 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: /// consumer that cannot decode a kind still refuses it at use. Differential:
/// control-plane/tests/gguf_header_differential.rs. /// control-plane/tests/gguf_header_differential.rs.
@@ -80,7 +80,7 @@ fn alt_paths(a: &AltArgs) -> Result<AltPaths, String> {
let kab = kab_path(a); let kab = kab_path(a);
if !kab.is_file() { if !kab.is_file() {
return Err(format!( 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() 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 | //! | Rust module | Python oracle | what it writes |
//! |--------------------|------------------------------|-------------------------------------------------------| //! |--------------------|------------------------------|-------------------------------------------------------|
+1 -1
View File
@@ -1,7 +1,7 @@
//! The ported tools against the Python originals' exact outputs. //! 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 //! `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. //! synthetic inputs. `scripts/offline/diff_tools.py` is the live differential over more cases.
use std::{ use std::{
fs, 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 //! 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`, //! (`sampler_greedy_kernel`, `sampler_kernel`, `sampler_one_block_kernel`,
//! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick` //! `sampled_tail_warp`) and the host mirrors `mirror_select` / `mirror_pick`
//! in `sampler_parity.cpp`. The three sampled kernels of the Original (old, //! 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. //! Coupled draft sampling arithmetic and the host penalty-history helpers.
//! //!
//! Sources: `engine/strata/include/strata/core/coupled_draft.hpp` (cell / //! Sources: `Strata 41cf05a0, include/strata/core/coupled_draft.hpp` (cell /
//! counter / ring arithmetic), `engine/strata/include/strata/kernels/sampler.hpp` //! counter / ring arithmetic), `Strata 41cf05a0, include/strata/kernels/sampler.hpp`
//! (`penalty_rows`) and the coupled kernels of `sampler.cu` //! (`penalty_rows`) and the coupled kernels of `sampler.cu`
//! (`coupled_penalize_kernel`, `coupled_merge_kernel`). //! (`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 //! This crate is a *literal transcription* of the Original host/device sampler
//! logic, not a re-design: //! logic, not a re-design:
+2 -2
View File
@@ -3,11 +3,11 @@
//! //!
//! Sources of truth in the Original: //! 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`, //! 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 //! `min_p = 0`, no penalties, `seed = 0` meaning "clock seed"; `min_p` is
//! clamped to `[0, 1]` and `penalty_last_n` to `>= 0`. //! 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` / //! emitted and how floats are printed) and `sampling_defaults_from_config` /
//! `clean_shared_defaults` (the ranges the server enforces on configured //! `clean_shared_defaults` (the ranges the server enforces on configured
//! defaults). //! defaults).
+1 -1
View File
@@ -1,7 +1,7 @@
//! The Original's counter-based uniform generator. //! The Original's counter-based uniform generator.
//! //!
//! Transcribed from `philox4x32_round` / `philox_uniform` in //! 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 //! in `sampler_parity.cpp`). NOTE: this is "Philox-shaped", not the textbook
//! Philox4x32-10: the multipliers are the golden-ratio constants //! Philox4x32-10: the multipliers are the golden-ratio constants
//! `0x9E3779B9` / `0xBB67AE85` and the round key is the bare round index //! `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`. //! 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 //! 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 //! `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 //! synthetic byte-level BPE vocabulary (256-byte alphabet, 300 trained merges that reach past the 64-symbol heap
+10 -7
View File
@@ -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: 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 ```sh
export CUDACXX=/absolute/path/to/cuda/bin/nvcc export CUDACXX=/absolute/path/to/cuda/bin/nvcc
export CUDAToolkit_ROOT=/absolute/path/to/cuda 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; and source tensor hashes; `source.json` records the verified shard identities;
the receipt lists the optional files that are present. the receipt lists the optional files that are present.
`scripts/smoke-native-pack.py` compares dense bytes, index rows and the complete 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
v3/v4 expert table against the unmodified pinned `tools/iq_pack.py` oracle on on small single/split GGUF fixtures, including per-role shard offsets, with zero numerical and byte tolerance (`scripts/smoke-native-pack.py` and
small single/split GGUF fixtures, including per-role shard offsets. Numerical `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
and byte tolerance is zero. `scripts/offline/diff_native_pack.py` extends this to `spec node offline-port.md`). Python/numpy are test-only dependencies. This does
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
not establish full-model GPU readiness: real-model pack parity and clean-node not establish full-model GPU readiness: real-model pack parity and clean-node
GPU startup still require their separate gates. Automatic fetch/prepare/start GPU startup still require their separate gates. Automatic fetch/prepare/start
orchestration remains a subsequent integration step. 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 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 must not be described as lossless. MTP activation stays explicit and real-model
qualification is still required. CPU verification: 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 `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`, 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: 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 ```sh
scripts/build-static-cuda.sh scripts/build-static-cuda.sh
engine="$PWD/artifacts/build-static-cuda/strata" engine="$PWD/artifacts/build-static-cuda/strata"
+10 -10
View File
@@ -1,6 +1,6 @@
# Strata upstream provenance # Strata upstream provenance
**Status:** `engine/strata/` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch **Status:** `Strata 41cf05a0 ` was brought to upstream `41cf05a0` (engine 0.1.50, app 0.2.5) on 2026-10-25 on branch
`claude/upstream-sync`, with the local patches re-applied. The previous pin (`d9ab8435`, engine 0.1.35) is kept below and in Git `claude/upstream-sync`, with the local patches re-applied. The previous pin (`d9ab8435`, engine 0.1.35) is kept below and in Git
history (`570201a:engine/strata`). Nothing was pushed. The quality-gate reference build (`stra169-ladder` Original) stays a build of the history (`570201a:engine/strata`). Nothing was pushed. The quality-gate reference build (`stra169-ladder` Original) stays a build of the
OLD pin plus the old local patches; the new subtree is not that reference (see "What this does to the quality reference"). OLD pin plus the old local patches; the new subtree is not that reference (see "What this does to the quality reference").
@@ -14,7 +14,7 @@ OLD pin plus the old local patches; the new subtree is not that reference (see "
| Upstream commit date | 2026-10-25 11:35 +0100 ("README (all 7 languages): models in the order Qwen3.8-Flash-Next, Qwen3.6-35B-A3B, DeepSeek V4.1-Flash") | | Upstream commit date | 2026-10-25 11:35 +0100 ("README (all 7 languages): models in the order Qwen3.8-Flash-Next, Qwen3.6-35B-A3B, DeepSeek V4.1-Flash") |
| Upstream version at the pin | engine and Control 0.1.50, Terminal and app 0.2.5 (`1aff6d14`, 2026-10-24) | | Upstream version at the pin | engine and Control 0.1.50, Terminal and app 0.2.5 (`1aff6d14`, 2026-10-24) |
| Upstream tree object of the pin | not recorded (the subtree is the pin plus local patches and omissions; the exact differences are listed below) | | Upstream tree object of the pin | not recorded (the subtree is the pin plus local patches and omissions; the exact differences are listed below) |
| Local repository path | `engine/strata/` | | Local repository path | `Strata 41cf05a0 ` |
| Update date | 2026-10-25 | | Update date | 2026-10-25 |
| Update method | documented tree replacement: 3-way `git merge-tree` of the old subtree against the new upstream, base = the old pin (see "How this update was made") | | Update method | documented tree replacement: 3-way `git merge-tree` of the old subtree against the new upstream, base = the old pin (see "How this update was made") |
| Hosted project repository URL | https://github.com/paveldhq/leleka-api (private) | | Hosted project repository URL | https://github.com/paveldhq/leleka-api (private) |
@@ -24,8 +24,8 @@ OLD pin plus the old local patches; the new subtree is not that reference (see "
| Pin | Upstream commit | Date | Engine | In this repository | | Pin | Upstream commit | Date | Engine | In this repository |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `engine/strata/` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) | | 1 (initial import) | `d9ab8435f654c368c586340d490915f6addf56a3` | 2026-10-02 | 0.1.35 | `Strata 41cf05a0 ` up to `570201a` (git subtree merge `c4e2137` of squash `906afc5de9dd` in the pre-squash history; later squashed into `4013e0c`) |
| 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `engine/strata/` on `claude/upstream-sync` | | 2 (this update) | `41cf05a06a25dd29103b7b27a2279a3f60c21876` | 2026-10-25 | 0.1.50 | `Strata 41cf05a0 ` on `claude/upstream-sync` |
**Upstream rewrote its history.** `d9ab8435` is not an ancestor of upstream `origin/main` (`git merge-base --is-ancestor` fails). Its **Upstream rewrote its history.** `d9ab8435` is not an ancestor of upstream `origin/main` (`git merge-base --is-ancestor` fails). Its
tree is identical (`git diff` is empty, tree `487c4cc0`) to upstream commit `5b734e42` ("Engine 0.1.35", same date), which is an tree is identical (`git diff` is empty, tree `487c4cc0`) to upstream commit `5b734e42` ("Engine 0.1.35", same date), which is an
@@ -44,7 +44,7 @@ so `git subtree pull` has nothing to anchor on. The update therefore used a tree
the local patches), `theirs` = upstream `41cf05a0`. the local patches), `theirs` = upstream `41cf05a0`.
2. `git merge-tree --write-tree --merge-base=<base> <ours> <theirs>`; conflicts were resolved by hand (below); the result was checked by 2. `git merge-tree --write-tree --merge-base=<base> <ours> <theirs>`; conflicts were resolved by hand (below); the result was checked by
listing every blob that differs from upstream `41cf05a0` (only the 21 patched files, the 4 added files and the left-out files differ). listing every blob that differs from upstream `41cf05a0` (only the 21 patched files, the 4 added files and the left-out files differ).
3. The result tree went into `engine/strata/` with `git read-tree --prefix=engine/strata/ -u` (`core.autocrlf=false`, LF kept), then the 3. The result tree went into `Strata 41cf05a0 ` with `git read-tree --prefix=Strata 41cf05a0 -u` (`core.autocrlf=false`, LF kept), then the
left-out files were removed from the index and the working tree. left-out files were removed from the index and the working tree.
4. `docs/upstream/local-patches-on-0.1.35.patch` is the patch that was re-applied (old pin to old subtree, 25 files); 4. `docs/upstream/local-patches-on-0.1.35.patch` is the patch that was re-applied (old pin to old subtree, 25 files);
`docs/upstream/local-patches-on-0.1.50.patch` is the same patches as they stand on the new pin (new pin to new subtree, 25 files). `docs/upstream/local-patches-on-0.1.50.patch` is the same patches as they stand on the new pin (new pin to new subtree, 25 files).
@@ -62,7 +62,7 @@ All of them are default-off or build-profile only. None changes the default beha
| Keyless V-only QSA arm (`a8411b5`; failed its quality gate, see `docs/experiments/2026-10-04-keyless-runtime.md`, `docs/keyless-runtime.md`) | `include/strata/core/keyless.hpp`, `src/core/keyless.cpp`, `src/kernels/cuda/keyless.cu`, `src/kernels/keyless_parity.cpp` (new files), plus `layer.cpp/.hpp`, `verify.cpp/.hpp`, `prefill.cpp`, `src/prefill/kernels.cu`, `kv_q8.cu`, `kv_stream.cu/.hpp`, `qsa_decode_attn.cu/.hpp`, `kv_stream_parity.cpp`, `conversation_snapshot.cpp/_test.cpp`, `mtp.cpp`, `generate.cpp` | Re-applied by hand (see conflicts). Needs `STRATA_KEYLESS_ROUTING` and `--kv int8`; refuses K8V4 and the new fused norm+rope; no slots / rows attention variant (falls back to per-query calls) | | Keyless V-only QSA arm (`a8411b5`; failed its quality gate, see `docs/experiments/2026-10-04-keyless-runtime.md`, `docs/keyless-runtime.md`) | `include/strata/core/keyless.hpp`, `src/core/keyless.cpp`, `src/kernels/cuda/keyless.cu`, `src/kernels/keyless_parity.cpp` (new files), plus `layer.cpp/.hpp`, `verify.cpp/.hpp`, `prefill.cpp`, `src/prefill/kernels.cu`, `kv_q8.cu`, `kv_stream.cu/.hpp`, `qsa_decode_attn.cu/.hpp`, `kv_stream_parity.cpp`, `conversation_snapshot.cpp/_test.cpp`, `mtp.cpp`, `generate.cpp` | Re-applied by hand (see conflicts). Needs `STRATA_KEYLESS_ROUTING` and `--kv int8`; refuses K8V4 and the new fused norm+rope; no slots / rows attention variant (falls back to per-query calls) |
| Mode bits | `setup.sh` | The 0644 mode our 2026-10-14 snapshot (`7f896a8`) set on `setup.sh` and `docker-entrypoint.sh` is not carried: `setup.sh` is 0755 as upstream; upstream deleted `docker-entrypoint.sh` (it is `docker/entrypoint.sh` now) | | Mode bits | `setup.sh` | The 0644 mode our 2026-10-14 snapshot (`7f896a8`) set on `setup.sh` and `docker-entrypoint.sh` is not carried: `setup.sh` is 0755 as upstream; upstream deleted `docker-entrypoint.sh` (it is `docker/entrypoint.sh` now) |
Other commits that touched `engine/strata` in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are Other commits that touched Strata 41cf05a0, in the pre-squash history (`b1da05f` first-window logits capture, `78e92d5` telemetry) are
either not part of the tracked snapshot at `570201a` or are the telemetry line listed above; `git grep` for the capture finds nothing in either not part of the tracked snapshot at `570201a` or are the telemetry line listed above; `git grep` for the capture finds nothing in
`570201a:engine/strata`, so nothing was lost by this update. `570201a:engine/strata`, so nothing was lost by this update.
@@ -90,7 +90,7 @@ Content conflicts (15 files, 44 hunks) and one modify/delete. Everything else in
### What this does to the quality reference ### What this does to the quality reference
`engine/strata/` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it `Strata 41cf05a0 ` on this branch is a different engine from the one the `stra169-ladder` Original was built from: with default flags it
behaves differently from the old pin (upstream flipped defaults on: route tail skip, PcieAuto, sm_120 and sm_86 kernel sets, fused int8 behaves differently from the old pin (upstream flipped defaults on: route tail skip, PcieAuto, sm_120 and sm_86 kernel sets, fused int8
prompt experts, auto conversation cache; see `docs/upstream-digest-2026-10-25.md`). Do not use a build of this subtree for the greedy/tensor prompt experts, auto conversation cache; see `docs/upstream-digest-2026-10-25.md`). Do not use a build of this subtree for the greedy/tensor
baselines of `docs/quality-gate.md`. The old pin remains reproducible from `git show 570201a:engine/strata` and from the upstream tree baselines of `docs/quality-gate.md`. The old pin remains reproducible from `git show 570201a:engine/strata` and from the upstream tree
@@ -124,12 +124,12 @@ upstream's instructions for its product and do not apply to work in this reposit
| Check | Result | | Check | Result |
| --- | --- | | --- | --- |
| Tree identity: every blob of `engine/strata/` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) | | Tree identity: every blob of `Strata 41cf05a0 ` compared with upstream `41cf05a0` | identical except the 21 patched files + 4 new files (and the left-out files) |
| `git diff --stat` for line-ending churn | none (LF kept, `core.autocrlf=false`; the nested `.gitattributes` of the subtree sets `eol=crlf` for `*.bat/*.cmd/*.ps1` as upstream does) | | `git diff --stat` for line-ending churn | none (LF kept, `core.autocrlf=false`; the nested `.gitattributes` of the subtree sets `eol=crlf` for `*.bat/*.cmd/*.ps1` as upstream does) |
| `scripts/build-cpu.sh` in WSL Ubuntu 24.04, GCC 13.3, CMake 3.31.6 | 16 of 16 ctest tests pass (the script's target list had to be extended: upstream registers 11 more CPU tests than the old pin; `Not Run` otherwise) | | `scripts/build-cpu.sh` in WSL Ubuntu 24.04, GCC 13.3, CMake 3.31.6 | 16 of 16 ctest tests pass (the script's target list had to be extended: upstream registers 11 more CPU tests than the old pin; `Not Run` otherwise) |
| CUDA compile (sm_86 only, `nvcc` 13.2, no GPU use) of the patched translation units: `kv_q8.cu`, `kv_stream.cu`, `qsa_decode_attn.cu`, `keyless.cu`, `prefill/kernels.cu`, `prefill.cpp`, `layer.cpp`, `verify.cpp`, `expert_source.cpp`, `mtp.cpp`, `conversation_snapshot.cpp`, `keyless.cpp`, `ngram.cpp`, `generate.cpp`, `kv_stream_parity.cpp`, `keyless_parity.cpp` | all 17 objects compile (warnings only) in the default configuration; the 7 objects that depend on the KAR/PLE macros (`ngram.cpp`, `expert_source.cpp`, `prefill.cpp`, `generate.cpp`, `kar_ple_cache.cu`, `kar_expert.cu`, `kar_expert_miss.cpp`) also compile with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON`, `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON`. The compile found one error a textual merge cannot (a duplicate `trace_h_` member in `verify.hpp`), fixed by renaming ours to `kl_trace_*`. Not built: link, the `strata` binary, the parity tests, the sm_120 PTX | | CUDA compile (sm_86 only, `nvcc` 13.2, no GPU use) of the patched translation units: `kv_q8.cu`, `kv_stream.cu`, `qsa_decode_attn.cu`, `keyless.cu`, `prefill/kernels.cu`, `prefill.cpp`, `layer.cpp`, `verify.cpp`, `expert_source.cpp`, `mtp.cpp`, `conversation_snapshot.cpp`, `keyless.cpp`, `ngram.cpp`, `generate.cpp`, `kv_stream_parity.cpp`, `keyless_parity.cpp` | all 17 objects compile (warnings only) in the default configuration; the 7 objects that depend on the KAR/PLE macros (`ngram.cpp`, `expert_source.cpp`, `prefill.cpp`, `generate.cpp`, `kar_ple_cache.cu`, `kar_expert.cu`, `kar_expert_miss.cpp`) also compile with `STRATA_NEXT_EXPERIMENTAL_KAR_PLE=ON`, `STRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=ON`, `STRATA_NEXT_EXPERIMENTAL_PLE_TRACE=ON`. The compile found one error a textual merge cannot (a duplicate `trace_h_` member in `verify.hpp`), fixed by renaming ours to `kl_trace_*`. Not built: link, the `strata` binary, the parity tests, the sm_120 PTX |
| GPU parity, quality gate, any model run | not run (by instruction); the keyless, KAR and PLE arms are default off and unexercised | | GPU parity, quality gate, any model run | not run (by instruction); the keyless, KAR and PLE arms are default off and unexercised |
| Port crates that `include_str!` files from `engine/strata` | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) | | Port crates that `include_str!` files from Strata 41cf05a0 | none of those files changed upstream (`LICENSE`, `serve/chat_template.jinja`, `serve/chat_golden.json`, `tests/data/native_experts/*.txt`, `serve/mcp_fake_server.py`, `tools/mtp_rt.py`) |
## Local CUDA validation, 2026-10-04 ## Local CUDA validation, 2026-10-04
@@ -171,7 +171,7 @@ quality arm, not full compressed-model residency or a qualified speedup.
The Leleka runtime under `crates/`, `desktop-core/` and `control-plane/` is a Rust/CUDA port of the Original mode17 serve path written The Leleka runtime under `crates/`, `desktop-core/` and `control-plane/` is a Rust/CUDA port of the Original mode17 serve path written
for this project; it shares the model artifacts and the algorithms (not the C++ code) with Strata. The Original used as the quality for this project; it shares the model artifacts and the algorithms (not the C++ code) with Strata. The Original used as the quality
reference and for the vanilla baselines is a separate build of the OLD pin (`d9ab8435` / `5b734e42`, engine 0.1.35) plus the local reference and for the vanilla baselines is a separate build of the OLD pin (`d9ab8435` / `5b734e42`, engine 0.1.35) plus the local
patches that were in `engine/strata/` before this update; `engine/strata/` itself is no longer that source. The agreement of the port patches that were in `Strata 41cf05a0 ` before this update; `Strata 41cf05a0 ` itself is no longer that source. The agreement of the port
with the Original is measured in `docs/quality-gate.md`; the request-end prefix checkpoints (`docs/prefix-cache.md`) and the chain with the Original is measured in `docs/quality-gate.md`; the request-end prefix checkpoints (`docs/prefix-cache.md`) and the chain
kernels (`docs/chain-kernels.md`) are port-side additions with their own gates. kernels (`docs/chain-kernels.md`) are port-side additions with their own gates.
+1 -1
View File
@@ -2,7 +2,7 @@
"_comment": "Policy of scripts/check-limits.py (STRA-367, lawbook chapter 301). The limits apply to new and changed code (diff gate) and to the whole tree as a falling census. See spec node architecture/limits-gate.md.", "_comment": "Policy of scripts/check-limits.py (STRA-367, lawbook chapter 301). The limits apply to new and changed code (diff gate) and to the whole tree as a falling census. See spec node architecture/limits-gate.md.",
"limits": {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, "limits": {"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5},
"tab_width": 4, "tab_width": 4,
"exclude": ["engine/strata/", "target/", ".git/"], "exclude": ["third_party/strata/", "target/", ".git/"],
"python_include": [ "python_include": [
"scripts/limits/", "scripts/archcheck/", "scripts/check-limits.py", "scripts/check_limits_test.py", "scripts/limits/", "scripts/archcheck/", "scripts/check-limits.py", "scripts/check_limits_test.py",
"scripts/check-architecture.py", "scripts/check_architecture_test.py" "scripts/check-architecture.py", "scripts/check_architecture_test.py"
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-cpu}"
jobs="${BUILD_JOBS:-4}"
if ! command -v cmake >/dev/null 2>&1; then
printf 'CMake 3.24 or newer is required.\n' >&2
exit 1
fi
cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \
-DSTRATA_ENABLE_CUDA=OFF \
-DSTRATA_ENABLE_HIP=OFF \
-DSTRATA_BUILD_TESTS=OFF \
-DSTRATA_BUILD_CONVERSATION_TESTS=ON
# The standalone CPU tests ctest registers under STRATA_BUILD_CONVERSATION_TESTS. Upstream 0.1.50 registers eleven more than
# the 0.1.35 pin did; a registered test whose binary is not built shows up as "Not Run" and fails ctest, so every one is listed.
cmake --build "${build_dir}" --parallel "${jobs}" --target \
strata-gguf strata-dequant strata-plan \
conversation_cache_test conversation_memory_test \
conv_cache_test coupled_draft_test bf16_bits_test \
conversation_split_failure_test conversation_file_test session_save_reclaim_test message_boundary_test \
split_ring_test draft_kv_plan_test spec_prob_test draft_cap_test batch_rows_test batch_groups_test \
nvfp4_avx512_parity
ctest --test-dir "${build_dir}" --output-on-failure
@@ -1,25 +0,0 @@
#!/usr/bin/env bash
# Test-only bounded native reference; no serving/model build or GPU execution.
# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution.
set -euo pipefail
[[ $# == 2 ]] || { echo 'Usage: build-cuda-projection-family-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; }
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
toolkit="$(cd "$1" && pwd)"
output="$2"
[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]]
"$toolkit/bin/nvcc" --version | grep 'V13.0.88'
python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY'
import json,sys
assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2]))
PY
# Exact native source identity is an oracle gate, not caller-selected reference.
echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check)
echo '07fe5567a7fc75a079dcc7887975dffe490607564c16ad884423b903ab08a537 engine/strata/src/kernels/cuda/iq_kernels.cu' | (cd "$root" && sha256sum --check)
echo '0061131b615c5721fc88a78feeb22c1f8c450f1c2646a317d80796a653bf595c engine/strata/third_party/ggml/ggml-common.h' | (cd "$root" && sha256sum --check)
sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-projection-family-oracle/native_fixture.cu"
"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \
-Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \
-I"$root/engine/strata/include" -I"$root/engine/strata/third_party/ggml" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \
"$root/engine/strata/src/kernels/cuda/iq_kernels.cu" \
"$root/scripts/cuda-projection-family-oracle/native_fixture.cu" -ldl -o "$output"
sha256sum "$output"
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Test-only bounded native reference; no serving/model build or GPU execution.
# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution.
set -euo pipefail
[[ $# == 2 ]] || { echo 'Usage: build-cuda-q5-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; }
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
toolkit="$(cd "$1" && pwd)"
output="$2"
[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]]
"$toolkit/bin/nvcc" --version | grep 'V13.0.88'
python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY'
import json,sys
assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2]))
PY
# Exact native source identity is an oracle gate, not caller-selected reference.
echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check)
sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-q5-oracle/native_fixture.cu"
"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \
-Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \
-I"$root/engine/strata/include" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \
"$root/scripts/cuda-q5-oracle/native_fixture.cu" -ldl -o "$output"
sha256sum "$output"
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Test-only bounded native reference; no serving/model build or GPU execution.
# TOOLKIT must be the verified deploy/cuda-toolkit.lock.json 13.0.88 distribution.
set -euo pipefail
[[ $# == 2 ]] || { echo 'Usage: build-cuda-q6-oracle.sh TOOLKIT PRIVATE_OUTPUT' >&2; exit 2; }
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
toolkit="$(cd "$1" && pwd)"
output="$2"
[[ ! -e "$output" && -f "$toolkit/TOOLKIT-PROVENANCE.json" ]]
"$toolkit/bin/nvcc" --version | grep 'V13.0.88'
python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$root/deploy/cuda-toolkit.lock.json" <<'PY'
import json,sys
assert json.load(open(sys.argv[1]))['lock']==json.load(open(sys.argv[2]))
PY
# Exact native source identity is an oracle gate, not caller-selected reference.
echo 'f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f engine/strata/src/kernels/cuda/native_mmvq.cu' | (cd "$root" && sha256sum --check)
sha256sum "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" "$root/scripts/cuda-q6-oracle/native_fixture.cu"
"$toolkit/bin/nvcc" -std=c++17 -O3 -arch=sm_120 --use_fast_math \
-Xcompiler=-ffunction-sections,-fdata-sections -Xlinker=--gc-sections \
-I"$root/engine/strata/include" "$root/engine/strata/src/kernels/cuda/native_mmvq.cu" \
"$root/scripts/cuda-q6-oracle/native_fixture.cu" -ldl -o "$output"
sha256sum "$output"
-19
View File
@@ -1,19 +0,0 @@
#!/usr/bin/env bash
# New test-only harness; never launches a GPU or rebuilds the server.
set -euo pipefail
[[ $# == 1 ]] || { echo 'Usage: build-cuda-qsa-oracle.sh PRIVATE_OUTPUT_DIRECTORY' >&2; exit 2; }
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
out="$1"
mkdir -p "$out"
nvcc --version | tee "$out/compiler.txt"
grep 'V12.8.93' "$out/compiler.txt"
(cd "$root" && sha256sum --check scripts/cuda-qsa-oracle/source.sha256)
common=(-std=c++17 -O3 -arch=sm_120 -Xcompiler=-ffunction-sections,-fdata-sections -I"$root/engine/strata/include")
for part in native rope index; do
nvcc "${common[@]}" --use_fast_math -c "$root/scripts/cuda-qsa-oracle/oracle_$part.cu" -o "$out/$part.o"
done
for part in select attention; do
nvcc "${common[@]}" --fmad=true --ftz=false -c "$root/scripts/cuda-qsa-oracle/oracle_$part.cu" -o "$out/$part.o"
done
nvcc "${common[@]}" --fmad=false --ftz=false "$root/scripts/cuda-qsa-oracle/main.cu" "$out/"{native,rope,index,select,attention}.o -Xlinker=--gc-sections -L/usr/local/cuda/lib64/stubs -lcuda -o "$out/qsa_oracle"
sha256sum "$out/qsa_oracle" "$out/"*.o > "$out/binary.sha256"
-184
View File
@@ -1,184 +0,0 @@
#!/usr/bin/env bash
# Produce the fixed CUDA Driver assets consumed by OriginalVerifyBank, direct prompt, and MTP paths.
#
# This is an offline compilation step for the Linux CPU Docker runner. It does
# not load libcuda, expose a GPU, start a model, or run an inference request.
set -euo pipefail
[[ $# == 1 ]] || {
echo "Usage: scripts/build-original-verify-ptx.sh PINNED_CUDA_TOOLKIT" >&2
exit 2
}
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
toolkit="$(cd "$1" && pwd)"
lock="$root/deploy/cuda-toolkit.lock.json"
[[ -f "$toolkit/TOOLKIT-PROVENANCE.json" ]] || {
echo "missing pinned toolkit provenance" >&2
exit 2
}
"$toolkit/bin/nvcc" --version | grep -F 'V13.0.88' >/dev/null
python3 - "$toolkit/TOOLKIT-PROVENANCE.json" "$lock" <<'PY'
import json, sys
if json.load(open(sys.argv[1], encoding='utf-8'))['lock'] != json.load(open(sys.argv[2], encoding='utf-8')):
raise SystemExit('toolkit provenance does not match deploy/cuda-toolkit.lock.json')
PY
stage="$(mktemp -d "$root/crates/cuda-driver/src/.original-verify-ptx.XXXXXX")"
trap 'rm -rf "$stage"' EXIT
compile() {
local source="$1" output="$2"
"$toolkit/bin/nvcc" --ptx -std=c++17 -O3 -arch=sm_120 \
--fmad=true --ftz=false -I"$root/engine/strata/include" -I"$root/engine/strata/third_party/ggml" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-cuda" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-include" -I"$root/crates/cuda-driver/src/third_party/llamacpp/ggml-src" "$source" -o "$output"
}
compile "$root/crates/cuda-driver/src/original_verify.cu" "$stage/original_verify.ptx"
compile "$root/crates/cuda-driver/src/original_verify_qsa.cu" "$stage/original_verify_qsa.ptx"
compile "$root/crates/cuda-driver/src/qsa_prompt_device_gate.cu" "$stage/qsa_prompt_device_gate.ptx"
compile "$root/crates/cuda-driver/src/ple_prompt_device.cu" "$stage/ple_prompt_device.ptx"
compile "$root/crates/cuda-driver/src/gr_prompt_device.cu" "$stage/gr_prompt_device.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_tail.cu" "$stage/mtp_original_tail.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_kv.cu" "$stage/mtp_original_kv.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_prefill.cu" "$stage/mtp_original_prefill.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_prefill_embedding.cu" "$stage/mtp_original_prefill_embedding.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_prefill_quant.cu" "$stage/mtp_original_prefill_quant.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_prefill_mmq.cu" "$stage/mtp_original_prefill_mmq.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_prefill_fixup.cu" "$stage/mtp_original_prefill_fixup.ptx"
# Full MTP forward: every asset is compiled from its matching direct CUDA source.
compile "$root/crates/cuda-driver/src/mtp_original_full_s2.cu" "$stage/mtp_original_full_s2.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_quant80.cu" "$stage/mtp_original_full_quant80.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_shared.cu" "$stage/mtp_original_full_shared.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_router.cu" "$stage/mtp_original_full_router.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_router_legacy.cu" "$stage/mtp_original_full_router_legacy.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_combine.cu" "$stage/mtp_original_full_combine.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_bf16.cu" "$stage/mtp_original_full_bf16.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_gr_norm.cu" "$stage/mtp_original_full_gr_norm.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_gr_post.cu" "$stage/mtp_original_full_gr_post.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_gr_write.cu" "$stage/mtp_original_full_gr_write.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_element.cu" "$stage/mtp_original_full_element.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_qsa_gate.cu" "$stage/mtp_original_full_qsa_gate.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_verify.cu" "$stage/mtp_original_full_verify.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_head_native.cu" "$stage/mtp_original_full_head_native.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_head_iq.cu" "$stage/mtp_original_full_head_iq.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_head_sampler.cu" "$stage/mtp_original_full_head_sampler.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_qnorm.cu" "$stage/mtp_original_full_qnorm.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_fused_gr.cu" "$stage/mtp_original_full_fused_gr.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_checks.cu" "$stage/mtp_original_full_checks.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_attention.cu" "$stage/mtp_original_full_attention.ptx"
compile "$root/crates/cuda-driver/src/mtp_original_full_coupled.cu" "$stage/mtp_original_full_coupled.ptx"
python3 - "$stage/original_verify.ptx" "$stage/original_verify_qsa.ptx" "$stage/qsa_prompt_device_gate.ptx" "$stage/ple_prompt_device.ptx" "$stage/gr_prompt_device.ptx" "$stage/mtp_original_tail.ptx" "$stage/mtp_original_kv.ptx" "$stage/mtp_original_prefill.ptx" "$stage/mtp_original_prefill_embedding.ptx" "$stage/mtp_original_prefill_quant.ptx" "$stage/mtp_original_prefill_mmq.ptx" "$stage/mtp_original_prefill_fixup.ptx" "$stage/mtp_original_full_s2.ptx" "$stage/mtp_original_full_quant80.ptx" "$stage/mtp_original_full_shared.ptx" "$stage/mtp_original_full_router.ptx" "$stage/mtp_original_full_router_legacy.ptx" "$stage/mtp_original_full_combine.ptx" "$stage/mtp_original_full_bf16.ptx" "$stage/mtp_original_full_gr_norm.ptx" "$stage/mtp_original_full_gr_post.ptx" "$stage/mtp_original_full_gr_write.ptx" "$stage/mtp_original_full_element.ptx" "$stage/mtp_original_full_qsa_gate.ptx" "$stage/mtp_original_full_verify.ptx" "$stage/mtp_original_full_head_native.ptx" "$stage/mtp_original_full_head_iq.ptx" "$stage/mtp_original_full_head_sampler.ptx" "$stage/mtp_original_full_qnorm.ptx" "$stage/mtp_original_full_fused_gr.ptx" "$stage/mtp_original_full_checks.ptx" "$stage/mtp_original_full_attention.ptx" "$stage/mtp_original_full_coupled.ptx" <<'PY'
import sys
from pathlib import Path
required = {
'original_verify.ptx': (
'verify_gdn_conv_l2_multi_kernel', 'verify_gdn_conv_commit_kernel',
'verify_gdn_ab_multi_kernel', 'verify_gdn_step_norm_multi_kernel',
'verify_embedding_gather_dev_kernel', 'verify_broadcast_streams_kernel',
'verify_copy_indexed_kernel', 'verify_fetch_blobs_kernel',
'verify_rebase_ptrs_kernel', 'verify_add_streams_broadcast_kernel',
'verify_ident_hits_kernel', 'verify_gather_rows_16', 'verify_gather_rows_4',
'verify_gather_rows_1', 'verify_map_ids_kernel', 'verify_row_top_prob_kernel',
'verify_mtp_select_kernel', 'verify_dense_steps_kernel', 'verify_window_ids_kernel',
'verify_wait_flag_ge_kernel', 'verify_resident_plan_kernel',
'verify_wait_flag_ge_or_kernel', 'verify_copy_i32_unless_kernel',
'verify_copy_or_zero_kernel', 'verify_gpu_stamp_kernel',
'verify_copy_from_mapped_kernel', 'verify_copy_rows_from_mapped_kernel',
'verify_doorbell_publish_kernel', 'verify_copy_i32_from_mapped_kernel',
'verify_clear_status', 'verify_scan_logits',
),
'original_verify_qsa.ptx': (
'verify_qsa_append_analytic', 'verify_qsa_append_table',
),
'qsa_prompt_device_gate.ptx': (
'qsa_prompt_device_gate',
),
'ple_prompt_device.ptx': (
'ple_rms', 'ple_gate', 'ple_broadcast', 'ple_conv', 'ple_history', 'ple_finite',
),
'gr_prompt_device.ptx': (
'gr_norm_rs_kernel', 'gr_silu_kernel', 'gr_mix_r_kernel', 'gr_write_kernel', 'gr_scan',
'gr_norm_scan', 'gr_silu_scan', 'gr_product_scan', 'gr_write_norm_rs_kernel',
),
'mtp_original_tail.ptx': (
'mtp_original_quantize', 'mtp_original_q80_1', 'mtp_original_q80_2', 'mtp_original_q80_3',
'mtp_original_q80_4', 'mtp_original_q80_5', 'mtp_original_q80_6', 'mtp_original_q80_7',
'mtp_original_q80_8', 'mtp_original_knorm', 'mtp_original_krope', 'mtp_original_finite', 'mtp_original_q8_guard',
),
'mtp_original_kv.ptx': (
'mtp_original_append', 'mtp_original_ring_table', 'mtp_original_window_ids', 'mtp_original_encoded_guard',
),
'mtp_original_prefill.ptx': (
'mtp_prefill_rms', 'mtp_prefill_gr_norm', 'mtp_prefill_gr_silu', 'mtp_prefill_gr_mix',
'mtp_prefill_broadcast', 'mtp_prefill_embedding', 'mtp_prefill_rope', 'mtp_prefill_append',
'mtp_prefill_finite', 'mtp_prefill_iota', 'mtp_prefill_encoded', 'mtp_prefill_zero',
'mtp_prefill_gr_norm_scan', 'mtp_prefill_gr_silu_scan', 'mtp_prefill_bf16_scan',
'mtp_prefill_gr_product_scan', 'mtp_prefill_q8_scan',
),
'mtp_original_prefill_embedding.ptx': ('mtp_prefill_native_embedding',),
'mtp_original_prefill_quant.ptx': ('mtp_prefill_q8',),
'mtp_original_prefill_mmq.ptx': (
'_Z9mul_mat_qIL9ggml_type8ELi8ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi16ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi24ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi32ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi40ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi48ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi64ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi80ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi96ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi112ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
'_Z9mul_mat_qIL9ggml_type8ELi128ELb0EEvPKcPKiS4_S4_PfS5_PKf5uint3iiiiiS8_S8_iiiS8_S8_iiiS8_',
),
'mtp_original_prefill_fixup.ptx': (
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi8ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi16ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi24ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi32ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi40ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi48ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi64ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi80ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi96ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi112ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
'_Z24mul_mat_q_stream_k_fixupIL9ggml_type8ELi128ELb0EEvPKiS2_PfS3_5uint3iiiS4_iS4_iS4_',
),
'mtp_original_full_coupled.ptx': (
'sampler_split_part_kernel', 'coupled_stage_kernel', 'coupled_penalize_kernel', 'coupled_merge_kernel',
),
}
symbols = (Path.cwd() / 'crates/cuda-driver/src/mtp_dense_kv/original_int8/prefill/scalar/full_forward/symbols.rs').read_text(encoding='utf-8')
for asset, exports in __import__('re').findall(r'include_bytes!\(\"([^\"]+\.ptx)\"\).*?&\[(.*?)\]\)', symbols, __import__('re').S):
required[asset] = tuple(__import__('re').findall(r'c\"([^\"]+)\"', exports))
for raw in map(Path, sys.argv[1:]):
body = raw.read_bytes()
if not (0 < len(body) <= 16 * 1024 * 1024) or b'\0' in body or not body.isascii():
raise SystemExit(f'{raw.name}: invalid PTX encoding or size')
text = body.decode('ascii')
missing = [name for name in required[raw.name] if f'.entry {name}' not in text]
if missing:
raise SystemExit(f'{raw.name}: missing exports: {", ".join(missing)}')
if 'UNSEALED' in text:
raise SystemExit(f'{raw.name}: unsealed marker')
PY
for name in original_verify.ptx original_verify_qsa.ptx qsa_prompt_device_gate.ptx ple_prompt_device.ptx gr_prompt_device.ptx; do
install -m 0644 "$stage/$name" "$root/crates/cuda-driver/src/.$name.new"
mv -f "$root/crates/cuda-driver/src/.$name.new" "$root/crates/cuda-driver/src/$name"
sha256sum "$root/crates/cuda-driver/src/$name"
done
# MTP FFI loads include_bytes! assets directly and requires precisely one
# terminal NUL. Validate generated ASCII raw PTX above, then append only that
# terminator during atomic installation.
for name in mtp_original_tail.ptx mtp_original_kv.ptx mtp_original_prefill.ptx mtp_original_prefill_embedding.ptx mtp_original_prefill_quant.ptx mtp_original_prefill_mmq.ptx mtp_original_prefill_fixup.ptx mtp_original_full_s2.ptx mtp_original_full_quant80.ptx mtp_original_full_shared.ptx mtp_original_full_router.ptx mtp_original_full_router_legacy.ptx mtp_original_full_combine.ptx mtp_original_full_bf16.ptx mtp_original_full_gr_norm.ptx mtp_original_full_gr_post.ptx mtp_original_full_gr_write.ptx mtp_original_full_element.ptx mtp_original_full_qsa_gate.ptx mtp_original_full_verify.ptx mtp_original_full_head_native.ptx mtp_original_full_head_iq.ptx mtp_original_full_head_sampler.ptx mtp_original_full_qnorm.ptx mtp_original_full_fused_gr.ptx mtp_original_full_checks.ptx mtp_original_full_attention.ptx mtp_original_full_coupled.ptx; do
python3 -c 'import sys; from pathlib import Path; raw=Path(sys.argv[1]).read_bytes(); assert raw and raw.isascii() and b"\0" not in raw; Path(sys.argv[2]).write_bytes(raw+b"\0")' "$stage/$name" "$root/crates/cuda-driver/src/.$name.new"
chmod 0644 "$root/crates/cuda-driver/src/.$name.new"
mv -f "$root/crates/cuda-driver/src/.$name.new" "$root/crates/cuda-driver/src/$name"
sha256sum "$root/crates/cuda-driver/src/$name"
done
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
build_dir="${STRATA_BUILD_DIR:-${repo_root}/artifacts/build-static-cuda}"
jobs="${BUILD_JOBS:-2}"
[[ "$(uname -s)" == Linux ]] || { echo 'Static CUDA engine builds require Linux.' >&2; exit 1; }
if [[ ${STRATA_KAR_PLE+x} ]]; then
kar_ple="${STRATA_KAR_PLE}"
else
kar_ple=0
fi
case "${kar_ple}" in
0) cmake_kar_ple=OFF ;;
1) cmake_kar_ple=ON ;;
*) echo 'STRATA_KAR_PLE must be exactly 0 or 1.' >&2; exit 2 ;;
esac
if [[ ${SOURCE_REVISION+x} ]]; then
source_revision="${SOURCE_REVISION}"
else
source_revision="$(git -C "${repo_root}" rev-parse HEAD)"
fi
if [[ ! "${source_revision}" =~ ^[0-9a-f]{40}$ ]]; then
echo 'SOURCE_REVISION must be an exact lowercase 40-character Git commit.' >&2
exit 2
fi
# CUDACXX/CUDAToolkit_ROOT select an existing toolkit; STRATA_GGML_DIR avoids fetching GGML.
cmake_args=(
-S "${repo_root}/engine/strata" -B "${build_dir}"
-DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF -DSTRATA_CUDA_STATIC=ON \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="${CUDA_ARCHITECTURES:-120}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_PLE="${cmake_kar_ple}" \
-DSTRATA_NEXT_EXPERIMENTAL_KAR_EXPERTS=OFF \
-DSTRATA_NEXT_EXPERIMENTAL_PLE_TRACE=OFF \
-DSTRATA_NEXT_KAR_DIR="${repo_root}/gpu/kar" \
-DSTRATA_BUILD_TESTS=OFF -DSTRATA_NATIVE_EXPERTS=ON \
-DSTRATA_PORTABLE=ON
)
if [[ -n "${STRATA_GGML_DIR:-}" ]]; then
cmake_args+=("-DSTRATA_GGML_DIR=${STRATA_GGML_DIR}")
fi
cmake "${cmake_args[@]}"
cmake --build "${build_dir}" --parallel "${jobs}" --target strata
python3 "${repo_root}/scripts/check-static-cuda-elf.py" "${build_dir}/strata"
# generate.cpp handles --help before any model or GPU initialization.
env -u LD_LIBRARY_PATH CUDA_VISIBLE_DEVICES= "${build_dir}/strata" --help
# This records compile capability only. The runtime still requires an explicit
# model/profile selection; PLE is experimental and defaults off at serving time.
python3 - "${build_dir}/BUILD-FEATURES.json" "${kar_ple}" "${CUDA_ARCHITECTURES:-120}" "${source_revision}" <<'PYFEATURES'
import json
import os
from pathlib import Path
import sys
import tempfile
destination, ple, architectures, revision = sys.argv[1:]
record = {
'schema_version': 1,
'source_revision': revision,
'cuda_architectures': architectures,
'features': {
'cuda': True,
'cuda_static_runtime': True,
'cxx_static_runtime': True,
'kar_ple': ple == '1',
'kar_experts': False,
'ple_trace': False,
},
}
path = Path(destination)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix='.BUILD-FEATURES-', dir=path.parent)
try:
with os.fdopen(fd, 'w') as output:
json.dump(record, output, sort_keys=True, indent=2)
output.write('\n')
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
PYFEATURES
-20
View File
@@ -1,20 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
build_dir="${STRATA_KEYLESS_BUILD_DIR:-${repo_root}/artifacts/build-keyless-gpu}"
# A separate CUDA test context must fit; never stop the user's serving process.
used="$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | head -n 1)"
if (( used > 1024 )); then
printf 'GPU is occupied; run keyless validation after unloading the model.\n' >&2
exit 1
fi
cmake -S "${repo_root}/engine/strata" -B "${build_dir}" \
-DSTRATA_ENABLE_CUDA=ON -DSTRATA_ENABLE_HIP=OFF \
-DSTRATA_NATIVE_EXPERTS=ON -DSTRATA_BUILD_TESTS=OFF \
-DSTRATA_BUILD_CONVERSATION_TESTS=ON \
-DCMAKE_CUDA_ARCHITECTURES="${STRATA_CUDA_ARCHITECTURES:-native}"
cmake --build "${build_dir}" --parallel "${BUILD_JOBS:-4}" --target \
keyless_parity keyless_stream_parity conversation_snapshot_test
ctest --test-dir "${build_dir}" --output-on-failure \
-R '^(keyless_parity|keyless_stream_parity|conversation_snapshot_test)$'
+3 -36
View File
@@ -14,8 +14,6 @@
# Environment: # Environment:
# STRICT_DEBT=1 fail on the known format/Clippy debt listed below instead of warning # STRICT_DEBT=1 fail on the known format/Clippy debt listed below instead of warning
# SKIP_LINUX_TYPECHECK=1 skip the x86_64-unknown-linux-gnu type-check (needs `rustup target add` otherwise) # SKIP_LINUX_TYPECHECK=1 skip the x86_64-unknown-linux-gnu type-check (needs `rustup target add` otherwise)
# OFFLINE_ORACLE_PYTHON, STRATA_GGUF_PY
# enable the live Python-oracle differentials
# LELEKA_LINUX_TESTS=1 also run scripts/linux-tests/run.sh (Docker Linux harness, branch claude/port-linux-tests) # LELEKA_LINUX_TESTS=1 also run scripts/linux-tests/run.sh (Docker Linux harness, branch claude/port-linux-tests)
# #
# No model weights, tokens or network access to model hosts are used by any step. # No model weights, tokens or network access to model hosts are used by any step.
@@ -66,8 +64,6 @@ fast_path() {
debt cargo fmt -p leleka-model-format -p leleka-experimental-ref --check debt cargo fmt -p leleka-model-format -p leleka-experimental-ref --check
cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref --all-targets --no-deps -- -D warnings cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref --all-targets --no-deps -- -D warnings
debt cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets --no-deps -- -D warnings debt cargo clippy --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-model-format --all-targets --no-deps -- -D warnings
# leleka-experimental-ref includes tests/literal_port.rs, the drift guard between engine/strata/src/kernels/cuda and the checked-in
# experimental ports (re-synced to the upstream 41cf05a0 kernels on 2026-11-03).
cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref -p leleka-model-format cargo test --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-experimental-ref -p leleka-model-format
} }
@@ -90,24 +86,8 @@ port_oracles() {
# Pure-host tests of the Linux-only sampler files, against fixtures built from the unmodified Original host code. # Pure-host tests of the Linux-only sampler files, against fixtures built from the unmodified Original host code.
"${repo_root}/crates/sampler-ref/oracle/run_port_host_tests.sh" "${repo_root}/crates/sampler-ref/oracle/run_port_host_tests.sh"
# Golden fixtures built from the Original C++/Python (rope, memory plan, serving policy, conversation, experimental # Golden fixtures built from the Original C++/Python (rope, memory plan, serving policy, conversation, experimental
# references, offline tools, tokenizer) are replayed by the cargo tests above. Live Python differentials follow. # references, offline tools, tokenizer) are checked in and replayed by the cargo tests above. The generators and the live
offline_oracles # Python differentials needed the vendored Strata tree, which was removed (third_party/strata/UPSTREAM.md, STRA-406).
}
# Live differentials against the unmodified Python oracle. Opt in with a venv that has
# numpy, pyyaml, tqdm, jinja2 and regex, and the pinned llama.cpp gguf-py:
# OFFLINE_ORACLE_PYTHON=/venv/bin/python STRATA_GGUF_PY=/llama.cpp/gguf-py scripts/check-local.sh
offline_oracles() {
if [[ -n "${OFFLINE_ORACLE_PYTHON:-}" && -n "${STRATA_GGUF_PY:-}" ]]; then
cargo build --manifest-path "${repo_root}/Cargo.toml" --locked -p leleka-control-plane --bin leleka-api
local strata_next="${CARGO_TARGET_DIR:-${repo_root}/target}/debug/leleka-api"
local oracle
for oracle in native_pack gguf_header tokenizer dequant tools mtp_fetch chat_template; do
"${OFFLINE_ORACLE_PYTHON}" "${repo_root}/scripts/offline/diff_${oracle}.py" "${strata_next}"
done
else
echo "== live Python oracle differentials skipped (set OFFLINE_ORACLE_PYTHON and STRATA_GGUF_PY)"
fi
} }
linux_harness() { linux_harness() {
@@ -210,20 +190,18 @@ port_oracles
linux_harness linux_harness
[[ "${mode}" == port ]] && exit 0 [[ "${mode}" == port ]] && exit 0
python3 -m py_compile "${repo_root}/scripts/prepare-keyless-routing.py" "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/test-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py" python3 -m py_compile "${repo_root}/scripts/calibrate-keyless-routing.py" "${repo_root}/scripts/bench-chat-paired.py" "${repo_root}/scripts/compare-chat-reports.py" "${repo_root}/scripts/bench-chat-sequential-server.py" "${repo_root}/scripts/check-kar-cuda-records.py" "${repo_root}/scripts/strata-agent-profile.py" "${repo_root}/scripts/strata-dual-256-experiment.py" "${repo_root}/scripts/strata-dual-request-proxy.py" "${repo_root}/scripts/kv-keyless-feasibility.py" "${repo_root}/scripts/kv-keyless-attention.py" "${repo_root}/scripts/bench-expert-reserve.py" "${repo_root}/scripts/ple-cache-reuse.py" "${repo_root}/scripts/split-ple-row-trace.py" "${repo_root}/scripts/bench-kar-ple-device.py" "${repo_root}/scripts/bench-kar-ple-serve.py"
python3 "${repo_root}/scripts/test-benchmark-harness.py" python3 "${repo_root}/scripts/test-benchmark-harness.py"
python3 "${repo_root}/scripts/test-native-service.py" python3 "${repo_root}/scripts/test-native-service.py"
python3 "${repo_root}/scripts/test-native-api.py" python3 "${repo_root}/scripts/test-native-api.py"
python3 "${repo_root}/scripts/test-native-menu.py" python3 "${repo_root}/scripts/test-native-menu.py"
python3 "${repo_root}/scripts/test-model-switch.py" python3 "${repo_root}/scripts/test-model-switch.py"
python3 "${repo_root}/scripts/test-cuda-bootstrap.py" python3 "${repo_root}/scripts/test-cuda-bootstrap.py"
python3 "${repo_root}/scripts/test-static-cuda-profile.py"
python3 "${repo_root}/scripts/test-static-cuda-elf.py" python3 "${repo_root}/scripts/test-static-cuda-elf.py"
python3 "${repo_root}/scripts/test-linux-package.py" python3 "${repo_root}/scripts/test-linux-package.py"
python3 "${repo_root}/scripts/test-runtime-image.py" python3 "${repo_root}/scripts/test-runtime-image.py"
python3 "${repo_root}/scripts/test-ple-config-parity.py" python3 "${repo_root}/scripts/test-ple-config-parity.py"
python3 "${repo_root}/scripts/test-gitea-release.py" python3 "${repo_root}/scripts/test-gitea-release.py"
python3 "${repo_root}/scripts/test-keyless-routing.py"
# leleka-cuda-driver and leleka-runtime build only for Linux; on other hosts the type-check above is the check. # leleka-cuda-driver and leleka-runtime build only for Linux; on other hosts the type-check above is the check.
if [[ "${host_os}" == Linux ]]; then if [[ "${host_os}" == Linux ]]; then
@@ -238,19 +216,8 @@ if [[ "${host_os}" == Linux ]]; then
else else
echo "== Linux-only crate tests skipped on ${host_os}" echo "== Linux-only crate tests skipped on ${host_os}"
fi fi
# every ported .cu parses against the CUDA stub headers (no nvcc needed; see scripts/cuda-stubs/cuda_stub.h)
# (verified on macOS/Apple clang; on other hosts libstdc++'s math headers may need stub additions, so it is advisory there)
if command -v clang++ >/dev/null 2>&1; then
if [ "$(uname -s)" = Darwin ]; then
python3 "${repo_root}/scripts/cuda-stubs/check-cu.py"
else
# glibc/libstdc++ hosts: clang's CUDA frontend needs macOS-only stub overloads, so the C++-only pass (--plain) is the advisory check here
python3 "${repo_root}/scripts/cuda-stubs/check-cu.py" --plain || echo "warning: cuda stub syntax check failed (advisory off macOS)" >&2
fi
fi
cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check cargo fmt --manifest-path "${repo_root}/control-plane/Cargo.toml" --check
cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets --no-deps -- -D warnings cargo clippy --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --all-targets --no-deps -- -D warnings
cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked cargo test --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked
replay="$(cargo run --quiet --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --bin replay-responses -- --sse "${repo_root}/benchmarks/fixtures/responses/structured-tool.json")" replay="$(cargo run --quiet --manifest-path "${repo_root}/control-plane/Cargo.toml" --locked --bin replay-responses -- --sse "${repo_root}/benchmarks/fixtures/responses/structured-tool.json")"
[[ "${replay}" == *"event: response.completed"* ]] [[ "${replay}" == *"event: response.completed"* ]]
"${repo_root}/scripts/build-cpu.sh"
+4 -4
View File
@@ -19,7 +19,7 @@ from limits import allow, baseline, census, cli, clippy_ratchet, diffs, files, g
from limits import model, policy, pyscan, rscan # noqa: E402 from limits import model, policy, pyscan, rscan # noqa: E402
POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, 4, POLICY = policy.Policy({"fn_lines": 30, "complexity": 10, "nesting": 4, "width": 120, "params": 5}, 4,
("engine/strata/",), ("third_party/strata/",),
("scripts/limits/",), ("claude/hexagonal-integ", "main")) ("scripts/limits/",), ("claude/hexagonal-integ", "main"))
LIMITS = POLICY.limits LIMITS = POLICY.limits
@@ -298,7 +298,7 @@ class TempRepo(unittest.TestCase):
self.root = pathlib.Path(self.tmp.name) self.root = pathlib.Path(self.tmp.name)
git(self.root, "init", "-q", "-b", "main") git(self.root, "init", "-q", "-b", "main")
(self.root / "limits.json").write_text(json.dumps({ (self.root / "limits.json").write_text(json.dumps({
"limits": LIMITS, "tab_width": 4, "exclude": ["engine/strata/"], "python_include": [], "limits": LIMITS, "tab_width": 4, "exclude": ["third_party/strata/"], "python_include": [],
"base_candidates": ["claude/hexagonal-integ", "main"]}), encoding="utf-8") "base_candidates": ["claude/hexagonal-integ", "main"]}), encoding="utf-8")
self.write("old.rs", LONG) self.write("old.rs", LONG)
git(self.root, "add", "-A") git(self.root, "add", "-A")
@@ -344,7 +344,7 @@ class GateOnARepository(TempRepo):
self.assertEqual(self.run_gate(), 1) self.assertEqual(self.run_gate(), 1)
def test_excluded_paths_are_ignored(self): def test_excluded_paths_are_ignored(self):
self.write("engine/strata/x.rs", LONG) self.write("third_party/strata/x.rs", LONG)
self.assertEqual(self.run_gate(), 0) self.assertEqual(self.run_gate(), 0)
def test_base_resolution(self): def test_base_resolution(self):
@@ -393,7 +393,7 @@ class BaselineRatchet(unittest.TestCase):
class Policy(unittest.TestCase): class Policy(unittest.TestCase):
def test_scope_of_files(self): def test_scope_of_files(self):
self.assertEqual(policy.language(POLICY, "crates/x/src/a.rs"), "rust") self.assertEqual(policy.language(POLICY, "crates/x/src/a.rs"), "rust")
self.assertIsNone(policy.language(POLICY, "engine/strata/src/a.rs")) self.assertIsNone(policy.language(POLICY, "third_party/strata/src/a.rs"))
self.assertIsNone(policy.language(POLICY, "crates/x/target/debug/build.rs")) self.assertIsNone(policy.language(POLICY, "crates/x/target/debug/build.rs"))
self.assertEqual(policy.language(POLICY, "scripts/limits/cli.py"), "python") self.assertEqual(policy.language(POLICY, "scripts/limits/cli.py"), "python")
self.assertIsNone(policy.language(POLICY, "scripts/other.py")) self.assertIsNone(policy.language(POLICY, "scripts/other.py"))
-64
View File
@@ -1,64 +0,0 @@
#!/usr/bin/env python3
"""Compare native token IDs and roundtrips with the pinned upstream Python oracle.
Offline evaluation only. Requires `regex` for engine/strata/tools/strata_tokenizer.py.
The real GGUF and extracted tokenizer assets must stay outside Git.
"""
import argparse
import json
import pathlib
import subprocess
import sys
CORPUS = (
"Hello world!",
"Привіт, світе! Як справи?",
"e\u0301 café — naïve",
"😀👨‍👩‍👧‍👦",
"空白 漢字\n数字123",
"\t\r\nTwo spaces\x00end",
"<|im_start|>user\nSay hi<|im_end|>",
'<tool_call>{"name":"calc","arguments":{"x":1}}</tool_call>',
"a" * 70 + " next",
"print(1 + 2) # ✓",
)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=pathlib.Path, required=True)
parser.add_argument("--gguf", type=pathlib.Path, required=True)
parser.add_argument("--assets", type=pathlib.Path, required=True)
args = parser.parse_args()
binary = args.binary.resolve(strict=True)
gguf = args.gguf.resolve(strict=True)
assets = args.assets.resolve(strict=True)
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent / "engine/strata/tools"))
from strata_tokenizer import Tokenizer # pylint: disable=import-outside-toplevel
oracle = Tokenizer.from_gguf(gguf)
for special in (False, True):
for number, value in enumerate(CORPUS):
command = [binary, "model", "tokenize", assets, "--stdin"]
if special:
command.append("--special")
native = json.loads(subprocess.run(
command, input=value, text=True, capture_output=True, check=True,
).stdout)
expected = oracle.encode(value, parse_special=special)
if native != expected:
raise ValueError(f"token IDs differ for case {number}, special={special}")
decoded = json.loads(subprocess.run(
[binary, "model", "detokenize", assets, ",".join(map(str, native))],
text=True, capture_output=True, check=True,
).stdout)
if decoded != value or oracle.decode(expected) != value:
raise ValueError(f"roundtrip differs for case {number}, special={special}")
print(json.dumps({"cases": len(CORPUS) * 2, "vocab": len(oracle.tokens),
"merges": len(oracle.ranks), "result": "exact native/upstream parity"}))
if __name__ == "__main__":
main()
@@ -1,60 +0,0 @@
// Independent test-only runner. Compile the ORIGINAL native_mmvq.cu unchanged.
// Does not decode native weights, share candidate scratch, or select arbitrary entries.
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include <cuda_runtime.h>
#include <cuda.h>
#include <dlfcn.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <cstdint>
#include <cstring>
#include <cmath>
static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));}
template<class T> static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast<T>(p);}
int main(int argc,char**argv) try {
if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_COMMON_QUANTIZER_PTX");
std::ifstream in(argv[1],std::ios::binary);uint32_t h[4];in.read(reinterpret_cast<char*>(h),sizeof h);
if(!in||h[0]!=0x31464b51||h[1]>9||h[2]<1||h[2]>10240||h[3]<32||h[3]>6144||h[3]%32)throw std::runtime_error("bounded synthetic geometry");
const auto mode=h[1],m=h[2],n=h[3];
static const unsigned be[]={32,256,256,256,256,32,32,256,256,64};
static const unsigned bb[]={34,144,98,110,82,18,18,136,136,18};
if(n%be[mode])throw std::runtime_error("format block geometry");
size_t wb=size_t(m)*(n/be[mode])*bb[mode],qb=size_t(n/32)*36;
std::vector<unsigned char>w(wb),q(qb),fresh(qb),candidate(qb);std::vector<float>x(n),y(m);
in.read(reinterpret_cast<char*>(w.data()),wb);in.read(reinterpret_cast<char*>(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length");
// Invalid activation is tested in Rust/candidate admission; never feed it into
// the original unchecked native float-to-integer quantizer.
for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input");
ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds;
ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4));
ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice));
strata::kernels::native_quantize_q8_1(static_cast<float*>(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost));
// Composition independently quantizes a second fresh native scratch allocation.
strata::kernels::native_quantize_q8_1(static_cast<float*>(dx),df,n,1,stream);
strata::kernels::iq_set_old_kernels(true); // exact original row_dot, not grouped expert combine
switch(mode){
case 0:strata::kernels::native_q8_0_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);break;
case 1:strata::kernels::native_q4_k_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);break;
case 5:strata::kernels::native_iq4_nl_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);break;
case 7:strata::kernels::native_iq4_xs_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);break;
default:{static const int tag[]={8,12,18,21,22,20,20,23,23,42};
strata::kernels::iq_mmvq(tag[mode],dw,df,static_cast<float*>(dy),n,m,1,stream);break;}
}ck(cudaStreamSynchronize(stream));
ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees");
std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator<char>(pt)),{});if(ptx.empty()||ptx.size()>262144||ptx.find(char(0))!=std::string::npos)throw std::runtime_error("bounded trusted test asset");for(unsigned char c:ptx)if(c>127)throw std::runtime_error("trusted PTX must be ASCII");ptx.push_back(0);
void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing");
auto load=sym<CUresult(*)(CUmodule*,const void*)>(lib,"cuModuleLoadData");auto get=sym<CUresult(*)(CUfunction*,CUmodule,const char*)>(lib,"cuModuleGetFunction");
auto launch=sym<CUresult(*)(CUfunction,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,CUstream,void**,void**)>(lib,"cuLaunchKernel");auto unload=sym<CUresult(*)(CUmodule)>(lib,"cuModuleUnload");
CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4));
CUdeviceptr px=reinterpret_cast<CUdeviceptr>(dx),pq=reinterpret_cast<CUdeviceptr>(dcq),ps=reinterpret_cast<CUdeviceptr>(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols};
dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast<CUstream>(stream),args,nullptr));ck(cudaStreamSynchronize(stream));
uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib);
std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x31464f51,mode,m,n,status};out.write(reinterpret_cast<char*>(oh),sizeof oh);out.write(reinterpret_cast<char*>(q.data()),qb);out.write(reinterpret_cast<char*>(candidate.data()),qb);out.write(reinterpret_cast<char*>(y.data()),m*4);if(!out)throw std::runtime_error("output write");
for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset());
std::cout<<"NATIVE_ORACLE rows="<<m<<" columns="<<n<<" q8_bytes="<<qb<<" status="<<status<<" independent_scratch=true cleanup=ok\n";return 0;
} catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
-77
View File
@@ -1,77 +0,0 @@
# Independent Q5_K projection oracle
Test-only fixtures for STRA-142. They do not run a model forward pass, measure
performance, or install a Toolkit on the GPU server. Production uses its existing
owned CUDA Driver boundary and embedded PTX.
## Reference and independent expectations
`native_fixture.cu` links the **unchanged** imported
`engine/strata/src/kernels/cuda/native_mmvq.cu` (SHA-256
`f2fc636e5e8f6db9bbb8146fbf2b78a717c0e0076bf8c72ac2b784df7b3f455f`).
The native source is pinned through `c3020b71ba6cc49a81d8b374c29dd3be36fe239c`
and attributed to llama.cpp `3cf03257f219afbe7334045ff7c6a06ac68c627d`.
Its source/MIT notice is preserved; no quantizer or projection implementation is
copied into this test runner.
Build with verified CUDA 13.0.88, `-arch=sm_120 --use_fast_math -O3`.
`--use_fast_math` is essential: FTZ, approximate division and contraction are the
native baseline. Function/data sections and linker garbage collection remove
unused format dispatch references without editing the original translation unit.
`scripts/prepare-cuda-q5-oracle-toolkit.py PRIVATE_OUTPUT` fetches only the six
hash-pinned compiler/runtime components in `deploy/cuda-toolkit.lock.json`, verifies
the manifest and archive hashes, and records the selection. BLAS is not needed.
`scripts/build-cuda-q5-oracle.sh TOOLKIT PRIVATE_ELF` refuses an existing output,
checks the native source hash, and compiles the bounded reference. Build in a
GPU-hidden isolated Linux amd64 CPU container; preserve its actual architecture,
compiler versions, exact commands, source hashes and ELF hash as evidence.
The native runner accepts a private input file: three little-endian u32 words
(magic `0x35314b51`, M, N), exactly `M*(N/256)*176` packed bytes, then `4*N` bytes
of finite F32 activation. Bounds are `1 <= M <= 640`, `256 <= N <= 6144`, N%256=0.
It quantizes one native scratch allocation, then calls `native_q5_k_f32` with a
**second fresh native scratch** and checks those native bytes agree. Neither
native call receives candidate scratch. Separately it loads the trusted candidate
asset and launches only `leleka_quantize_q8_1` in the private test Driver boundary.
All allocations, stream and module are consumed on success; errors terminate the
isolated process. Original native quantization is never fed nonfinite inputs.
Output has four LE u32 words (magic `0x35314f51`, M, N, candidate admission status),
then native Q8 bytes, candidate Q8 bytes, and native F32 output bits. These are
separate assertions: every Q8 byte must match; finite/zero/Inf outputs require
identical bits; NaN outputs require NaN classification. No tolerance is calibrated
from candidate results.
`tests/q5_oracle.rs` independently constructs/decodes GGUF six-bit scales/minima,
high bits and nibbles; its packed words and exact scalar dot are recorded hand
expectations. It does not import a production decoder. The GPU hand case uses
constant activation 127: native d8=1 and original-input sums are exact, yielding
959104 per Q5 block. CPU scalar arithmetic is supplementary and does not redefine
native fast-math output.
## Executable gates
- `tests/q5_gpu.rs`: installed-driver opt-in tests. The standard test covers
M=1/3/4/5 × N=256/512/2048/2560/6144, ties away from zero, signed zeros,
cancellation, half-scale underflow, FP16 range, hand arithmetic and nonfinite
weight halves. Public calls repeat against the frozen native result, verify
immutable caller inputs and zero remaining temporary charge. Six numeric
refusal cases exercise the native status path and preserve caller output.
- Its separate real-tensor test accepts only the explicitly selected Qwen
`blk.4.ffn_up_shexp.weight` 640×2560 private fixture and our deterministic
synthetic activation. This proves one projection, not model quality or forward
execution. Packed weights stay outside Git.
- `tests/q5_mock.rs` / `q5_mock_cuda.c`: independent CPU ELF routing, geometry,
admission, cache, delayed argument ownership, sync/restore poison, and consuming
cleanup proof. The existing fixture is included unchanged. Synthetic mock
scratch/output arithmetic is **not** the native numerical oracle.
- `test-cuda-driver-bootstrap.sh` preserves the complete existing CPU gate and
adds the focused Q5 matrix and an output-alias compile refusal.
GPU tests require `LELEKA_CUDA_REAL_GPU=1`, use one test thread and a bounded outer
`timeout`. The parity test additionally requires absolute private paths in
`LELEKA_Q5_EVIDENCE`, `LELEKA_Q5_NATIVE_ORACLE`, `LELEKA_Q5_TRUSTED_PTX`.
The real-tensor test also requires `LELEKA_Q5_REAL_INPUT`. Fixture subprocesses have
30-second deadlines. Capture stdout/stderr/exits and hardware/driver/pre-post GPU
state, retain private digests and remove only owned remote resources. Ordinary
`cargo test` leaves these GPU tests ignored.
-46
View File
@@ -1,46 +0,0 @@
// Independent test-only runner. Compile the ORIGINAL native_mmvq.cu unchanged.
// Does not decode native weights, share candidate scratch, or select arbitrary entries.
#include "strata/kernels/native_mmvq.hpp"
#include <cuda_runtime.h>
#include <cuda.h>
#include <dlfcn.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <cstdint>
#include <cstring>
#include <cmath>
static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));}
template<class T> static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast<T>(p);}
int main(int argc,char**argv) try {
if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_Q5_PTX");
std::ifstream in(argv[1],std::ios::binary);uint32_t h[3];in.read(reinterpret_cast<char*>(h),sizeof h);
if(!in||h[0]!=0x35314b51||h[1]<1||h[1]>640||h[2]<256||h[2]>6144||h[2]%256)throw std::runtime_error("bounded synthetic geometry");
const auto m=h[1],n=h[2];size_t wb=size_t(m)*(n/256)*176,qb=size_t(n/32)*36;
std::vector<unsigned char>w(wb),q(qb),fresh(qb),candidate(qb);std::vector<float>x(n),y(m);
in.read(reinterpret_cast<char*>(w.data()),wb);in.read(reinterpret_cast<char*>(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length");
// Invalid activation is tested in Rust/candidate admission; never feed it into
// the original unchecked native float-to-integer quantizer.
for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input");
ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds;
ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4));
ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice));
strata::kernels::native_quantize_q8_1(static_cast<float*>(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost));
// Composition independently quantizes a second fresh native scratch allocation.
strata::kernels::native_q5_k_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);ck(cudaStreamSynchronize(stream));
ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees");
std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator<char>(pt)),{});if(ptx.empty()||ptx.size()>262144)throw std::runtime_error("bounded trusted test asset");ptx.push_back(0);
void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing");
auto load=sym<CUresult(*)(CUmodule*,const void*)>(lib,"cuModuleLoadData");auto get=sym<CUresult(*)(CUfunction*,CUmodule,const char*)>(lib,"cuModuleGetFunction");
auto launch=sym<CUresult(*)(CUfunction,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,CUstream,void**,void**)>(lib,"cuLaunchKernel");auto unload=sym<CUresult(*)(CUmodule)>(lib,"cuModuleUnload");
CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4));
CUdeviceptr px=reinterpret_cast<CUdeviceptr>(dx),pq=reinterpret_cast<CUdeviceptr>(dcq),ps=reinterpret_cast<CUdeviceptr>(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols};
dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast<CUstream>(stream),args,nullptr));ck(cudaStreamSynchronize(stream));
uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib);
std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x35314f51,m,n,status};out.write(reinterpret_cast<char*>(oh),sizeof oh);out.write(reinterpret_cast<char*>(q.data()),qb);out.write(reinterpret_cast<char*>(candidate.data()),qb);out.write(reinterpret_cast<char*>(y.data()),m*4);if(!out)throw std::runtime_error("output write");
for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset());
std::cout<<"NATIVE_ORACLE rows="<<m<<" columns="<<n<<" q8_bytes="<<qb<<" status="<<status<<" independent_scratch=true cleanup=ok\n";return 0;
} catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
-46
View File
@@ -1,46 +0,0 @@
// Independent test-only runner. Compile the ORIGINAL native_mmvq.cu unchanged.
// Does not decode native weights, share candidate scratch, or select arbitrary entries.
#include "strata/kernels/native_mmvq.hpp"
#include <cuda_runtime.h>
#include <cuda.h>
#include <dlfcn.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <cstdint>
#include <cstring>
#include <cmath>
static void ck(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
static void dc(CUresult e){if(e!=CUDA_SUCCESS)throw std::runtime_error("Driver test fixture status "+std::to_string(e));}
template<class T> static T sym(void* lib,const char* name){void* p=dlsym(lib,name);if(!p)throw std::runtime_error(name);return reinterpret_cast<T>(p);}
int main(int argc,char**argv) try {
if(argc!=4)throw std::runtime_error("Usage: native_fixture INPUT OUTPUT TRUSTED_Q6_PTX");
std::ifstream in(argv[1],std::ios::binary);uint32_t h[3];in.read(reinterpret_cast<char*>(h),sizeof h);
if(!in||h[0]!=0x36314b51||h[1]<1||h[1]>10240||h[2]<256||h[2]>6144||h[2]%256)throw std::runtime_error("bounded synthetic geometry");
const auto m=h[1],n=h[2];size_t wb=size_t(m)*(n/256)*210,qb=size_t(n/32)*36;
std::vector<unsigned char>w(wb),q(qb),fresh(qb),candidate(qb);std::vector<float>x(n),y(m);
in.read(reinterpret_cast<char*>(w.data()),wb);in.read(reinterpret_cast<char*>(x.data()),n*4);if(!in||in.peek()!=EOF)throw std::runtime_error("fixture length");
// Invalid activation is tested in Rust/candidate admission; never feed it into
// the original unchecked native float-to-integer quantizer.
for(float v:x)if(!std::isfinite(v))throw std::runtime_error("native fixture requires finite input");
ck(cudaSetDevice(0));cudaStream_t stream;ck(cudaStreamCreate(&stream));void *dw,*dx,*dq,*df,*dcq,*dy,*ds;
ck(cudaMalloc(&dw,wb));ck(cudaMalloc(&dx,n*4));ck(cudaMalloc(&dq,qb));ck(cudaMalloc(&df,qb));ck(cudaMalloc(&dcq,qb));ck(cudaMalloc(&dy,m*4));ck(cudaMalloc(&ds,4));
ck(cudaMemcpy(dw,w.data(),wb,cudaMemcpyHostToDevice));ck(cudaMemcpy(dx,x.data(),n*4,cudaMemcpyHostToDevice));
strata::kernels::native_quantize_q8_1(static_cast<float*>(dx),dq,n,1,stream);ck(cudaStreamSynchronize(stream));ck(cudaMemcpy(q.data(),dq,qb,cudaMemcpyDeviceToHost));
// Composition independently quantizes a second fresh native scratch allocation.
strata::kernels::native_q6_k_f32(dw,static_cast<float*>(dx),df,static_cast<float*>(dy),n,m,1,stream);ck(cudaStreamSynchronize(stream));
ck(cudaMemcpy(fresh.data(),df,qb,cudaMemcpyDeviceToHost));ck(cudaMemcpy(y.data(),dy,m*4,cudaMemcpyDeviceToHost));if(q!=fresh)throw std::runtime_error("fresh native quantization disagrees");
std::ifstream pt(argv[3],std::ios::binary);std::string ptx((std::istreambuf_iterator<char>(pt)),{});if(ptx.empty()||ptx.size()>262144)throw std::runtime_error("bounded trusted test asset");ptx.push_back(0);
void* lib=dlopen("libcuda.so.1",RTLD_NOW|RTLD_LOCAL);if(!lib)throw std::runtime_error("installed Driver missing");
auto load=sym<CUresult(*)(CUmodule*,const void*)>(lib,"cuModuleLoadData");auto get=sym<CUresult(*)(CUfunction*,CUmodule,const char*)>(lib,"cuModuleGetFunction");
auto launch=sym<CUresult(*)(CUfunction,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,unsigned,CUstream,void**,void**)>(lib,"cuLaunchKernel");auto unload=sym<CUresult(*)(CUmodule)>(lib,"cuModuleUnload");
CUmodule mod;CUfunction f;dc(load(&mod,ptx.data()));dc(get(&f,mod,"leleka_quantize_q8_1"));ck(cudaMemset(ds,0,4));
CUdeviceptr px=reinterpret_cast<CUdeviceptr>(dx),pq=reinterpret_cast<CUdeviceptr>(dcq),ps=reinterpret_cast<CUdeviceptr>(ds);uint32_t cols=n;void*args[]={&px,&pq,&ps,&cols};
dc(launch(f,(n+255)/256,1,1,256,1,1,0,reinterpret_cast<CUstream>(stream),args,nullptr));ck(cudaStreamSynchronize(stream));
uint32_t status;ck(cudaMemcpy(&status,ds,4,cudaMemcpyDeviceToHost));ck(cudaMemcpy(candidate.data(),dcq,qb,cudaMemcpyDeviceToHost));dc(unload(mod));dlclose(lib);
std::ofstream out(argv[2],std::ios::binary);uint32_t oh[]={0x36314f51,m,n,status};out.write(reinterpret_cast<char*>(oh),sizeof oh);out.write(reinterpret_cast<char*>(q.data()),qb);out.write(reinterpret_cast<char*>(candidate.data()),qb);out.write(reinterpret_cast<char*>(y.data()),m*4);if(!out)throw std::runtime_error("output write");
for(void*p:{dw,dx,dq,df,dcq,dy,ds})ck(cudaFree(p));ck(cudaStreamDestroy(stream));ck(cudaDeviceReset());
std::cout<<"NATIVE_ORACLE rows="<<m<<" columns="<<n<<" q8_bytes="<<qb<<" status="<<status<<" independent_scratch=true cleanup=ok\n";return 0;
} catch(const std::exception&e){std::cerr<<e.what()<<'\n';return 1;}
-58
View File
@@ -1,58 +0,0 @@
# Independent QSA component oracle
Test-only caller for the fixed 24-query-head / 2-KV-head / 256-dimension profile.
It loads the exact retained candidate PTX through the CUDA driver. Separate
translation units include the unchanged original Strata sources; those sources
are numerical references only and are never linked into Leleka serving.
`build-cuda-qsa-oracle.sh PRIVATE_OUTPUT_DIRECTORY` compiles without launching a
GPU. Use the admitted cached GPU-hidden CUDA 12.8.93 image. Original native norm,
RoPE, indexer and gate use `--use_fast_math`; selection and attention retain
`--fmad=true --ftz=false`. All eleven producer files and original source/header
inputs are pinned in `source.sha256`. Never silently refresh these pins.
The resulting executable accepts `ASSET_DIRECTORY PRIVATE_OUTPUT_DIRECTORY`
and an optional group: `norm`, `rope`, `pack`, `index`, `select`, `attention`,
`gate`, or `invalid`. The directory must already exist. Groups permit continuing
unexecuted cases after a concrete failure without repeating passing operators.
The default runs all groups and stops at the first mismatch.
## Fixed corpus and gates
- Weighted norm: Q 24×256, K 2×256, index query 4×128; exact original F32 bits.
- Partial RoPE: those geometries at positions 0, 1, 4, 7, 262143; exact original
F32 bits and unchanged dimensions 64 onward.
- Interleaved Q/gate split: independent literal indexing. FP16 pack: original
append plus independent words for round-to-even ties, signed zero, subnormal
and maximum finite values.
- Index append: chronological positions 0 through 7, exact rounded raw tail,
fixed spare and pooled output against the original native indexer.
- Score/selection: extents 1, 4, 7, 2051, 2052, 2053, 4096, 262144; exact source
scores and IDs, independent stable cell sort, literal lowest-ID all-equal ties.
- Attention: selected widths 1, 7, 257, 2051; exact original output plus separate
double dot/softmax/V reference on identical FP16 words, relative L1 ≤ 1e-5.
One-cell different KV values expose incorrect modulo head grouping.
- Native F32 gate: literal -1000, -100, -1, signed zeros, 1, 100, 1000 and exact
source bits; finite sigmoid saturation is valid. NaN norm and NaN/Inf gate
outputs must remain failure-only NaNs.
Inputs are deterministic literal/integer-rational data defined in `main.cu`.
Every successful comparison writes raw expected and actual values into the
private output directory. Preserve failures, compiler/source/binary hashes and
the actual hardware/software receipt. Do not adjust tolerances to match output.
`host_theta.cpp` and `theta_probe.cu` diagnose the concrete fixed-literal versus
runtime-parameter fast-pow lowering issue without changing the production
source or the reference. Their output is a diagnosis, not asset admission.
The supplemental `repair RETAINED_PROOF_DIRECTORY` group reuses the five
retained original reference objects. It checks Q RoPE at 1, 4, 7, 262143 and
K/index RoPE at 0, 1, 4, 7, 262143. Index append 7 restores its prior state
from `index_append_6.want` and `index_append_3.want`; positions 0 through 6
are not relaunched. Keep these retained fixtures and new proof in separate
private directories. Producer pins reflect the runtime-theta lowering repair
in DEV receipt `d070342f-3afa-44ef-9c54-27758bae07c5` only.
This harness does not qualify projections, full-model forward, model quality,
readiness, token transaction integration, latency or throughput. Root owns
review and admission of each fixed driver asset after independent evidence.
-6
View File
@@ -1,6 +0,0 @@
// Read-only diagnosis: original host powf is runtime libm dependent.
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
int main(){volatile float base=10000000.0f;const float x=powf(base,-2.0f/64);uint32_t word;std::memcpy(&word,&x,4);std::printf("original_runtime_host_theta=%08x value=%.9g\n",word,x);}
-173
View File
@@ -1,173 +0,0 @@
// Independent test caller: candidate PTX is never an expected-value oracle.
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
extern "C" void oracle_norm(const float*,const float*,float*,int,int,cudaStream_t);
extern "C" void oracle_gate(const float*,const float*,float*,cudaStream_t);
extern "C" void oracle_rope(const float*,float*,int,int,const int*,cudaStream_t);
extern "C" void oracle_index(const float*,const float*,const int*,float*,float*,float*,int*,cudaStream_t);
extern "C" void oracle_scores(const float*,const float*,const float*,const int*,int64_t,float*,cudaStream_t);
extern "C" void oracle_topk(const float*,const int*,int64_t,int*,cudaStream_t);
extern "C" void oracle_pack(const float*,const float*,uint16_t*,uint16_t*,const int*,cudaStream_t);
extern "C" void oracle_attention(const float*,const uint16_t*,const uint16_t*,const int*,float*,cudaStream_t);
static std::string output;
static std::string retained;
static uint64_t words=0;
static unsigned cases=0;
static void rt(cudaError_t e){if(e!=cudaSuccess)throw std::runtime_error(cudaGetErrorString(e));}
static void drv(CUresult e){if(e!=CUDA_SUCCESS){const char*s=nullptr;cuGetErrorString(e,&s);throw std::runtime_error(s?s:"driver failure");}}
template<class T> struct Buffer {
T*p=nullptr;size_t n;
explicit Buffer(size_t count):n(count){rt(cudaMalloc(&p,n*sizeof(T)));rt(cudaMemset(p,0,n*sizeof(T)));}
explicit Buffer(const std::vector<T>&v):Buffer(v.size()){set(v);}
~Buffer(){if(p)cudaFree(p);}
void set(const std::vector<T>&v){if(v.size()!=n)throw std::runtime_error("fixture extent");rt(cudaMemcpy(p,v.data(),n*sizeof(T),cudaMemcpyHostToDevice));}
std::vector<T> get(){std::vector<T>v(n);rt(cudaMemcpy(v.data(),p,n*sizeof(T),cudaMemcpyDeviceToHost));return v;}
Buffer(const Buffer&)=delete;
};
static void raw(const std::string&name,const void*p,size_t n){std::ofstream f(output+"/"+name,std::ios::binary);f.write(static_cast<const char*>(p),n);if(!f)throw std::runtime_error("proof write");}
template<class T> static void exact(const std::string&name,const std::vector<T>&want,const std::vector<T>&got){
raw(name+".want",want.data(),want.size()*sizeof(T));raw(name+".got",got.data(),got.size()*sizeof(T));
if(want.size()!=got.size())throw std::runtime_error(name+": extent");
for(size_t i=0;i<want.size();++i)if(std::memcmp(&want[i],&got[i],sizeof(T))){
std::fprintf(stderr,"FAIL %s index=%zu\n",name.c_str(),i);throw std::runtime_error("exact bits differ");}
words+=want.size();++cases;std::printf("PASS %s exact_words=%zu\n",name.c_str(),want.size());
}
static std::vector<float> values(size_t n,int salt){std::vector<float>v(n);for(size_t i=0;i<n;++i)v[i]=float(int((i*37+salt*13)%127)-63)/64.0f;return v;}
static std::vector<float> norm_weights(size_t n){std::vector<float>v(n);for(size_t i=0;i<n;++i)v[i]=float(int(i%13)+8)/16.0f;return v;}
static std::vector<int> step(unsigned p){return {int(p),int(p+1),int((p+1)/4),int(std::min(p+1,2051u))};}
static cudaStream_t stream;
static CUmodule modules[4];
static void launch(int m,const char*name,unsigned gx,unsigned gy,unsigned bx,unsigned shared,std::vector<void*>args){
CUfunction f;drv(cuModuleGetFunction(&f,modules[m],name));
drv(cuLaunchKernel(f,gx,gy,1,bx,1,1,shared,reinterpret_cast<CUstream>(stream),args.data(),nullptr));
rt(cudaStreamSynchronize(stream));
}
static void norms(){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4;
Buffer<float>x(values(c*n,mode+1)),g(norm_weights(c)),w(c*n),y(c*n);
oracle_norm(x.p,g.p,w.p,c,n,stream);rt(cudaStreamSynchronize(stream));
const char*names[]={"leleka_qsa_norm_q","leleka_qsa_norm_k","leleka_qsa_norm_index_q"};
launch(0,names[mode],n,1,256,0,{&x.p,&g.p,&y.p});exact(std::string("norm_")+std::to_string(mode),w.get(),y.get());
}}
static void ropes(bool repair=false){for(int mode=0;mode<3;++mode){int c=mode==2?128:256,n=mode==0?24:mode==1?2:4;
const char*names[]={"leleka_qsa_rope_q","leleka_qsa_rope_k","leleka_qsa_rope_index_q"};
for(unsigned p:{0u,1u,4u,7u,262143u}){
if(repair&&mode==0&&p==0)continue; // Exact Q position0 proof is already retained.
auto input=values(c*n,mode+4);Buffer<float>x(input),w(c*n),y(c*n);Buffer<int>positions(std::vector<int>(n,int(p)));
oracle_rope(x.p,w.p,c,n,positions.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,names[mode],1,n,128,0,{&x.p,&p,&y.p});auto got=y.get();
exact("rope_"+std::to_string(mode)+"_"+std::to_string(p),w.get(),got);
for(int row=0;row<n;++row)for(int d=64;d<c;++d)if(std::memcmp(&input[row*c+d],&got[row*c+d],4))throw std::runtime_error("partial RoPE suffix changed");
}}}
static void split_pack(){
auto full=values(12288,8);Buffer<float>x(full),q(6144),g(6144);
launch(0,"leleka_qsa_split_q_gate",24,1,256,0,{&x.p,&q.p,&g.p});
std::vector<float>wq(6144),wg(6144);for(int h=0;h<24;++h)for(int d=0;d<256;++d){wq[h*256+d]=full[h*512+d];wg[h*256+d]=full[h*512+256+d];}
exact("split_q",wq,q.get());exact("split_gate",wg,g.get());
const uint32_t bits[]={0,0x80000000u,0x3f800000u,0x3f801000u,0x3f803000u,0xbf801000u,0x33800000u,0x33000000u,0x477fe000u,0xc77fe000u};
const uint16_t half[]={0,0x8000,0x3c00,0x3c00,0x3c02,0xbc00,1,0,0x7bff,0xfbff};
std::vector<float>kv(512);std::vector<uint16_t>want(512);for(int i=0;i<512;++i){std::memcpy(&kv[i],&bits[i%10],4);want[i]=half[i%10];}
Buffer<float>k(kv),v(kv);Buffer<uint16_t>kh(512),vh(512),wk(512),wv(512);Buffer<int>st(step(0));
oracle_pack(k.p,v.p,wk.p,wv.p,st.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_pack_kv",2,1,256,0,{&k.p,&v.p,&kh.p,&vh.p});
exact("pack_original_k",wk.get(),kh.get());exact("pack_literal_k",want,kh.get());exact("pack_original_v",wv.get(),vh.get());
}
static void indexer(){
Buffer<float>g(norm_weights(128)),tail(384),dead(128),pool(384);Buffer<int>bpos(1);
std::vector<float>prior(512,0.0f);
for(unsigned p=0;p<8;++p){auto input=values(128,p+9);Buffer<float>x(input),old(prior),next(640);Buffer<int>position(std::vector<int>{int(p)});
oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&old.p,&next.p,&p});
auto got=next.get(),wt=tail.get(),wd=dead.get(),wp=pool.get();std::vector<float>want=wt;want.insert(want.end(),wd.begin(),wd.end());
size_t row=p==0?0:p%4==3?p/4+0:(p+1)/4;
want.insert(want.end(),wp.begin()+row*128,wp.begin()+(row+1)*128);
exact("index_append_"+std::to_string(p),want,got);prior.assign(got.begin(),got.begin()+512);
}}
static std::vector<float> retained_words(const std::string&name){
std::vector<float>v(640);std::ifstream f(retained+"/"+name,std::ios::binary);
f.read(reinterpret_cast<char*>(v.data()),2560);if(!f||f.peek()!=std::ifstream::traits_type::eof())throw std::runtime_error("retained fixture extent");return v;
}
static void repaired_indexer(){
// Restore the independently proven prior at6; no operator0..6 is relaunched.
auto previous=retained_words("index_append_6.want"),first_block=retained_words("index_append_3.want");
std::vector<float>old(previous.begin(),previous.begin()+512),tail_words(old.begin(),old.begin()+384),dead_words(old.begin()+384,old.end()),pool_words(384,0);
std::copy(first_block.begin()+512,first_block.end(),pool_words.begin());std::copy(dead_words.begin(),dead_words.end(),pool_words.begin()+128);
Buffer<float>g(norm_weights(128)),tail(tail_words),dead(dead_words),pool(pool_words),x(values(128,16)),prior(old),next(640);
Buffer<int>bpos(1),position(std::vector<int>{7});unsigned p=7;
oracle_index(x.p,g.p,position.p,tail.p,dead.p,pool.p,bpos.p,stream);rt(cudaStreamSynchronize(stream));
launch(0,"leleka_qsa_index_append",1,1,256,0,{&x.p,&g.p,&prior.p,&next.p,&p});
auto want=tail.get(),wd=dead.get(),wp=pool.get();want.insert(want.end(),wd.begin(),wd.end());want.insert(want.end(),wp.begin()+128,wp.begin()+256);
exact("index_append_7_repaired",want,next.get());
}
static std::vector<int> cpu_ids(const std::vector<float>&scores,unsigned n){
std::vector<int>ids(n);std::iota(ids.begin(),ids.end(),0);
std::stable_sort(ids.begin(),ids.end(),[&](int a,int b){float x=scores[a/4],y=scores[b/4];return x==y?a<b:x>y;});
ids.resize(std::min(n,2051u));std::sort(ids.begin(),ids.end());return ids;
}
static void selection(){for(unsigned n:{1u,4u,7u,2051u,2052u,2053u,4096u,262144u}){unsigned p=n-1;size_t blocks=n/4+1;
Buffer<float>k(values(blocks*128,3)),dead(values(128,7)),q(values(512,19)),w(blocks),y(blocks);Buffer<int>st(step(p)),wid(2051),id(2051);
oracle_scores(k.p,dead.p,q.p,st.p,blocks,w.p,stream);rt(cudaStreamSynchronize(stream));
launch(1,"leleka_qsa_block_scores",256,1,256,0,{&k.p,&dead.p,&q.p,&y.p,&p});auto scores=y.get();
exact("scores_"+std::to_string(n),w.get(),scores);
oracle_topk(w.p,st.p,blocks,wid.p,stream);rt(cudaStreamSynchronize(stream));
launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});auto got=id.get(),want=wid.get();got.resize(std::min(n,2051u));want.resize(got.size());
exact("topk_source_"+std::to_string(n),want,got);exact("topk_independent_"+std::to_string(n),cpu_ids(scores,n),got);
// Literal all-equal block scores force lowest-ID ties even at the truncation boundary.
std::vector<float>ties(blocks,0.0f);y.set(ties);launch(1,"leleka_qsa_block_topk",1,1,256,0,{&y.p,&id.p,&p});got=id.get();got.resize(std::min(n,2051u));
std::vector<int>literal(got.size());std::iota(literal.begin(),literal.end(),0);exact("topk_literal_tie_"+std::to_string(n),literal,got);
}}
static double half_double(uint16_t x){return double(__half2float(__ushort_as_half(x)));}
static void attention(){for(unsigned width:{1u,7u,257u,2051u}){
auto query=values(6144,11);std::vector<uint16_t>k(size_t(width)*512),v(k.size());
const uint16_t kb[]={0x0000,0x3400,0xb800,0x3a00,0xbc00,0x3800};
const uint16_t vb[]={0x3c00,0xbc00,0x4000,0xb800,0x3400,0x4200};
for(size_t i=0;i<k.size();++i){k[i]=kb[(i*7+i/256)%6];v[i]=vb[(i*11+i/512)%6];}
if(width==1){for(int d=0;d<256;++d){v[d]=0x4200;v[256+d]=0xc700;}}
Buffer<float>q(query),w(6144),y(6144);Buffer<uint16_t>dk(k),dv(v);Buffer<int>st(step(width-1));
oracle_attention(q.p,dk.p,dv.p,st.p,w.p,stream);rt(cudaStreamSynchronize(stream));
launch(2,"leleka_qsa_attend",24,1,256,(2051+32)*4,{&q.p,&dk.p,&dv.p,&y.p,&width});auto got=y.get();exact("attention_source_"+std::to_string(width),w.get(),got);
std::vector<double>reference(6144),scores(width);
for(int h=0;h<24;++h){int kv=h/12;
for(unsigned j=0;j<width;++j){double dot=0;for(int d=0;d<256;++d)dot+=half_double(k[(size_t(j)*2+kv)*256+d])*double(query[h*256+d]);scores[j]=dot/16.0;}
double maximum=*std::max_element(scores.begin(),scores.end()),den=0;for(double&s:scores){s=std::exp(s-maximum);den+=s;}for(double&s:scores)s/=den;
for(int d=0;d<256;++d){double a=0;for(unsigned j=0;j<width;++j)a+=scores[j]*half_double(v[(size_t(j)*2+kv)*256+d]);reference[h*256+d]=a;}
}
raw("attention_double_"+std::to_string(width)+".want",reference.data(),reference.size()*8);
double diff=0,mag=0;for(size_t i=0;i<got.size();++i){if(!std::isfinite(got[i]))throw std::runtime_error("nonfinite attention");diff+=std::abs(reference[i]-double(got[i]));mag+=std::abs(reference[i]);}
double rel=diff/(mag==0?1:mag);std::printf("DOUBLE attention width=%u relL1=%.17g limit=1e-5\n",width,rel);if(rel>1e-5)throw std::runtime_error("attention double tolerance");++cases;
}}
static void gate(){
const float literals[]={-1000,-100,-1,-0.0f,0.0f,1,100,1000};auto a=values(6144,21);std::vector<float>gate(6144),full(12288,777);
for(int h=0;h<24;++h)for(int d=0;d<256;++d){float x=literals[(h+d)%8];gate[h*256+d]=x;full[h*512+256+d]=x;}
Buffer<float>x(a),g(gate),f(full),w(6144),y(6144);
oracle_gate(x.p,f.p,w.p,stream);rt(cudaStreamSynchronize(stream));launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&g.p,&y.p});exact("gate_native_f32_saturation",w.get(),y.get());
}
static void invalid(){
auto a=values(6144,2);a[0]=std::numeric_limits<float>::quiet_NaN();Buffer<float>x(a),g(norm_weights(256)),y(6144);
launch(0,"leleka_qsa_norm_q",24,1,256,0,{&x.p,&g.p,&y.p});auto out=y.get();for(int d=0;d<256;++d)if(!std::isnan(out[d]))throw std::runtime_error("norm NaN hidden");++cases;std::puts("PASS invalid_norm_row_nan");
auto gate=values(6144,3);gate[19]=std::numeric_limits<float>::infinity();Buffer<float>gg(gate);
launch(3,"leleka_qsa_gate_f32",24,1,256,0,{&x.p,&gg.p,&y.p});out=y.get();if(!std::isnan(out[0])||!std::isnan(out[19]))throw std::runtime_error("gate invalid hidden");++cases;std::puts("PASS invalid_gate_nan_inf");
}
int main(int argc,char**argv){try{
if(argc<3||argc>5)throw std::runtime_error("Usage: qsa_oracle ASSET_DIRECTORY PRIVATE_OUTPUT_DIRECTORY [group [RETAINED_PROOF_DIRECTORY]]");output=argv[2];std::string group=argc>=4?argv[3]:"all";
if(group=="repair"){if(argc!=5)throw std::runtime_error("repair requires retained prior-proof directory");retained=argv[4];}
rt(cudaSetDevice(0));rt(cudaFree(nullptr));drv(cuInit(0));rt(cudaStreamCreate(&stream));
const char*asset[]={"qwen_qsa_native.ptx","qwen_qsa_select.ptx","qwen_qsa_attention.ptx","qwen_qsa_attention_native.ptx"};
for(int i=0;i<4;++i)drv(cuModuleLoad(&modules[i],(std::string(argv[1])+"/"+asset[i]).c_str()));
cudaDeviceProp prop;rt(cudaGetDeviceProperties(&prop,0));int driver=0;rt(cudaDriverGetVersion(&driver));std::printf("DEVICE %s cc=%d.%d driver=%d\n",prop.name,prop.major,prop.minor,driver);
auto enabled=[&](const char*s){return group=="all"||group==s;};
if(enabled("norm"))norms();if(enabled("rope"))ropes();if(enabled("pack"))split_pack();if(enabled("index"))indexer();if(enabled("select"))selection();if(enabled("attention"))attention();if(enabled("gate"))gate();if(enabled("invalid"))invalid();
if(group=="repair"){ropes(true);repaired_indexer();}
for(auto m:modules)drv(cuModuleUnload(m));rt(cudaStreamDestroy(stream));std::printf("RESULT PASS cases=%u exact_words=%llu\n",cases,(unsigned long long)words);return 0;
}catch(const std::exception&e){std::fprintf(stderr,"RESULT FAIL %s\n",e.what());return 1;}}
@@ -1,10 +0,0 @@
#include "../../engine/strata/src/kernels/cuda/qsa.cu"
extern "C" void oracle_pack(const float*k,const float*v,uint16_t*kp,uint16_t*vp,const int*step,cudaStream_t s) {
// One-page geometry makes original cache append a contiguous two-head pack.
int*table; cudaMalloc(&table,4); const int zero=0; cudaMemcpy(table,&zero,4,cudaMemcpyHostToDevice);
strata::kernels::kv_append_kernel<<<2,256,0,s>>>(kp,vp,table,step,k,v,2,256,1,{});
cudaStreamSynchronize(s); cudaFree(table);
}
extern "C" void oracle_attention(const float*q,const uint16_t*k,const uint16_t*v,const int*step,float*y,cudaStream_t s) {
strata::kernels::qsa_attend_kernel<<<24,256,(2051+32)*4,s>>>(q,k,v,step,24,2,256,y,nullptr);
}
-5
View File
@@ -1,5 +0,0 @@
#include "../../engine/strata/src/kernels/cuda/native_qsa_indexer.cu"
extern "C" void oracle_index(const float*x,const float*g,const int*p,float*tail,float*dead,float*pool,int*bpos,cudaStream_t s) {
strata::kernels::QsaIndexerBuffers b{tail,dead,pool,bpos};
strata::kernels::native_qsa_indexer_append(x,p,0,g,1e-6f,b,strata::kernels::qsa_real_shapes(),8,strata::kernels::RopeScaling{},s);
}
-8
View File
@@ -1,8 +0,0 @@
// Test only: the original implementation is an independent translation unit.
#include "../../engine/strata/src/kernels/cuda/native_qsa.cu"
extern "C" void oracle_norm(const float*x,const float*g,float*y,int c,int n,cudaStream_t s) {
strata::kernels::native_qsa_rms_norm_weighted(x,g,y,c,n,1e-6f,s);
}
extern "C" void oracle_gate(const float*x,const float*full,float*y,cudaStream_t s) {
strata::kernels::native_qsa_gate_apply(x,full,y,24,256,s);
}
-4
View File
@@ -1,4 +0,0 @@
#include "../../engine/strata/src/kernels/cuda/native_rope.cu"
extern "C" void oracle_rope(const float*x,float*y,int c,int n,const int*p,cudaStream_t s) {
strata::kernels::native_rope_apply(x,y,n,c,64,strata::kernels::RopeScaling{},p,s);
}
-8
View File
@@ -1,8 +0,0 @@
#include "../../engine/strata/src/kernels/cuda/qsa_select.cu"
extern "C" void oracle_scores(const float*k,const float*d,const float*q,const int*step,int64_t blocks,float*y,cudaStream_t s) {
// Select exactly the original deterministic multi-query warp path, nq=1.
strata::kernels::block_scores_multi_kernel<<<256,256,0,s>>>(k,d,q,step,1,blocks,y);
}
extern "C" void oracle_topk(const float*x,const int*step,int64_t blocks,int*y,cudaStream_t s) {
strata::kernels::block_topk_kernel<<<1,256,0,s>>>(x,step,blocks,2051,y);
}
-65
View File
@@ -1,65 +0,0 @@
101eec0eba8c5afff046d5040c6d5044f7aaf82ceae5c19832925e070a1c8e01 crates/engine-qwen35-cuda/src/model_binding/weight_binding/qsa.rs
ed281c74a39e07f58d23a22be195fffce4a8840840dc767a0bef2ff0b7683b6c crates/engine-qwen35-cuda/src/qwen_forward/qsa_index.rs
cc996a7f1a0f56adbbcd6d514fe6ba4a4d06c3ce5c244f24b4acc11bf0a0214c crates/engine-qwen35-cuda/src/qwen_forward/qsa_attention.rs
78ab8d9240963876e2a1578f845894cd38af148a37242a2dfc9a8668afeb1bc6 crates/cuda-driver/assets/qwen_qsa_attention.cu
91219cfbc1a77c4bb66661060ac939a50dc4c4d7d4db8d50bc59fbcd167562b2 crates/cuda-driver/assets/qwen_qsa_attention.ptx
6b90b748df610f26a40b82ebbacdebd15d35252c3feb76ea1aaad0ed519db22a crates/cuda-driver/assets/qwen_qsa_attention_native.cu
7772e4e75d78a9910144ca108551800fd4296955781540afb65f53d612d7e1f3 crates/cuda-driver/assets/qwen_qsa_attention_native.ptx
35e3672926fe27fed13f9e560163d7a4cf89e827c6256a3ede71f487c7f85ab5 crates/cuda-driver/assets/qwen_qsa_native.cu
d60489fb70ce4370047bf54fae8dd46dfb53bb73b1618c58942932a789d064c5 crates/cuda-driver/assets/qwen_qsa_native.ptx
03df9d4d42cf742e4e06068d30bfc30bf7303fee188fad456b53a0788c4f1a7f crates/cuda-driver/assets/qwen_qsa_select.cu
e094e10f84cca612ca28596aa394ee999e33fe7bc84b359bfab6da0730d4a519 crates/cuda-driver/assets/qwen_qsa_select.ptx
a9f47aa583e656757e4b81830143e05cac1a8266fb22cee085663732d5c6948a engine/strata/src/kernels/cuda/native_qsa.cu
21cc2bc7c84254811fc0ff66c8b995d2c3a5abf91260068f7ae6767d5e217ab2 engine/strata/src/kernels/cuda/native_rope.cu
bc46a3a289a4decc400fe1db05b54879dac4c3cd1a91634c18a08dbd2f71360a engine/strata/src/kernels/cuda/native_qsa_indexer.cu
b579d6f9e3829407b9f31153790b11bba3186ec687a27d81d0c32e65ce429894 engine/strata/src/kernels/cuda/qsa_select.cu
dc7ff0992355ec744bcdcb919f50cf8925a340438e0c5209ae917177d938295a engine/strata/src/kernels/cuda/qsa.cu
5e7c6b5fed22f8681e96203d42ca9c9368b9075c8568e5144c5811d5c9d997a3 engine/strata/src/kernels/qsa_parity.cpp
813b51f17c5c264d642f4d77b3d6e5f35e7ea7310ba87b18b3a2a5bc9185198f engine/strata/include/strata/kernels/bf16_bits.hpp
402538e5405d93e6617997ffa45561e259e01bf3d7b00ffca5379721ff4a71f3 engine/strata/include/strata/kernels/bf16_gemv.hpp
34e0a44c41392634451d4d676a0035623b205cf2952685aa1946b4df78dd5a65 engine/strata/include/strata/kernels/cvec.hpp
6b49ba8f050e6684caa57879f14657c5453078a3ccb8f963432ea3049a4178ca engine/strata/include/strata/kernels/dequant_bf16.hpp
d8f3aa8d610887451f177f05ada1135d52daf21b95a8c2c58686c07403c8013d engine/strata/include/strata/kernels/dequant_s2.hpp
05404993da1f077653a1dbf2dc54278b03821dfc3fe31ae1b963d30e94e95cf9 engine/strata/include/strata/kernels/dp4a.hpp
2f57555de85d267391036e2693f215cd3ec3b1b4af243654120781ca640a86df engine/strata/include/strata/kernels/elementwise.hpp
0f74e6dd832da427b681c9971265a0af1a91198694fdef3654d860b98863fc8c engine/strata/include/strata/kernels/f16_bits.hpp
595205dcf531d8fb758bcd7b2d3ac4e4158bd06f20160199e592824d530e2078 engine/strata/include/strata/kernels/fused_gdn.hpp
0506a16f95e4f0ab05dab62619d642598282677a126efa05303a8b278b712360 engine/strata/include/strata/kernels/fused_gr.hpp
f44626e3f52813b9be289aee72f708e9ad61aa9b3a0e43037ba5ff8b358fc638 engine/strata/include/strata/kernels/gdn.hpp
2a5bbba0ea74752dceba2e14bcf5e7c470dd69dd74e533a3e2e9aa76804ef74e engine/strata/include/strata/kernels/gr.hpp
2b8f5a08be7c7a501e8af7103d7d3ce412295c4467bbfd08b8dc0d02cea7c70d engine/strata/include/strata/kernels/iq_kernels.hpp
c7624d5567d464edd0e5e99951dca08f8a748545af2f0be4f18398a011c8ab89 engine/strata/include/strata/kernels/kv_q4.hpp
8917232c10900e85a6193012d2cc56138c7ab000c01d964bc9d296cf2b2e4bb6 engine/strata/include/strata/kernels/kv_q8.hpp
1ba39fb94fd3425cdaaa86b62e659567b8d09c8d190b8a1cfd832bc5f0ef0de6 engine/strata/include/strata/kernels/kv_stream.hpp
92d153fcedd6fcb747fee61fb0e01c3adb0c36e205154255b81e4337cb782402 engine/strata/include/strata/kernels/mrope.hpp
6cc7bb288fc263ee800f5b5329bcc8d139ddde7e31a022364850cf80b1e5f7ff engine/strata/include/strata/kernels/native_flash_attn.hpp
2b65e1b5b689c06d099bc061d746d606dcc5b974a7bffe0820ce01e7295d1971 engine/strata/include/strata/kernels/native_gdn.hpp
7533d8464b6ae8e2800e43ee3036d23f21181c2472c069d19bacf115beeafc69 engine/strata/include/strata/kernels/native_gdn_preprocess.hpp
520230cbf749a13c4f91687da31c0136fdcb2f14d4e4f956c38334d0e2cf742c engine/strata/include/strata/kernels/native_gr_norm.hpp
572867fecf55294f99251e679b934bb6ce63e2162f9c5c0e27bcec167a74d0f6 engine/strata/include/strata/kernels/native_gr_postops.hpp
283d882a96e1f22d97ee170bd0c8bca5cc226ab5f82fa1df133c8fd901efe487 engine/strata/include/strata/kernels/native_mmvq.hpp
b8400379c2f0deea4f440a2aeb343d45377f4a334bf4b1c8eb8aa933eaace51f engine/strata/include/strata/kernels/native_moe.hpp
eeeec9650c6e19402dcec9c4c807ff5a62f0b64b4a3ad86e6a286489ee7af091 engine/strata/include/strata/kernels/native_ple_postops.hpp
ef43d79914eb433458e2b212a9733e6a0e15be115aa156675d18a8d012c66387 engine/strata/include/strata/kernels/native_qsa.hpp
d040ccbef7943f16c7ce99d8070979b555a8c740950a6f53945b7199226d3fc3 engine/strata/include/strata/kernels/native_qsa_indexer.hpp
d57ba2509e97093ed2bfa3cbe73886407211a5d476a0b629ed925dd992369354 engine/strata/include/strata/kernels/native_qsa_score.hpp
550e8640263e0fbf2319e0d26426371b917eb34b6a24d3d672d502ff94717040 engine/strata/include/strata/kernels/native_rope.hpp
e5e0a529c11235080ec541cdc65a1ac1c0dba8eb994cf5373609fc8985311502 engine/strata/include/strata/kernels/native_router.hpp
b77415af3194a3181b7491bcbe22f4660b4f59d54d061edc486e6da4f10a9996 engine/strata/include/strata/kernels/ngram.hpp
d658e7186f1e81a8b183a583b5fa6bfaf228042cda4e88aa1c41ada260db6b12 engine/strata/include/strata/kernels/ple.hpp
87c02222284f842fcecb46a422b119af769c72c3914edc8da5b2ee782456dc74 engine/strata/include/strata/kernels/qsa.hpp
9450de49e491cdf59f315bbdd2abfbe7b0b761d4638c224339913626709e3485 engine/strata/include/strata/kernels/qsa_decode_attn.hpp
c49066bcb4e9d84ca7e374680c453e226cdc2efa2ec02262561a5f8f228bc35f engine/strata/include/strata/kernels/qsa_prompt_attn.hpp
eb3d61f08249db03c9d2212082c285de954c34f58d711e8cd8f6dce9d259e2a8 engine/strata/include/strata/kernels/qsa_select.hpp
baad6fe6c691f8f5aee2d6dbbb3513eead12c754b485ee41af4618d5035772f7 engine/strata/include/strata/kernels/quantize_act.hpp
bd9094c0f0f761971a6760fde2b84a5660c934ce9a654dc287c686acd284a65a engine/strata/include/strata/kernels/rope.hpp
05a8dcf57c9b12a23128f22e4bef01445c3a37991df5e1ffacd01d077c46595d engine/strata/include/strata/kernels/rope_scaling.hpp
cd0d8e91e702bfa2cfd681d4ccf4f6c4c62af2cd612d2d109e5369845ddf362d engine/strata/include/strata/kernels/router_top10.hpp
74802f312c20daa90b7fbacba4a3357c8e94c7ecdab75f402be507dd303a8193 engine/strata/include/strata/kernels/s2_expert_grouped.hpp
cc146b9c652f1ee0c89be65ce179ea4cb31d4b4d32366c07f06b45644bbb8eb0 engine/strata/include/strata/kernels/s2_gemv.hpp
5c2ccbdc5b3f3a66b9afef5bc799ae2a83bcb2103b258bb84e8d82aad06b4eb1 engine/strata/include/strata/kernels/s2_gemv_q8.hpp
369ab6cc010b49ac1d82bb680246e93b4c10f4f7081f56a325f6c7138ab1c3fb engine/strata/include/strata/kernels/s_gemv.hpp
89f0889563938cb12aa75744f6342e22de3f4d641c2e645ea5a8b609f062f841 engine/strata/include/strata/kernels/sampler.hpp
9f49d44286650219f488dea3fbe0474b009498e88921cc3ef806e87c372da8e2 engine/strata/include/strata/kernels/shared_expert.hpp
54e349fe4ab994f57a15ae8c15f81c3778652aa881ce6d25aa4136670bfa9ba7 engine/strata/include/strata/kernels/verify_kernels.hpp
eb3df4efe89642f069420e0f68ec526b33d4cc66f9a6b26de0583492b5758a77 engine/strata/include/strata/core/emulate.hpp

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