diff --git a/.github/workflows/docker-images.yml b/.github/workflows/docker-images.yml index e72c8e99..ac0bf8a4 100644 --- a/.github/workflows/docker-images.yml +++ b/.github/workflows/docker-images.yml @@ -13,7 +13,7 @@ on: workflow_dispatch: inputs: release_tag: - description: 'Release tag whose engine packages go into the images (for example v0.2.3)' + description: 'Release tag whose engine packages go into the images (for example v0.2.7)' required: true type: string flavors: diff --git a/docker/Dockerfile b/docker/Dockerfile index ed4b09bc..44efa5f4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -5,13 +5,13 @@ # # Build it with docker/build.sh (it assembles the build context: the Terminal sources and the package folder): # -# docker/build.sh --flavor cuda --engine /path/to/0.1.45.3-linux-x86_64-cuda-cuda13 --tag strata:0.2.3-cuda13 +# docker/build.sh --flavor cuda --engine /path/to/0.1.45.3-linux-x86_64-cuda-cuda13 --tag strata:0.2.7-cuda13 # # Plain `docker build` also works when the context folder has this layout (build.sh makes it): # terminal-src/ the files package_terminal.py needs (packaging/, strata_cli/, strata_control/, serve/, tools/, data/, ...) # engine/ one folder per engine package, exactly as `package_engine.py` wrote it (engine-component.json inside) # docker/ entrypoint.sh, strata-wrapper.sh, healthcheck.sh -# docker build --build-arg FLAVOR=cuda -t strata:0.2.3-cuda13 -f Dockerfile +# docker build --build-arg FLAVOR=cuda -t strata:0.2.7-cuda13 -f Dockerfile # # FLAVOR picks the small set of system libraries the runtime image adds and its base: # cuda NVIDIA: the engine package carries cudart/cublas; the driver's libcuda comes from nvidia-container-toolkit diff --git a/docker/build.sh b/docker/build.sh index 3048b8bc..94f820b3 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -2,9 +2,9 @@ # Build a Strata image from an engine component package. Run it on a Linux x86_64 machine with Docker (it needs the internet # for the base image and for the Terminal's pinned Python and locked wheels; the engine package is local). # -# docker/build.sh --flavor cuda --engine ~/pkgs/0.1.45.3-linux-x86_64-cuda-cuda13 --tag strata:0.2.3-cuda13 -# docker/build.sh --flavor hip --engine ~/pkgs/0.1.45.3-linux-x86_64-hip-gfx120X --tag strata:0.2.3-rocm-gfx120x -# docker/build.sh --flavor sycl --engine ~/pkgs/0.1.45.3-linux-x86_64-sycl --tag strata:0.2.3-sycl +# docker/build.sh --flavor cuda --engine ~/pkgs/0.1.45.3-linux-x86_64-cuda-cuda13 --tag strata:0.2.7-cuda13 +# docker/build.sh --flavor hip --engine ~/pkgs/0.1.45.3-linux-x86_64-hip-gfx120X --tag strata:0.2.7-rocm-gfx120x +# docker/build.sh --flavor sycl --engine ~/pkgs/0.1.45.3-linux-x86_64-sycl --tag strata:0.2.7-sycl # # --engine is the package FOLDER that packaging/package_engine.py wrote (engine-component.json inside). It can be given more than # once to put several packages in one image (the Terminal picks the one that fits the card). diff --git a/docker/compose/.env.example b/docker/compose/.env.example index 4fb20560..5cf47826 100644 --- a/docker/compose/.env.example +++ b/docker/compose/.env.example @@ -1,5 +1,5 @@ # Copy to .env next to the compose file you use. Every line is optional. -# STRATA_IMAGE=strata:0.2.3-cuda13 # only to use an image you built yourself (docker/build.sh); the default is the published ghcr.io/niko1221/strata image +# STRATA_IMAGE=strata:0.2.7-cuda13 # only to use an image you built yourself (docker/build.sh); the default is the published ghcr.io/niko1221/strata image # MODEL=IQ3_XXS # MODEL_PATH=/models # with a volume line - /srv/gguf/IQ3_XXS:/models:ro # CONTEXT=32k diff --git a/docker/compose/docker-compose.amd.yml b/docker/compose/docker-compose.amd.yml index e89e0639..fac80806 100644 --- a/docker/compose/docker-compose.amd.yml +++ b/docker/compose/docker-compose.amd.yml @@ -4,10 +4,10 @@ # cp .env.example .env # docker compose -f docker-compose.amd.yml up -d # -# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.3- docker compose up -d +# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.7- docker compose up -d services: strata: - image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.3-rocm-gfx120x} + image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.7-rocm-gfx120x} container_name: strata restart: unless-stopped ports: diff --git a/docker/compose/docker-compose.intel.yml b/docker/compose/docker-compose.intel.yml index 60eac13b..5c5ded76 100644 --- a/docker/compose/docker-compose.intel.yml +++ b/docker/compose/docker-compose.intel.yml @@ -4,10 +4,10 @@ # cp .env.example .env # docker compose -f docker-compose.intel.yml up -d # -# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.3- docker compose up -d +# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.7- docker compose up -d services: strata: - image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.3-sycl} + image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.7-sycl} container_name: strata restart: unless-stopped ports: diff --git a/docker/compose/docker-compose.nvidia.yml b/docker/compose/docker-compose.nvidia.yml index b2550ec2..72a5bcc8 100644 --- a/docker/compose/docker-compose.nvidia.yml +++ b/docker/compose/docker-compose.nvidia.yml @@ -5,10 +5,10 @@ # docker compose -f docker-compose.nvidia.yml logs -f # the first start downloads the model (resumable) # # Image: cuda13 for RTX 20-50 with driver 580 or newer; cuda12 for Pascal / Volta (GTX 10, Tesla P100, V100) or drivers 575-579. -# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.3- docker compose up -d +# Images: ghcr.io/niko1221/strata (published from 0.2.1 on). To use one you built yourself: STRATA_IMAGE=strata:0.2.7- docker compose up -d services: strata: - image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.3-cuda13} + image: ${STRATA_IMAGE:-ghcr.io/niko1221/strata:0.2.7-cuda13} container_name: strata restart: unless-stopped ports: diff --git a/docker/fetch-engines.py b/docker/fetch-engines.py index f6112e08..042d6e1c 100644 --- a/docker/fetch-engines.py +++ b/docker/fetch-engines.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 """Fetch the engine packages for the Docker images from a release, checked against the signed update feed. - python3 docker/fetch-engines.py --release-tag v0.2.3 --flavors cuda13,cuda12,rocm-gfx120x --out ./pkgs + python3 docker/fetch-engines.py --release-tag v0.2.7 --flavors cuda13,cuda12,rocm-gfx120x --out ./pkgs python3 docker/fetch-engines.py --source /path/to/release-folder --flavors cuda13 --out ./pkgs - python3 docker/fetch-engines.py --release-tag v0.2.3 --list + python3 docker/fetch-engines.py --release-tag v0.2.7 --list What it does, in the same order and with the same code as `strata update`: @@ -98,7 +98,7 @@ def fetch_one(feed: feedmod.Feed, pkg: feedmod.EnginePackage, out: Path, trusted def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - ap.add_argument("--release-tag", help="the GitHub release tag, for example v0.2.3") + ap.add_argument("--release-tag", help="the GitHub release tag, for example v0.2.7") ap.add_argument("--repo", default="Niko1221/Strata", help="owner/name of the GitHub repository (default %(default)s)") ap.add_argument("--source", help="a release folder or base URL holding strata-feed.json(.sig) and the archives (instead of --release-tag)") ap.add_argument("--flavors", default=",".join(FLAVORS), help="comma separated; default: all (%s)" % ", ".join(FLAVORS)) diff --git a/docker/publish.sh b/docker/publish.sh index b8d2906e..989cefa2 100755 --- a/docker/publish.sh +++ b/docker/publish.sh @@ -2,9 +2,9 @@ # Build the Strata images of one release from its engine packages and, only with --push, push them to the registry. # The GitHub Actions workflow (.github/workflows/docker-images.yml) runs this script once per flavor; you can run it by hand too. # -# docker/publish.sh --release-tag v0.2.3 # builds every flavor the release has a package for; pushes nothing -# docker/publish.sh --release-tag v0.2.3 --flavors cuda13,cuda12 --push -# docker/publish.sh --source ~/release-folder --version 0.2.3-test --flavors cuda13 --no-latest +# docker/publish.sh --release-tag v0.2.7 # builds every flavor the release has a package for; pushes nothing +# docker/publish.sh --release-tag v0.2.7 --flavors cuda13,cuda12 --push +# docker/publish.sh --source ~/release-folder --version 0.2.7-test --flavors cuda13 --no-latest # # For every flavor: # 1. docker/fetch-engines.py downloads the engine package from the release (a GitHub release URL, or --source) and checks it @@ -15,7 +15,7 @@ # 4. with --push: docker push of :- and, unless --no-latest, :latest-. You must be logged in # to the registry already (`docker login ghcr.io`; the workflow logs in with GITHUB_TOKEN). # -# --release-tag TAG the release, for example v0.2.3; the image version is the tag without the leading v +# --release-tag TAG the release, for example v0.2.7; the image version is the tag without the leading v # --source DIR|URL use this folder or URL (with strata-feed.json, its .sig and the archives) instead of the GitHub release # --version V image version (default: the tag without v) # --flavors LIST comma separated (default: all that the release has: cuda13 cuda12 rocm-gfx120x rocm-gfx110x rocm-gfx1151 sycl) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 5a762381..14c3f844 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -1019,7 +1019,7 @@ them on your own card. | `STRATA_PREFILL_EQUAL=1` | CUDA | A prompt segment is read in chunks of equal size, not full chunks and a short last one. Changes rounding. | | | `STRATA_OWNED_PRICE=exact` | CUDA | The cache sizing prices the prompt path's own buffers by their real allocation. | | | `STRATA_IQ_MT_MIN=1`, `STRATA_IQ3S_MT1=1` | CPU | See [Draft layer](#draft-layer) (reproducible output; the second gives IQ3_S the multi-token kernel for one token on Alder Lake and later without AVX-512). | | -| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=1.5` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards; the first 0.2.7 candidates used 2.0, see the 12 GB default in the release notes for why it is 1.5); `STRATA_ROUTE_PRIOR=0` turns it off and an explicit value wins. It is never a default on a Radeon, an integrated GPU or a bigger card. | +| `STRATA_ROUTE_PRIOR`, `STRATA_ROUTE_RESIDENT`, `STRATA_ROUTE_RESIDENT_MTP` | CUDA | Routing changes that add speed and also add KL. | Not recommended, except that 0.2.7 turns `STRATA_ROUTE_PRIOR=1.5` on by itself on a discrete NVIDIA card of 13 GiB or less (the owner approved the quality trade for 12 GB cards; the first 0.2.7 candidates used 2.0, see the 12 GB default in the release notes for why it is 1.5); `STRATA_ROUTE_PRIOR=0` turns it off and an explicit value wins. It is never a default on a Radeon, an integrated GPU or a bigger card. The 1.5 default was checked with 61 tasks on an RTX 3060 12 GB (IQ3_XXS): no copy, code-constant, JSON-spelling, retrieval or unanswerable defects (retrieval 12/12, JSON 3/3, unanswerable 9/9, extraction equal to off), and two long-winded answers (a rambling agent paragraph, a code answer cut off in a comment); the runs with the prior off show two or three such cases each. Speed against off: story +15%, code +37%. | | `STRATA_HOST_CORE=last\|sibling` (or `--host-core`) | Windows | `last` puts the host thread on the last physical core, away from the core that gets the GPU's interrupts. `sibling` keeps it on the first core's other hardware thread, so the workers keep every core. The default `first` leaves a hybrid CPU as it is. | One layer-split box went from a ±6% swing to steady and 8% faster. | | `--pool-affinity measure` | Hybrid CPUs, native packs | Times the `all` and `p-cores` layouts at start (about a second) and takes the faster. The measurement is taken once; where the E-cores' speed changes while the engine runs, `--pool-affinity p-cores` is the steady choice. | | | `STRATA_KEEP_EMPTY_TURNS=1`, `STRATA_TOPK_STREAM=0` | | See [TROUBLESHOOTING.md](TROUBLESHOOTING.md). | | @@ -1222,7 +1222,7 @@ On 12.0 cards (sm_120) these also apply: prompt time and start-up time, which is why smaller PCs keep the SSD reads. A prompt chunk above 8192 (`--prefill auto:16384` or `auto:32768`) is not bit-exact on CUDA, so the default stays 8192 on -NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 1.5 by itself only on a discrete NVIDIA card of 13 GiB or less. +NVIDIA. It is exact on gfx12, where 16384 is the default. `STRATA_ROUTE_PRIOR` raises KL, so below 0.2.7 it was opt-in; 0.2.7 sets 1.5 by itself only on a discrete NVIDIA card of 13 GiB or less. A 61-task check of 1.5 on an RTX 3060 found no copy, constant, spelling or retrieval defects and two long-winded answers (the prior off has two or three per run); story +15%, code +37%. --- diff --git a/docs/DOCKER.md b/docs/DOCKER.md index d0825fd6..8b6ea78e 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -17,12 +17,12 @@ Docker on a **Mac** has no access to the Mac's graphics chip (no Metal): use the | Your graphics card | Image tag | Needs on the computer | | --- | --- | --- | -| NVIDIA **RTX 20, 30, 40, 50** series (and the matching RTX A / Quadro cards) | `0.2.3-cuda13` | NVIDIA driver **580 or newer**, [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) | -| NVIDIA **GTX 10 (Pascal), Tesla P100, V100 (Volta)**, or any NVIDIA card whose driver is **575 to 579** | `0.2.3-cuda12` | NVIDIA driver **575 or newer**, the same toolkit | -| AMD **RX 9000** series and Radeon AI PRO R9700 (RDNA 4, gfx1200 / gfx1201) | `0.2.3-rocm-gfx120x` | the `amdgpu` kernel driver (Linux 6.8+) | -| AMD **RX 7000** series (RDNA 3, gfx1100 / gfx1101 / gfx1102) | `0.2.3-rocm-gfx110x` | the `amdgpu` kernel driver | -| AMD **Ryzen AI Max** ("Strix Halo", Radeon 8060S, gfx1151) | `0.2.3-rocm-gfx1151` | the `amdgpu` kernel driver | -| Intel **Arc** A-series and B-series (including Arc Pro B70) | `0.2.3-sycl` (if no image exists for a release, [build it](#build-it-yourself)) | the `i915` or `xe` kernel driver; **prepared model files** (see [Intel](#intel-arc)) | +| NVIDIA **RTX 20, 30, 40, 50** series (and the matching RTX A / Quadro cards) | `0.2.7-cuda13` | NVIDIA driver **580 or newer**, [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) | +| NVIDIA **GTX 10 (Pascal), Tesla P100, V100 (Volta)**, or any NVIDIA card whose driver is **575 to 579** | `0.2.7-cuda12` | NVIDIA driver **575 or newer**, the same toolkit | +| AMD **RX 9000** series and Radeon AI PRO R9700 (RDNA 4, gfx1200 / gfx1201) | `0.2.7-rocm-gfx120x` | the `amdgpu` kernel driver (Linux 6.8+) | +| AMD **RX 7000** series (RDNA 3, gfx1100 / gfx1101 / gfx1102) | `0.2.7-rocm-gfx110x` | the `amdgpu` kernel driver | +| AMD **Ryzen AI Max** ("Strix Halo", Radeon 8060S, gfx1151) | `0.2.7-rocm-gfx1151` | the `amdgpu` kernel driver | +| Intel **Arc** A-series and B-series (including Arc Pro B70) | `0.2.7-sycl` (if no image exists for a release, [build it](#build-it-yourself)) | the `i915` or `xe` kernel driver; **prepared model files** (see [Intel](#intel-arc)) | **Measured on:** images built from the 0.1.45 engine packages. Size on disk: `cuda13` 2.2 GB, `cuda12` 2.9 GB, `rocm-gfx120x` 2.8 GB, `rocm-gfx110x` 2.4 GB, `rocm-gfx1151` 1.5 GB. The download is about a third of that: `cuda13` 640 MB, `cuda12` 845 MB, @@ -32,9 +32,9 @@ Not sure which NVIDIA image? Take `cuda13` when `nvidia-smi` shows driver 580 or A wrong pick does no harm: the container starts, says in plain words that the engine does not fit this card, and stops. **Ready-made images are published from version 0.2.1 on**, to the GitHub Container Registry: `ghcr.io/niko1221/strata:-` -(for example `0.2.3-cuda13`), and `ghcr.io/niko1221/strata:latest-` for the newest release of that flavor. Pin the version +(for example `0.2.7-cuda13`), and `ghcr.io/niko1221/strata:latest-` for the newest release of that flavor. Pin the version tag if you want updates only when you decide. The examples below use these images. If you built an image yourself -([Build it yourself](#build-it-yourself)), use the tag you gave it (for example `strata:0.2.3-cuda13`) in their place. +([Build it yourself](#build-it-yourself)), use the tag you gave it (for example `strata:0.2.7-cuda13`) in their place. ## One command per card @@ -49,7 +49,7 @@ downloaded for the model itself ([Files you already have](#files-you-already-hav docker run -d --name strata --gpus all -p 127.0.0.1:8080:8080 \ --ulimit memlock=-1:-1 --shm-size 2g --stop-timeout 120 \ -v strata-data:/data -e FAMILY=qwen -e MODEL=IQ3_XXS -e API_KEY=$(openssl rand -hex 24) \ - ghcr.io/niko1221/strata:0.2.3-cuda13 + ghcr.io/niko1221/strata:0.2.7-cuda13 ``` **AMD** @@ -59,7 +59,7 @@ docker run -d --name strata --device /dev/kfd --device /dev/dri \ --group-add video --group-add $(getent group render | cut -d: -f3) -p 127.0.0.1:8080:8080 \ --ulimit memlock=-1:-1 --shm-size 2g --stop-timeout 120 \ -v strata-data:/data -e FAMILY=qwen -e MODEL=IQ3_XXS -e API_KEY=$(openssl rand -hex 24) \ - ghcr.io/niko1221/strata:0.2.3-rocm-gfx120x + ghcr.io/niko1221/strata:0.2.7-rocm-gfx120x ``` **Intel Arc** @@ -68,7 +68,7 @@ docker run -d --name strata --device /dev/kfd --device /dev/dri \ docker run -d --name strata --device /dev/dri --group-add $(getent group render | cut -d: -f3) \ -p 127.0.0.1:8080:8080 --ulimit memlock=-1:-1 --shm-size 2g --stop-timeout 120 \ -v strata-data:/data -e FAMILY=qwen -e MODEL=IQ3_S -e MODEL_PATH=/models -v /srv/gguf/IQ3_S:/models:ro \ - -e API_KEY=$(openssl rand -hex 24) ghcr.io/niko1221/strata:0.2.3-sycl + -e API_KEY=$(openssl rand -hex 24) ghcr.io/niko1221/strata:0.2.7-sycl ``` What the options are for: `--ulimit memlock=-1:-1` lets the engine pin the RAM it uses for the model, `--shm-size 2g` gives @@ -206,7 +206,7 @@ The health check asks `GET /v1/models` with the key. During the first download t ## Updating ```sh -docker pull ghcr.io/niko1221/strata:0.2.3-cuda13 # the new tag (with a self-built image, build it again instead) +docker pull ghcr.io/niko1221/strata:0.2.7-cuda13 # the new tag (with a self-built image, build it again instead) docker stop strata && docker rm strata # run the same docker run command again with the new tag (compose: docker compose pull && docker compose up -d) ``` @@ -288,9 +288,9 @@ This is the way to get an image for a computer without registry access or after folder (made by `packaging/package_engine.py`, or fetched by `strata update` into a components folder) and Docker on Linux: ```sh -docker/build.sh --flavor cuda --engine ~/components/engine/ --tag strata:0.2.3-cuda13 -docker/build.sh --flavor hip --engine ~/components/engine/ --tag strata:0.2.3-rocm-gfx120x -docker/build.sh --flavor sycl --engine ~/components/engine/ --tag strata:0.2.3-sycl +docker/build.sh --flavor cuda --engine ~/components/engine/ --tag strata:0.2.7-cuda13 +docker/build.sh --flavor hip --engine ~/components/engine/ --tag strata:0.2.7-rocm-gfx120x +docker/build.sh --flavor sycl --engine ~/components/engine/ --tag strata:0.2.7-sycl ``` `build.sh` assembles the build context (the Terminal's files and the package) and runs `docker build`. The build makes the @@ -316,13 +316,13 @@ files the signed update feed names. Nothing publishes by itself: a maintainer st 1. Make the release first (its `strata-feed.json`, `strata-feed.json.sig` and the engine archives must be on the GitHub release). 2. GitHub, **Actions, Docker images, Run workflow** ([.github/workflows/docker-images.yml](../.github/workflows/docker-images.yml); the file has to be on - the default branch to show up). Inputs: the release tag (`v0.2.3`), the flavors (empty: every flavor the release has a package + the default branch to show up). Inputs: the release tag (`v0.2.7`), the flavors (empty: every flavor the release has a package for), **push** and **latest**. Run it once with **push off**: it builds every image and publishes nothing (a dry run). 3. Run it again with **push on**. It logs in to `ghcr.io` with the job's `GITHUB_TOKEN` (`packages: write`) and pushes - `ghcr.io/niko1221/strata:0.2.3-` and `latest-`. Turn **latest** off for a pre-release. + `ghcr.io/niko1221/strata:0.2.7-` and `latest-`. Turn **latest** off for a pre-release. 4. The first push creates each package as private. In the repository's Packages, open every package, **Package settings, Change visibility, Public**, and check it is linked to the repository (the image carries the `org.opencontainers.image.source` label). -5. Check one pull from a computer that is not logged in: `docker pull ghcr.io/niko1221/strata:0.2.3-cuda13`. +5. Check one pull from a computer that is not logged in: `docker pull ghcr.io/niko1221/strata:0.2.7-cuda13`. For each flavor the job runs [docker/fetch-engines.py](../docker/fetch-engines.py), which reads the release's signed feed (the Ed25519 key in `strata_control/update_keys.json`), downloads the package, and checks the archive's size and SHA-256, the manifest @@ -340,7 +340,7 @@ the job starts the image once to see that the Terminal inside it runs. | `sycl` | `linux-x86_64`, sycl; only when the feed lists one | A flavor the feed has no package for is left out, with a line in the log. The same steps run from a Linux computer with Docker: -`docker/publish.sh --release-tag v0.2.3` builds everything and pushes nothing; add `--push` (after `docker login ghcr.io`) to publish. +`docker/publish.sh --release-tag v0.2.7` builds everything and pushes nothing; add `--push` (after `docker login ghcr.io`) to publish. The images run on the runner without a graphics card, so the card checks (`docker/smoke-test.sh`) stay a manual step on a computer with the card. ## Known limits diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 37bd82aa..78277bca 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -90,6 +90,7 @@ estimated 2 GB of its own buffers. - Intel GPUs in a split, and a mix of NVIDIA and AMD cards. An engine drives one make of card. The app, `strata launch` and setup offer only the cards the engine can drive, and say so when the other make has the bigger card. AMD cards share a model among themselves: `./setup.sh --backend hip --gpus 1,0` ([AMD_HIP.md](AMD_HIP.md)). + A prompt read on one card and an answer made on another, with the session handed over in RAM, is a different opt-in: [SPLIT_SERVE.md](SPLIT_SERVE.md). ## How the split works diff --git a/docs/README.md b/docs/README.md index 9baad441..945cfb21 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,7 @@ Use the guide for your GPU and operating system. Model and feature support can d | Intel Arc on Linux | [Intel Arc](INTEL_ARC.md) | | Apple Silicon | [Mac / Metal](MAC.md) | | More than one GPU | [Multiple GPUs](MULTI_GPU.md) | +| Two cards: one reads the prompt, one makes the answer (opt-in) | [Split serving](SPLIT_SERVE.md) | | Older GPUs | [Experimental hardware](OLDER_GPUS.md) | ## Developers and contributors diff --git a/docs/SPLIT_SERVE.md b/docs/SPLIT_SERVE.md new file mode 100644 index 00000000..9eaee8b7 --- /dev/null +++ b/docs/SPLIT_SERVE.md @@ -0,0 +1,218 @@ +# Split serving: read the prompt on one card, make the answer on another + +> **Status: opt-in, first version, same make of cards on one PC. Not recommended on two alike cards: measured slower than the layer +> split on every workload we tried ([Measured](#measured)).** Nothing changes unless you turn it on. It needs two cards that can +> each run the whole model, and it can only pay when one card is clearly better at reading prompts and another at making answers. + +The idea, the hand-made setup and the first measurements are by @MarcoTool in issue #4000: a router in front of two +engines, an RTX 3070 reading the prompt and two MI50 cards making the answer, with the session handed over through +`/dev/shm`. This page describes the built-in version of the same idea. + +> **On this page:** [What it does](#what-it-does) · [Turning it on](#turning-it-on) · [When it helps](#when-it-helps) · +> [Measured](#measured) · [How it works](#how-it-works) · [What must match](#what-must-match) · [Limits](#limits) · +> [NVIDIA with AMD, and other PCs](#nvidia-with-amd-and-other-pcs) + +## What it does + +A normal two-card setup ([MULTI_GPU.md](MULTI_GPU.md)) cuts the model into layers and every card works on both stages. Split +serving does not cut the model. It starts two engines, each on one card, each with the whole model: + +- the **prefill engine** reads the prompt and stops just before the first answer token; +- the engine saves that session into RAM, the **decode engine** loads it, and makes the answer. + +The two engines share one copy of the experts in RAM (`--shared-expert-arena`, Linux). The client still talks to one +OpenAI-compatible endpoint; the server hands the session over between the two. + +A prompt whose new part is short (a chat follow-up, an agent step) never leaves the decode engine: it is read in place, as +without the option. Only a long new part goes to the prefill engine. + +## Turning it on + +In the run config (`strata-.json`), next to the other keys: + +```json +{ + "split_serve": {"prefill_gpu": 0, "decode_gpu": 1} +} +``` + +or `python serve/server.py --split-serve 0,1` (prefill card first). The cards are numbered as `nvidia-smi` numbers them. The option +replaces `gpu`; the config must not also name `replicas`, `--layer-split`, `--batch`/`--slots` or `--prompt-cache 0` (the +server stops at start and says which). + +| Key | Default | Meaning | +| --- | --- | --- | +| `prefill_gpu`, `decode_gpu` | required | The two cards. Different cards. | +| `min_prompt_tokens` | 2048 | A request is handed over when the decode engine would otherwise read at least this many new tokens. Below it the decode engine reads them in place. | +| `dir` | `/dev/shm` if it has room, else the temp folder | Where the session file lives for the seconds of a hand-over. | +| `shared_arena` | `true` | One copy of the experts in RAM for both engines (Linux, a file in `/dev/shm` when the experts fit there). `false`: each engine keeps its own copy (two copies of the experts in RAM). A file name: that file backs the arena (a file on disk works; it is written once). | +| `prefill_args`, `decode_args` | none | Extra engine arguments for one role, for example a bigger expert cache for the decode engine. They must not change the [session settings](#what-must-match). | + +The startup line says what was chosen, including when the arena cannot be shared: + +``` +[strata] split serving: the prompt is read on card 0, the answer is made on card 1 (prompts with 2048+ new tokens are handed over); one shared expert arena in /dev/shm (32.0 GiB) +``` + +`/metrics` has a `split_serve` block: requests, hand-overs, fallbacks, bytes moved and the time spent saving and restoring. + +## When it helps + +Prefill needs matrix units and compute. Decode is limited by memory bandwidth and by how much of the model sits in VRAM. If one +card is much better at the first and another at the second, each can do what it is best at. That was the case in #4000: an +RTX 3070 reads a 32K prompt at about 1,600 tokens a second, the two MI50 cards read it at about 390 but decode at 40 tokens a +second with every expert in VRAM. The hand-over costs 2 seconds at 32K. + +It does **not** pay when: + +- the two cards are alike. A layer split over both cards reads a long prompt faster than one card and decodes faster than one card. + Split serving gives both up, and each engine has only one card's VRAM for experts. On two RTX A6000 it was 4% to 48% slower; +- the hand-over (the session file's size over RAM bandwidth, written and read) costs more than reading the new tokens on the + decode card would have; +- the new part of each request is short, which is most chat and agent use: nothing is handed over. + +[Measured](#measured) shows the numbers on two identical cards. + +## Measured + +Two identical cards, so this is the case where split serving has the least to offer: 2x RTX A6000 48 GB (a lent box, Linux, +CUDA 13.1), Qwen3.8-Flash-Next IQ3_S, `--kv int8`, MTP drafting, default engine flags, greedy decoding. Three arms, each started +fresh for every round (3 rounds, 2 repetitions each, so 6 values per cell; every request is a cold prompt, no cache hit): + +- **layer**: one engine over both cards (`--layer-split auto`), the normal two-card setup; +- **single**: one engine on one card; +- **split**: the prefill engine on one card, the decode engine on the other, through this option. + +Wall time of the whole request, median of 6 (a prompt of the given length and 256 answer tokens; the chats are 3 turns, 128 answer +tokens each, follow-ups of 200 or 6,000 tokens, no turn markers in the token stream): + +| Workload | layer | single | split | split / layer | split faster than layer | +| --- | --- | --- | --- | --- | --- | +| 8K prompt + 256 | 4.91 s | 5.27 s | 5.69 s | 1.16 | 0 of 6 | +| 32K prompt + 256 | 9.82 s | 13.64 s | 14.48 s | 1.48 | 0 of 6 | +| chat, 4K + two 200-token follow-ups | 4.75 s | 5.27 s | 5.99 s | 1.30 | 0 of 6 | +| chat, 8K + two 6,000-token follow-ups | 12.09 s | 13.43 s | 12.58 s | 1.04 | 0 of 6 | + +Where the time goes: + +| | layer | single | split | +| --- | --- | --- | --- | +| Prompt reading, 8K (to first token) | 3.10 s | 3.25 s | 3.68 s (3.23 s on the prefill card + 0.41 s hand-over) | +| Prompt reading, 32K | 7.89 s | 11.53 s | 12.34 s (11.54 s + 0.74 s) | +| Decode, tokens per second at 8K / 32K | 141 / 131 | 126 / 120 | 128 / 117 | + +- **The hand-over is small but not free:** 0.20 s to save and 0.19 s to restore a 345 MiB session at 8K, 0.35 s and 0.39 s for 702 MiB + at 32K. The file is about 225 MiB plus 14.7 MiB for every 1,000 tokens (285 MiB at 4K, 464 MiB at 16K). That is 7% of an 8K request and + 5% of a 32K one. +- **Alike cards give it nothing to win with.** The prefill card reads at the speed of one card (about 2,500 to 2,900 tokens a + second) and the decode card decodes at the speed of one card. A layer split reads a 32K prompt in 32% less time than one card, + because the pipeline keeps both cards busy, and decodes 9% to 12% faster. It wins every request here. +- **Short follow-ups are not handed over** (they are under `min_prompt_tokens`): the decode card reads them in place, as one engine would. +- **Long follow-ups are handed over every time** (the second chat). The prefill engine does not hold the answer the decode engine just + made, so it reads the answer and the follow-up again (2.5 s for 6,128 tokens) and the session moves again. That chat is the closest + to the layer split (12.58 s against 12.09 s). Nothing runs at the same time in this version, so the two cards still take turns. + +**Exactness.** A fresh engine and the split path give the same answer, token for token, and the same session state: + +| Check | Model, cards | Prompt | New tokens | Result | +| --- | --- | --- | --- | --- | +| two fresh single engines, then prefill engine + session file + fresh decode engine | Q2_0, 2x RTX A4000 | 4,096 | 64 | tokens equal, state fingerprints equal | +| the same | IQ3_S, 2x RTX A6000 | 4,096 | 64 | tokens equal, state fingerprints equal | +| the same | IQ3_S, 2x RTX A6000 | 16,384 | 128 | tokens equal, state fingerprints equal | + +"State fingerprint" is the engine's `STRATA_STATE_HASH`: the whole session (running state, K/V of every layer, the draft layer's K/V) hashed after +the request. The fingerprint of the prefill engine's session also equals the decode engine's right after the restore. The check ran with +`--adapt-swaps 0 --pcie-frac 0 STRATA_IQ_MT_MIN=1`, the settings under which two fresh single engines already give the same answer +(without them the engine is not always deterministic from run to run, with or without this option). The tool is `tools/split_serve_check.py exact`. + +On two alike cards, split serving does not pay for one request at a time. It can pay when one card is clearly better at reading +prompts and another at making answers, as in #4000. The gain there is the prompt time the weaker card would have needed, minus the +hand-over (0.4 s at 8K and 0.7 s at 32K on this box). We have not measured such a pair. + +## How it works + +1. The server sees a request with at least `min_prompt_tokens` new tokens for the decode engine (it tracks what the decode + engine's session holds). +2. It sends the prompt to the prefill engine as `GEN 0 prefill=1 `. The engine reads the prompt as a request would, in + the same chunks, with the same checkpoints, up to the place where the first answer window starts, and stops. Its session + then holds all but the last prompt token. That is exactly the state a following turn resumes from, so the decode engine + needs no new code path. +3. `SAVE `: the engine's existing session file (see [DETAILS.md](DETAILS.md#session-files-disk)): the running state, the + K/V of every layer and the draft layer's K/V, the deepest checkpoint. +4. `RESTORE ` on the decode engine, which checks the file against its own model files and settings. +5. The request goes to the decode engine as usual. It finds the restored session as the start of the prompt, reads the last + token, and makes the answer. The file is deleted. + +If anything on the way fails (the prefill engine died, the file was refused, the card is out of memory), the decode engine reads +the prompt itself, as without the option, and the log says why. A prefill engine that died is started again in the background. + +The figures the server reports for the request (prompt time, tokens read, tokens reused) count the prefill engine's work and +the two file steps, so a client sees one request. + +## What must match + +The session file is bound to everything that changes what its bytes mean. Both engines start from one config, so these match; +they would not if `prefill_args`/`decode_args` changed them: + +- the model files (sampled by size and first and last MiB) and the engine version; +- the backend (CUDA or HIP): **no cross-backend restore**; +- `--kv`, `--max-context`, `--kv-resident`, `--mtp-window`, `STRATA_KV_ROT`, the resolved rope settings, a loaded control vector; +- the arithmetic switches that change the computed state (the engine lists them in the file's fingerprint). + +These may differ between the two engines: the expert cache size, `--prefill` chunk, sampling, drafting depth, the expert tier. +That is the point of the two roles: the prefill engine can spend its VRAM on prompt buffers and the decode engine on experts. + +## Limits + +- One request at a time, as for a single engine. The prefill engine could read the next request's prompt while the decode engine + answers the current one; this version does not overlap them. +- The decode engine holds one conversation. A hand-over replaces it (the engine's restore does not park the session it + replaces). A request that continues the conversation the decode engine holds is read in place. +- No parallel slots (`--batch`), no layer split inside an engine, no pictures (a request with pictures goes to the decode + engine alone). +- Needs RAM for the experts once (shared arena, Linux) or twice (otherwise), plus the session file while it exists: + about 225 MiB plus 14.7 MiB per 1,000 tokens at `--kv int8` on the Qwen3.8 model. +- Token for token the same answer as one engine, in the checks listed under [Measured](#measured). + +## NVIDIA with AMD, and other PCs + +This version runs on any two cards of one make that each hold the model (the engine drives one make of card, and a session file is +bound to its backend). It was tested on NVIDIA only. What the cases beyond it need, from reading the code and from #4000, none of it +built or measured here: + +**NVIDIA with AMD on one PC** (the setup in #4000): + +- *The session file must be allowed across backends.* Today the file's fingerprint contains the backend (`cuda` or `hip`) and the + arithmetic switches that differ per card family, so a restore is refused. A cross-backend mode has to compare only what defines the + bytes: model files, engine version, `--kv`, `--max-context`, `--kv-resident`, `--mtp-window`, the rope settings, `STRATA_KV_ROT`. The K/V, + running-state and draft-layer layouts come from one source tree, but nobody has checked that the bytes are interchangeable on both + backends. +- *A byte check is no longer possible.* The two backends do not compute the same bits, so the proof is not a state fingerprint. It + would be a teacher-forced KL of the answer after a hand-over against the same backend's own continuation, with the noise floor of the + decode engine against itself, plus needle and task checks, as for any change of arithmetic. +- *Two engine builds.* One CUDA and one HIP executable of the same version, so the config needs an executable and a card per role + (`prefill_exe`, `decode_exe`), the card variable per backend (`CUDA_VISIBLE_DEVICES`, `HIP_VISIBLE_DEVICES`), and a start check that both + report the same version. +- *The shared expert arena works across makes* (#4000 does it with `--shared-expert-arena` in `/dev/shm`): it holds the pack's bytes and + each engine pins them with its own runtime. It needs the experts to fit `/dev/shm`, or a file on disk, as for the same-make case. +- *Roles chosen from measurement.* Setup and `--calibrate` would read each card's prompt speed and decode speed and suggest which + card reads and which answers, and say when the pair is not worth splitting. Without that the owner of the PC has to know. +- *A test machine with both makes.* We have none in 0.2.7. + +**Another PC** (prefill on one machine, decode on another): + +- The session file is 225 MiB plus 14.7 MiB per 1,000 tokens (about 2 GiB at 128K). A 10 Gb/s link moves that in 2 to 3 seconds; a + gigabit link in 20. +- Each PC loads its own copy of the experts, so there is no shared arena. Both need the same model files and engine version; the + fingerprint samples the files' size and first and last MiB, not their path. +- The engines read a session file from a local path and trust it ("restore only files this engine wrote"). A network hand-over needs a + transport with authentication and an upload/download call on the server, which does not exist. +- Requests would have to be routed to the PC that holds the conversation, which is the replica router's job already. + +**Several clients at once** (not built, not measured): the prefill card could read the next request's prompt while the decode card +answers the current one. That would raise the throughput of a busy server. It would not make one request faster than the layer split on +alike cards. This version runs one request at a time. Overlapping needs the server to take two requests at once (a prefill queue and a +decode queue), and the decode engine to take a restore between two of its own requests, which the session file already allows. + +Credit: the idea, the hand-built router and the first measurements are @MarcoTool's (issue #4000, repository +`MarcoTool/PDHyperMix-Strata-MI50`). diff --git a/docs/release-notes-0.2.7.md b/docs/release-notes-0.2.7.md index 73965645..cdcfc12a 100644 --- a/docs/release-notes-0.2.7.md +++ b/docs/release-notes-0.2.7.md @@ -1,131 +1,88 @@ -# Strata 0.2.7 (draft): a faster Qwen3.8 on NVIDIA +# Strata 0.2.7: faster 12 GB NVIDIA cards, DeepSeek on Ryzen AI Max, a bigger web chat page, French -> **DRAFT for the owner.** Written by the CUDA speed work on branch `f-027-cuda`; no engine version is claimed here -> because the owner decides what else 0.2.7 carries. Every number below was measured on the borrowed boxes named in -> each line, same day, against the same build with the new default turned off. +The app and the Terminal are 0.2.7. Control and every engine package (Qwen and DeepSeek) are 0.1.52, because both engines changed. -## What is faster, by default +DRAFT of 27 October. Text in square brackets that starts with "pending" or "TO CONFIRM" is work that was not merged or checked when this was written. `phaseA-tests\rel027\check_notes027.py` lists them and removes the ones that landed. None of them may be left in the published text. -- **The hyper-connection read on RTX 50 and RTX PRO Blackwell cards (compute capability 12.0).** The model's - hyper-connection mixing runs 96 small projections per token; its "up" half now runs one warp per row instead of - eight rows per warp, which fills a modern card's SMs instead of 160 blocks on 192 of them. Measured on an RTX PRO - 5000 Blackwell 72 GB (Qwen3.8-Flash-Next IQ3_S, every expert in VRAM), five interleaved pairs of fresh engines: - **story 197.6 -> 201.3 tokens/s (+1.9%), code 243.5 -> 245.1 (+0.7%)**. The answers are unchanged - the new - kernel does the same arithmetic in the same order, the produced tokens were identical in all six pairs and the - engine's own kernel check is bitwise. - - Off switch: `STRATA_GR_UP_WIDE=0`. `STRATA_SM120_PERF=0` still turns off the whole Blackwell set. - - Other cards are untouched: the old kernel runs everywhere else. +## What you will notice -- **Two more kernel switches are on by default where they were measured.** Both sum in another order (about 1e-7), so a - tie between two near-equal words can flip and a reply can differ from 0.2.6 here and there. - - The prompt attention on int8 tensor cores (NVIDIA Ampere and newer): **+1.6% / +1.8% prompt at 8K / 16K on the RTX PRO 5000 - and +1.1% / +1.3% on 2x RTX A4000**, decode unchanged, five pairs each. Off switch: `STRATA_PROMPT_ATTN_IMMA=0`. - - The hyper-connection read split over two kernels (a discrete RTX 50 / RTX PRO Blackwell card with more than 13 GiB): **+1.2% - decode on the RTX PRO 5000 with identical tokens**, about +1.5% together with the switch above. On 2x RTX A4000 and the - RTX 3060 it was slower, so those cards keep the old read. Off switch: `STRATA_GR_V3=0`. - - RTX 40 cards (Ada, compute capability 8.9): new decode row tables for the interleaved matrix kernels, on by default. The output is the - same bit for bit; only how many rows a warp takes changes. **We have not measured them on an RTX 40 card**: the tables come from two - community runs (an RTX 4070 and an RTX 4080), and the report with the 4090 saw no change in decode speed. If you have an RTX 40 - card, please try 0.2.7 and post your decode numbers on issue 3453. Off switch: `STRATA_MMVQ_IL_89=0`. - - NVIDIA A100 / A30 / CMP 170HX class cards (compute capability 8.0): the wide dense dequantizer and decode row tables of PR 3779, on by default, - same output bit for bit, measured only on a CMP 170HX by the contributor. Off switches: `STRATA_DEQUANT_WIDE=0`, `STRATA_MMVQ_IL_SM80=0`. +- **NVIDIA cards with 12 GB or less answer faster.** The router now prefers experts that are already on the card, which saves page-ins from RAM. On an RTX 3060 12 GB (Qwen3.8-Flash-Next IQ3_XXS, five paired runs against the same build with the setting off), a story answer went from 46.2 to 53.1 tok/s (+15%) and a code answer from 45.7 to 62.5 tok/s (+37%). It picks a slightly different set of experts, so the wording of answers changes. We checked the quality of the answers with 61 test tasks on that card. Retrieval (12 of 12), JSON (3 of 3) and unanswerable questions (9 of 9) were all right, and extraction found the same facts as with the setting off; we found no copy, code-constant or spelling defect. It did give two long-winded answers: one rambling paragraph in an agent task and one code answer that was cut off in the middle of a comment. Runs with the setting off show two or three such cases each too. The automatic grader passed 49 of the 61 tasks against 54 with the setting off; we read all five tasks it lost: three were grader flags (a name in a summary, a product name in a summary and a non-breaking hyphen in an agent task) and two were the long-winded answers above. A stronger setting (2.0) did show copy and code defects, so the default is 1.5. It applies to a discrete NVIDIA card of 13 GiB or less; larger cards, Radeon and Strix Halo are not changed. Off: "Faster answers on 12 GB NVIDIA cards" in the model's settings, or `STRATA_ROUTE_PRIOR=0`. +- **Radeon RX 9000 and AI PRO R9700: faster Qwen.** Two changes: the large per-token lookup table stays in RAM when the PC has room for it, and the decode split between card and processor starts at a better value. One R9700 (32 GB) with 125 GB of RAM on Linux, Qwen IQ3_S, medians of three runs: + + | Context | Prompt before | Prompt now | Decode before | Decode now | + |---|---|---|---|---| + | 8K | 2,047 tok/s | 2,505 tok/s (+22%) | 82.9 tok/s | 94.6 tok/s (+14%) | + | 32K | 2,491 tok/s | 2,802 tok/s (+12%) | 64.9 tok/s | 85.1 tok/s (+31%) | + + Answers can differ in wording because the work is split differently; 30 test tasks passed in every arm with no invented fact. Off: "Faster answers on Radeon RX 9000 / AI PRO R9700". +- **DeepSeek-V4.1-Flash runs on Ryzen AI Max (Strix Halo) PCs with Windows.** It has its own engine package for the gfx1151 chip, and the app or `strata launch` downloads it with the model. The new guide [docs/STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md) has the numbers and the traps, measured on a GMKtec EVO-X2 (Ryzen AI Max+ 395, 128 GB shared memory, Adrenalin 26.10.1). DeepSeek 2.00 answers a short chat at 12 to 14 tok/s and reads a 4K prompt at 214 to 226 tok/s, a 16K prompt at 326 and a 32K prompt at 342 tok/s. Qwen IQ3_S on the same PC: chat 44 tok/s, 4K prompt 755, 32K prompt 792 tok/s. [TO CONFIRM: re-measure the DeepSeek and Qwen rows on the final build if strix is lent before the release] The shared-expert stream is off by default on Windows there, because it is slower: 43.6 to 46.6 tok/s decode (+6.9%, three paired starts), same token ids. Only the 128 GB machine was tested. You need Adrenalin 26.10.1 or newer. +- **DeepSeek reads prompts faster on most PCs.** The engine no longer re-reads a batch of experts from the SSD after every prompt, picks the attention buffer size by itself and fills the RAM store more cleverly. On an RTX 5070 (12 GB, 64 GB RAM, 2.25 set, three paired runs against an earlier 0.2.7 candidate): 4K prompt 116 to 170 tok/s (+47%), 8K prompt 202 to 268 tok/s (+33%). On one R9700 with the 2.25 set: 32K prompt 382 to 444 tok/s (+16%), 8K prompt 200 to 286 tok/s (+43%, but that prompt is limited by SSD reads and varies a lot between runs). The cost: the first words after a long prompt can come slower, because the store is no longer pre-filled. On the RTX 5070 a long answer still finished 8.7% sooner overall (137.5 s against 150.6 s); on one R9700 a 300-token answer after an 8K prompt took 51.9 s without the pre-fill and 48.6 s with it. `DS4_SETTLE_STORE=1` brings the pre-fill back. The speed-up switch "DeepSeek speed-ups" turns the new behaviour off in one step. +- **Four Radeon AI PRO R9700 cards run DeepSeek faster, with five experts per word by default.** With the launcher's own settings, DeepSeek 2.25: an 8K prompt 342 to 399 tok/s on the first read and 967 to 1,350 once warm (+17%, +40%), a 32K prompt 1,127 to 1,604 first and 1,183 to 1,697 warm (+42%, +43%), decode on code 88.9 to 95.0 tok/s (+7%) and on an agent task 73.5 to 79.7 (+8%). Loading takes 58 to 60 s instead of 51 s. The default is now "Faster" (5 of 6 experts per word); the quality run passed 19 of 19 tasks against 18 of 19 with six experts, and the distance to the reference model is the same (0.1102 against 0.1102). Choose Full quality in the app, or `--experts 6`, to use six. +- **DeepSeek can use 512K and 1M contexts.** Setup, the Terminal and the app offer them up to the limit of the model files, with a plain "not tested yet" note past 256K. The default stays 8K, and the app now loads a DeepSeek model with the context you chose. On an RTX 5070 a 1M context loaded in 18 s and cost about 1 GB of graphics memory, which pushed 136 experts off the card. We did not test long prompts at these sizes. The idea comes from Project Maya v1.1.28 (#442, by @needmorevram). +- **More cards get small gains from kernel changes that were measured.** On an RTX PRO 5000 (72 GB, Qwen IQ3_S, five paired runs): story answers 195.9 to 211.8 tok/s (+8.1%), code 240.6 to 244.7 (+1.7%), prompts +1.2% at 4K, +1.5% at 8K, +1.6% at 16K. On two RTX A4000: story +2.2%, code +0.5%. These switches sum numbers in another order, so a reply can differ from 0.2.6 at a near-tie. RTX 40 cards (compute capability 8.9) use measured speed tables for the quantised matrix products; they are bit for bit the same as before and we have no Ada card, so the reporter's measurements are the only ones. Off: `STRATA_MMVQ_IL_89=0`. A100-class cards (sm_80) get the bitwise-identical defaults of #3779 (wider dequantisation, tuned tables, measured only on a CMP 170HX by the contributor); its many opt-ins stay off, and the reporters are asked to test. Off: `STRATA_DEQUANT_WIDE=0`, `STRATA_MMVQ_IL_SM80=0`. +- **Long prompts on two NVIDIA cards read much faster.** On a layer split over two CUDA cards the prompt is now read layer by layer in large pieces, so each layer's experts are read once per piece instead of once per 8,192 tokens. On two RTX A4000 (Qwen IQ3_XXS, experts streamed, five paired runs): first token after a 32K prompt 141.8 s to 27.7 s (5.1x), after a 20K prompt 98.8 s to 17.5 s (5.7x), after an 8K prompt 41.8 s to 15.2 s (2.8x); the answer speed is the same (38.6 against 38.4 tok/s), the 12 needle questions at 16K and 32K were all found, and the 19-task quick suite passed 18 of 19 with and without it (13 answers byte-identical, the 6 others differ in wording only). The numbers differ slightly from the old path because the experts' results are added in another order: the first-token KL against the old path is at the level of the difference between two prompt chunk sizes, and the most likely token matched on every prompt. One card, Radeon and the approximate-read mode keep the old path. Off: `STRATA_PREFILL_LAYER_MAJOR=0`, or `STRATA_DEFAULTS=026`. From PR 3976 (@Norhiro, building on @vizdatom's #1670). +- **MTP drafts in the pipelined batch groups (opt-in).** `STRATA_PIPED_MTP=1` with `--batch-mtp` lets each slot of a pipelined layer split bring its own draft tokens: on two RTX A6000 with two concurrent streams +12 to +15% total tokens per second, four streams +0 to +5%, one stream unchanged, and every slot decodes exactly the tokens it decodes alone. From PR 4121 (@wannagoxuf). +- **The served web chat page gets a large update.** Wide windows use the width and narrow screens fit (#3176). Saved chats with search, rename and delete, editing a question, rewinding to an earlier turn and branching a new chat from it, sending a message while the answer is still coming (wait, send after, or interrupt), math written in LaTeX rendered with KaTeX, a sandboxed preview of HTML and SVG the model writes, and Load and Unload buttons in the header. The chat view is translated into the same languages as the app, French included. The history features are off until you switch them on in Chat settings: with them off the page sends the same requests as before. Monitor, Images and About are still English. +- **The desktop app.** French is the ninth language. Settings now has: a sound when a task finishes (on request), a desktop notification when Manual mode needs your approval, minimise to the system tray, a fixed port so API clients keep working across updates (with a warning when the port is busy), and an interface size up to 200%. The Monitor has a readings strip: power draw, an electricity price you set (in your local currency, found from the system region), disk temperature where Windows or Linux can report it. The DeepSeek card says how much free disk the set needs. Not tried inside the real packaged app on screen yet: tray icon, the native notification and the busy-port warning. [TO CONFIRM: run once in the release e2e] +- **Speed switches.** In Models, Native engine settings, Speed (and in the Terminal's Advanced table): "Faster long prompts" (off by default), "Faster answers on 12 GB NVIDIA cards", "Faster answers on Radeon RX 9000 / AI PRO R9700", "DeepSeek speed-ups". The Terminal also has "Qwen: 0.2.6 behaviour" for troubleshooting. ## Going back to 0.2.6 -Two switches bring back every default that 0.2.7 changed, in one step, for a test or for a PC where something looks wrong. The app's -"off" for its speed switches sends them. +Two switches bring back every default that 0.2.7 changed, in one step, for a test or for a PC where something looks wrong. -- **`DS4_DEFAULTS=026`** (DeepSeek): the staging ring, the prompt chunk rule, the attention slab (its base and its growth), the pinned - copy and the huge-page arena, the matrix-core attention, the drafter's cumulative cut, the 5-experts default on several Radeon cards, - the RAM store's spare slots and put and its settle after a prompt, the dense dequantizer, the F16 gate/up operand, the drafter's - markov head and the head's column count, and the RDNA3 dense GEMM all go back to what 0.2.6 did. -- **`STRATA_DEFAULTS=026`** (Qwen): the residency-biased routing, the wide and the stream-split hyper-connection reads, the int8 - prompt attention, the RTX 40 (sm_89) and sm_80 decode tables and sm_80 dense dequantizer, the four gfx12 decode switches, the PLE residency policy and the gfx12 decode split of 0.15 (back to 0.55). - Long prompts on the approximate read (`STRATA_KVA`) are off by default and stay as `STRATA_KVA` says. +- **`DS4_DEFAULTS=026`** (DeepSeek): the staging ring, the prompt chunk rule, the attention buffer, the pinned copy and the huge-page arena, the matrix-core attention, the drafter's cut, the five-experts default, the RAM store's spare slots and its pre-fill after a prompt, the dense dequantiser, the head and gate/up operand formats and the RDNA3 dense GEMM go back to what 0.2.6 did. +- **`STRATA_DEFAULTS=026`** (Qwen): residency-biased routing, the wide and split hyper-connection reads, the int8 prompt attention, the four gfx12 decode switches, the PLE residency policy, the gfx12 decode split (back to 0.55), the RTX 40 (sm_89) tables, the sm_80 defaults and the layer-major prefill of a two-card CUDA split. -A variable or flag you set yourself (`DS4_ATTN_SLAB=N`, `STRATA_ROUTE_PRIOR=2`, `--experts 5`, `--prefill-chunk N`, `--pcie-frac`, -`--ple-io`) still wins over the switch. The older single switches (`DS4_FAST_ATTN=0`, `DS4_ATTN_SLAB=0`, `DS4_COPY_PIN=0`, -`DS4_COPY_HUGETLB=0`, `DS4_STORE_SPARE=0`, `DS4_STORE_PUT=0`, `STRATA_ROUTE_PRIOR=0`, ...) work as before. +A variable or flag you set yourself still wins over the switch, and the older single switches work as before. In the app, "DeepSeek speed-ups" off sends `DS4_DEFAULTS=026`. -- **Strix Halo (`gfx1151`) on Windows: the shared expert no longer runs on its own stream.** `STRATA_SH_STREAM` was on by default on - `gfx1151`; on a Windows PC it is slower. Qwen3.8-Flash-Next IQ3_S, three interleaved pairs: chat decode **43.6 -> 46.6 tokens/s (+6.9%)** - with it off, prompts unchanged. The answers are the same: five fixed greedy prompts (up to 16,383 tokens) gave identical token ids with - the switch on and off, in four runs. Linux `gfx1151` keeps it on, other cards are untouched. Turn it back on with - `STRATA_SH_STREAM=1`; `STRATA_DEFAULTS=026` restores the 0.2.6 behaviour. Details and the other numbers of that PC: - [docs/STRIX_HALO_WINDOWS.md](STRIX_HALO_WINDOWS.md). +## Off unless you turn it on -## What is faster if your PC is set up for it +- **Faster long prompts** (`STRATA_KVA=1`, or the switch in Models, Native engine settings, Speed). Reads the last 12 layers of a very long prompt in an approximate way, for Qwen3.8-Flash-Next on one NVIDIA or AMD card, on the first read of a prompt of 4,096 tokens or more. On an RTX 5070 with IQ3_S it was 11% faster at 14K and 18% faster at 30K. It stays off because earlier, more aggressive settings dropped records from long lists and failed agent tasks. The setting that ships when you turn it on (layers 36 to 47 approximate, the last 2,048 tokens exact) found the same 585 of 606 facts as the exact read and finished 6 of 10 agent tasks where the exact read finished 4 and 7 in two runs. It can still lose details. +- **Prefill on one card, decode on another** (`--split-serve P,D`, or `split_serve` in the run config; #4000, first version). The idea, the hand-made setup (an RTX 3070 reading the prompt, two MI50 cards making the answer) and the first measurements are by @MarcoTool. One engine reads the prompt and hands the finished state to a second engine that answers. The words are the same as with one engine, token for token (checked at 4,096 and 16,384 tokens, with equal state fingerprints). On two RTX A6000 (3 rounds, 6 values per cell, whole-request time) it was slower than the normal layer split on every workload: an 8K prompt took 16% longer, a 32K prompt 48% longer, a 3-turn chat 30% and 4% longer. So we do not recommend it on two alike cards. It can only pay with two different cards, one good at reading prompts and one good at making answers; we have not measured such a pair. `docs/SPLIT_SERVE.md` has the numbers and the limits. +- **Pipelined drafts** (`STRATA_PIPED_MTP`, #4121 by @wannagoxuf): the draft model also runs for batch slots. On two RTX A6000 cards with a batch of slots, two streams +15.4% (five of five pairs), four streams +4.7%, one stream +0.1%. [pending: f-027-gh-eng-pm2] +- **Layer-major prefill on a CUDA layer split** (#3976, ports of two contributors). [pending: f-027-gh-eng-lm - state whether it is on or off and give the measured prompt gain, or delete the bullet] +- **Huge pages for DeepSeek on Linux.** If you reserve 2 MB huge pages (`vm.nr_hugepages`) big enough for the expert copy, the engine uses them and copies prompt data in place: an 8K prompt on the 2.25 set read 651 tok/s without and 694 with (R9700 limited to 12 GB; that run also set two buffers by hand). Without a reserved pool nothing changes. Not run with a reserved pool on the release package. +- **Settings that help if your PC fits them, no engine change:** `--ple-io ram` (the 28.8 GB table in RAM; on the 72 GB card prompts +16.5% at 1K, +30.6% at 4K, +16.8% at 8K), `--mtp-draft-vocab draft_vocab_en.bin` (+2.7 to +3.1% decode for English text), `--slots 2` for two conversations at once (+10% to +12% aggregate throughput on RTX PRO 5000 and RTX 3060), `--prefill-pipe` on a two-card layer split (+15% at 4K, +23% at 8K prompts on two RTX A4000). `--kv q4_0` on a 12 GB card did not reproduce a gain, so it is a choice, not a default. -These need no engine change; they are settings. Each was measured on the same boxes. +## Fixed, from your reports -- **`--ple-io ram`** - the 28.8 GB n-gram table in RAM instead of read from the SSD row by row. On the 72 GB card - (251 GB RAM): prompt **+16.5% at 1K, +30.6% at 4K, +16.8% at 8K**, -2.6% at 16K. Setup chooses it on a Linux PC - with RAM to spare - check `setup --plan` on yours before trusting that. -- **`--mtp-draft-vocab draft_vocab_en.bin`** - the helper that guesses the next words considers 162 KB of the - vocabulary instead of 425 KB, so it reads less per guess: **+2.7..3.1% story and +2.2..3.0% code** decode on both - big boxes. The big model checks every guess, so the answers are unchanged (identical tokens in every run where - the machine is deterministic). A CJK or Cyrillic user should keep the wider subset. -- **`--slots 2`** - when the engine serves more than one conversation at a time (an agent with several sessions), decoding two - requests together returns **+10% aggregate throughput on the RTX PRO 5000 and +12% on the RTX 3060**, for a slightly higher - latency per token. Three and four slots add nothing measurable (+8.4% and +11.7%): the gain is all in the second slot, and - more slots cost KV memory. A single conversation gains nothing from it. -- **`--prefill-pipe `** - on a two-card layer split, plan the prompt's chunks for the pipeline: **+15.4% at 4K, - +22.5% at 8K, +2.7% at 16K** prompt on 2x RTX A4000 (5 interleaved pairs). `R` is the PC's own ratio; `setup --calibrate` measures it - (1,500 on that box). -- **`--kv q4_0` on a 12 GB card** - the KV cache at 4 bits leaves room for ~1,000 more experts. On the RTX 3060 - 12 GB (IQ3_XXS) the gain did **not** reproduce: +12.0% story over three pairs, -2.9% over five, with that box's - own baseline moving 41.6 -> 49.0 tok/s between sessions, so no speed claim is made for it. It costs KV precision - on long documents (document perplexity +8% at 1K, +12% at 8K in `bench/results/2026-09-27-kv-q4`), so it is a - choice, not a default. +Each issue number gets its own reply. -## The 12 GB default: residency-biased routing +- Chat: scrolling up while an answer streams works (#4014); a request that timed out shows a badge (#3991). +- The Monitor asks the NVIDIA tool only while it is open or a model runs, which stops the Windows stutter (#4066). The app no longer insists on CUDA when you have a HIP card on Windows (#3892), and the source-checkout host starts an engine with an empty API key (#3851). Deleting a model in the app removes all files of a multi-file model and leaves your own files (#3716). +- The Terminal: `strata launch --set dspark=on` works (#3959); `launch --show-key` knows the config setup wrote (#3570); a model on disk in a differently cased folder is found on Linux instead of being offered for download again (#3996); `--spec 5` can be saved with a warning (#3844) [pending: f-027-gh-eng-d]. +- Manual mode: read-only commands that have write or execute options now ask first (#3975). +- Engine [pending: f-027-gh-eng]: a conversation cache no longer reuses another conversation's keys and values (#1503); a short draft-vocabulary row can't be written past (#3911); a checkpoint save that runs out of memory no longer exits the engine (#3350); a hand build for RTX 50 no longer ends up as sm_75 (#4029, #4023); the DeepSeek CUDA packages now include RTX 40 cards (sm_89, #3935); an undeclared tool call returned as text is recovered, declared-only kept (#3796). +- Engine, audit fixes [pending: f-027-gh-eng-d]: a failed read in the per-layer table reader no longer leaves the next request waiting for ever (#3602); a conversation restore that would have to create a new copy stream on a card with almost no free memory goes back to the cache instead of failing (#2409); an engine that cannot allocate on a layer split now says how much memory it planned to keep free and how much is free (#3638, #3702); `--spec 5` and other values outside the tuner's range can be saved with a warning (#3844). +- Setup and Docker: setup accepts engines that come from the update feed (#4027); a silent re-download in Docker fails loudly (#3421); the Docker image stage carries the scripts the Terminal needs (#3974, #3644); images are tagged 0.2.7. +- Docs: TROUBLESHOOTING is back with every entry that the 0.2.5 rewrite dropped, updated for 0.2.7; the Strix Halo Windows guide (#3029, first written by @HaiYunChuang, measured again here); a Polish README (#3355, by @j-luwierski, the 8th README). +- A graphics card that went through GPU resets can hang engine starts until the PC is rebooted. We saw it on a 4 x R9700 box; 40 loads after a fresh boot had no stall. -**On by default at 1.5 on a discrete NVIDIA card with 13 GiB of memory or less** (`STRATA_ROUTE_PRIOR=0` turns it off, an explicit value wins; -not a default on a Radeon, a Strix Halo or any integrated GPU, where it was not measured). The router prefers -experts that are already resident, so a window stops waiting on a page-in that the next window would need again. The first -0.2.7 candidates used a bonus of 2.0, and the table below was measured at 2.0 on the RTX 3060 12 GB (IQ3_XXS), five interleaved -pairs of fresh engines. The default was lowered to 1.5 by the owner on 26 October after the copy and code check on that card -(IQ3_XXS) found real defects in the answers at 2.0 and **no defect in 19 tasks at 1.5** (or at 1.0). 1.5 keeps most of the speed: -story **+15%** and code **+37%** against the routing off. That is 19 tasks, not a proof; a longer 61-task check of 0, 1.5 and 2.0 -is still running, and if it shows defects at 1.5 the default falls back to 1.0. The 2.0 measurements: +Names stay on the commits: 35 contributors' pull requests were ported with their authorship. -| axis | before | after | -|---|---|---| -| decode story | 45.9 | **61.6 (+34.1%)** | -| decode code | 43.6 | **73.1 (+67.6%)** | -| prompt | **not claimed** - this box's prompt read swings between 218 and 466 tok/s across runs, and a repeat of the same five-pair A/B read +254% and -20.5% where the first read +35% and +17% | -| decode behind a 4K document | 45.1 | **62.2 (+37.9%)** | +## What we did not test -It holds where it matters most: with **two conversations in flight** the whole recipe reads **31.2 -> 62.0 tok/s aggregate -(+99%)** on that card and +22% on the 2x A4000, both answers arriving in half the wall time on the 12 GB box, and the routing -default alone is **+67% aggregate** there (59.7 against 35.6 tok/s) - -and on content the tuning was never fitted to it **+29.0%** (43.5 -> 55.0 tok/s on a -document prompt), and the whole recipe - routing, a workload-fitted expert profile, `--adapt-every 0`, `--vram-reserve-mib -896` and the English draft vocabulary - gives **+26.5%** there and **+80%** on code in a sustained 80-request session. - -It works by choosing a slightly different set of experts, so replies change: the owner approved that trade for 12 GB cards. -**Do not raise the bonus to 2.0 or more.** 2.0 showed defects in the copy and code check; 3.0 measures +17.7% / +24.0% on the test -prompts but **-4.5% on held-out content**, and 4.0 breaks outright. `STRATA_ROUTE_PRIOR=2` still works if you want the old value. - -## What was tried and did not make it - -Recorded so nobody repeats it: deeper or wider MTP windows, `STRATA_QFUSE`, `STRATA_STAGE_TRIM`, `STRATA_HC_Q8`, -DFlash2 as the drafter, 4-bit draft copies, `pcie_frac` changes on the 3060, `--pipeline-windows` on a two-card -split, the K-split and the shared-memory-free variants of the hyper-connection down projection, `--prefill` chunks -above 8K, and every Blackwell default switch turned off one at a time. The numbers are in -`CUDA Plan/RESULTS.md` outside this repository. +- Prompts longer than a few thousand tokens at 512K or 1M DeepSeek contexts. +- RTX 40 cards (no Ada card here), A100-class cards, RX 6000 on Windows (#3895) and a two-GPU PC with a slow CPU (#3930): shipped from the reporters' measurements; please tell us. +- Whether the new summation orders (RTX PRO and Ampere-class cards) change answers: a 61-task check on the RTX PRO 5000 passed 54 against 55 with the switches off, and its differences stayed inside the spread between two identical runs; it is a small sample. +- The huge-page path with a reserved pool on the release package. +- The DeepSeek Strix Halo package on a 64 GB or 32 GB machine, and the 2.25 set on it. +- The route prior on the owner's RTX 5070: it applies there, and the quality check ran on the RTX 3060. +- The in-app updater from 0.2.6 to 0.2.7 (its files and signatures are checked; we run it after publishing). +- Any Mac beyond the signed build; Metal and SYCL got no 0.2.7 speed change. ## Updating -- The engine package that carries this is chosen by the owner; the app and the Terminal keep their own versions. -- From 0.2.6: the usual update path for the part that changed. +- **App:** the in-app updater installs the new installer. The app then offers the 0.1.52 engine. [TO CONFIRM with the update test] +- **Terminal:** run `strata update`. It fetches Control 0.1.52 and the newer engine. [TO CONFIRM with the update test] +- **DeepSeek engine:** updates itself on the next `strata launch`. + +## Downloads + +Three installers, the three Control packages (0.1.52), 13 Qwen engine packages and 4 DeepSeek engine packages (all 0.1.52: Windows CUDA 13, Windows AMD for Ryzen AI Max, Linux CUDA 13, Linux AMD rx9070), plus `strata-feed.json` with its signature, `latest.json`, `install-manifest.txt`, `install.sh`, `install.ps1` and `SHA256SUMS.txt`. The DeepSeek CUDA packages are built for sm_86, sm_89 and sm_120. [pending: f-027-gh-eng] --- Strata is free and open source. If it runs well on your PC, a coffee keeps the work on it going: Buy Me A Coffee - - - - diff --git a/serve/server.py b/serve/server.py index 4748a721..4276cf52 100644 --- a/serve/server.py +++ b/serve/server.py @@ -2227,7 +2227,7 @@ class StrataEngine: "tok_s": round(r["generated"] / max(1e-6, now - ft), 1) if ft else None}) return view - def generate(self, ids, max_new, sampling, cancel, embeddings=None): + def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only=False): """Yields token ids, and None as a heartbeat every 10 s while the engine is quiet (reading a long prompt): the HTTP layer turns it into an SSE comment, which keeps clients' watchdogs calm and notices a client that has gone. A consumer that stops early (or `cancel`) makes the engine STOP, so it does not run to max_new.""" @@ -2248,6 +2248,10 @@ class StrataEngine: # an image request takes the same sampling keys as text (#75: it used to decode greedily whatever was asked) head = f"GENI {int(max_new)}{self.sampling_keys(sampling or {})} {embeddings}" if embeddings else \ f"GEN {int(max_new)}{self.sampling_keys(sampling or {})}" + if prefill_only: # split serving (serve/split.py): read the prompt, make no token + if embeddings or int(max_new) != 0: + raise ValueError("prefill_only is a text prompt and max_new 0") + head = "GEN 0 prefill=1" try: self.proc.stdin.write(f"{head} {','.join(str(int(t)) for t in ids)}\n") self.proc.stdin.flush() @@ -4763,6 +4767,8 @@ class Service: live["state"] = "generating" if hasattr(self.engine, "replica_view"): # opt-in replicas: each one's state and requests routed to it live["replicas"] = self.engine.replica_view() + if hasattr(self.engine, "split_view"): # opt-in split serving: the hand-overs so far (serve/split.py) + live["split_serve"] = self.engine.split_view() engine = {"model": self.model, "max_context": self.reported_ctx(), "images": self.vision is not None, **dict(getattr(self.engine, "info", {}) or {})} tel = self.telemetry.snapshot() if getattr(self, "telemetry", None) else {"now": {}, "history": {}, "static": {}} @@ -8470,6 +8476,39 @@ def start_replicas(cfg: dict, groups: list[list[int]], exe: str, effort_end: lis return rp.ReplicaEngine(engines, load_tokens=load) +def start_split(cfg: dict, spec: dict, exe: str, effort_end: list[str], lazy: bool, *, offline: bool = False): + """Opt-in split serving (serve/split.py): a prefill engine and a decode engine, one card each, the same model and the + same session settings. Started one after the other, so a shared expert arena is filled once; the SplitEngine in + front hands a long prompt from the first to the second.""" + from serve import split as sp + sp.check_cfg(cfg, spec) + arena, arena_note = sp.arena_path(cfg, spec) + work = sp.session_dir(spec) + print(f"[strata] split serving: the prompt is read on card {spec['prefill_gpu']}, the answer is made on card " + f"{spec['decode_gpu']} (prompts with {spec['min_prompt_tokens']}+ new tokens are handed over); {arena_note}", + flush=True) + engines = {} + try: + for role in ("prefill", "decode"): + rc = sp.role_cfg(cfg, spec, role) + if arena: + rc["args"] = list(rc["args"]) + ["--shared-expert-arena", arena] + if role == "prefill": + warn_budget_over_ram(engine_args(rc) if "args" in rc else []) + engines[role] = StrataEngine(exe, engine_args(rc) + effort_end, cwd=rc.get("cwd"), log=rc.get("log"), + env=child_env(rc, offline=offline), lazy=lazy) + except BaseException: + for e in engines.values(): + try: + e.close() + except Exception: # noqa: BLE001 + pass + shutil.rmtree(work, ignore_errors=True) + raise + return sp.SplitEngine(engines["prefill"], engines["decode"], min_tokens=spec["min_prompt_tokens"], work_dir=work, + arena_file=arena) + + def check_request_sampling(req) -> None: """A request's sampling field of the wrong JSON type ("temperature": "0.7", "top_k": 40.0, "seed": true) is a 400 that names the field, as the same value is through POST /settings or the run config. Unchecked, the value @@ -8673,6 +8712,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in help="data-parallel replicas (opt-in): cut the \"gpu\" list into N equal groups and run one engine on " "each, requests spread over them (also \"replicas\" in the config: a number, or " "[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])") + ap.add_argument("--split-serve", default=None, metavar="PREFILL,DECODE", + help="split serving (opt-in): one engine on card PREFILL reads the prompt, a second on card DECODE makes " + "the answer, the session handed over in RAM (also \"split_serve\" in the config: " + "{\"prefill_gpu\": 0, \"decode_gpu\": 1}; docs/SPLIT_SERVE.md)") launch_args = list(sys.argv[1:] if argv is None else argv) a = ap.parse_args(launch_args) if a.engine == "strata" and (_rt := rttime_limit_note()): # #3238: say it before the first unexplained -9 @@ -8746,6 +8789,12 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in lift_reasoning_effort_arg(cfg) if a.replicas is not None: cfg["replicas"] = a.replicas + if a.split_serve is not None: + pair = [x.strip() for x in a.split_serve.split(",")] + if len(pair) != 2 or not all(x.isdecimal() for x in pair): + ap.error("--split-serve takes two card numbers: PREFILL,DECODE (for example 0,1)") + cfg["split_serve"] = {**(cfg.get("split_serve") if isinstance(cfg.get("split_serve"), dict) else {}), + "prefill_gpu": int(pair[0]), "decode_gpu": int(pair[1])} if a.gpu is not None: cfg["gpu"] = int(a.gpu) if a.gpu.strip().isdigit() else a.gpu a.host = a.host or cfg.get("host") or "127.0.0.1" # issue #26: the run scripts pass no --host, the config can @@ -8880,15 +8929,24 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in groups = rp.gpu_groups(cfg) except rp.ReplicaConfigError as e: raise SystemExit(f"[strata] config {e}") + from serve import split as split_mod + try: + split = split_mod.split_spec(cfg) + if split: + split_mod.check_cfg(cfg, split) + except split_mod.SplitConfigError as e: + raise SystemExit(f"[strata] config {e}") if groups: engine = start_replicas(cfg, groups, exe, effort_end or [], lazy, offline=a.offline) + elif split: + engine = start_split(cfg, split, exe, effort_end or [], lazy, offline=a.offline) else: engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) engine.silence_s = silence # an attribute of its own: restart() keeps it warn_tight_ram(engine.info.get("arena_mib")) note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], - linux_desktop()) if not groups else None + linux_desktop()) if not groups and not split else None if note: # #560 #516: before --open starts a browser on that card print(note, flush=True) else: @@ -9056,8 +9114,12 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in svc.gpu_indices = [c for g in groups for c in g] svc.gpu_index = svc.gpu_indices[0] svc.replica_gpu_groups = groups + if a.engine == "strata" and split: # split serving: the two cards (the prefill card first) + svc.gpu_indices = [split["prefill_gpu"], split["decode_gpu"]] + svc.gpu_index = split["decode_gpu"] svc.terminal_visibility_order = visible_device_order(env, cfg.get("backend")) if a.engine == "strata" else [] svc.terminal_topology_mode = ("replicas (configured)" if a.engine == "strata" and groups + else "split serve (configured)" if a.engine == "strata" and split else "layer split (configured)" if a.engine == "strata" and layer_split_of(cfg) else "single GPU or CPU" if a.engine == "strata" else "mock") svc.terminal_configured_split = (layer_split_value(cfg) if a.engine == "strata" and layer_split_of(cfg) diff --git a/serve/split.py b/serve/split.py new file mode 100644 index 00000000..5b28394a --- /dev/null +++ b/serve/split.py @@ -0,0 +1,488 @@ +"""Split serving: one engine reads the prompt, another makes the answer (issue #4000, idea and manual setup by @MarcoTool). + +Two engines on the same PC, one card each, the same model files and the same session settings. A long prompt is read by +the prefill engine, which saves the session (the engine's own session file: SAVE ) into RAM; the decode engine +restores it (RESTORE ) and makes the answer. The server keeps its one HTTP front, its one Service and its one set of +endpoints; `SplitEngine` stands in for the engine, as `ReplicaEngine` does for replicas. + +Opt-in, in the run config (nothing changes without it): + + "split_serve": {"prefill_gpu": 0, "decode_gpu": 1} + + prefill_gpu / decode_gpu the card of each engine, numbered as nvidia-smi numbers them (required, different) + min_prompt_tokens hand a request over only when the decode engine would read at least this many new tokens + itself (default 2048); a shorter tail is read by the decode engine in place + dir where the session files go (default /dev/shm when it has room, else the temp folder) + shared_arena true (default): one copy of the experts in RAM for both engines (Linux, a file in /dev/shm + when the experts fit there); false: each engine keeps its own copy; a path: that file + prefill_args / decode_args extra engine arguments for one role (a bigger expert cache for the decode engine, say) + +What must match between the two engines is what the session file checks (docs/SPLIT_SERVE.md): the model files, the engine +version, the backend, --kv, --max-context, --kv-resident, --mtp-window, the rope settings and the arithmetic switches. They +start from one config, so they do. Every failure on the way (a prefill engine that died, a refused file) is not an error +for the client: the decode engine reads the prompt itself, as it would without the option. + +Honest limit of this first version: one request at a time (the Service's FIFO), one conversation resident on the decode +engine (a restore replaces what it held), no parallel slots (--batch), no layer split in an engine, no pictures (a request +with pictures goes to the decode engine alone). +""" +from __future__ import annotations + +import os +import shutil +import tempfile +import threading +import time + +MIN_TOKENS = 2048 # the decode engine's own tail below this is read in place +KNOWN_KEYS = {"prefill_gpu", "decode_gpu", "min_prompt_tokens", "dir", "shared_arena", "prefill_args", "decode_args"} +FORBIDDEN_ARGS = { # engine arguments that cannot be used in a split-serve engine, and why + "--layer-split": "an engine of the split runs on one card", + "--split-device": "an engine of the split runs on one card", + "--peer-device": "session files do not support --peer-device", + "--batch": "session files do not support --batch (parallel requests)", + "--slots": "session files do not support parallel slots", +} +HEAL_COOLDOWN_S = 60.0 # a prefill engine that died is started again at most this often +HEARTBEAT_S = 5.0 # a long file step sends a keep-alive this often + + +class SplitConfigError(ValueError): + pass + + +def split_spec(cfg: dict) -> dict | None: + """The checked "split_serve" section of the run config, or None when the option is off.""" + raw = cfg.get("split_serve") + if raw is None or raw is False: + return None + if not isinstance(raw, dict): + raise SplitConfigError('"split_serve" must be {"prefill_gpu": N, "decode_gpu": M}, not ' + repr(raw)) + unknown = sorted(set(raw) - KNOWN_KEYS) + if unknown: + raise SplitConfigError(f'"split_serve" has no key {unknown[0]!r} (keys: {", ".join(sorted(KNOWN_KEYS))})') + cards = [] + for k in ("prefill_gpu", "decode_gpu"): + v = raw.get(k) + if isinstance(v, str) and v.strip().isdigit(): + v = int(v.strip()) + if isinstance(v, bool) or not isinstance(v, int) or v < 0: + raise SplitConfigError(f'"split_serve" needs "{k}": the number of a card (0, 1, ...), not {v!r}') + cards.append(v) + if cards[0] == cards[1]: + raise SplitConfigError(f'"split_serve": prefill_gpu and decode_gpu are both card {cards[0]}; each engine needs a ' + "card of its own") + out = {"prefill_gpu": cards[0], "decode_gpu": cards[1]} + n = raw.get("min_prompt_tokens", MIN_TOKENS) + if isinstance(n, bool) or not isinstance(n, int) or n < 0: + raise SplitConfigError(f'"split_serve": "min_prompt_tokens" must be a number of tokens (0 or more), not {n!r}') + out["min_prompt_tokens"] = n + d = raw.get("dir") + if d is not None and (not isinstance(d, str) or not d.strip()): + raise SplitConfigError(f'"split_serve": "dir" must be a folder name, not {d!r}') + out["dir"] = d + sa = raw.get("shared_arena", True) + if not (isinstance(sa, bool) or (isinstance(sa, str) and sa.strip())): + raise SplitConfigError(f'"split_serve": "shared_arena" must be true, false or a file name, not {sa!r}') + out["shared_arena"] = sa + for k in ("prefill_args", "decode_args"): + a = raw.get(k, []) + if not isinstance(a, list) or not all(isinstance(x, (str, int, float)) and not isinstance(x, bool) for x in a): + raise SplitConfigError(f'"split_serve": "{k}" must be a list of engine arguments') + out[k] = [str(x) for x in a] + return out + + +def check_cfg(cfg: dict, spec: dict) -> None: + """Refuse (with the reason, in plain words) a config the split cannot run.""" + if cfg.get("replicas") not in (None, False): + raise SplitConfigError('"split_serve" and "replicas" cannot be used together: both start engines on the cards') + args = [str(a) for a in cfg.get("args") or []] + spec["prefill_args"] + spec["decode_args"] + for flag, why in FORBIDDEN_ARGS.items(): + if flag in args: + raise SplitConfigError(f'"split_serve" cannot be used with {flag} in the engine arguments: {why}') + for i, a in enumerate(args): + if a == "--prompt-cache" and i + 1 < len(args) and args[i + 1].strip() == "0": + raise SplitConfigError('"split_serve" needs the conversation cache (--prompt-cache 1 or more): the session ' + "file is made from it") + if cfg.get("batch") or cfg.get("parallel"): + raise SplitConfigError('"split_serve" does not run parallel requests ("parallel"/"batch"): remove it') + + +def _suffixed(path, tag: str): + if not isinstance(path, str) or not path: + return path + root, ext = os.path.splitext(path) + return f"{root}.{tag}{ext}" + + +def role_cfg(cfg: dict, spec: dict, role: str) -> dict: + """The config of one engine of the split: its own card, log and learned-profile file; its role's extra arguments.""" + import copy + c = copy.deepcopy(cfg) + c.pop("split_serve", None) + c["gpu"] = spec[f"{role}_gpu"] + c.pop("hip_ordinal", None) + c.pop("gpu_roles", None) # the roles were for a layer split over several cards + c["log"] = _suffixed(cfg.get("log"), role) + if cfg.get("expert_profile_save"): + c["expert_profile_save"] = _suffixed(cfg["expert_profile_save"], role) + extra = spec[f"{role}_args"] + if extra: + c["args"] = list(c["args"]) + extra + return c + + +def _arg_value(args: list, flag: str): + for i, a in enumerate(args): + if a == flag and i + 1 < len(args): + return args[i + 1] + return None + + +def arena_path(cfg: dict, spec: dict) -> tuple[str | None, str]: + """(file for --shared-expert-arena or None, a line for the log). Only Linux can share the arena; the experts + file must fit /dev/shm (a tmpfs is half of the RAM by default) unless the config names another file.""" + args = [str(a) for a in cfg.get("args") or []] + if "--shared-expert-arena" in args: + return None, "the config already names a shared expert arena" + sa = spec["shared_arena"] + if sa is False: + return None, "shared_arena is off: each engine keeps its own copy of the experts in RAM" + if os.name == "nt": + return None, ("this OS cannot share the expert arena between two engines (Linux only): each engine keeps its own " + "copy of the experts in RAM, so the PC needs RAM for two") + if isinstance(sa, str): + return os.path.abspath(sa), f"shared expert arena in {os.path.abspath(sa)}" + pack = _arg_value(args, "--pack") + experts = os.path.join(pack, "experts.bin") if pack else None + if not experts or not os.path.isfile(experts): + return None, ("no experts.bin to size a shared arena from (a pack that reads the GGUF in place): each engine " + "keeps its own copy of the experts; name a file in \"shared_arena\" to share one") + need = os.path.getsize(experts) + try: + free = shutil.disk_usage("/dev/shm").free + except OSError: + free = 0 + if free < need + (1 << 30): + return None, (f"/dev/shm has {free / 2**30:.1f} GiB free and the experts are {need / 2**30:.1f} GiB: each engine " + "keeps its own copy of the experts in RAM (two copies). To share one copy name a file in " + "\"shared_arena\" (a file on disk works, it is written once) or make /dev/shm bigger") + return "/dev/shm/strata-split-arena.bin", f"one shared expert arena in /dev/shm ({need / 2**30:.1f} GiB)" + + +def session_dir(spec: dict) -> str: + d = spec.get("dir") + if d: + os.makedirs(d, exist_ok=True) + return d + shm = "/dev/shm" + try: + if os.name != "nt" and os.path.isdir(shm) and os.access(shm, os.W_OK) and shutil.disk_usage(shm).free > (6 << 30): + return tempfile.mkdtemp(prefix="strata-split-", dir=shm) + except OSError: + pass + return tempfile.mkdtemp(prefix="strata-split-") + + +def common_prefix(a, b) -> int: + n = min(len(a), len(b)) + i = 0 + while i < n and a[i] == b[i]: + i += 1 + return i + + +class SplitEngine: + """Stands in for one engine (the interface Service uses), over a prefill engine and a decode engine.""" + + NOT_HERE = {"session_file", "vram", "ctl", "slot_cv"} # not offered: one conversation file / VRAM resize / control line + PROPAGATE = {"silence_s", "gpu_busy"} + + def __init__(self, prefill, decode, *, min_tokens: int = MIN_TOKENS, work_dir: str | None = None, + arena_file: str | None = None, say=print): + d = self.__dict__ + d["prefill"], d["decode"] = prefill, decode + d["cur"] = decode # the engine the request is on now (progress, last) + d["min_tokens"] = int(min_tokens) + d["work_dir"] = work_dir or tempfile.mkdtemp(prefix="strata-split-") + d["arena_file"] = arena_file + d["say"] = say + d["held"] = [] # the tokens the decode engine's session holds (an estimate: ids + answer) + d["seq"] = 0 + d["heal_at"] = 0.0 + d["healing"] = False + d["lock"] = threading.Lock() + d["stats"] = {"requests": 0, "handed_over": 0, "fallbacks": 0, "short": 0, "bytes": 0, "prefill_ms": 0.0, + "save_ms": 0.0, "restore_ms": 0.0, "last": None} + + # ---- attribute plumbing + def __getattr__(self, name): + if name in self.NOT_HERE or name.startswith("__"): + raise AttributeError(name) + return getattr(self.decode, name) + + def __setattr__(self, name, value): + if name in self.PROPAGATE: + self.prefill.__setattr__(name, value) + self.decode.__setattr__(name, value) + else: + self.__dict__[name] = value + + @property + def last(self): + return self.decode.last + + @last.setter + def last(self, value): + self.decode.last = value + + @property + def progress(self): + return self.cur.progress + + @property + def prefill_tok_s_mean(self): + return self.cur.prefill_tok_s_mean + + @property + def batch(self) -> int: + return 0 + + @property + def max_context(self) -> int: + v = [e.max_context for e in (self.prefill, self.decode) if getattr(e, "max_context", 0) and e.alive()] + return min(v) if v else 0 + + @property + def unloaded(self) -> bool: + return all(getattr(e, "unloaded", False) for e in (self.prefill, self.decode)) + + @property + def starting(self) -> bool: + return not self.alive() and any(getattr(e, "starting", False) for e in (self.prefill, self.decode)) + + @property + def info(self) -> dict: + i = dict(self.decode.info) + i["split_serve"] = True + i["split_prefill_alive"] = bool(self.prefill.alive()) + return i + + @info.setter + def info(self, value): + pass + + def alive(self) -> bool: + return bool(self.decode.alive()) + + def exit_code(self): + return next((c for c in (e.exit_code() for e in (self.decode, self.prefill) if not e.alive()) if c is not None), + None) + + def death_note(self) -> str: + return next((e.death_note() for e in (self.decode, self.prefill) if not e.alive()), "") + + def split_view(self) -> dict: + """For /metrics: how the two engines are used.""" + s = dict(self.stats) + s.update(prefill_alive=bool(self.prefill.alive()), decode_alive=bool(self.decode.alive()), + min_prompt_tokens=self.min_tokens) + return s + + # ---- life cycle + def restart(self, tries: int = 3): + errors = {} + for name, e in (("decode", self.decode), ("prefill", self.prefill)): # one at a time: the arena fills once + if e.alive(): + continue + try: + e.restart(tries) + except BaseException as x: # noqa: BLE001 + errors[name] = x + if "decode" in errors: + raise errors["decode"] + for name, x in errors.items(): + self.say(f"[strata] the {name} engine of the split did not start ({x}); the other one serves") + self.__dict__["held"] = [] + + def unload(self): + for e in (self.prefill, self.decode): + e.unload() + self.__dict__["held"] = [] + + def close(self): + err = None + for e in (self.prefill, self.decode): + try: + e.close() + except BaseException as x: # noqa: BLE001 + err = err or x + shutil.rmtree(self.work_dir, ignore_errors=True) + if self.arena_file and self.arena_file.startswith("/dev/shm/strata-split-"): + try: + os.unlink(self.arena_file) # RAM until it is gone + except OSError: + pass + if err: + raise err + + def heal(self) -> None: + """Start a prefill engine that died again, in the background (the decode engine serves meanwhile).""" + e = self.prefill + now = time.monotonic() + if e.alive() or getattr(e, "unloaded", False) or getattr(e, "starting", False) or self.healing or now < self.heal_at: + return + self.__dict__["heal_at"] = now + HEAL_COOLDOWN_S + self.__dict__["healing"] = True + + def run(): + try: + self.say("[strata] split: the prefill engine had stopped; starting it again") + e.restart() + self.say("[strata] split: the prefill engine is running again") + except BaseException as x: # noqa: BLE001 + self.say(f"[strata] split: the prefill engine did not start again: {x}") + finally: + self.__dict__["healing"] = False + threading.Thread(target=run, daemon=True).start() + + # ---- the request + def wants_handover(self, ids) -> tuple[bool, int]: + """(hand the prompt to the prefill engine?, the tokens the decode engine would read itself).""" + n = len(ids) + if n < 2: + return False, 0 + need = (n - 1) - min(common_prefix(self.held, ids), n - 1) + return need >= max(1, self.min_tokens) and self.prefill.alive(), need + + def _wait(self, fn): + """Run a blocking engine call on a thread; yields None as a keep-alive while it runs. -> its result.""" + box = {} + + def run(): + try: + box["r"] = fn() + except BaseException as e: # noqa: BLE001 + box["e"] = e + th = threading.Thread(target=run, daemon=True) + th.start() + while th.is_alive(): + th.join(HEARTBEAT_S) + if th.is_alive(): + yield None + if "e" in box: + raise box["e"] + return box.get("r") + + def _hand_over(self, ids, cancel, rec: dict): + """Prefill engine reads the prompt, saves the session; the decode engine restores it. Yields keep-alives. + rec['ok'] is True when the decode engine now holds the prompt's first n-1 tokens.""" + from serve.server import EngineDied, SessionRefused + P, D = self.prefill, self.decode + n = len(ids) + self.__dict__["seq"] += 1 + path = os.path.join(self.work_dir, f"handover-{os.getpid()}-{self.seq}.session") + rec.update(ok=False) + t0 = time.monotonic() + self.__dict__["cur"] = P + try: + try: + for _ in P.generate(ids, 0, {}, cancel, prefill_only=True): + yield None + except (EngineDied, ValueError) as e: + self.say(f"[strata] split: the prefill engine failed ({e}); the decode engine reads the prompt itself") + self.heal() + return + if cancel.is_set(): + return + p_last = dict(P.last or {}) + rec["prefill_ms"] = (time.monotonic() - t0) * 1000.0 + rec["p_last"] = p_last + try: + saved = yield from self._wait(lambda: P.session_file("save", path)) + self.__dict__["cur"] = D + restored = yield from self._wait(lambda: D.session_file("restore", path)) + except SessionRefused as e: + self.say(f"[strata] split: the session file was refused ({e}); the decode engine reads the prompt itself") + return + except EngineDied as e: + if not D.alive(): + raise + self.say(f"[strata] split: the prefill engine failed while saving ({e}); the decode engine reads the prompt " + "itself") + self.heal() + return + rec.update(save_ms=float(saved["ms"]), restore_ms=float(restored["ms"]), bytes=int(saved["bytes"]), + tokens=int(restored["tokens"]), ok=restored["tokens"] == n - 1) + if not rec["ok"]: + self.say(f"[strata] split: the decode engine restored {restored['tokens']} tokens, not the {n - 1} the " + "prompt needs; it reads the rest itself") + rec["ok"] = restored["tokens"] > 0 + finally: + self.__dict__["cur"] = D + try: + os.unlink(path) + except OSError: + pass + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + D = self.decode + ids = list(ids) + st = self.stats + st["requests"] += 1 + rec: dict = {} + use, need = (False, 0) if embeddings is not None else self.wants_handover(ids) + if not use: + st["short"] += 1 + if use: + if not self.prefill.alive(): + self.heal() + yield from self._hand_over(ids, cancel, rec) + if cancel.is_set(): + self.__dict__["held"] = [] + return + if rec.get("ok"): + st["handed_over"] += 1 + st["bytes"] += rec["bytes"] + st["prefill_ms"] += rec["prefill_ms"] + st["save_ms"] += rec["save_ms"] + st["restore_ms"] += rec["restore_ms"] + self.__dict__["held"] = ids[:len(ids) - 1] + else: + st["fallbacks"] += 1 + self.__dict__["cur"] = D + produced: list[int] = [] + ok = False + try: + gen = D.generate(ids, max_new, sampling, cancel, embeddings=embeddings) if embeddings is not None \ + else D.generate(ids, max_new, sampling, cancel) + for t in gen: + if t is not None: + produced.append(t) + yield t + ok = True + finally: + self.__dict__["held"] = (ids + produced) if ok else [] + if rec.get("ok") and ok: + self._account(ids, rec) + + def _account(self, ids, rec: dict) -> None: + """The figures of the engine's last DONE, as the whole request: the prefill engine's read, the file steps and the + decode engine's own start are the prompt time; what the prefill engine reused is the cached part.""" + D = self.decode + last = dict(D.last or {}) + p = rec.get("p_last") or {} + total_prompt_ms = rec["prefill_ms"] + rec["save_ms"] + rec["restore_ms"] + float(last.get("prompt_ms") or 0.0) + p_read = p.get("prompt_read") + if p_read is None: + p_read = len(ids) - int(p.get("reused") or 0) + last.update(prompt_ms=total_prompt_ms, reused=int(p.get("reused") or 0), + prompt_read=max(0, min(len(ids), int(p_read) + int(last.get("prompt_read") or 0))), + split_prefill_ms=round(rec["prefill_ms"], 1), split_save_ms=round(rec["save_ms"], 1), + split_restore_ms=round(rec["restore_ms"], 1), split_bytes=rec["bytes"]) + D.last = last + self.stats["last"] = {k: last[k] for k in last if k.startswith("split_")} + self.say(f"[strata] split: prompt {len(ids)} tokens read on the prefill card in {rec['prefill_ms'] / 1000:.1f} s, " + f"session {rec['bytes'] / 2**20:.0f} MiB saved in {rec['save_ms'] / 1000:.2f} s and restored in " + f"{rec['restore_ms'] / 1000:.2f} s; the decode card makes the answer") diff --git a/serve/test_split.py b/serve/test_split.py new file mode 100644 index 00000000..a1216436 --- /dev/null +++ b/serve/test_split.py @@ -0,0 +1,271 @@ +"""Split serving (serve/split.py): the config, the decision, the hand-over with two fake engines, and every fallback. +The engine-side proof (the continuation after a hand-over equals a single engine's) is tests/split_serve_exact.py.""" +import os +import tempfile +import threading +import unittest + +from serve import split as sp +from serve.server import EngineDied, SessionRefused +from serve.split import SplitConfigError, SplitEngine, check_cfg, common_prefix, role_cfg, split_spec + + +class Config(unittest.TestCase): + def test_off_without_the_key(self): + self.assertIsNone(split_spec({})) + self.assertIsNone(split_spec({"split_serve": False})) + self.assertIsNone(split_spec({"split_serve": None})) + + def test_cards_and_defaults(self): + s = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": "1"}}) + self.assertEqual((s["prefill_gpu"], s["decode_gpu"]), (0, 1)) + self.assertEqual(s["min_prompt_tokens"], sp.MIN_TOKENS) + self.assertIs(s["shared_arena"], True) + self.assertEqual((s["prefill_args"], s["decode_args"]), ([], [])) + + def test_mistakes_are_said(self): + bad = [{"split_serve": 1}, {"split_serve": {"prefill_gpu": 0}}, {"split_serve": {"prefill_gpu": 1, "decode_gpu": 1}}, + {"split_serve": {"prefill_gpu": 0, "decode_gpu": -1}}, {"split_serve": {"prefill_gpu": True, "decode_gpu": 1}}, + {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "x": 1}}, + {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "min_prompt_tokens": "9"}}, + {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "prefill_args": "--x"}}, + {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": 3}}] + for cfg in bad: + with self.assertRaises(SplitConfigError, msg=cfg): + split_spec(cfg) + + def test_check_cfg_refuses_what_cannot_run(self): + spec = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1}}) + check_cfg({"args": ["--serve", "--prompt-cache", "3"]}, spec) + for cfg in ({"args": ["--layer-split", "24"]}, {"args": ["--batch", "2"]}, {"args": ["--prompt-cache", "0"]}, + {"args": [], "replicas": 2}, {"args": [], "parallel": 2}, {"args": ["--peer-device", "1"]}): + with self.assertRaises(SplitConfigError, msg=cfg): + check_cfg(cfg, spec) + spec2 = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "decode_args": ["--batch", "2"]}}) + with self.assertRaises(SplitConfigError): + check_cfg({"args": []}, spec2) + + def test_role_cfg(self): + cfg = {"gpu": [0, 1], "args": ["--x"], "log": "/l/strata.log", "hip_ordinal": 1, "gpu_roles": {"0": "main"}, + "expert_profile_save": "/p/prof.bin", + "split_serve": {"prefill_gpu": 2, "decode_gpu": 3, "decode_args": ["--expert-cache", "auto"]}} + spec = split_spec(cfg) + p, d = role_cfg(cfg, spec, "prefill"), role_cfg(cfg, spec, "decode") + self.assertEqual((p["gpu"], d["gpu"]), (2, 3)) + self.assertEqual((p["log"], d["log"]), ("/l/strata.prefill.log", "/l/strata.decode.log")) + self.assertEqual(p["args"], ["--x"]) + self.assertEqual(d["args"], ["--x", "--expert-cache", "auto"]) + self.assertEqual(d["expert_profile_save"], "/p/prof.decode.bin") + for c in (p, d): + self.assertNotIn("split_serve", c) + self.assertNotIn("hip_ordinal", c) + self.assertNotIn("gpu_roles", c) + self.assertEqual(cfg["args"], ["--x"]) # the original is untouched + + def test_arena_choice(self): + spec = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1}}) + off = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": False}}) + named = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": "/data/a.bin"}}) + self.assertIsNone(sp.arena_path({"args": ["--shared-expert-arena", "/x"]}, spec)[0]) + self.assertIsNone(sp.arena_path({"args": []}, off)[0]) + if os.name != "nt": + self.assertEqual(sp.arena_path({"args": []}, named)[0], os.path.abspath("/data/a.bin")) + path, note = sp.arena_path({"args": ["--pack", "/no/such/pack"]}, spec) # nothing to size it from + self.assertIsNone(path) + self.assertIn("experts.bin", note) + + def test_common_prefix(self): + self.assertEqual(common_prefix([1, 2, 3], [1, 2, 9, 4]), 2) + self.assertEqual(common_prefix([], [1]), 0) + self.assertEqual(common_prefix([1, 2], [1, 2]), 2) + + +class FakeEngine: + """The part of StrataEngine the SplitEngine uses. `session` is the token list its session holds (a file is a json-free + list in a dict keyed by path, shared between the two fakes).""" + files = {} + + def __init__(self, name, tokens_per_answer=3): + self.name, self.up, self.max_context, self.info, self.last = name, True, 4096, {}, {} + self.session, self.log, self.progress, self.prefill_tok_s_mean = [], [], None, None + self.answer = tokens_per_answer + self.fail_save = self.fail_restore = self.fail_prefill = None + self.unloaded = False + + def alive(self): + return self.up + + def restart(self, tries=3): + self.up = True + + def exit_code(self): + return None + + def death_note(self): + return "" + + def unload(self): + self.up = False + + def close(self): + self.up = False + + def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only=False): + if not self.up: + raise EngineDied("down") + if prefill_only: + if self.fail_prefill: + raise self.fail_prefill + have = common_prefix(self.session, ids[:-1]) + self.log.append(("prefill", len(ids))) + self.session = list(ids[:-1]) + self.last = {"generated": 0, "prompt_tokens": len(ids), "prompt_ms": 1000.0, "decode_ms": 0.0, + "finish": "length", "reused": have, "prompt_read": len(ids) - have} + yield None + return + have = common_prefix(self.session, ids[:-1]) + out = [100 + i for i in range(min(max_new, self.answer))] + self.log.append(("generate", len(ids), have)) + self.session = list(ids) + out[:-1] + self.last = {"generated": len(out), "prompt_tokens": len(ids), "prompt_ms": 50.0, "decode_ms": 200.0, + "finish": "length", "reused": have, "prompt_read": len(ids) - have} + for t in out: + yield t + + def session_file(self, action, path): + if action == "save": + if self.fail_save: + raise self.fail_save + FakeEngine.files[path] = list(self.session) + with open(path, "wb") as f: + f.write(b"x" * 1000) + return {"tokens": len(self.session), "bytes": 1000, "ms": 12.0} + if self.fail_restore: + raise self.fail_restore + self.session = list(FakeEngine.files[path]) + return {"tokens": len(self.session), "bytes": 1000, "ms": 7.0} + + +class Handover(unittest.TestCase): + def setUp(self): + FakeEngine.files = {} + self.dir = tempfile.mkdtemp(prefix="split-test-") + self.p, self.d = FakeEngine("p"), FakeEngine("d") + self.said = [] + self.e = SplitEngine(self.p, self.d, min_tokens=100, work_dir=self.dir, say=self.said.append) + self.cancel = threading.Event() + + def run_one(self, ids, max_new=5): + return [t for t in self.e.generate(ids, max_new, {}, self.cancel) if t is not None] + + def test_a_long_prompt_is_handed_over(self): + ids = list(range(500)) + out = self.run_one(ids) + self.assertEqual(out, [100, 101, 102]) + self.assertEqual(self.p.log, [("prefill", 500)]) + self.assertEqual(self.d.log, [("generate", 500, 499)]) # the decode engine read one token itself + self.assertEqual(self.e.stats["handed_over"], 1) + self.assertEqual(os.listdir(self.dir), []) # the session file is gone + last = self.e.last + self.assertEqual(last["reused"], 0) + self.assertEqual(last["prompt_read"], 500) # 499 read by the prefill engine, 1 by the decode one... 500 + self.assertGreaterEqual(last["prompt_ms"], 12.0 + 7.0 + 50.0) # the file steps and the decode engine's start + self.assertLess(last["prompt_ms"], 12.0 + 7.0 + 50.0 + 1000.0) + self.assertEqual(last["split_bytes"], 1000) + + def test_a_short_prompt_stays_on_the_decode_engine(self): + self.run_one(list(range(50))) + self.assertEqual(self.p.log, []) + self.assertEqual(self.e.stats["short"], 1) + + def test_the_next_turn_is_not_handed_over_when_the_decode_engine_holds_it(self): + ids = list(range(500)) + out = self.run_one(ids) + turn2 = ids + out + list(range(7000, 7040)) # the answer and a short question + self.run_one(turn2) + self.assertEqual(len(self.p.log), 1) # only the first turn went through the prefill engine + self.assertEqual(self.d.log[-1][0], "generate") + self.assertGreater(self.d.log[-1][2], 490) # and the decode engine continued its own session + + def test_a_big_new_part_is_handed_over_again(self): + ids = list(range(500)) + out = self.run_one(ids) + self.run_one(ids + out + list(range(9000, 9400))) + self.assertEqual(len(self.p.log), 2) + + def test_pictures_go_to_the_decode_engine(self): + list(self.e.generate(list(range(500)), 3, {}, self.cancel, embeddings="/tmp/x")) + self.assertEqual(self.p.log, []) + + def test_a_dead_prefill_engine_is_not_an_error(self): + self.p.up = False + self.e.heal = lambda: None + out = self.run_one(list(range(500))) + self.assertEqual(out, [100, 101, 102]) + self.assertEqual(self.d.log, [("generate", 500, 0)]) # the decode engine read all of it + + def test_a_prefill_engine_that_dies_midway_falls_back(self): + self.p.fail_prefill = EngineDied("gone") + self.e.heal = lambda: None + out = self.run_one(list(range(500))) + self.assertEqual(out, [100, 101, 102]) + self.assertEqual(self.d.log, [("generate", 500, 0)]) + self.assertTrue(any("failed" in s for s in self.said)) + + def test_a_refused_file_falls_back(self): + for which in ("fail_save", "fail_restore"): + FakeEngine.files = {} + self.p.session, self.d.session = [], [] + setattr(self.p if which == "fail_save" else self.d, which, SessionRefused("invalid", "other model", False)) + self.d.log.clear() + ids = list(range(500)) if which == "fail_save" else list(range(1000, 1500)) + out = self.run_one(ids) + self.assertEqual(out, [100, 101, 102]) + self.assertEqual(self.d.log, [("generate", 500, 0)], which) + setattr(self.p if which == "fail_save" else self.d, which, None) + self.assertEqual(self.e.stats["fallbacks"], 2) + self.assertEqual(os.listdir(self.dir), []) + + def test_a_decode_engine_that_dies_in_the_restore_is_an_error(self): + def boom(*a): + self.d.up = False + raise EngineDied("transfer failed") + self.d.fail_restore = None + orig = self.d.session_file + self.d.session_file = lambda action, path: boom() if action == "restore" else orig(action, path) + with self.assertRaises(EngineDied): + self.run_one(list(range(500))) + self.assertEqual(os.listdir(self.dir), []) + + def test_cancel_during_the_prefill_ends_quietly(self): + self.cancel.set() + orig = self.p.generate + + def gen(*a, **k): + for t in orig(*a, **k): + yield t + self.p.generate = gen + out = self.run_one(list(range(500))) + self.assertEqual(out, []) + self.assertEqual(self.d.log, []) + self.assertEqual(self.e.held, []) + + def test_attributes_come_from_the_decode_engine(self): + self.assertEqual(self.e.max_context, 4096) + self.assertEqual(self.e.batch, 0) + self.assertFalse(hasattr(self.e, "session_file")) + self.assertTrue(self.e.alive()) + self.d.up = False + self.assertFalse(self.e.alive()) + self.assertTrue(self.e.info["split_serve"]) + self.e.silence_s = 5 + self.assertEqual((self.p.silence_s, self.d.silence_s), (5, 5)) + + def test_close_removes_the_work_dir(self): + self.e.close() + self.assertFalse(os.path.exists(self.dir)) + self.assertFalse(self.p.up or self.d.up) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 45e12e5a..65470b24 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -13692,6 +13692,10 @@ int main(int argc, char** argv) { // parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root // when that reaches --prompt-cache-root. Absent = checkpointed as before. int req_ckpt = 1; + // prefill=1 (with max_new 0): split serving. Read the prompt as a request would, up to the place where the first + // verify window starts (the session holds n - 1 tokens, exactly what a next turn that continues it needs), and + // stop: no token is made. A SAVE after it is the hand-over to another engine (docs/SPLIT_SERVE.md). + bool req_prefill_only = false; // pin=N: the first N prompt tokens are a shared read-only prefix (a long document that many short queries // follow). The prompt is read in two parts at N, the checkpoint there is PINNED (retention never evicts it, // a parked conversation holding it stays parked) and a later request that resumes from it does not park the @@ -13722,6 +13726,7 @@ int main(int argc, char** argv) { if (key == "logit_bias") { req_bias_text = tok.substr(eq + 1); req_bias_present = true; } else if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1); else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0; + else if (key == "prefill") req_prefill_only = std::atoi(tok.c_str() + eq + 1) != 0; else if (key == "pin") req_pin = std::max(0, std::atoll(tok.c_str() + eq + 1)); else if (key == "temperature") req_temperature = fv; else if (key == "top_p") req_top_p = fv; @@ -13779,11 +13784,16 @@ int main(int argc, char** argv) { } std::vector ids; std::string pe; - if (max_new < 1 || endp == nullptr || (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) { + if ((max_new < 1 && !(max_new == 0 && req_prefill_only)) || (req_prefill_only && max_new != 0) || endp == nullptr || + (geni && emb_path.empty()) || !parse_i64_list(endp, ids, pe)) { std::printf("ERR bad request: %s\n", pe.empty() ? "max_new" : pe.c_str()); continue; } const int64_t n = (int64_t) ids.size(); + if (req_prefill_only && (geni || o.batch > 0 || n < 2)) { + std::printf("ERR prefill=1 needs a text prompt of at least 2 tokens and no --batch\n"); + continue; + } req_imgs.clear(); if (geni && !o.vision) { std::printf("ERR this engine was started without --vision\n"); continue; } if (geni || !mrope_identity) { diff --git a/tests/terminal/test_docker_files.py b/tests/terminal/test_docker_files.py index d146282a..295e0349 100644 --- a/tests/terminal/test_docker_files.py +++ b/tests/terminal/test_docker_files.py @@ -205,10 +205,10 @@ class Document(unittest.TestCase): def test_tags_in_the_document_match_the_compose_defaults(self): doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") - for tag in ("0.2.3-cuda13", "0.2.3-cuda12", "0.2.3-rocm-gfx120x", "0.2.3-rocm-gfx110x", "0.2.3-rocm-gfx1151", "0.2.3-sycl"): + for tag in ("0.2.7-cuda13", "0.2.7-cuda12", "0.2.7-rocm-gfx120x", "0.2.7-rocm-gfx110x", "0.2.7-rocm-gfx1151", "0.2.7-sycl"): self.assertIn(tag, doc) - for name, tag in (("docker-compose.nvidia.yml", "ghcr.io/niko1221/strata:0.2.3-cuda13"), ("docker-compose.amd.yml", "ghcr.io/niko1221/strata:0.2.3-rocm-gfx120x"), - ("docker-compose.intel.yml", "ghcr.io/niko1221/strata:0.2.3-sycl")): + for name, tag in (("docker-compose.nvidia.yml", "ghcr.io/niko1221/strata:0.2.7-cuda13"), ("docker-compose.amd.yml", "ghcr.io/niko1221/strata:0.2.7-rocm-gfx120x"), + ("docker-compose.intel.yml", "ghcr.io/niko1221/strata:0.2.7-sycl")): self.assertIn(tag, (DOCKER / "compose" / name).read_text(encoding="utf-8")) def test_the_user_doc_says_images_are_published_from_0_2_1(self): @@ -239,7 +239,7 @@ class Publishing(unittest.TestCase): doc = (ROOT / "docs" / "DOCKER.md").read_text(encoding="utf-8") self.assertTrue({"cuda13", "cuda12", "rocm-gfx120x", "rocm-gfx110x", "rocm-gfx1151", "sycl"} <= set(flavors), flavors) for flavor in flavors: - self.assertIn(f"0.2.3-{flavor}", doc) + self.assertIn(f"0.2.7-{flavor}", doc) def test_build_script_copies_everything_the_terminal_package_needs(self): """docker/build.sh lists the Terminal's files by hand; the list must cover package_terminal.py's payload (it once missed docs/TERMINAL_LAUNCH.md).""" diff --git a/tools/split_serve_check.py b/tools/split_serve_check.py new file mode 100644 index 00000000..f441bdb0 --- /dev/null +++ b/tools/split_serve_check.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Split serving (serve/split.py): the exactness check and the speed comparison, run on a test box with the real engine. + + python3 tools/split_serve_check.py exact CONFIG.json OUT.json [--tokens N] + python3 tools/split_serve_check.py bench CONFIG.json OUT.json --arm layer|single|split [--reps 3] + +Run it from the repository root (it imports serve.server and serve.split). CONFIG.json: + + {"exe": "/path/strata", "cwd": "/path/repo", "args": ["--serve", "--pack", ..., "--max-context", "40960", ...], + "env": {...}, "prompts": "/path/prompts", "dir": "/path/work", + "prefill_gpu": 0, "decode_gpu": 1, "arena": "/path/arena.bin" (optional), "min_prompt_tokens": 2048} + +`args` holds no --layer-split, --shared-expert-arena or card choice: the tool adds them for each arm. +The prompts folder has pp_.txt files of comma-separated token ids (the bench harness's). + +exact: a fresh engine reads a prompt and answers (the reference, twice, to show the engine's own run-to-run noise); +then the prefill engine reads the same prompt, saves the session, a fresh decode engine restores it and answers. Compared: +the state fingerprint (STRATA_STATE_HASH) of the prefill engine and of the decode engine right after the restore, then the +answer's token ids and the fingerprint after the answer. + +bench: one arm per call (run it in its own job so the engines start fresh): + layer one engine over both cards (--layer-split auto), the normal two-card setup + single one engine on the decode card + split prefill engine on one card, decode engine on the other, through SplitEngine (the production path) +Workloads: 8K and 32K prompt + 256 tokens, a 3-turn chat with short follow-ups, a 3-turn chat with long follow-ups. +""" +import argparse +import copy +import json +import os +import re +import statistics +import sys +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +from serve import server as srv # noqa: E402 +from serve import split as split_mod # noqa: E402 + + +def read_ids(path): + return [int(x) for x in open(path).read().replace("\n", ",").split(",") if x.strip()] + + +def session_dir(cfg): + """Where the session files go: cfg["session_dir"], else /dev/shm when it has room (as the server chooses), else cfg["dir"].""" + d = cfg.get("session_dir") + if not d and os.path.isdir("/dev/shm"): + import shutil + if shutil.disk_usage("/dev/shm").free > (6 << 30): + d = "/dev/shm/strata-split-check" + d = d or cfg["dir"] + os.makedirs(d, exist_ok=True) + return d + + +def mem_available_gib(): + for line in open("/proc/meminfo"): + if line.startswith("MemAvailable"): + return int(line.split()[1]) / 1048576.0 + return 0.0 + + +def make_engine(cfg, gpus, tag, extra_args=(), arena=None, min_free_gib=8.0, state_hash=False): + free = mem_available_gib() + if free < min_free_gib: + raise SystemExit(f"only {free:.1f} GiB of RAM available (< {min_free_gib}): not starting an engine") + c = copy.deepcopy(cfg) + c["gpu"] = gpus + c["args"] = list(c["args"]) + list(extra_args) + (["--shared-expert-arena", arena] if arena else []) + c["log"] = os.path.join(cfg["dir"], f"engine-{tag}.log") + open(c["log"], "w").close() + env = srv.child_env(c) + if state_hash: # the fingerprint after every request costs time proportional to the prompt: exact mode only + env["STRATA_STATE_HASH"] = "1" + for k, v in (cfg.get("env") or {}).items(): + env[str(k)] = str(v) + t0 = time.time() + e = srv.StrataEngine(c["exe"], srv.engine_args(c), cwd=c.get("cwd"), log=c["log"], env=env) + e.silence_s = 0 + e.tag, e.load_s = tag, time.time() - t0 + return e + + +def log_tail(e, start): + try: + with open(e.log_path, "rb") as f: + f.seek(start) + return f.read().decode("utf-8", "replace") + except OSError: + return "" + + +def log_size(e): + try: + return os.path.getsize(e.log_path) + except OSError: + return 0 + + +def state_hashes(text): + """The STATE_HASH lines of an engine log excerpt, as dicts.""" + out = [] + for m in re.finditer(r"STATE_HASH L=(\d+) (.*)", text): + d = {"L": int(m.group(1))} + d.update(dict(kv.split("=", 1) for kv in m.group(2).split() if "=" in kv)) + out.append(d) + return out + + +def run_gen(engine, ids, max_new): + """One request through engine.generate (a StrataEngine or a SplitEngine). -> dict of tokens and times.""" + cancel = threading.Event() + toks, t_first = [], None + t0 = time.perf_counter() + for t in engine.generate(ids, max_new, {}, cancel): + if t is None: + continue + if t_first is None: + t_first = time.perf_counter() + toks.append(t) + t_end = time.perf_counter() + last = dict(engine.last or {}) + dec = (len(toks) - 1) / (t_end - t_first) if t_first and len(toks) > 1 and t_end > t_first else None + return {"tokens": toks, "ttft_s": (t_first - t0) if t_first else None, "wall_s": t_end - t0, + "dec_tok_s": dec, "last": last} + + +def close_all(*engines): + for e in engines: + try: + e.close() + except Exception as x: # noqa: BLE001 + print("close:", x, flush=True) + + +def cmd_exact(a, cfg): + ids = read_ids(os.path.join(cfg["prompts"], f"pp_{a.prompt}.txt"))[:a.prompt] + arena = cfg.get("arena") + P, Dg = cfg["prefill_gpu"], cfg["decode_gpu"] + res = {"prompt_tokens": len(ids), "new_tokens": a.tokens, "runs": {}} + # 1. the reference twice: a fresh engine on the decode card each time + for k in (1, 2): + e = make_engine(cfg, Dg, f"ref{k}", arena=arena, state_hash=True) + pos = log_size(e) + r = run_gen(e, ids, a.tokens) + h = state_hashes(log_tail(e, pos)) + res["runs"][f"ref{k}"] = {"tokens": r["tokens"], "hash_end": h[-1] if h else None, "last": r["last"], + "wall_s": r["wall_s"]} + print(f"ref{k}: {len(r['tokens'])} tokens, wall {r['wall_s']:.1f} s", flush=True) + close_all(e) + # 2. the split: prefill engine, save, fresh decode engine, restore, answer + pe = make_engine(cfg, P, "prefill", arena=arena, state_hash=True) + pos = log_size(pe) + cancel = threading.Event() + for _ in pe.generate(ids, 0, {}, cancel, prefill_only=True): + pass + hp = state_hashes(log_tail(pe, pos)) + path = os.path.join(session_dir(cfg), "exact.session") + saved = pe.session_file("save", path) + print(f"prefill engine: held {saved['tokens']} tokens, saved {saved['bytes'] / 2**20:.0f} MiB in {saved['ms']:.0f} ms", + flush=True) + de = make_engine(cfg, Dg, "decode", arena=arena, state_hash=True) + restored = de.session_file("restore", path) + print(f"decode engine: restored {restored['tokens']} tokens in {restored['ms']:.0f} ms", flush=True) + pos = log_size(de) + for _ in de.generate(ids, 0, {}, cancel, prefill_only=True): # nothing to read: only the state fingerprint + pass + hd = state_hashes(log_tail(de, pos)) + pos = log_size(de) + r = run_gen(de, ids, a.tokens) + h = state_hashes(log_tail(de, pos)) + res["runs"]["split"] = {"tokens": r["tokens"], "hash_end": h[-1] if h else None, "last": r["last"], + "wall_s": r["wall_s"], "hash_prefill_engine": hp[-1] if hp else None, + "hash_decode_after_restore": hd[-1] if hd else None, "saved": saved, "restored": restored} + print(f"split: {len(r['tokens'])} tokens, wall {r['wall_s']:.1f} s", flush=True) + close_all(pe, de) + try: + os.unlink(path) + except OSError: + pass + # verdicts + ref1, ref2, sp = (res["runs"][k] for k in ("ref1", "ref2", "split")) + + def first_diff(x, y): + for i, (p, q) in enumerate(zip(x, y)): + if p != q: + return i + return None if len(x) == len(y) else min(len(x), len(y)) + v = { + "restore_round_trip_state_equal": sp["hash_prefill_engine"] == sp["hash_decode_after_restore"] and + sp["hash_prefill_engine"] is not None, + "ref1_vs_ref2_first_diff": first_diff(ref1["tokens"], ref2["tokens"]), + "ref1_vs_split_first_diff": first_diff(ref1["tokens"], sp["tokens"]), + "ref2_vs_split_first_diff": first_diff(ref2["tokens"], sp["tokens"]), + "end_state_ref1_eq_ref2": ref1["hash_end"] == ref2["hash_end"], + "end_state_ref1_eq_split": ref1["hash_end"] == sp["hash_end"], + } + res["verdict"] = v + json.dump(res, open(a.out, "w"), indent=1) + print(json.dumps(v, indent=1), flush=True) + # the check passes when the split run equals the reference wherever the reference equals itself + same_ref = v["ref1_vs_ref2_first_diff"] is None + ok = v["restore_round_trip_state_equal"] and ( + (v["ref1_vs_split_first_diff"] is None and v["end_state_ref1_eq_split"]) if same_ref + else v["ref1_vs_split_first_diff"] is None or v["ref2_vs_split_first_diff"] is None) + print("EXACT: PASS" if ok else "EXACT: FAIL", flush=True) + return 0 if ok else 1 + + +WORKLOADS = [ + ("p8k", {"prompt": 8192, "gen": 256}), + ("p32k", {"prompt": 32768, "gen": 256}), + ("chat_short", {"prompt": 4096, "gen": 128, "turns": 3, "follow": 200}), + ("chat_long", {"prompt": 8192, "gen": 128, "turns": 3, "follow": 6000}), +] + + +def follow_ids(cfg, n, turn): + """n token ids for a follow-up message: a slice of the 16K prompt (different for each turn).""" + pool = read_ids(os.path.join(cfg["prompts"], "pp_16384.txt")) + start = 1000 + turn * 7000 + return pool[start:start + n] + + +def cmd_bench(a, cfg): + arm = a.arm + P, Dg = cfg["prefill_gpu"], cfg["decode_gpu"] + arena = cfg.get("arena") + t_load = time.time() + if arm == "layer": + eng = make_engine(cfg, [min(P, Dg), max(P, Dg)], "layer") + closers = [eng] + elif arm == "single": + eng = make_engine(cfg, Dg, "single") + closers = [eng] + elif arm == "single_shared": # one card, the arena in the shared file: what the split's engines read from + eng = make_engine(cfg, Dg, "single_shared", arena=arena) + closers = [eng] + elif arm == "split": + spec = split_mod.split_spec({"split_serve": {"prefill_gpu": P, "decode_gpu": Dg, + "min_prompt_tokens": cfg.get("min_prompt_tokens", 2048)}}) + pe = make_engine(cfg, P, "prefill", extra_args=cfg.get("prefill_args", []), arena=arena) + de = make_engine(cfg, Dg, "decode", extra_args=cfg.get("decode_args", []), arena=arena) + eng = split_mod.SplitEngine(pe, de, min_tokens=spec["min_prompt_tokens"], work_dir=session_dir(cfg), say=print) + closers = [pe, de] + else: + raise SystemExit("--arm layer|single|split") + load_s = time.time() - t_load + print(f"[{arm}] loaded in {load_s:.0f} s", flush=True) + rows = [] + try: + warm = read_ids(os.path.join(cfg["prompts"], "dec_story.txt")) + for _ in range(3): # warm-up: graphs, the adaptive tier (discarded) + run_gen(eng, warm, 100) + if arm == "split": + wp = read_ids(os.path.join(cfg["prompts"], "pp_4096.txt")) + wp[0] = 2999 # its own prompt: no workload below finds it in a cache + run_gen(eng, wp, 16) # one hand-over: warms the file path + for rep in range(a.reps): + for widx, (name, w) in enumerate(WORKLOADS): + if a.only and name not in a.only: + continue + ids = read_ids(os.path.join(cfg["prompts"], f"pp_{w['prompt']}.txt"))[:w["prompt"]] + ids[0] = 3000 + rep * 16 + widx # a prompt of its own: a cold start in every arm, every rep + if "turns" not in w: + # a fresh conversation each time: a tiny unrelated request first, so no session is continued + run_gen(eng, warm[:40], 1) + r = run_gen(eng, ids, w["gen"]) + turns = [r] + else: + run_gen(eng, warm[:40], 1) + turns, conv = [], list(ids) + for t in range(w["turns"]): + r = run_gen(eng, conv, w["gen"]) + turns.append(r) + conv = conv + r["tokens"] + follow_ids(cfg, w["follow"], t) + row = {"arm": arm, "rep": rep, "workload": name, "load_s": round(load_s, 1), "turns": []} + for r in turns: + last = r["last"] + row["turns"].append({ + "prompt": last.get("prompt_tokens"), "generated": len(r["tokens"]), + "ttft_s": round(r["ttft_s"], 3) if r["ttft_s"] else None, "wall_s": round(r["wall_s"], 3), + "dec_tok_s": round(r["dec_tok_s"], 2) if r["dec_tok_s"] else None, + "reused": last.get("reused"), "prompt_ms": last.get("prompt_ms"), + "split": {k: last[k] for k in last if k.startswith("split_")} or None, + "finish": last.get("finish"), "tokens": r["tokens"][:8]}) + row["total_wall_s"] = round(sum(r["wall_s"] for r in turns), 3) + rows.append(row) + print(json.dumps({k: row[k] for k in ("arm", "rep", "workload", "total_wall_s")}), flush=True) + for t in row["turns"]: + print(" ", json.dumps({k: t[k] for k in ("prompt", "generated", "ttft_s", "wall_s", "dec_tok_s", + "reused", "split")}), flush=True) + finally: + out = {"arm": arm, "rows": rows, "cfg": {k: v for k, v in cfg.items() if k != "env"}, + "split_view": eng.split_view() if hasattr(eng, "split_view") else None} + json.dump(out, open(a.out, "w"), indent=1) + close_all(*closers) + return 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("mode", choices=["exact", "bench"]) + ap.add_argument("config") + ap.add_argument("out") + ap.add_argument("--tokens", type=int, default=64) + ap.add_argument("--prompt", type=int, default=4096) + ap.add_argument("--arm", default="split", choices=["layer", "single", "single_shared", "split"]) + ap.add_argument("--reps", type=int, default=2) + ap.add_argument("--only", nargs="*", default=None) + a = ap.parse_args() + cfg = json.load(open(a.config)) + os.makedirs(cfg["dir"], exist_ok=True) + return cmd_exact(a, cfg) if a.mode == "exact" else cmd_bench(a, cfg) + + +if __name__ == "__main__": + sys.exit(main())