From 600d73070c5f5da224b080b850aa46f819630954 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:32:41 +0200 Subject: [PATCH 1/5] HIP: __byte_perm as v_perm_b32 and SWAR __vsub4/__vsubss4/__vcmpne4 (from #262 by ttio2tech) Cut down from #262 (ttio2tech): only the intrinsics and their test. - HIP's __byte_perm indexes a byte array in private memory (scratch traffic in the IQ4_XS/Q2_0 table lookups); byte_perm() is the same selection (nibble & 7 of the pair {y:x}) in one v_perm_b32. - __vsub4, __vsubss4 and __vcmpne4 work on all four byte lanes at once (Hacker's Delight 2-18) instead of a per-lane loop. - tests/hip/intrinsics checks them on 1,024 random operands against host references (passes on gfx1201). Left out: the arch/setup/device.cu parts (0.1.30 already builds and checks gfx1201; main's dp4a covers gfx1100-1102/1200/1201) and the gfx1201 hipBLASLt table (none is shipped for gfx1201). A/B vs main on amdbox (Coder IQ1_M, 128 greedy tokens): identity with a fixed cache (--expert-cache 1500 --prefill 2048), 5 + 5 starts per card, 4K / 16K / 4K again: the modal outputs are identical on the R9700 and on the RX 9070 XT (one start of 20 differed from its arm's mode, the known HIP start drift). Speed with setup's settings (auto cache/chunk), 2 + 2 starts per card, tok/s: | card | arm | 4K cold | 4K warm | 16K cold | 16K warm | decode | | R9700 | main | 1,027 | 1,792 | 1,695 | 1,812 | 46.0-52.2 | | | #262 | 1,023 | 1,786 | 1,681 | 1,808 | 53.0-61.0 | | RX 9070 XT | main | 781 | 1,018 | 1,421 | 1,517 | 32.7-41.4 | | | #262 | 780 | 1,017 | 1,424 | 1,517 | 34.9-44.0 | Decode +15% on the R9700, +5-7% on the 9070 XT; prompts unchanged. Co-Authored-By: ttio2tech <125389792+ttio2tech@users.noreply.github.com> --- docs/AMD_HIP.md | 4 +- include/strata/hip_compat/intrinsics.hpp | 58 ++++++++++++------------ tests/hip/intrinsics.cpp | 51 ++++++++++++++++++++- 3 files changed, 83 insertions(+), 30 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 84ee8a55..00f625d2 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -145,7 +145,9 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 | RX 9070 XT 16 GB | 4,931 slots, 9.4 GiB | 15.6 GiB | 782 tok/s | 30.8 tok/s | 1,235 tok/s | 35.4 tok/s | | R9700, TheRock 7.10 wheels | 12,288 slots | | 957 tok/s | 44.2 tok/s | 1,284 tok/s | 43.9 tok/s | - The engine's resident memory was about 26 GB in every run. + The engine's resident memory was about 26 GB in every run. Since 0.1.31 `__byte_perm` is one `v_perm_b32` and the + packed byte subtracts/compare work on four lanes at once (#262, ttio2tech): decode +15% on the R9700 (46.0 -> 53.0 + tok/s on a 4K prompt, 52.0 -> 60.5 warm) and +5-7% on the 9070 XT, prompts unchanged, the same tokens. - **hipBLASLt:** there is no gfx1201 table in `tools/hip`. A table calibrated on the R9700 at the engine's shapes (hipBLASLt 1.4.1; 0.98-1.76x per GEMM over hipBLAS) changed the end-to-end prompt speed by 0-3%, within noise, so none is shipped: on gfx1201 the plain hipBLAS path is already close. diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp index b1d7378c..9e6eda74 100644 --- a/include/strata/hip_compat/intrinsics.hpp +++ b/include/strata/hip_compat/intrinsics.hpp @@ -32,45 +32,46 @@ __device__ __forceinline__ int dp4a(int a, int b, int c) { #endif } -// CUDA's packed byte subtract wraps independently in each unsigned byte lane. +// CUDA's __byte_perm (default mode): result byte i is byte s.nibble[i] & 7 of the pair {y:x}, x the low word. +// HIP's own version indexes a byte array in private memory, which becomes scratch traffic in the i-quant table +// lookups; v_perm_b32 is the same selection in one instruction (selector bytes 0-3 pick from its second +// operand, 4-7 from its first), so the nibble selector is spread to bytes and masked to 0-7. +__device__ __forceinline__ uint32_t byte_perm(uint32_t x, uint32_t y, uint32_t s) { + const uint32_t sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} + +// The packed byte operations below work on all four lanes at once (SWAR, Hacker's Delight 2-18): gfx11/gfx12 have +// no packed 8-bit subtract, and a per-lane loop costs the Q3_K/Q6_K dots and the i-quant sign expansion several +// times the instructions. kHigh is each lane's top bit. +constexpr uint32_t kHigh = 0x80808080u; + +// CUDA's packed byte subtract wraps independently in each unsigned byte lane: subtract the low seven bits with the +// minuend's top bit forced on (so no borrow crosses a lane), then fix each top bit by XOR. __device__ __forceinline__ int vsub4(int a, int b) { const uint32_t ua = static_cast(a); const uint32_t ub = static_cast(b); - uint32_t out = 0; -#pragma unroll - for (int lane = 0; lane < 4; ++lane) { - const uint32_t x = (ua >> (lane * 8)) & 0xffu; - const uint32_t y = (ub >> (lane * 8)) & 0xffu; - out |= ((x - y) & 0xffu) << (lane * 8); - } - return static_cast(out); + return static_cast(((ua | kHigh) - (ub & ~kHigh)) ^ ((ua ^ ~ub) & kHigh)); } -// CUDA's packed signed-byte saturating subtract. +// CUDA's packed signed-byte saturating subtract: the wrapping difference, and in each lane that overflowed (operand +// signs differ and the result's sign differs from the minuend's) the bound on the minuend's side, 0x7f or 0x80. __device__ __forceinline__ int vsubss4(int a, int b) { const uint32_t ua = static_cast(a); const uint32_t ub = static_cast(b); - uint32_t out = 0; -#pragma unroll - for (int lane = 0; lane < 4; ++lane) { - int value = signed_byte(ua, lane) - signed_byte(ub, lane); - value = value < -128 ? -128 : (value > 127 ? 127 : value); - out |= (static_cast(value) & 0xffu) << (lane * 8); - } - return static_cast(out); + const uint32_t d = static_cast(vsub4(a, b)); + const uint32_t overflow = (ua ^ ub) & (ua ^ d) & kHigh; + const uint32_t mask = (overflow >> 7) * 0xffu; + const uint32_t bound = 0x7f7f7f7fu + ((ua & kHigh) >> 7); + return static_cast((d & ~mask) | (bound & mask)); } -// CUDA's four-lane byte compare, returning 0xff for each unequal lane and 0 otherwise. +// CUDA's four-lane byte compare, returning 0xff for each unequal lane and 0 otherwise: a lane of a ^ b is nonzero +// when its low seven bits carry into the top bit on adding 0x7f, or its top bit is already set. __device__ __forceinline__ int vcmpne4(int a, int b) { - const uint32_t ua = static_cast(a); - const uint32_t ub = static_cast(b); - uint32_t out = 0; -#pragma unroll - for (int lane = 0; lane < 4; ++lane) { - if (((ua >> (lane * 8)) & 0xffu) != ((ub >> (lane * 8)) & 0xffu)) - out |= 0xffu << (lane * 8); - } - return static_cast(out); + const uint32_t t = static_cast(a) ^ static_cast(b); + const uint32_t nonzero = (((t & ~kHigh) + ~kHigh) | t) & kHigh; + return static_cast((nonzero >> 7) * 0xffu); } // CUDA's mask argument describes participating lanes. The current kernel set uses full @@ -111,6 +112,7 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) { } // namespace strata::hip_compat #define __dp4a(a, b, c) (::strata::hip_compat::dp4a((a), (b), (c))) +#define __byte_perm(x, y, s) (::strata::hip_compat::byte_perm((x), (y), (s))) #define __vsub4(a, b) (::strata::hip_compat::vsub4((a), (b))) #define __vsubss4(a, b) (::strata::hip_compat::vsubss4((a), (b))) #define __vcmpne4(a, b) (::strata::hip_compat::vcmpne4((a), (b))) diff --git a/tests/hip/intrinsics.cpp b/tests/hip/intrinsics.cpp index e07c5679..ff2b93e3 100644 --- a/tests/hip/intrinsics.cpp +++ b/tests/hip/intrinsics.cpp @@ -50,6 +50,29 @@ __global__ void intrinsic_probe(int* integer_results, float* float_shuffle, doub } } +// The byte-lane intrinsics over many operands: __byte_perm with selector bits it ignores (bit 3 of each nibble and +// the upper half), since the i-quant table lookups pass data-dependent selectors; the packed subtracts and compare +// on every sign and overflow combination (the compare's second operand keeps two lanes of the first). +constexpr int kPermCases = 1024; +constexpr int kPermResults = 4; +__global__ void byte_perm_probe(const uint32_t* inputs, uint32_t* results) { + const int i = static_cast(blockIdx.x * blockDim.x + threadIdx.x); + if (i >= kPermCases) return; + const uint32_t x = inputs[3 * i], y = inputs[3 * i + 1], s = inputs[3 * i + 2]; + results[kPermResults * i + 0] = __byte_perm(x, y, s); + results[kPermResults * i + 1] = static_cast(__vsub4(static_cast(x), static_cast(y))); + results[kPermResults * i + 2] = static_cast(__vsubss4(static_cast(x), static_cast(y))); + results[kPermResults * i + 3] = + static_cast(__vcmpne4(static_cast(x), static_cast(x ^ (s & 0xff00ff00u)))); +} + +uint32_t byte_perm_reference(uint32_t x, uint32_t y, uint32_t s) { + const uint64_t pair = (static_cast(y) << 32) | x; + uint32_t out = 0; + for (int i = 0; i < 4; ++i) out |= static_cast((pair >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i); + return out; +} + int signed_byte(uint32_t word, int lane) { const unsigned value = (word >> (lane * 8)) & 0xffu; return value < 0x80u ? static_cast(value) : static_cast(value) - 0x100; @@ -153,6 +176,32 @@ int main() { ok = ok && double_shuffle[lane] == static_cast(lane ^ 1) + 0.25; } + uint32_t perm_inputs[kPermCases * 3]{}; + uint32_t state = 0x9e3779b9u; + for (uint32_t& v : perm_inputs) { + state ^= state << 13; state ^= state >> 17; state ^= state << 5; + v = state; + } + uint32_t* device_perm_inputs = nullptr; + uint32_t* device_perm_results = nullptr; + CHECK(hipMalloc(reinterpret_cast(&device_perm_inputs), sizeof(perm_inputs))); + CHECK(hipMalloc(reinterpret_cast(&device_perm_results), kPermCases * kPermResults * sizeof(uint32_t))); + CHECK(hipMemcpy(device_perm_inputs, perm_inputs, sizeof(perm_inputs), hipMemcpyHostToDevice)); + hipLaunchKernelGGL(byte_perm_probe, dim3(kPermCases / 256), dim3(256), 0, 0, device_perm_inputs, device_perm_results); + CHECK(hipDeviceSynchronize()); + uint32_t perm_results[kPermCases * kPermResults]{}; + CHECK(hipMemcpy(perm_results, device_perm_results, sizeof(perm_results), hipMemcpyDeviceToHost)); + for (int i = 0; i < kPermCases; ++i) { + const uint32_t x = perm_inputs[3 * i], y = perm_inputs[3 * i + 1], s = perm_inputs[3 * i + 2]; + const uint32_t* r = perm_results + kPermResults * i; + ok = ok && r[0] == byte_perm_reference(x, y, s); + ok = ok && r[1] == byte_sub_reference(x, y); + ok = ok && r[2] == signed_saturating_sub_reference(x, y); + ok = ok && r[3] == not_equal_reference(x, x ^ (s & 0xff00ff00u)); + } + CHECK(hipFree(device_perm_results)); + CHECK(hipFree(device_perm_inputs)); + CHECK(hipFree(device_ballot)); CHECK(hipFree(device_dot_inputs)); CHECK(hipFree(device_double_shuffle)); @@ -162,6 +211,6 @@ int main() { std::fprintf(stderr, "HIP intrinsic parity failed (ballot 0x%08x)\n", ballot); return 1; } - std::puts("HIP intrinsics parity OK: dynamic signed dot4/overflow, packed integer boundaries, wave32 shuffles, ballot and sleep"); + std::puts("HIP intrinsics parity OK: dynamic signed dot4/overflow, byte permute, packed integer boundaries, wave32 shuffles, ballot and sleep"); return 0; } From 489623c7d30b3ff2ce85037302bd788d778c56d7 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:37:21 +0200 Subject: [PATCH 2/5] AMD: gfx1101 (RX 7800 XT, #254 by jhohertz) and gfx1200 (RX 9060 XT, #256 by Efeisot) as community-validated cards Cut down from #254 and #256 onto 0.1.30's AMD tables: - setup.py: AMD_ARCHS / AMD_NAMES / ROCM_INDEXES / AMD_CARDS list gfx1101 (TheRock gfx110X-dgpu) and gfx1200 (gfx120X-all); amd_gpus() takes the sysfs root so the detection can be tested. - cmake/hip_backend.cmake: gfx1101 and gfx1200 build without the "not validated" warning (a status line names them community-validated); gfx1102 (#192: ctest only) keeps the warning. - docs/AMD_HIP.md (Community-validated cards: the owners' setups, ctest and numbers) and README. - tools/test_setup_amd.py: detection on a mocked KFD topology (every family, the CPU node, an iGPU and gfx1102 listed as not supported, product-name fallbacks, the ROCm index per family). Left out: the PRs' own cmake/device.cu arch checks (0.1.30's compiled_for covers them), the dp4a change (main has it), math_constants.h, the bench JSONs, the launcher, and both hipBLASLt tables (neither PR measured the prompt speed without its table). Co-Authored-By: Joseph Hohertz Co-Authored-By: efeisot --- README.md | 3 +- cmake/hip_backend.cmake | 13 ++++--- docs/AMD_HIP.md | 47 ++++++++++++++++++------ setup.py | 31 ++++++++++------ tools/test_setup_amd.py | 81 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 145 insertions(+), 30 deletions(-) create mode 100644 tools/test_setup_amd.py diff --git a/README.md b/README.md index 5241dca3..bc1eb30c 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,8 @@ one later with `SETUP.bat` (the same as `START-HERE.bat --setup`; on Linux `./se For **OrcaRouter's Flash-Next Uncensored IQ3_XXS**, see the [manual compatibility setup](docs/ORCA.md). It needs an explicit packing conversion and is not an installer menu option. -An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental): +An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental; the +RX 7800 XT / 7700 XT and RX 9060 XT were validated by their owners): `./setup.sh --backend hip`, chosen by itself on a PC with no NVIDIA card Strata can use. It installs ROCm without sudo and compiles the engine (one GPU, no images yet). Details: [AMD HIP](docs/AMD_HIP.md). diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index c22d9463..9cd0cfed 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -4,20 +4,23 @@ if(NOT DEFINED CMAKE_HIP_ARCHITECTURES OR CMAKE_HIP_ARCHITECTURES STREQUAL "") set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture(s), e.g. gfx1100 or gfx1100;gfx1201") endif() -# Validated on real cards: gfx1100 (RX 7900 XT / XTX) and gfx1201 (RX 9070 / 9070 XT, Radeon AI PRO R9700). -# The other RDNA3 / RDNA4 wave32 chips have the same LDS limit and dot4 instruction and build the same code, but -# the maintainers have not run them (community reports: gfx1102 #192, gfx1200 #176). +# Validated on real cards: gfx1100 (RX 7900 XT / XTX) and gfx1201 (RX 9070 / 9070 XT, Radeon AI PRO R9700) by the +# maintainers; gfx1101 (RX 7800 XT, #254) and gfx1200 (RX 9060 XT, #256) by their owners. gfx1102 (RX 7600) has the +# same LDS limit and dot4 instruction and passed ctest (#192), but no model run has been reported yet. set(_strata_hip_validated gfx1100 gfx1201) -set(_strata_hip_unvalidated gfx1101 gfx1102 gfx1200) +set(_strata_hip_community gfx1101 gfx1200) +set(_strata_hip_unvalidated gfx1102) set(STRATA_HIP_ARCH_LIST "") foreach(_arch IN LISTS CMAKE_HIP_ARCHITECTURES) string(REGEX REPLACE ":.*$" "" _base "${_arch}") # gfx1100:xnack- -> gfx1100 if(_base IN_LIST _strata_hip_validated) + elseif(_base IN_LIST _strata_hip_community) + message(STATUS "Strata HIP: ${_base} was validated by community reports (docs/AMD_HIP.md)") elseif(_base IN_LIST _strata_hip_unvalidated) message(WARNING "Strata HIP: ${_base} builds, but it is not validated on a real card yet; please report results") else() message(FATAL_ERROR - "Strata HIP supports wave32 gfx1100 and gfx1201 (unvalidated: ${_strata_hip_unvalidated}); " + "Strata HIP supports wave32 gfx1100, gfx1101, gfx1200 and gfx1201 (unvalidated: ${_strata_hip_unvalidated}); " "CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'") endif() list(APPEND STRATA_HIP_ARCH_LIST "${_base}") diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 00f625d2..3d6695d5 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -1,8 +1,9 @@ -# Experimental AMD HIP backend (gfx1100, gfx1201) +# Experimental AMD HIP backend (gfx1100, gfx1101, gfx1200, gfx1201) This is a Linux source build for the RX 7900 XT / XTX (RDNA3, gfx1100) and the -RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). -It is opt-in; the NVIDIA installer and CUDA build remain the default. Other AMD +RX 9070 / 9070 XT / Radeon AI PRO R9700 (RDNA4, gfx1201; see [RDNA4](#rdna4-gfx1201)). The RX 7800 XT / 7700 XT +(gfx1101) and the RX 9060 XT (gfx1200) were validated by their owners (see [Community-validated +cards](#community-validated-cards)). It is opt-in; the NVIDIA installer and CUDA build remain the default. Other AMD architectures, wave64, Windows HIP, and mixed AMD/NVIDIA execution are outside this contribution. The backend maps the CUDA-shaped runtime and BLAS calls to HIP/hipBLAS, uses @@ -15,8 +16,8 @@ This does not claim bit-identical model answers across backends. See ## Install with setup (recommended) -On Linux with an RX 7900 XT / XTX or an RX 9070 / 9070 XT / Radeon AI PRO R9700 and the kernel's amdgpu driver -(no ROCm install needed): +On Linux with an RX 7900 XT / XTX, RX 7800 XT / 7700 XT, RX 9060 XT, RX 9070 / 9070 XT or Radeon AI PRO R9700 and +the kernel's amdgpu driver (no ROCm install needed): ```sh ./setup.sh --backend hip @@ -26,8 +27,8 @@ On Linux with an RX 7900 XT / XTX or an RX 9070 / 9070 XT / Radeon AI PRO R9700 supported. On a PC without an NVIDIA card Strata can use, `--backend hip` is chosen automatically. - **ROCm:** a system ROCm 7 in `/opt/rocm` (or `$ROCM_PATH`) with hipcc and hipBLAS is used when present. Otherwise (or when it is older than 7.0) ROCm is installed into `.venv` from AMD's TheRock wheels (~10 GB, no sudo), pinned - to the version this backend was tested with, from the card family's index: `gfx110X-dgpu` for gfx1100, - `gfx120X-all` for gfx1201 (`STRATA_ROCM_VERSION` / `STRATA_ROCM_INDEX` override them). + to the version this backend was tested with, from the card family's index: `gfx110X-dgpu` for gfx1100 / gfx1101, + `gfx120X-all` for gfx1200 / gfx1201 (`STRATA_ROCM_VERSION` / `STRATA_ROCM_INDEX` override them). - **Engine:** compiled on your PC for the card's architecture (10-20 minutes, once; again after a `git pull` that changes it, or when you pick a card of another architecture). This needs a C++ compiler and git (`sudo apt install build-essential git`). @@ -54,9 +55,9 @@ cmake -S . -B build-hip \ cmake --build build-hip --target strata -j2 ``` -`CMAKE_HIP_ARCHITECTURES` is `gfx1100`, `gfx1201`, or a list such as `"gfx1100;gfx1201"` (one binary for both). -gfx1101, gfx1102 and gfx1200 (the same wave32, 64 KiB LDS and dot4 instruction) build with a warning: they have -not been validated on a real card here. At startup the engine and `strata-device` compare each GPU they use +`CMAKE_HIP_ARCHITECTURES` is `gfx1100`, `gfx1101`, `gfx1200`, `gfx1201`, or a list such as `"gfx1100;gfx1201"` +(one binary for both). gfx1102 (the same wave32, 64 KiB LDS and dot4 instruction) builds with a warning: it passed +ctest (#192) but no model run has been reported. At startup the engine and `strata-device` compare each GPU they use (`gcnArchName` up to the `:` feature suffix) with the architectures the binary was compiled for, and require wave32. A binary carried to another card stops with the card's name, its architecture and the build's list, instead of failing later with "invalid device function". @@ -168,8 +169,30 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 expert arena (a Windows limit that also applies here). - **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on one card or two and on engine 0.1.29 as well; not yet explained. -- **Not validated:** gfx1200 (RX 9060 XT; a community report is #176), images, long contexts beyond 16K, - answer-quality benchmarks. +- **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. + +## Community-validated cards + +Run by their owners, not on the maintainers' machines; setup accepts them like gfx1100 / gfx1201. No hipBLASLt table +is shipped for them (make one with [Tuning table](#tuning-table) and compare the prompt speed with and without it). + +- **gfx1101, RX 7800 XT 16 GB** (jhohertz, #254; engine 0.1.29, Ryzen 9 5950X, 121 GiB RAM, system ROCm with + hipBLASLt 1.4.1): `./setup.sh --backend hip` detected the card and compiled the engine; `strata-device --selftest` + passed; ctest 30/32 (`ple_parity` needs the Q2_0 fixture, `platform_memory_test` the memlock limit). Coder IQ1_M, + 64K context, MTP, with a table the owner calibrated: fresh prompts of 4K-9K tokens at 898-953 tok/s, decode + 38-44 tok/s (128 tokens). +- **gfx1200, RX 9060 XT 16 GB** (Efeisot, #256 after #176; engine 0.1.29, Ryzen 9 7950X, 64 GiB RAM, ROCm 7.2 with + hipBLASLt 1.2.2): ctest 32/32 (without `ple_parity` and `platform_memory_test`). Coder IQ1_M, greedy, MTP + `--spec 4 --spec-min-p 0.5`, with a table the owner calibrated: + + | prompt | prompt speed | decode | + |---|---|---| + | 2,374 tokens | 540 tok/s | 27.1 tok/s (0.69 draft acceptance; 31.0 at 1.00) | + | 65K (`--kv int8 --kv-resident 65536 --prefill 16384`) | 748-753 tok/s | 26-40 tok/s by acceptance | + | 130K (the same flags) | 725 tok/s | - | + + Greedy output was the same across runs. For comparison, llama.cpp's HIP build measured 20 tok/s decode and + 450 tok/s prompt on that card. ## Tuning table diff --git a/setup.py b/setup.py index 924bd34f..b17031f1 100644 --- a/setup.py +++ b/setup.py @@ -710,27 +710,34 @@ def cuda_lib_dirs(): # ------------------------------------------------------------------------------------------------ AMD (experimental) # The RX 7900 XT / XTX (gfx1100) and the RX 9070 series / Radeon AI PRO R9700 (gfx1201) on Linux, through the HIP -# backend (docs/AMD_HIP.md). There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv -# (no sudo; a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for -# the card. One GPU, no images yet. +# backend (docs/AMD_HIP.md); the RX 7800 XT / 7700 XT (gfx1101, #254) and the RX 9060 XT (gfx1200, #256) were run by +# their owners. There is no ready-made AMD engine: ROCm comes from AMD's TheRock Python wheels into .venv (no sudo; +# a system ROCm 7 in /opt/rocm is used when it has hipcc and hipBLAS) and the engine is compiled here for the cards. +# No images yet. ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family + "gfx1101": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", + "gfx1200": "https://rocm.nightlies.amd.com/v2/gfx120X-all/", "gfx1201": "https://rocm.nightlies.amd.com/v2/gfx120X-all/"} ROCM_VERSION = os.environ.get("STRATA_ROCM_VERSION", "7.10.0a20251120") # what Strata's HIP build was tested with ROCM_SYSTEM_MIN = (7, 0) # an older system ROCm is passed over for the wheels (gfx1201 needs ROCm 6.4 or newer) -AMD_ARCHS = ("gfx1100", "gfx1201") +AMD_ARCHS = ("gfx1100", "gfx1101", "gfx1200", "gfx1201") AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name + "gfx1101": "AMD Radeon RX 7800 XT / 7700 XT (gfx1101)", + "gfx1200": "AMD Radeon RX 9060 series (gfx1200)", "gfx1201": "AMD Radeon RX 9070 series / AI PRO R9700 (gfx1201)"} -AMD_CARDS = "the RX 7900 XT / XTX (gfx1100) and the RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201)" +AMD_CARDS = ("the RX 7900 XT / XTX (gfx1100), RX 7800 XT / 7700 XT (gfx1101), RX 9060 XT (gfx1200) and " + "RX 9070 / 9070 XT / Radeon AI PRO R9700 (gfx1201)") def rocm_index(arch): return os.environ.get("STRATA_ROCM_INDEX") or ROCM_INDEXES[arch] -def amd_gpus(): +def amd_gpus(sysfs="/sys"): """AMD GPUs from the kernel's KFD topology (the amdgpu driver; no ROCm needed), numbered as HIP numbers them: - the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported).""" - base = Path("/sys/class/kfd/kfd/topology/nodes") + the GPU nodes in order, the CPU nodes skipped. Integrated GPUs are listed too (not supported). + sysfs: the tree to read (tools/test_setup_amd.py passes a mocked one).""" + base = Path(sysfs) / "class/kfd/kfd/topology/nodes" found = [] if WIN or not base.is_dir(): return found @@ -746,7 +753,7 @@ def amd_gpus(): except (OSError, ValueError): continue arch = f"gfx{ver // 10000}{(ver // 100) % 100:x}{ver % 100:x}" - dev = Path(f"/sys/class/drm/renderD{props.get('drm_render_minor', '')}/device") + dev = Path(sysfs) / f"class/drm/renderD{props.get('drm_render_minor', '')}/device" try: vram = int((dev / "mem_info_vram_total").read_text()) / 2 ** 30 except (OSError, ValueError): @@ -1767,8 +1774,8 @@ def main() -> int: "this mode the experts the GPU does not hold are copied into RAM once when they fit (resident), " "else read through the OS file cache (mmap); resident / mmap force one of the two") ap.add_argument("--backend", choices=["cuda", "hip"], - help="cuda = NVIDIA (default), hip = AMD RX 7900 XT/XTX or RX 9070 / AI PRO R9700 on Linux (experimental; chosen by itself " - "when the PC has no NVIDIA card Strata can use)") + help="cuda = NVIDIA (default), hip = AMD RX 7900 / 7800 / 7700 XT, RX 9060 XT / 9070 / AI PRO R9700 on " + "Linux (experimental; chosen by itself when the PC has no NVIDIA card Strata can use)") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() if a.gpu is not None: # --gpu 0,2 means --gpus 0,2 (a user tried it: issue report) @@ -1882,7 +1889,7 @@ def main() -> int: if not found: fail("no NVIDIA GPU found (nvidia-smi did not answer)", "install the NVIDIA driver from https://www.nvidia.com/drivers and restart the PC" - + ("; an AMD RX 7900 XT/XTX or RX 9070 / AI PRO R9700: --backend hip" if amd else "")) + + (f"; AMD ({', '.join(AMD_ARCHS)}): --backend hip" if amd else "")) if len(found) > 1 or gpu_problem(found[0]) is not None: gpu_table(found) sel = choose_gpus(a, found) # asked when two or more cards can share the model diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py new file mode 100644 index 00000000..99bb90f4 --- /dev/null +++ b/tools/test_setup_amd.py @@ -0,0 +1,81 @@ +"""Tests for setup.py's AMD card detection on a mocked KFD topology (/sys/class/kfd + /sys/class/drm): the arch +names from gfx_target_version, the CPU node skipped, HIP numbering, product names, which cards are supported and +which TheRock index each family installs from. No GPU, no ROCm, no downloads. + + python -m unittest tools.test_setup_amd +""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import setup # noqa: E402 + + +def fake_sysfs(root: Path, nodes: list) -> None: + """nodes: (gfx_target_version, simd_count, render_minor, product_name or None, vram_bytes)""" + for i, (ver, simd, minor, name, vram) in enumerate(nodes): + n = root / "class/kfd/kfd/topology/nodes" / str(i) + n.mkdir(parents=True) + (n / "properties").write_text(f"cpu_cores_count {0 if simd else 12}\nsimd_count {simd}\n" + f"gfx_target_version {ver}\ndrm_render_minor {minor}\n") + if simd: + d = root / f"class/drm/renderD{minor}/device" + d.mkdir(parents=True) + (d / "mem_info_vram_total").write_text(str(vram)) + if name is not None: + (d / "product_name").write_text(name + "\n") + + +class KfdDetection(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) + self.win = setup.WIN + setup.WIN = False + + def tearDown(self): + setup.WIN = self.win + self.tmp.cleanup() + + def test_every_family(self): + fake_sysfs(self.root, [ + (0, 0, 0, None, 0), # the CPU node: skipped + (110001, 120, 128, "", 16 << 30), # gfx1101 without a product name + (120000, 64, 129, None, 16 << 30), # gfx1200, no product_name file + (120001, 128, 130, "AMD Radeon AI PRO R9700", 32 << 30), + (110002, 64, 131, None, 8 << 30), # gfx1102: listed, not supported + (100306, 4, 132, None, 512 << 20), # an integrated gfx1036: listed, not supported + (110000, 192, 133, "Radeon RX 7900 XTX", 24 << 30), + ]) + g = setup.amd_gpus(str(self.root)) + self.assertEqual([x["arch"] for x in g], ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1036", "gfx1100"]) + self.assertEqual([x["index"] for x in g], [0, 1, 2, 3, 4, 5]) # HIP numbers: GPU nodes only + self.assertEqual(g[0]["name"], setup.AMD_NAMES["gfx1101"]) + self.assertEqual(g[1]["name"], setup.AMD_NAMES["gfx1200"]) + self.assertEqual(g[2]["name"], "AMD Radeon AI PRO R9700") + self.assertEqual(g[3]["name"], "AMD Radeon (gfx1102)") + self.assertAlmostEqual(g[2]["vram_gb"], 32.0) + ok = [x["arch"] for x in g if setup.amd_problem(x) is None] + self.assertEqual(ok, ["gfx1101", "gfx1200", "gfx1201", "gfx1100"]) + self.assertIn("gfx1102", setup.amd_problem(g[3])) + self.assertIn("gfx1036", setup.amd_problem(g[4])) + + def test_no_kfd(self): + self.assertEqual(setup.amd_gpus(str(self.root)), []) + + def test_rocm_index_per_family(self): + for arch in setup.AMD_ARCHS: + self.assertIn(arch, setup.ROCM_INDEXES) + self.assertTrue(setup.ROCM_INDEXES["gfx1101"].endswith("/gfx110X-dgpu/")) + self.assertTrue(setup.ROCM_INDEXES["gfx1200"].endswith("/gfx120X-all/")) + self.assertEqual(setup.ROCM_INDEXES["gfx1101"], setup.ROCM_INDEXES["gfx1100"]) + self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"]) + + +if __name__ == "__main__": + unittest.main() From ebe52edd8b4951c728bc1667670e248000e738ff Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:41:46 +0200 Subject: [PATCH 3/5] setup: AMD layer splits with --gpus (every chosen card a supported AMD arch; the engine compiled for each) setup refused AMD GPU lists at install and at start ("NVIDIA only for now"), although the engine's layer split runs on two AMD cards (0.1.30, from a hand-written config). - amd_parse_gpus(): --gpus "1,0" (setup's HIP numbering, the first card the main one) or "all" (every supported card, the most VRAM first); every card must be in AMD_ARCHS, else a plain message with what can be used. - install: --backend hip --gpus writes "gpu": [..] + "layer_split" like the NVIDIA path; build_engine_hip compiles for the set of the chosen cards' archs (CMAKE_HIP_ARCHITECTURES "gfx1100;gfx1201" already worked) and records it in BUILD.json; an engine whose archs cover the cards is not rebuilt; update_installed_engine keeps every arch. - rocm_root(archs): cards of two families need a system ROCm (TheRock's wheels hold one family) - said plainly. - start: --gpus on an AMD install is saved like on NVIDIA (refused when the engine has no code for a card); --gpus all finds the AMD cards on a PC without NVIDIA cards that can share. - docs/AMD_HIP.md, README; tools/test_setup_amd.py: lists, "all", refusals, the one-family wheel rule, the arch set in the build and BUILD.json. --- README.md | 2 +- docs/AMD_HIP.md | 13 ++-- docs/MULTI_GPU.md | 4 +- setup.py | 145 +++++++++++++++++++++++++++++++--------- tools/test_setup_amd.py | 75 +++++++++++++++++++++ 5 files changed, 201 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index bc1eb30c..a5531808 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ It needs an explicit packing conversion and is not an installer menu option. An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental; the RX 7800 XT / 7700 XT and RX 9060 XT were validated by their owners): `./setup.sh --backend hip`, chosen by itself on a PC with no NVIDIA card Strata can use. It installs ROCm without sudo -and compiles the engine (one GPU, no images yet). Details: [AMD HIP](docs/AMD_HIP.md). +and compiles the engine (no images yet; several cards with `--gpus`). Details: [AMD HIP](docs/AMD_HIP.md). ## Install diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 3d6695d5..862b0e75 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -36,7 +36,13 @@ the kernel's amdgpu driver (no ROCm install needed): card's architecture and the installed hipBLASLt version (read from `hipblaslt-version.h`; 1.2.0 is `100200`). Otherwise it says so and the prompt's dense matrix products use plain hipBLAS (slower prompts, same answers). A table's solution ids are valid only for that pair, and the engine refuses any other table. -- **Limits for now:** one GPU, no images, no calibration. The Monitor shows no GPU statistics. +- **Several cards:** setup takes one card (the one with the most VRAM, or `--gpu N`) unless you name more: + `./setup.sh --backend hip --gpus 1,0` splits the model's layers across them, the first one the main card (numbers + as setup lists them; `--gpus all` = every supported card, the most VRAM first). Every chosen card must be one of the + architectures above; the engine is compiled for each of them (cards of two families, e.g. gfx1100 + gfx1201, need + a system ROCm 7: AMD's wheels hold one family). A split pays only when no single card holds the model's experts + (see RDNA4 below). +- **Limits for now:** no images, no calibration. The Monitor shows no GPU statistics. The rest of setup is the same as on NVIDIA: the model download, the start script, the server. @@ -115,8 +121,7 @@ The 4K context is a smoke-test starting point, not a model limit. The expert cac sizes itself automatically and leaves 1 GiB of VRAM headroom. The installer supports this backend (see "Install with setup" above). The vision helper is NVIDIA-only for now. -Setup installs one AMD card; the engine's layer split also runs on two AMD cards when the config is written by hand -(see RDNA4 below). +Setup installs one AMD card, or several with `--gpus` (the engine's layer split; see RDNA4 below). ## RDNA4 (gfx1201) @@ -153,7 +158,7 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 (hipBLASLt 1.4.1; 0.98-1.76x per GEMM over hipBLAS) changed the end-to-end prompt speed by 0-3%, within noise, so none is shipped: on gfx1201 the plain hipBLAS path is already close. - **Both cards in one run (layer split, engine 0.1.30):** the config's `"backend": "hip", "gpu": [1, 0]` (R9700 - first) runs through `serve/server.py`; setup does not offer it yet. Auto split put layers 0-27 on the R9700 and + first) runs through `serve/server.py` (setup writes it with `--gpus 1,0` since 0.1.31). Auto split put layers 0-27 on the R9700 and 28-47 on the 9070 XT. With every expert on the GPUs the split gives exactly the tokens of the R9700 alone (4K and 16K prompts); checkpoints on the split (second turn, rewind, a prompt sharing a prefix, a cancelled prompt retried) give exactly the tokens of a fresh read. The conversation cache refuses a split at start (exit 2). diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 61ec5291..53d8ec3d 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -44,8 +44,8 @@ now on; the answer is kept. - a card older than the RTX 20 series (compute capability below 7.5: GTX 10 and older); - a card with less than 8 GB of VRAM, together with others (each card holds a copy of the dense weights and its own prompt buffers); -- AMD and Intel GPUs, and a mix of NVIDIA with them. (Two AMD RDNA4 cards run the split from a hand-written - config; see [AMD_HIP.md](AMD_HIP.md#rdna4-gfx1201).) +- Intel GPUs, and a mix of NVIDIA and AMD cards. (AMD cards share a model among themselves: `./setup.sh --backend + hip --gpus 1,0`, see [AMD_HIP.md](AMD_HIP.md).) Or edit an existing config (`strata-*.json`), then restart: diff --git a/setup.py b/setup.py index b17031f1..93eafc59 100644 --- a/setup.py +++ b/setup.py @@ -414,6 +414,15 @@ def engine_archs(): return [int(x) for x in meta.get("archs", [])], bool(meta.get("ptx")) +def engine_archs_hip(): + """The AMD architectures the installed HIP engine was compiled for ("gfx1201", ...), or None.""" + try: + meta = json.loads((ROOT / "engine" / "BUILD.json").read_text()) + except (OSError, ValueError): + return None + return [str(x) for x in meta.get("archs", [])] if meta.get("backend") == "hip" else None + + def engine_runs_on(g) -> bool: ea = engine_archs() if ea is None or not ea[0]: @@ -422,6 +431,18 @@ def engine_runs_on(g) -> bool: return int(g["arch"]) in archs or (ptx and int(g["arch"]) > max(archs)) +def start_gpus(text): + """--gpus when starting an installed model: NVIDIA cards as nvidia-smi numbers them, or on a PC whose AMD cards + are the ones Strata can use, AMD cards as setup lists them ("all": every supported AMD card).""" + if not text: + return None + if str(text).strip().lower() == "all" and not WIN and not together_ok(gpus()): + amd = amd_gpus() + if len([g for g in amd if amd_problem(g) is None]) >= 2: + return [g["index"] for g in amd_parse_gpus("all", amd)] + return parse_gpus(text, gpus()) + + def choose_gpus(a, found) -> list: """Which cards this install uses: --gpus / --gpu, or asked when two or more can share the model (the two best together recommended), else the supported card with the most VRAM. Returns their numbers, the main one first.""" @@ -775,6 +796,33 @@ def amd_problem(g): return None +def amd_parse_gpus(text, amd) -> list: + """--gpus with AMD cards, numbered as HIP numbers them (setup's list): "1,0", or "all" (every supported card, the + most VRAM first). Every chosen card must be one Strata supports (AMD_ARCHS; they may be of different + architectures: the engine is compiled for each). Returns the cards, the main one first.""" + usable = [g for g in amd if amd_problem(g) is None] + if str(text).strip().lower() == "all": + sel = [g["index"] for g in sorted(usable, key=lambda x: (-round(x["vram_gb"]), x["index"]))] + else: + try: + sel = [int(x) for x in str(text).split(",") if x.strip()] + except ValueError: + fail(f"--gpus takes AMD GPU numbers as setup lists them, e.g. --gpus 1,0 (or --gpus all), not {text!r}") + if len(sel) < 2 or len(set(sel)) != len(sel): + fail("--gpus takes two or more different GPUs, e.g. --gpus 1,0 (one GPU: --gpu 1)", + "this PC has " + (f"{len(usable)} AMD card{'s' if len(usable) != 1 else ''} Strata can use" + + (": " + ", ".join(f"GPU {g['index']} ({g['name']})" for g in usable) if usable else ""))) + byid = {g["index"]: g for g in amd} + for i in sel: + g = byid.get(i) + p = "not found on this PC" if g is None else amd_problem(g) + if p is not None: + fail(f"AMD GPU {i}{'' if g is None else ' (' + g['name'] + ')'} cannot be used: {p}", + ("use these together: --gpus " + ",".join(str(x["index"]) for x in usable)) if len(usable) >= 2 else + ("use one card: --gpu " + str(usable[0]["index"])) if usable else f"the AMD backend runs on {AMD_CARDS}") + return [byid[i] for i in sel] + + def rocm_version(root): """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" try: @@ -784,9 +832,11 @@ def rocm_version(root): return None -def rocm_root(arch): - """ROCm for compiling and running the HIP engine for `arch`: (root, library folders). A system ROCm 7 with hipcc - and hipBLAS, else AMD's TheRock wheels (ROCM_VERSION, from the card family's index) installed into .venv.""" +def rocm_root(archs): + """ROCm for compiling and running the HIP engine for `archs` (one arch or a list: the cards of a layer split): + (root, library folders). A system ROCm 7 with hipcc and hipBLAS, else AMD's TheRock wheels (ROCM_VERSION, from the + card family's index) installed into .venv.""" + archs = [archs] if isinstance(archs, str) else list(archs) sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): ver = rocm_version(sysroot) @@ -794,7 +844,11 @@ def rocm_root(arch): return sysroot, [str(sysroot / "lib")] warn(f"the ROCm in {sysroot} is {ver[0]}.{ver[1]}; Strata needs {ROCM_SYSTEM_MIN[0]}.{ROCM_SYSTEM_MIN[1]} or " "newer: using AMD's wheels in .venv instead") - index = rocm_index(arch) + indexes = list(dict.fromkeys(rocm_index(a) for a in archs)) + if len(indexes) > 1: # TheRock's wheels hold one GPU family's libraries + fail(f"cards of two GPU families ({', '.join(archs)}) need a system ROCm 7 (in /opt/rocm): AMD's Python " + "wheels come per family", "install ROCm 7 system-wide, or use cards of one family (--gpu N for one card)") + index = indexes[0] stamp = Path(sys.prefix) / ".strata-rocm.json" have = json.loads(stamp.read_text()) if stamp.exists() else {} if have.get("version") != ROCM_VERSION or have.get("index") != index: @@ -854,19 +908,22 @@ def hipblaslt_table(arch, lib_dirs): def build_engine_hip(gpu, llama) -> Path: - """Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`).""" + """Compile the HIP engine for this AMD GPU into engine/ (again only when its source changed: a `git pull`). + gpu["archs"]: every architecture it needs code for (the cards of a layer split), else gpu["arch"].""" eng = ROOT / "engine" eng.mkdir(exist_ok=True) stamp = eng / "BUILD.json" meta = json.loads(stamp.read_text()) if stamp.exists() else {} src = source_hash(ENGINE_SOURCES) - if meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and gpu["arch"] in meta.get("archs", []): + archs = sorted(set(gpu.get("archs") or [gpu["arch"]])) + has_archs = set(archs) <= set(meta.get("archs", [])) + if meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs: ok("engine already built for this PC") return eng if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): fail("a C++ compiler and git are needed to compile the AMD engine", "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") - root, dirs = rocm_root(gpu["arch"]) + root, dirs = rocm_root(archs) libs = [str(Path(d).parent) for d in dirs[1:]] bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), root / "amdgcn" / "bitcode") @@ -875,18 +932,19 @@ def build_engine_hip(gpu, llama) -> Path: os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) say(" The engine's source changed: compiling it again (only what changed, a few minutes) ..." - if meta.get("backend") == "hip" and (eng / EXE).exists() and gpu["arch"] in meta.get("archs", []) - else " Compiling the Strata engine for your AMD GPU (10-20 minutes, once) ...") + if meta.get("backend") == "hip" and (eng / EXE).exists() and has_archs + else f" Compiling the Strata engine for your AMD GPU{'s' if len(archs) > 1 else ''} ({', '.join(archs)}; " + "10-20 minutes, once) ...") cmake_build(ROOT, ROOT / "build-hip", "strata", ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", - "-DSTRATA_PREFILL_MMQ=ON", f"-DCMAKE_HIP_ARCHITECTURES={gpu['arch']}", + "-DSTRATA_PREFILL_MMQ=ON", "-DCMAKE_HIP_ARCHITECTURES=" + ";".join(archs), f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}", f"-DSTRATA_GGML_DIR={llama}"], None, "") shutil.copy2(ROOT / "build-hip" / EXE, eng / EXE) stamp.write_text(json.dumps({"source": "local-hip", "backend": "hip", "version": source_version(), - "archs": [gpu["arch"]], "vision": "none", "lib_dirs": dirs, "src": src}, indent=1)) + "archs": archs, "vision": "none", "lib_dirs": dirs, "src": src}, indent=1)) ok(f"engine compiled: {eng / EXE}") return eng @@ -993,7 +1051,9 @@ def update_installed_engine(url_base) -> None: g = next((x for x in usable if x["arch"] in meta.get("archs", [])), usable[0] if usable else None) if g is None: raise RuntimeError("no supported AMD GPU found") - build_engine_hip(g, get_llama_cpp()) + # every architecture it was built for (a layer split across two families keeps both) + build_engine_hip({**g, "archs": [x for x in meta.get("archs", []) if x in AMD_ARCHS] or [g["arch"]]}, + get_llama_cpp()) except (Exception, SystemExit) as e: warn(f"could not compile the updated engine{'' if isinstance(e, SystemExit) else f' ({e})'}: " "starting the installed one") @@ -1557,17 +1617,32 @@ def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_ refresh_draft_vocab(Path(cfg["args"][cfg["args"].index("--mtp") + 1]), cfg.get("draft_vocab", "cjk")) cmd = [sys.executable, str(ROOT / "serve" / "server.py"), "--engine", "strata", "--config", str(cfg_path), "--port", str(port or cfg.get("port", 8080))] - if cfg.get("backend") == "hip": # AMD: one card, numbered as HIP numbers them - if isinstance(gpu, list): - fail("several GPUs sharing one model: NVIDIA only for now", "use one AMD card (--gpu N)") - if gpu is not None: + if cfg.get("backend") == "hip": # AMD, numbered as HIP numbers them (setup's KFD order) + amd = amd_gpus() + if isinstance(gpu, list): # --gpus: saved, this model runs on these cards from now on + cards = amd_parse_gpus(",".join(str(i) for i in gpu), amd) + built = (engine_archs_hip() or []) + miss = [x for x in cards if built and x["arch"] not in built] + if miss: + fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), + "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) + cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" + cfg_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + gpu = None + elif gpu is not None: cmd += ["--gpu", str(gpu)] found = [] use = gpu if gpu is not None else cfg.get("gpu") - g = next((x for x in amd_gpus() if x["index"] == (use if use is not None else x["index"]) - and amd_problem(x) is None), None) - if g is not None: - ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)") + if isinstance(use, list): + byid = {x["index"]: x for x in amd} + ok("GPUs: " + " + ".join(gpu_name(byid[i]) if i in byid else f"GPU {i} (not found)" for i in use) + + f" together, AMD (layers split {cfg.get('layer_split') or 'auto'})") + else: + g = next((x for x in amd if x["index"] == (use if use is not None else x["index"]) + and amd_problem(x) is None), None) + if g is not None: + ok(f"GPU: {g['name']} ({g['vram_gb']:.0f} GB, AMD)") else: found = gpus() if cfg.get("backend") == "hip": @@ -1744,9 +1819,9 @@ def main() -> int: ap.add_argument("--port", type=int, help="the server's port (default: the one the install was set up with, 8080 for a new one)") ap.add_argument("--gpu", help="one GPU, numbered as nvidia-smi numbers them (default: asked when several can be " "used; with --setup it is saved, when starting it is for that start only)") - ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them: \"0,2\", or \"all\" " - "(every card that can); the first is the main one. Saved, also when starting " - "(see docs/MULTI_GPU.md)") + ap.add_argument("--gpus", help="several GPUs sharing one model, as nvidia-smi numbers them (AMD: as setup lists " + "them): \"0,2\", or \"all\" (every card that can); the first is the main one. " + "Saved, also when starting (see docs/MULTI_GPU.md)") ap.add_argument("--layer-split", help="with --gpus: where each later GPU's layers start (\"18\", \"16,32\"); " "default auto, placed from each GPU's free VRAM") ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other " @@ -1817,7 +1892,7 @@ def main() -> int: # starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start # on the first one alone unless given with --setup), --gpu N runs this start on one card; neither: the saved # choice, and asked once when the PC has cards that could share the model - run_gpu = (parse_gpus(a.gpus, gpus()) if a.gpus else None) or a.gpu + run_gpu = start_gpus(a.gpus) or a.gpu port = a.port or 8080 # a new install's port (issue #32: --port for an existing one) if have and a.calibrate and not (a.setup or a.model or a.family or a.check): if not a.build: @@ -1860,11 +1935,11 @@ def main() -> int: say(" 1) NVIDIA: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in found if gpu_problem(g) is None) + " (recommended)") say(" 2) AMD: " + ", ".join(f"{g['name']} ({g['vram_gb']:.0f} GB)" for g in amd_ok) - + " (experimental: compiled here, one GPU, no images - docs/AMD_HIP.md)") + + " (experimental: compiled here, no images - docs/AMD_HIP.md)") hip = ask("Which cards?", ["1", "2"], "1", a.yes or a.check) == "2" if a.check and not hip: say(" (the AMD card: ./setup.sh --backend hip)") - if hip: # AMD (experimental): one card, compiled here + if hip: # AMD (experimental): compiled here if WIN: fail("Strata's AMD backend runs on Linux only", "use an NVIDIA RTX 20 series or newer card on Windows") say(" Your AMD GPUs:" if amd else " No AMD GPU found (the amdgpu driver's KFD topology is empty).") @@ -1873,17 +1948,25 @@ def main() -> int: usable = [g for g in amd if amd_problem(g) is None] if not usable: fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS} on Linux") - if a.gpus: - fail("several GPUs sharing one model: NVIDIA only for now", "use one AMD card (--gpu N)") - if a.gpu is not None: + if a.gpus: # a layer split across these cards, the first one the main + chosen = amd_parse_gpus(a.gpus, amd) + gpu = chosen[0] + elif a.gpu is not None: gpu = next((g for g in usable if g["index"] == a.gpu), None) if gpu is None: fail(f"AMD GPU {a.gpu} cannot be used", "use one of: " + ", ".join(f"--gpu {g['index']}" for g in usable)) + chosen = [gpu] else: gpu = max(usable, key=lambda x: (round(x["vram_gb"]), -x["index"])) - gpu = {**gpu, "count": len(amd), "archs": [gpu["arch"]]} - sel, multi, chosen = [gpu["index"]], [], [gpu] + chosen = [gpu] + # the engine is compiled for every chosen card's architecture + gpu = {**gpu, "count": len(amd), "archs": sorted({g["arch"] for g in chosen})} + chosen = [gpu] + chosen[1:] + sel = [g["index"] for g in chosen] + multi = sel if len(sel) > 1 else [] a.gpu = gpu["index"] if len(amd) > 1 else a.gpu + if multi: + ok("GPUs: " + " + ".join(gpu_name(x) for x in chosen) + " together (the model's layers are split across them)") ok(f"GPU: {gpu['name']}, {gpu['vram_gb']:.1f} GB VRAM, {gpu['arch']} (AMD, experimental: docs/AMD_HIP.md)") else: if not found: diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 99bb90f4..6c82c35f 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -77,5 +77,80 @@ class KfdDetection(unittest.TestCase): self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"]) +class GpuLists(unittest.TestCase): + """--gpus with AMD cards: every chosen card must be supported; the first is the main one.""" + AMD = [{"index": 0, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0, "arch": "gfx1201"}, + {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"}, + {"index": 2, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}, + {"index": 3, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0, "arch": "gfx1100"}] + + def setUp(self): + self.say = setup.say + setup.say = lambda *a, **k: None + + def tearDown(self): + setup.say = self.say + + def test_list_in_order(self): + self.assertEqual([g["index"] for g in setup.amd_parse_gpus("1,0", self.AMD)], [1, 0]) + self.assertEqual([g["index"] for g in setup.amd_parse_gpus(" 0, 3 ", self.AMD)], [0, 3]) + + def test_all_is_every_supported_card_most_vram_first(self): + self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", self.AMD)], [1, 3, 0]) + + def test_refusals(self): + for text in ("1,2", "1,7", "1", "1,1", "x,y"): + with self.assertRaises(SystemExit, msg=text): + setup.amd_parse_gpus(text, self.AMD) + + def test_wheels_hold_one_family(self): + with tempfile.TemporaryDirectory() as d: # no system ROCm there: the wheels would be needed + old = setup.os.environ.get("ROCM_PATH") + setup.os.environ["ROCM_PATH"] = d + try: + with self.assertRaises(SystemExit): + setup.rocm_root(["gfx1100", "gfx1201"]) + finally: + if old is None: + del setup.os.environ["ROCM_PATH"] + else: + setup.os.environ["ROCM_PATH"] = old + + def test_build_for_every_arch(self): + """build_engine_hip compiles for the set of the chosen cards' archs and records it in BUILD.json.""" + calls = {} + saved = {k: getattr(setup, k) for k in ("ROOT", "rocm_root", "cmake_build", "source_hash", "source_version", + "ok", "shutil")} + with tempfile.TemporaryDirectory() as d: + root = Path(d) + + def fake_build(src, bdir, target, defs, vcvars, bat): + calls["defs"] = defs + (bdir).mkdir(parents=True, exist_ok=True) + (bdir / setup.EXE).write_text("engine") + + class Sh: + which = staticmethod(lambda name: "/usr/bin/" + name) + copy2 = staticmethod(lambda a, b: Path(b).write_text(Path(a).read_text())) + setup.ROOT, setup.cmake_build, setup.ok, setup.shutil = root, fake_build, lambda *a: None, Sh + setup.source_hash, setup.source_version = (lambda *a: "h"), (lambda: "0.1.31") + setup.rocm_root = lambda archs: (calls.setdefault("archs", archs) and root, [str(root / "lib")]) + try: + setup.build_engine_hip({"arch": "gfx1201", "archs": ["gfx1201", "gfx1100", "gfx1201"]}, root) + self.assertEqual(calls["archs"], ["gfx1100", "gfx1201"]) + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1100;gfx1201", calls["defs"]) + import json + self.assertEqual(json.loads((root / "engine" / "BUILD.json").read_text())["archs"], + ["gfx1100", "gfx1201"]) + calls.clear() # one of those cards alone: already built, no compile + setup.build_engine_hip({"arch": "gfx1100"}, root) + self.assertNotIn("defs", calls) + setup.build_engine_hip({"arch": "gfx1101"}, root) # another arch: compiled again + self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1101", calls["defs"]) + finally: + for k, v in saved.items(): + setattr(setup, k, v) + + if __name__ == "__main__": unittest.main() From 9f8fa9088e3a8f4194a401fe500d7a35b68cca07 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:43:12 +0200 Subject: [PATCH 4/5] #253: the 8 GiB arena pin cap only under WDDM; STRATA_ARENA_PIN_GIB; the split's prompt chunk steps down - The expert arena was pinned at most 8 GiB whenever a layer split (or remote experts) ran, on every OS - a Windows/WDDM workaround that cost a Linux 4090 + 3060 split two thirds of its prompt speed (#253, bettercallcaleb). The cap now applies only under WDDM (_WIN32, or WSL2 detected by /dev/dxg), for multi_gpu and expert_cache_remote alike. STRATA_ARENA_PIN_GIB overrides it on any OS: "0" pins the whole arena, N > 0 at most N GiB (arena_pin_cap_gib(), -1 when unset: the same name and meaning as the S2 branch's helper, file-local here). - The split's prompt chunk no longer stops the start when its buffers do not fit: a prompt path without a loan first gets the largest chunk whose buffers (Prefill::bytes_needed) leave 512 MiB free on its device, and an init that still fails steps down one size (8192 -> 6144 -> ... -> 2048 -> 1536 -> 1024 -> 512): Prefill::reset() frees what the failed init made, the loans are re-priced, and the failed allocation's sticky error is consumed (else the next launch check reported "out of memory"). - pinned.cu: the capped note no longer says "for CUDA1". - docs: MULTI_GPU.md, SECOND_GPU.md. Measured on amdbox (Linux, R9700 + RX 9070 XT, gpu [1, 0], Coder IQ1_M, 128 greedy tokens; tok/s): | cache | arm | 4K cold | 4K warm | 16K cold | 16K warm | decode | | auto (holds ~all) | 8 GiB cap | 678 | 1,355 | 1,709 | 1,880 | 44.5-51.5 | | | whole arena | 703 | 1,234 | 1,729 | 1,864 | 44.6-51.4 | | fixed 1500 on CUDA0 | 8 GiB cap | 608 | 1,101 | 1,287 | | 34.5-36.1 | | | whole arena | 716 | 1,160 | 1,803 | | 34.8-36.0 | (2 starts per arm for auto, 5 for fixed.) With most experts streamed the whole arena reads a 16K prompt 40% faster; with every expert already on the cards the two are within noise except 4K warm (-9%: the pinned share raises the auto lend to 90% and the streamed ring to 384 slots). Identity: the fixed-cache arms gave the same tokens in all 5 + 5 starts (4K, 16K, 4K again), and the auto arms 2 + 2. The step-down was exercised on the 9070 XT with --expert-cache 3000 --no-prefill-borrow --prefill 8192 ("need 4528 MiB, 2910 MiB free: 2048-token chunks"; with the init retry alone it went 8192 -> ... -> 2048, and 1536 ran all four requests). Known, also on main: that own-buffer configuration at 2048 makes hipBLAS pick hipBLASLt kernels whose code objects this ROCm 7.14 lacks (TensileLibrary_..._gfx1201-xnack+.co not found, "launchKernel failed") and the prompt hangs. The WDDM side (Windows, WSL2) is unchanged and not re-measured here. --- docs/AMD_HIP.md | 6 +- docs/MULTI_GPU.md | 6 +- docs/SECOND_GPU.md | 5 +- include/strata/prefill/prefill.hpp | 6 ++ src/core/pinned.cu | 2 +- src/prefill/prefill.cpp | 10 +- src/program/generate.cpp | 154 ++++++++++++++++++++++++----- 7 files changed, 159 insertions(+), 30 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 862b0e75..820b01b4 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -170,8 +170,10 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 | R9700 + 9070 XT, auto split | 1,384 tok/s | 1,906 tok/s | 42-43 tok/s | | RX 9070 XT alone | 1,016 tok/s | 1,519 tok/s | 38-40 tok/s | - A split is worth it when no single card holds the model's experts. On Linux the split pins at most 8 GiB of the - expert arena (a Windows limit that also applies here). + A split is worth it when no single card holds the model's experts. Since 0.1.31 a split pins the whole expert + arena on Linux (the 8 GiB cap is for Windows/WSL2 only, #253): with an expert cache of 1,500 on the R9700 (most + experts streamed) the split read a 16K prompt at 1,803 tok/s instead of 1,287, with the same tokens in 5 + 5 + starts. - **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on one card or two and on engine 0.1.29 as well; not yet explained. - **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 53d8ec3d..97e51543 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -95,8 +95,10 @@ into the card that owns the layer. - The prompt path has its own buffers on every card (1.5 GB each at the default 2048-token chunk; `--prefill 1024` halves that) instead of borrowing cache slots as one card does. An explicit `--expert-cache` on the first card is capped to leave room for them. -- On Windows only 8 GiB of the expert arena is pinned (more, mapped into two GPU contexts, leaves WDDM refusing - allocations); the PCIe share covers those layers. +- Under WDDM (Windows, and WSL2) only 8 GiB of the expert arena is pinned (more, mapped into two GPU contexts, + leaves WDDM refusing allocations); the rest streams through the pinned staging ring. A Linux driver has no such + limit, so there the whole arena is pinned (since 0.1.31; the cap cost a 4090 + 3060 split two thirds of its + prompt speed, #253). `STRATA_ARENA_PIN_GIB=N` pins at most N GiB, `0` the whole arena, on any OS. - Every card needs compute capability 7.5 (RTX 20 or newer). The pre-sm_80 QSA scorer path is fp32 FMAs, so a Turing card runs the same kernels instead of the tensor-core prompt attention. diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.md index 7eb69dfd..0ce94e7a 100644 --- a/docs/SECOND_GPU.md +++ b/docs/SECOND_GPU.md @@ -34,8 +34,9 @@ compute capacity. The experiment requires the corresponding visible CUDA devices and a CUDA enabled build. Each card must keep at least 512 MiB free. Tiers must be enabled -in order. On Windows, CUDA registration of the host expert arena is capped at -8 GiB to leave room for the contexts and MTP on CUDA0. The rest remains +in order. Under WDDM (Windows, WSL2), CUDA registration of the host expert arena is capped at +8 GiB to leave room for the contexts and MTP on CUDA0 (`STRATA_ARENA_PIN_GIB` overrides it; on Linux the whole +arena is registered). The rest remains available to the CPU pool; the PCIe expert path is available only for the registered layers. Without secondary GPUs, the original uncapped registration behavior applies. diff --git a/include/strata/prefill/prefill.hpp b/include/strata/prefill/prefill.hpp index b792ff04..38f64a91 100644 --- a/include/strata/prefill/prefill.hpp +++ b/include/strata/prefill/prefill.hpp @@ -52,6 +52,11 @@ public: Prefill(const Prefill&) = delete; Prefill& operator=(const Prefill&) = delete; + /// Frees every buffer, stream and event `init` made (as the destructor does) and starts over empty, so `init` can + /// run again - with a smaller chunk when the first one did not fit. The stage range (`set_stage`) and the + /// callbacks stay. The device `init` ran on must be current. + void reset(); + /// `host_res`: the static residency table (n_layers x n_expert, slot or -1) or null; `cache` its slots. /// `borrow`/`borrow_bytes`: device memory to carve every buffer from (the top slots of the expert cache, /// lent for the prompt and refilled after it); null = allocate normally. @@ -110,6 +115,7 @@ private: Prefill* next_ = nullptr; const float* hand_in_ = nullptr; ///< the previous stage's rows of the chunk being read (host, pinned) bool carve(std::size_t T, void* alloc); // the device buffers of a chunk (prefill.cpp's Alloc) + void release(); // the destructor's cleanup (also `reset`'s) struct Impl; std::unique_ptr impl_; PrefillStats stats_; diff --git a/src/core/pinned.cu b/src/core/pinned.cu index b64eb52a..663c508e 100644 --- a/src/core/pinned.cu +++ b/src/core/pinned.cu @@ -287,7 +287,7 @@ PinnedArena::PinnedArena(uint64_t bytes, const std::vector& bounds, ++registered_slices; } note = (capped ? "cudaHostRegister limited to " + std::to_string(max_pinned_bytes >> 30) + - " GiB for CUDA1; " : + " GiB of the arena; " : "cudaHostRegister of the whole arena FAILED (" + std::string(cudaGetErrorString(e)) + "); ") + std::to_string(registered_slices) + " slices pinned (" + std::to_string(registered_bytes >> 30) + " GiB); " + note; diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 116094ad..2b0ad0c4 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -372,7 +372,15 @@ strata::kernels::QsaAttnPools pools_of(const strata::kernels::KvHostPools& h, co } // namespace Prefill::Prefill() : impl_(new Impl) {} -Prefill::~Prefill() { +Prefill::~Prefill() { release(); } + +void Prefill::reset() { + release(); + impl_.reset(new Impl); + stats_ = PrefillStats{}; +} + +void Prefill::release() { if (!impl_) return; if (impl_->cs) cudaStreamSynchronize(impl_->cs); if (impl_->copy) cudaStreamSynchronize(impl_->copy); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 75e874b0..25c773f3 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -94,6 +94,29 @@ #include namespace { +// STRATA_ARENA_PIN_GIB: how much of the expert arena is registered (pinned) for the GPUs. Unset: -1 (the default +// rule below); "0": the whole arena; N > 0: at most N GiB. (The same helper as src/core/pinned.cu's on the S2 +// branch: identical name and meaning, file-local here.) +static int arena_pin_cap_gib() { + const char* v = std::getenv("STRATA_ARENA_PIN_GIB"); + if (v == nullptr || *v == '\0') return -1; + char* end = nullptr; + const long n = std::strtol(v, &end, 10); + return (end == v || n < 0) ? -1 : (int) std::min(n, 1 << 20); +} + +// Windows' WDDM driver model: native Windows, or WSL2 (its GPU goes through /dev/dxg to the Windows driver). There, +// pinning a large arena into two CUDA contexts leaves WDDM refusing every later allocation (the 5080 + 3090 rig); +// a Linux driver has no such limit (#253: the 8 GiB cap cost a 4090 + 3060 split 3x of its prompt speed). +bool under_wddm() { +#ifdef _WIN32 + return true; +#else + static const bool dxg = std::filesystem::exists("/dev/dxg"); + return dxg; +#endif +} + // perf-review D-4: the lent slots are refilled with queued copies and one wait; STRATA_REFILL_BLOCKING=1 waits on each bool refill_blocking() { static const bool v = std::getenv("STRATA_REFILL_BLOCKING") != nullptr; @@ -2274,11 +2297,20 @@ int main(int argc, char** argv) { srcp = &src; } else { arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1 - // On the multi-GPU Windows experiment, start with at most 8 GiB of mapped host pages. - // Unregistered layers remain in the resident arena and use the CPU expert path. - // (a layer split across GPUs too: pinning all of it into two contexts leaves WDDM refusing every later - // allocation - measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail) - const uint64_t pin_limit = (o.expert_cache_remote[0] > 0 || multi_gpu) ? (8ull << 30) : 0; + // Under WDDM (Windows, WSL2), a multi-GPU run (a layer split, or remote experts) starts with at most 8 GiB of + // mapped host pages: pinning all of it into two contexts leaves WDDM refusing every later allocation - + // measured on the 5080 + 3090 rig: cudaMemGetInfo and the next cudaMalloc fail. Unregistered layers remain + // in the resident arena; their streamed experts go through the pinned staging ring. A Linux driver has no + // such limit, so there the whole arena is pinned (#253). STRATA_ARENA_PIN_GIB overrides both ways. + const int pin_env = arena_pin_cap_gib(); + const bool pin_wddm_cap = pin_env < 0 && (o.expert_cache_remote[0] > 0 || multi_gpu) && under_wddm(); + const uint64_t pin_limit = pin_env >= 0 ? (uint64_t) pin_env << 30 : pin_wddm_cap ? (8ull << 30) : 0; + if (pin_env >= 0) + std::fprintf(stderr, "strata generate: STRATA_ARENA_PIN_GIB=%d: %s\n", pin_env, + pin_env == 0 ? "the whole expert arena is pinned" : "the expert arena's pinning is capped"); + else if (pin_wddm_cap) + std::fprintf(stderr, "strata generate: multi-GPU under WDDM: at most 8 GiB of the expert arena is pinned " + "(STRATA_ARENA_PIN_GIB changes it)\n"); if (!arena_src.open(o.pack, g.n_layers, g.n_expert, /*threads=*/6, err, pin_limit, o.shared_expert_arena)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); @@ -3555,26 +3587,104 @@ int main(int argc, char** argv) { } else { std::fprintf(stderr, "strata serve: the prompt path allocates its own buffers (too few cache slots to borrow)\n"); } - // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next - for (size_t i = 0; i < stages.size(); ++i) { - GpuStage& st = *stages[i]; - st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr); - const strata::core::OnDevice on(st.dev); - void* sb = nullptr; // this stage's own loan, out of its own cache - uint64_t sbb = 0; - // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers - if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) { - sb = st.cache.device_slot(pf_parts[i + 1].first); - sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first); + // layer split across GPUs: a prompt path per stage, each handing its chunk's rows to the next. + // THE CHUNK STEPS DOWN INSTEAD OF EXITING. A split's stage caches are sized after the arena is registered, and + // the prompt path's own buffers (no loan) are not priced into them: with the whole arena pinned (#253) a + // `--prefill auto` split could stop at start with "device buffers for a chunk of 2048 tokens do not fit". A + // chunk that does not fit is tried again one size smaller, down to 512 tokens (a smaller chunk only reads slower). + auto init_prompt_paths = [&]() -> int { // 0: ready; 1: failed (err set); 2: failed with "do not fit" + for (size_t i = 0; i < stages.size(); ++i) { + GpuStage& st = *stages[i]; + st.sp.set_stage(st.lb, i + 1 < stages.size() ? st.le : -1, i + 1 < stages.size() ? &stages[i + 1]->sp : nullptr); + const strata::core::OnDevice on(st.dev); + void* sb = nullptr; // this stage's own loan, out of its own cache + uint64_t sbb = 0; + // `first < 0`: no loan was taken (nothing was lendable), so this stage allocates its own buffers + if (i + 1 < pf_parts.size() && pf_parts[i + 1].first >= 0) { + sb = st.cache.device_slot(pf_parts[i + 1].first); + sbb = part_bytes(pf_parts[i + 1], pf_parts[i + 1].first); + } + if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, + err, sb, sbb)) { + err = "layer split, CUDA" + std::to_string(st.dev) + " prompt path: " + err; + return err.find("do not fit") != std::string::npos ? 2 : 1; + } } - if (!st.sp.init(st.wt, g, st.ss, srcp, &st.cache, host_res.data(), o.prefill_chunk, (void*) st.stream, err, - sb, sbb)) { - std::fprintf(stderr, "strata serve: layer split, CUDA%d prompt path: %s\n", st.dev, err.c_str()); - return 1; + if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); + if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) + return err.find("do not fit") != std::string::npos ? 2 : 1; + return 0; + }; + static constexpr int64_t kStepChunks[] = {6144, 4096, 3072, 2048, 1536, 1024, 512}; + { + // First by arithmetic: a prompt path without a loan allocates its buffers, so the chunk must leave + // headroom on that device (a chunk that fits to the last MiB left hipBLAS nothing: its GEMMs then + // failed to launch on gfx1201 and the prompt hung). `bytes_needed` is the same count `init` makes. + const int64_t kHeadroom = 512ll << 20; + auto own_fits = [&](int64_t c, int& dev_out, int64_t& need_out, int64_t& free_out) -> bool { + for (size_t i = 0; i <= stages.size(); ++i) { + const bool loan = i == 0 ? borrow != nullptr : (i < pf_parts.size() && pf_parts[i].first >= 0); + if (loan) continue; + const int dev = i == 0 ? -1 : stages[i - 1]->dev; + const strata::core::OnDevice on(dev); + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + const int64_t need = (int64_t) strata::prefill::Prefill::bytes_needed(g, i == 0 ? ss : stages[i - 1]->ss, c); + if (need + kHeadroom > (int64_t) fb) { + dev_out = dev < 0 ? 0 : dev; need_out = need; free_out = (int64_t) fb; + return false; + } + } + return true; + }; + int dev = 0; + int64_t need = 0, fb = 0; + if (!own_fits(o.prefill_chunk, dev, need, fb)) { + int64_t c = 0; + for (const int64_t s : kStepChunks) { + int d2 = 0; + int64_t n2 = 0, f2 = 0; + if (s < o.prefill_chunk && own_fits(s, d2, n2, f2)) { c = s; break; } + } + if (c > 0) { + std::fprintf(stderr, "strata serve: a %lld-token chunk's prompt buffers need %lld MiB on CUDA%d, " + "%lld MiB free: %lld-token chunks\n", (long long) o.prefill_chunk, + (long long) (need >> 20), dev, (long long) (fb >> 20), (long long) c); + o.prefill_chunk = c; + } } } - if (multi_gpu) sp.set_stage(0, split_at[0], &stages[0]->sp); - if (!sp.init(wt, g, ss, srcp, &xcache, host_res.data(), o.prefill_chunk, main_cs, err, borrow, borrow_bytes)) { + for (;;) { + const int r = init_prompt_paths(); + if (r == 0) break; + int64_t next = 0; + for (const int64_t c : kStepChunks) + if (c < o.prefill_chunk) { next = c; break; } + if (r == 2 && next > 0) { + std::fprintf(stderr, "strata serve: %s: trying a %lld-token chunk\n", err.c_str(), (long long) next); + // start the prompt paths over (a failed init may hold buffers), and consume the failed allocation's + // error: it is sticky, and the next launch check would report "out of memory" for a kernel + for (auto& stp : stages) { + const strata::core::OnDevice on(stp->dev); + stp->sp.reset(); + (void) cudaGetLastError(); + } + sp.reset(); + (void) cudaGetLastError(); + o.prefill_chunk = next; + if (borrow != nullptr) { // smaller loans for the smaller chunk + for (PfPart& p : pf_parts) + if (p.first >= 0) { + p.first = (int32_t) (p.cache->slots() - part_slots(p, next)); + p.first_now = p.first; + } + lend_first = pf_parts[0].first; + borrow = xcache.device_slot(lend_first); + borrow_bytes = part_bytes(pf_parts[0], lend_first); + } + err.clear(); + continue; + } std::fprintf(stderr, "strata serve: %s\n", err.c_str()); if (err.find("fit") != std::string::npos) // #85: say what frees VRAM std::fprintf(stderr, "strata serve: the GPU has too little free VRAM for the prompt path: turn images " From 18ad40c0dcf842d3851c15bc10b6e752d445620d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Wed, 30 Sep 2026 20:47:39 +0200 Subject: [PATCH 5/5] --split-skip-if-fits (opt-in): an auto split runs on the main card alone when it holds every profiled expert + KV Before any later stage loads, split-auto checks whether CUDA0 alone holds every profiled expert pair plus the whole session (KV of every layer), the drafter + head, the verify windows and the reserve; if so it clears the split (one GPU) and logs why, else it logs how much of the profile CUDA0 would hold and keeps the split. Default behaviour is unchanged: the engine flag is opt-in, and the server passes it only for a config with "split_skip_if_fits": true (and a GPU list). Not with remote expert caches. Measured on amdbox (Coder IQ1_M, --expert-cache auto --prefill auto, 128 greedy tokens, gpu [1, 0] = R9700 first, 2 starts per arm, warm = the second request of each size): | arm | 4K warm | 16K warm | decode | | split (flag off) | 1,244 | 1,897 | 50.5-53.0 | | --split-skip-if-fits (on) | 1,776 | 1,791 | 59.7-61.8 | | R9700 alone | 1,787 | 1,801 | 59.9-61.3 | The flag's run is the R9700-alone run (same tokens, all four requests); with the 9070 XT first it keeps the split ("would hold only 9.84 of the profile's 23.42 GiB"). On this pair the split still reads 16K prompts ~5% faster. --- docs/AMD_HIP.md | 4 ++- docs/MULTI_GPU.md | 6 +++++ serve/server.py | 3 +++ src/program/generate.cpp | 53 +++++++++++++++++++++++++++++++++++++++- 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 820b01b4..39a47002 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -173,7 +173,9 @@ an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 39 A split is worth it when no single card holds the model's experts. Since 0.1.31 a split pins the whole expert arena on Linux (the 8 GiB cap is for Windows/WSL2 only, #253): with an expert cache of 1,500 on the R9700 (most experts streamed) the split read a 16K prompt at 1,803 tok/s instead of 1,287, with the same tokens in 5 + 5 - starts. + starts. `"split_skip_if_fits": true` in the config (0.1.31, opt-in) runs such a pair on the first card alone when it + holds every profiled expert: with the R9700 first, 4K prompts 1,776 tok/s (split: 1,244) and decode ~60 tok/s + (split: ~51), the tokens of the R9700 alone (docs/MULTI_GPU.md). - **Known:** rarely (about 1 start in 10) a HIP run's greedy output differs from another start's at some token, on one card or two and on engine 0.1.29 as well; not yet explained. - **Not validated:** images, long contexts beyond 16K, answer-quality benchmarks. diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 97e51543..67fdfea1 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -54,6 +54,12 @@ Or edit an existing config (`strata-*.json`), then restart: "layer_split": "auto" ``` +**Skip the split when the first card holds everything** (opt-in, 0.1.31): `"split_skip_if_fits": true` in the config +(engine flag `--split-skip-if-fits`, with `--layer-split auto`) runs on the first card alone when it holds every +profiled expert plus the context's KV, the draft layer and the reserve, and says so in the log; otherwise the split +stays. On an R9700 32 GB + RX 9070 XT the R9700 holds all of the Coder's experts: with the flag 4K prompts read at +1,776 tok/s instead of 1,244 (split) and decode runs at ~60 tok/s instead of ~51 (16K prompts ~5% slower than split). + The engine flags behind it: `--layer-split K1[,K2..]|auto` and `--split-device D1[,D2..]` (the later stages' devices; default the next visible ones). `--layer-split K --split-device 0` runs both stages on one card sharing everything - the bit-exact check of the hand-off, not a speed mode. diff --git a/serve/server.py b/serve/server.py index e03379e0..fc8a8462 100644 --- a/serve/server.py +++ b/serve/server.py @@ -544,6 +544,9 @@ def engine_args(cfg: dict) -> list[str]: args = list(cfg["args"]) if len(gpu_list(cfg)) > 1 and "--layer-split" not in args: args += ["--layer-split", str(cfg.get("layer_split") or "auto")] + # opt-in: an auto split runs on the first card alone when it holds every profiled expert and the KV + if len(gpu_list(cfg)) > 1 and cfg.get("split_skip_if_fits") and "--split-skip-if-fits" not in args: + args.append("--split-skip-if-fits") return args diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 25c773f3..45f98871 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -360,6 +360,10 @@ struct Options { /// the later stages' devices "D1,D2,.." (default: the next visible GPUs; "0" with one K: both stages on this /// GPU, sharing everything - the bit-exact A/B of the hand-off) std::string split_device; + /// --split-skip-if-fits (opt-in; the server passes it for a config's "split_skip_if_fits"): with + /// --layer-split auto, run on CUDA0 alone when it holds every profiled expert pair plus the whole session (KV), + /// the drafter and the reserve - a split then only adds hand-offs (two RDNA4 cards: 1,384 vs 1,794 tok/s at 4K) + bool split_skip_if_fits = false; /// Plan v0.3 P8: stay resident and take requests on stdin (see the --serve block in main). bool serve = false; /// The vision path: keep a per-cell (t, h, w) rotary position table so --serve can take GENI requests. @@ -1109,6 +1113,7 @@ int main(int argc, char** argv) { else if (a == "--spec-split") o.spec_split = true; else if (a == "--layer-split") o.layer_split = next("--layer-split"); else if (a == "--split-device") o.split_device = next("--split-device"); + else if (a == "--split-skip-if-fits") o.split_skip_if_fits = true; else if (a == "--pcie-mode") o.pcie_mode = next("--pcie-mode"); else if (a == "--serve") o.serve = true; else if (a == "--vision") o.vision = true; @@ -1265,7 +1270,7 @@ int main(int argc, char** argv) { return 2; } } - const bool multi_gpu = !split_devs.empty() && !split_same; + bool multi_gpu = !split_devs.empty() && !split_same; // cleared by --split-skip-if-fits before any stage loads if (o.mmap_experts && !o.shared_expert_arena.empty()) { std::fprintf(stderr, "strata generate: --shared-expert-arena backs the resident arena and cannot be used with --mmap-experts\n"); return 2; @@ -1930,6 +1935,52 @@ int main(int argc, char** argv) { return 1; } + // ---- --split-skip-if-fits: before any later stage loads, does CUDA0 alone hold every profiled pair? What it + // still has to allocate on one GPU is the whole session (the KV of every layer), the drafter and the head + // (kDrafterMib below), the verify windows and the reserve; the prompt path borrows from the cache. If the + // profile's pairs fit in what is left, a split would only add the hand-offs: run on CUDA0 alone. + if (multi_gpu && split_auto && o.split_skip_if_fits) { + std::vector> prof; + int64_t pslots = 0; + std::string perr; + const bool remote = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; + if (remote || o.expert_profile.empty() || + !strata::core::read_expert_profile(o.expert_profile, g.n_layers, g.n_expert, prof, pslots, perr)) { + std::fprintf(stderr, "strata generate: --split-skip-if-fits: %s; the split stays\n", + remote ? "remote expert caches are in use" : perr.empty() ? "no expert profile" : perr.c_str()); + } else { + const auto& lay = strata::kernels::cpu::expert_layout(); + int64_t pairs_bytes = 0; + for (const auto& pr : prof) + pairs_bytes += native_pack ? ((int64_t) lay.blob_bytes(pr.first) + 255) / 256 * 256 : (int64_t) lay.max_blob; + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + const int64_t session = (int64_t) strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers); + const int64_t held_back = session + (((int64_t) o.vram_reserve_mib + 1000 + 96) << 20); // + drafter/head, windows + const int64_t room = (int64_t) fb - held_back; + cudaDeviceProp dp{}; + cudaGetDeviceProperties(&dp, 0); + if (pairs_bytes <= room) { + std::fprintf(stderr, "strata generate: layer split skipped (--split-skip-if-fits): CUDA0 (%s) holds all " + "%zu profiled pairs (%.2f GiB) with the session (%.2f GiB, %lld-token context), " + "the drafter and the reserve: %.2f GiB free, %.2f GiB to spare - one GPU\n", + dp.name, prof.size(), (double) pairs_bytes / 1073741824.0, (double) session / 1073741824.0, + (long long) o.max_context, (double) fb / 1073741824.0, + (double) (room - pairs_bytes) / 1073741824.0); + multi_gpu = false; + split_auto = false; + split_devs.clear(); + split_at.clear(); + o.layer_split.clear(); + } else { + std::fprintf(stderr, "strata generate: --split-skip-if-fits: CUDA0 (%s) would hold only %.2f of the " + "profile's %.2f GiB (%.2f GiB free, %.2f GiB for the session, drafter and " + "reserve): the split stays\n", dp.name, + (double) std::max(room, 0) / 1073741824.0, (double) pairs_bytes / 1073741824.0, + (double) fb / 1073741824.0, (double) held_back / 1073741824.0); + } + } + } // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) std::vector> stages;