diff --git a/CMakeLists.txt b/CMakeLists.txt index dc37363e..aff47134 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,7 +33,7 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) endif() option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) -option(STRATA_ENABLE_HIP "Build the HIP targets for gfx1100 wave32 hardware" OFF) +option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201)" OFF) option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") @@ -248,8 +248,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/platform/direct_file.cpp) target_link_libraries(strata_kernels PUBLIC strata_core strata_artifact) # perf-review D-1: the tensor-core prompt attention vs the FP32 kernel and FP64 (GPU, synthetic, no model); with - # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON - if(STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) + # the tests, or alone with -DSTRATA_PARITY_PROMPT_ATTN=ON. CUDA only: HIP compiles the tensor-core kernel out. + if((STRATA_BUILD_TESTS OR STRATA_PARITY_PROMPT_ATTN) AND STRATA_ENABLE_CUDA) add_executable(qsa_prompt_attn_parity src/kernels/qsa_prompt_attn_parity.cpp) target_include_directories(qsa_prompt_attn_parity PRIVATE ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) target_link_libraries(qsa_prompt_attn_parity PRIVATE strata_kernels CUDA::cudart) diff --git a/README.md b/README.md index c5424d0a..5241dca3 100644 --- a/README.md +++ b/README.md @@ -84,9 +84,9 @@ 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 on Linux** works too (experimental): `./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). +An **AMD Radeon RX 7900 XT / XTX, RX 9070 / 9070 XT or Radeon AI PRO R9700 on Linux** works too (experimental): +`./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). ## Install diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmake index 42f50e11..c22d9463 100644 --- a/cmake/hip_backend.cmake +++ b/cmake/hip_backend.cmake @@ -1,12 +1,34 @@ -# Opt-in HIP configuration. Strata's CUDA-shaped kernels currently target RDNA3 gfx1100 wave32. -# CMake/compiler discovery stays machine-independent; pass CMAKE_HIP_COMPILER when it is not on PATH. +# Opt-in HIP configuration. Strata's CUDA-shaped kernels target wave32 RDNA3 / RDNA4 (64 KiB LDS per workgroup, +# the signed dot4 instruction). CMake/compiler discovery stays machine-independent; pass CMAKE_HIP_COMPILER when it +# is not on PATH. if(NOT DEFINED CMAKE_HIP_ARCHITECTURES OR CMAKE_HIP_ARCHITECTURES STREQUAL "") - set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture") + set(CMAKE_HIP_ARCHITECTURES gfx1100 CACHE STRING "Strata HIP target architecture(s), e.g. gfx1100 or gfx1100;gfx1201") endif() -if(NOT CMAKE_HIP_ARCHITECTURES STREQUAL "gfx1100") - message(FATAL_ERROR - "Strata HIP currently supports only gfx1100 wave32; CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'") +# 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). +set(_strata_hip_validated gfx1100 gfx1201) +set(_strata_hip_unvalidated gfx1101 gfx1102 gfx1200) +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_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}); " + "CMAKE_HIP_ARCHITECTURES is '${CMAKE_HIP_ARCHITECTURES}'") + endif() + list(APPEND STRATA_HIP_ARCH_LIST "${_base}") +endforeach() +list(REMOVE_DUPLICATES STRATA_HIP_ARCH_LIST) +if(NOT STRATA_HIP_ARCH_LIST) + message(FATAL_ERROR "Strata HIP: CMAKE_HIP_ARCHITECTURES is empty") endif() +# The compiled architectures reach the runtime device check (src/core/device.cu) as "gfx1100,gfx1201": a binary +# carried to a card it has no code for stops at startup with a clear message instead of "invalid device function". +string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}") enable_language(HIP) find_package(hip CONFIG REQUIRED) @@ -33,7 +55,7 @@ set(STRATA_HIP_COMPAT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include/strata/hi add_library(strata_hip_runtime INTERFACE) target_include_directories(strata_hip_runtime BEFORE INTERFACE "${STRATA_HIP_COMPAT_INCLUDE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include") -target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1) +target_compile_definitions(strata_hip_runtime INTERFACE STRATA_USE_HIP=1 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"") target_link_libraries(strata_hip_runtime INTERFACE hip::host) foreach(_language IN ITEMS CXX HIP) target_compile_options(strata_hip_runtime INTERFACE @@ -55,4 +77,4 @@ foreach(_source IN ITEMS tests/hip/intrinsics.cpp tests/hip/native_qsa_score.cpp endif() endforeach() -message(STATUS "Strata: HIP enabled, arch ${CMAKE_HIP_ARCHITECTURES}") +message(STATUS "Strata: HIP enabled, arch ${STRATA_HIP_ARCHS}") diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index 0d3cea91..8203c0d6 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -1,20 +1,22 @@ -# Experimental AMD HIP backend (gfx1100) +# Experimental AMD HIP backend (gfx1100, gfx1201) -This is a manual Linux source build for the RX 7900 XTX. 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. +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 +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 -RDNA3's signed integer dot instruction for quantized kernels, and supplies +RDNA3/RDNA4's signed integer dot instruction for quantized kernels, and supplies wave32 shuffle/packed-byte operations. CUDA-only QSA matrix instructions have an ordered FP32 fallback. Prefill supports both dequantization plus hipBLAS GEMM and opt-in HIP ggml MMQ. -An optional, calibrated hipBLASLt path accelerates dense projections on gfx1100. +An optional, calibrated hipBLASLt path accelerates dense projections (per-architecture tables in `tools/hip`). This does not claim bit-identical model answers across backends. See [performance settings and evidence](AMD_HIP_PERFORMANCE.md). ## Install with setup (recommended) -On Linux with an RX 7900 XT / XTX and the kernel's amdgpu driver (no ROCm install needed): +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): ```sh ./setup.sh --backend hip @@ -22,11 +24,17 @@ On Linux with an RX 7900 XT / XTX and the kernel's amdgpu driver (no ROCm instal - **Detection:** setup finds the card through the kernel's KFD topology. Integrated Radeon GPUs are listed as not supported. On a PC without an NVIDIA card Strata can use, `--backend hip` is chosen automatically. -- **ROCm:** installed into `.venv` from AMD's TheRock wheels (~10 GB, no sudo), pinned to the version this backend was - tested with (`STRATA_ROCM_VERSION` / `STRATA_ROCM_INDEX` override it). A system ROCm in `/opt/rocm` (or - `$ROCM_PATH`) with hipcc and hipBLAS is used instead when present. -- **Engine:** compiled on your PC (10-20 minutes, once; again after a `git pull` that changes it). This needs a C++ - compiler and git (`sudo apt install build-essential git`). +- **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). +- **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`). +- **hipBLASLt tuning table:** setup uses `tools/hip/-hipblaslt-.txt` only when it matches both the + 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. The rest of setup is the same as on NVIDIA: the model download, the start script, the server. @@ -46,6 +54,13 @@ 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 +(`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". + If CMake cannot find the HIP compiler, add `-DCMAKE_HIP_COMPILER=/path/to/rocm/llvm/bin/clang++`. On the Fedora-family test host this was `/usr/lib64/rocm/llvm/bin/clang++`. Use the compiler and libraries @@ -101,6 +116,57 @@ sizes itself automatically and leaves 1 GiB of VRAM headroom. The installer supports this backend (see "Install with setup" above). The vision helper and multi-GPU layer splits are NVIDIA-only for now. +## RDNA4 (gfx1201) + +The RX 9070 / 9070 XT and the Radeon AI PRO R9700 run the same kernels as gfx1100: wave32, 64 KiB of LDS per +workgroup, the signed dot4 instruction (`v_dot4_i32_iu8` through `__builtin_amdgcn_sudot4`) and a 100 MHz wall +clock. The first report and patch came from doplxyz (#178). Validated on 2026-09-30 on doplxyz's test machine: +an RX 9070 XT 16 GB and a Radeon AI PRO R9700 32 GB (both gfx1201), a Ryzen 9 3900X (16 threads, no AVX-512), +47 GB RAM, Ubuntu 24.04 in a KVM/VFIO guest. + +- **Build:** complete HIP build with tests (`-DCMAKE_HIP_ARCHITECTURES=gfx1201 -DSTRATA_BUILD_TESTS=ON + -DSTRATA_PREFILL_MMQ=ON`), with the system ROCm 7.14 (hipBLASLt 1.4.1) and with setup's own path: TheRock + 7.10.0a20251120 wheels from `gfx120X-all` (hipBLASLt 1.2.0) and `build_engine_hip`. +- **ctest** (all 45 registered tests, R9700): 42 pass, `hip_prefill_hipblaslt_gemm` skips (no table), and two + fail for reasons outside the GPU: `ple_parity` needs the Q2_0 model fixture, `expert_multi_test` needs an + AVX-512 CPU. `hip_handoff` needed the volatile ring store: on gfx1201 a plain store to mapped pinned memory + stays in the GPU's L2 until the stream is synchronized. +- **Arch check:** a gfx1100-only build stops on the gfx1201 card at startup with the message above (engine and + `strata-device`). +- **End to end** (Coder IQ1_M, setup's arguments: `--expert-cache auto --prefill auto --spec 4 --spec-min-p 0.5`, + MTP, `--kv int8`, `--max-context 32768`; 128 greedy tokens, system ROCm 7.14, no hipBLASLt table). The answers + are coherent and the same on both cards. The live server smoke (`serve/server.py`: web page, models, props, + chat, prefix reuse, streaming, the Anthropic endpoint, a sampled code answer) passed 9/9 on each card. + + | card | expert cache | peak VRAM | 4K prompt | 4K decode | 16K prompt | 16K decode | + |---|---|---|---|---|---|---| + | Radeon AI PRO R9700 32 GB | 12,288 slots, 23.4 GiB | 29.7 GiB | 982 tok/s | 45.5 tok/s | 1,402 tok/s | 48.3 tok/s | + | 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. +- **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. +- **Not validated:** gfx1200 (RX 9060 XT; a community report is #176), both cards in one run (layer split), + images, long contexts beyond 16K, answer-quality benchmarks. + +## Tuning table + +A hipBLASLt table holds solution ids that are valid only for one GPU architecture and one hipBLASLt version, so it +is calibrated on the card with the ROCm the engine runs with. The shipped gfx1100 table's rows are the engine's +dense GEMM shapes; to calibrate them for another card or version (a few minutes): + +```sh +cmake --build build-hip --target tune_hipblaslt +CASES=$(awk 'NR>2 {printf " --case %s,%s,%s,%s,%s", $1, $5, $2, $3, $4}' tools/hip/gfx1100-hipblaslt-100200.txt) +./build-hip/tune_hipblaslt $CASES --tuning-out table.txt +``` + +The file's second line names the architecture and version (`STRATA_HIPBLASLT_TUNING_V1 gfx1201 100401`); save it +as `tools/hip/-hipblaslt-.txt` for setup, or point `STRATA_HIPBLASLT_TUNING` at it. Compare the +prompt speed with and without it before keeping it. + ## Original backend validation (PR #94) The following is historical validation of the original backend, not a fresh diff --git a/include/strata/core/device.hpp b/include/strata/core/device.hpp index 7a27e4f8..8fb93ad6 100644 --- a/include/strata/core/device.hpp +++ b/include/strata/core/device.hpp @@ -26,8 +26,18 @@ struct DeviceInfo { uint64_t free_bytes = 0; int driver_version = 0, runtime_version = 0; int multi_processor_count = 0; + std::string arch; // HIP: gcnArchName without its feature suffix ("gfx1201"); empty on CUDA }; +// HIP builds: whether GPU `ordinal` can run this binary - its architecture must be one the binary was COMPILED +// for (STRATA_HIP_ARCHS, set by cmake/hip_backend.cmake) and it must run wave32. "" when it can (or when there +// is no such device: the caller's own device errors apply), else the reason in a sentence. A binary carried to +// another card would otherwise fail later with "invalid device function". CUDA builds: always "". +std::string gpu_arch_problem(int ordinal); + +// The GPU architectures this binary was compiled for ("gfx1100,gfx1201"); "" on CUDA builds. +const char* compiled_gpu_archs(); + // Throws when there is no CUDA device. The engine targets sm_120 specifically and must say so rather than // run slowly on something else: `CMakeLists.txt` already refuses to COMPILE for another architecture, and // this is the matching check at run time (a binary can be carried to a different machine). diff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hpp index 1ab2462f..b1d7378c 100644 --- a/include/strata/hip_compat/intrinsics.hpp +++ b/include/strata/hip_compat/intrinsics.hpp @@ -1,6 +1,6 @@ #pragma once -// CUDA device intrinsics used by Strata kernels that HIP does not provide on gfx1100. +// CUDA device intrinsics used by Strata kernels that HIP does not provide on RDNA3 / RDNA4 (wave32). // This header is included only from the HIP cuda_runtime compatibility shim. #if defined(__HIPCC__) @@ -15,10 +15,11 @@ __device__ __forceinline__ int signed_byte(uint32_t word, int lane) { // CUDA's signed __dp4a: four signed byte products accumulated modulo 2^32. __device__ __forceinline__ int dp4a(int a, int b, int c) { -#if defined(__gfx1100__) && __has_builtin(__builtin_amdgcn_sudot4) - // RDNA3 exposes the signed/unsigned dot4 form. Mark both packed operands - // signed to preserve CUDA __dp4a semantics; keep the portable path for - // other HIP compilers/targets. +#if (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1200__) || \ + defined(__gfx1201__)) && __has_builtin(__builtin_amdgcn_sudot4) + // RDNA3 and RDNA4 expose the signed/unsigned dot4 form (v_dot4_i32_iu8). Mark + // both packed operands signed to preserve CUDA __dp4a semantics; keep the + // portable path for other HIP compilers/targets. return __builtin_amdgcn_sudot4(true, a, true, b, c, false); #else const uint32_t ua = static_cast(a); diff --git a/setup.py b/setup.py index f7380f45..4cffe188 100644 --- a/setup.py +++ b/setup.py @@ -709,13 +709,22 @@ def cuda_lib_dirs(): # ------------------------------------------------------------------------------------------------ AMD (experimental) -# The RX 7900 XT / XTX (gfx1100) 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 in /opt/rocm is used when it -# has hipcc and hipBLAS) and the engine is compiled here. One GPU, no images yet. -ROCM_INDEX = os.environ.get("STRATA_ROCM_INDEX", "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/") +# 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. +ROCM_INDEXES = {"gfx1100": "https://rocm.nightlies.amd.com/v2/gfx110X-dgpu/", # TheRock's wheels per GPU family + "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 -AMD_ARCHS = ("gfx1100",) -AMD_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)"} # when sysfs has no product name +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_NAMES = {"gfx1100": "AMD Radeon RX 7900 series (gfx1100)", # when sysfs has no product name + "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)" + + +def rocm_index(arch): + return os.environ.get("STRATA_ROCM_INDEX") or ROCM_INDEXES[arch] def amd_gpus(): @@ -755,35 +764,88 @@ def amd_gpus(): def amd_problem(g): if g["arch"] not in AMD_ARCHS: - return (f"not supported - Strata's AMD backend runs on the RX 7900 XT / XTX ({', '.join(AMD_ARCHS)}) only, " - f"this is {g['arch']}") + return f"not supported - Strata's AMD backend runs on {AMD_CARDS} only, this is {g['arch']}" return None -def rocm_root(): - """ROCm for compiling and running the HIP engine: (root, library folders). A system ROCm with hipcc and hipBLAS, - else AMD's TheRock wheels (ROCM_VERSION, from ROCM_INDEX) installed into .venv.""" +def rocm_version(root): + """(major, minor) of a ROCm install, from rocm-core's header; None when it has none.""" + try: + text = (Path(root) / "include" / "rocm-core" / "rocm_version.h").read_text() + return tuple(int(re.search(rf"#define\s+ROCM_VERSION_{k}\s+(\d+)", text).group(1)) for k in ("MAJOR", "MINOR")) + except (OSError, AttributeError, ValueError): + 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.""" sysroot = Path(os.environ.get("ROCM_PATH") or "/opt/rocm") if (sysroot / "bin" / "hipcc").exists() and list((sysroot / "lib").glob("libhipblas.so*")): - return sysroot, [str(sysroot / "lib")] + ver = rocm_version(sysroot) + if ver is None or ver >= ROCM_SYSTEM_MIN: + 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) stamp = Path(sys.prefix) / ".strata-rocm.json" - if not stamp.exists() or json.loads(stamp.read_text()).get("version") != ROCM_VERSION: + have = json.loads(stamp.read_text()) if stamp.exists() else {} + if have.get("version") != ROCM_VERSION or have.get("index") != index: say(f" Installing ROCm {ROCM_VERSION} for AMD GPUs into .venv (AMD's TheRock wheels, ~10 GB, no sudo) ...") - run([sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", - ROCM_INDEX, f"rocm[libraries,devel]=={ROCM_VERSION}"]) - stamp.write_text(json.dumps({"version": ROCM_VERSION, "index": ROCM_INDEX})) + pip = [sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "--index-url", index] + if have.get("version") == ROCM_VERSION: # the same version for another GPU family: its own libraries + run(pip + ["--force-reinstall", "--no-deps", f"rocm=={ROCM_VERSION}"]) + run(pip + [f"rocm[libraries,devel]=={ROCM_VERSION}"]) + stamp.write_text(json.dumps({"version": ROCM_VERSION, "index": index})) sdk = Path(sys.executable).parent / "rocm-sdk" root = Path(out([str(sdk), "path", "--root"]).strip()) if not (root / "llvm" / "bin" / "clang++").exists(): fail(f"ROCm was installed but its compiler is missing ({root})", f"remove {stamp} and run this again; or install ROCm 7 system-wide") + # the card family's libraries only (gfx120X-all -> _rocm_sdk_libraries_gfx120X_all): another family's + # libhipblaslt.so first on the path would have no kernels for this card + family = "_rocm_sdk_libraries_" + index.rstrip("/").rsplit("/", 1)[-1].replace("-", "_") dirs = [str(root / "lib")] for sp in {Path(p) for p in sys.path if p.endswith("site-packages")}: - dirs += [str(d / "lib") for d in sorted(sp.glob("_rocm_sdk_libraries_*")) if (d / "lib").is_dir()] + libs = sorted(sp.glob("_rocm_sdk_libraries_*")) + libs = [d for d in libs if d.name.lower() == family.lower()] or libs + dirs += [str(d / "lib") for d in libs if (d / "lib").is_dir()] ok(f"ROCm: {root}") return root, list(dict.fromkeys(dirs)) +def hipblaslt_version(lib_dirs): + """The installed hipBLASLt's version as the engine reads it (hipblasLtGetVersion: 1.4.1 -> 100401), from the + header of the ROCm whose libraries the engine loads; None when not found.""" + for d in lib_dirs: + try: + text = (Path(d).parent / "include" / "hipblaslt" / "hipblaslt-version.h").read_text() + v = [int(re.search(rf"#define\s+HIPBLASLT_VERSION_{k}\s+(\d+)", text).group(1)) + for k in ("MAJOR", "MINOR", "PATCH")] + except (OSError, AttributeError, ValueError): + continue + return v[0] * 100000 + v[1] * 100 + v[2] + return None + + +def hipblaslt_table(arch, lib_dirs): + """tools/hip/-hipblaslt-.txt for this card AND the installed hipBLASLt, else None: its solution + ids are valid only for that pair (the engine refuses any other table and uses plain hipBLAS).""" + ver = hipblaslt_version(lib_dirs) + table = ROOT / "tools" / "hip" / f"{arch}-hipblaslt-{ver}.txt" + if ver is not None and table.exists(): + head = table.read_text().split("\n", 2)[:2] + if f"STRATA_HIPBLASLT_TUNING_V1 {arch} {ver}" in (h.strip() for h in head): + ok(f"hipBLASLt tuning table: {table.name} (faster prompts)") + return table + have = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{arch}-hipblaslt-*.txt")) + warn(f"no hipBLASLt tuning table for {arch} with hipBLASLt {ver or '(version unknown)'}" + + (f" (have: {', '.join(have)})" if have else "") + + ": the prompt's dense matrix products use plain hipBLAS (tools/hip/tune_hipblaslt makes a table: " + "docs/AMD_HIP.md, Tuning table)") + return None + + 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`).""" eng = ROOT / "engine" @@ -791,13 +853,13 @@ def build_engine_hip(gpu, llama) -> Path: 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: + if meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and gpu["arch"] in meta.get("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() + root, dirs = rocm_root(gpu["arch"]) 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") @@ -806,7 +868,7 @@ 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() + 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) ...") cmake_build(ROOT, ROOT / "build-hip", "strata", ["-DSTRATA_ENABLE_HIP=ON", "-DSTRATA_ENABLE_CUDA=OFF", "-DSTRATA_BUILD_TESTS=OFF", @@ -920,7 +982,8 @@ def update_installed_engine(url_base) -> None: if meta.get("backend") == "hip": # AMD: compiled here, again when its source changed if meta.get("src") != source_hash(ENGINE_SOURCES): try: - g = next((x for x in amd_gpus() if amd_problem(x) is None), None) + usable = [x for x in amd_gpus() if amd_problem(x) is 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()) @@ -1704,7 +1767,7 @@ 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 on Linux (experimental; chosen by itself " + 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)") ap.add_argument("--skip-build", action="store_true", help=argparse.SUPPRESS) a = ap.parse_args() @@ -1802,7 +1865,7 @@ def main() -> int: say(f" GPU {g['index']}: {g['name']}, {g['vram_gb']:.0f} GB VRAM - " + (amd_problem(g) or "can be used")) usable = [g for g in amd if amd_problem(g) is None] if not usable: - fail("no AMD GPU Strata can use", "the AMD backend runs on the RX 7900 XT / XTX (gfx1100) on Linux") + 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: @@ -1819,7 +1882,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: --backend hip" if amd else "")) + + ("; an AMD RX 7900 XT/XTX or RX 9070 / AI PRO R9700: --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 @@ -2184,10 +2247,11 @@ def main() -> int: if hip: cfg["backend"] = "hip" # the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% - # prompt speed on the 7900 XTX); the engine refuses a table made for another hipBLASLt version and falls back - tables = sorted((ROOT / "tools" / "hip").glob(f"{gpu['arch']}-hipblaslt-*.txt")) - if tables: - cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(tables[-1])} + # prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the + # engine refuses any other one and falls back to plain hipBLAS) + table = hipblaslt_table(gpu["arch"], lib_dirs) + if table: + cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)} if resident: # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0" if gpu["count"] > 1 or a.gpu is not None: diff --git a/src/core/device.cu b/src/core/device.cu index 64a83735..c1dfbb1c 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -24,14 +24,80 @@ __global__ void poison_kernel(float* p, uint64_t n_floats) { if (i < n_floats) p[i] = __int_as_float(0x7fc00000); } +#if defined(STRATA_USE_HIP) +#if !defined(STRATA_HIP_ARCHS) +#error "STRATA_HIP_ARCHS (the compiled HIP architectures) is set by cmake/hip_backend.cmake" +#endif +// "gfx1201:sramecc-:xnack-" -> "gfx1201" +std::string base_arch(const char* gcn_arch_name) { + std::string arch(gcn_arch_name); + const size_t colon = arch.find(':'); + if (colon != std::string::npos) arch.resize(colon); + return arch; +} + +bool compiled_for(const std::string& arch) { + const std::string list = STRATA_HIP_ARCHS; + size_t a = 0; + while (a <= list.size()) { + size_t b = list.find(',', a); + if (b == std::string::npos) b = list.size(); + if (!arch.empty() && list.compare(a, b - a, arch) == 0 && b - a == arch.size()) return true; + a = b + 1; + } + return false; +} + +std::string arch_problem(const cudaDeviceProp& p, int ordinal) { + const std::string arch = base_arch(p.gcnArchName); + const std::string card = "GPU " + std::to_string(ordinal) + " (" + p.name + ", " + arch + ")"; + if (!compiled_for(arch)) { + return card + " is not an architecture this Strata engine was compiled for (" + STRATA_HIP_ARCHS + + "); compile it for this card (./setup.sh --backend hip, or -DCMAKE_HIP_ARCHITECTURES=" + arch + + ", docs/AMD_HIP.md) or choose another GPU with HIP_VISIBLE_DEVICES"; + } + if (p.warpSize != 32) { + return card + " runs wave" + std::to_string(p.warpSize) + "; Strata's HIP kernels need wave32"; + } + return ""; +} +#endif + } // namespace +const char* compiled_gpu_archs() { +#if defined(STRATA_USE_HIP) + return STRATA_HIP_ARCHS; +#else + return ""; +#endif +} + +std::string gpu_arch_problem(int ordinal) { +#if defined(STRATA_USE_HIP) + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess || ordinal < 0 || ordinal >= count) { + cudaGetLastError(); + return ""; + } + cudaDeviceProp p{}; + if (cudaGetDeviceProperties(&p, ordinal) != cudaSuccess) { + cudaGetLastError(); + return ""; + } + return arch_problem(p, ordinal); +#else + (void) ordinal; + return ""; +#endif +} + DeviceInfo device_info(int ordinal) { int count = 0; check(cudaGetDeviceCount(&count), "cudaGetDeviceCount"); if (count == 0) { #if defined(STRATA_USE_HIP) - throw CudaError("no HIP device is present; this backend targets gfx1100 wave32", -1); + throw CudaError(std::string("no HIP device is present; this engine was compiled for ") + STRATA_HIP_ARCHS, -1); #else throw CudaError("no CUDA device is present; Strata needs an NVIDIA GPU (RTX 20 series or newer)", -1); #endif @@ -64,11 +130,10 @@ DeviceInfo device_info(int ordinal) { // fp32-FMA fallback below sm_80, the tensor-core prompt kernels refuse and fall back). Compiling for a // supported arch is enforced by CMake; RUNNING on an older card is caught here, because a binary can be carried // to a machine with an older card and would otherwise silently take whatever path the driver chose. The HIP - // backend is validated on gfx1100 (wave32) only. + // backend checks the card against the architectures the binary was compiled for (and wave32). #if defined(STRATA_USE_HIP) - if (std::strncmp(p.gcnArchName, "gfx1100", 7) != 0 || p.warpSize != 32) { - throw CudaError("HIP backend requires validated gfx1100 wave32 hardware", -1); - } + d.arch = base_arch(p.gcnArchName); + if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1); #else if (d.cc_major * 10 + d.cc_minor < 75) { throw CudaError("device " + d.name + " reports compute capability " + std::to_string(d.cc_major) + diff --git a/src/core/device_main.cpp b/src/core/device_main.cpp index e97cefca..524e7b18 100644 --- a/src/core/device_main.cpp +++ b/src/core/device_main.cpp @@ -34,7 +34,8 @@ int main(int argc, char** argv) { const strata::core::DeviceInfo d = strata::core::device_info(0); std::printf("device %d: %s\n", d.ordinal, d.name.c_str()); #if defined(STRATA_USE_HIP) - std::printf(" HIP target gfx1100 wave32\n"); + std::printf(" HIP arch %s wave32 (compiled for %s)\n", d.arch.c_str(), + strata::core::compiled_gpu_archs()); #else std::printf(" compute capability %d.%d (sm_%d%d)\n", d.cc_major, d.cc_minor, d.cc_major, d.cc_minor); #endif diff --git a/src/kernels/cuda/elementwise.cu b/src/kernels/cuda/elementwise.cu index 69eb97e2..22d022e9 100644 --- a/src/kernels/cuda/elementwise.cu +++ b/src/kernels/cuda/elementwise.cu @@ -202,9 +202,13 @@ void silu_inplace(float* x, int64_t n, void* stream) { /// the write was not ordered into host-visible memory, so no amount of reading it would show it, and the driver /// call was flushing the whole pipeline enough to make it appear. A 10-22 us driver call per iteration is a /// very expensive substitute for one fence instruction. +/// +/// **THE STORE IS VOLATILE**, like `doorbell_publish_kernel`'s. On RDNA4 (gfx1201) a plain store to mapped pinned +/// memory stays in the GPU's L2 until the stream is synchronized - the host never saw the ring (tests/hip/handoff: +/// 0 of 100 rings seen without a sync; volatile, a system-scope atomic store or a fence after the store: 100 of 100). __global__ void doorbell_ring_kernel(uint32_t* seq) { __threadfence_system(); - *seq = *seq + 1u; + *(volatile uint32_t*) seq = *(volatile uint32_t*) seq + 1u; } __global__ void doorbell_wait_kernel(const volatile uint32_t* flag, const volatile uint32_t* seq) { diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index 6f1228bb..b0e26ff8 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -180,7 +180,7 @@ __global__ void __launch_bounds__(THREADS) gr_norm_multi_kernel(GrMulti m) { } #if defined(__HIPCC__) -constexpr int TILE = 1280; // eight-token tile fits gfx1100's 64 KiB LDS limit +constexpr int TILE = 1280; // eight-token tile fits RDNA3/RDNA4's 64 KiB LDS limit #else constexpr int TILE = 2560; // xn floats per token staged at a time: 320 chunks of 8, 10 per lane #endif diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 21d23440..69550156 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -546,7 +546,7 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) { unsigned long long t; #if defined(__HIPCC__) - t = wall_clock64() * 10ull; // gfx11: a constant 100 MHz counter, in ns + t = wall_clock64() * 10ull; // gfx11 / gfx12: a constant 100 MHz counter, in ns #else asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); #endif diff --git a/src/program/generate.cpp b/src/program/generate.cpp index faf2c0a1..75e874b0 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -14,6 +14,7 @@ // AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose // (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. +#include "strata/core/device.hpp" #include "strata/core/expert_cache.hpp" #include "strata/core/conversation_snapshot.hpp" #include "strata/core/conversation_memory.hpp" @@ -1293,6 +1294,22 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: layer split across %zu GPUs: CUDA0, then CUDA%s (split %s)\n", split_devs.size() + 1, devs.c_str(), o.layer_split.c_str()); } +#if defined(STRATA_USE_HIP) + { + // every GPU this run uses must be an architecture the binary has code for (a gfx1100 build on a gfx1201 + // card would otherwise fail later with "invalid device function") + std::vector used{0}; + if (multi_gpu) used.insert(used.end(), split_devs.begin(), split_devs.end()); + for (int r = 0; r < 3; ++r) + if (o.expert_cache_remote[(size_t) r] > 0) used.push_back(remote_dev[r]); + for (const int d : used) { + if (const std::string why = strata::core::gpu_arch_problem(d); !why.empty()) { + std::fprintf(stderr, "strata generate: %s\n", why.c_str()); + return 1; + } + } + } +#endif if (o.prefill_auto && (o.no_prefill_borrow || o.expert_profile.empty())) { o.prefill_auto = false; // nothing to lend from: the buffers are reserved for the session, so keep them small o.prefill_chunk = 2048;