Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
hip: add experimental gfx1012 support and legacy BLAS compatibility
Davide3e30eb131ec
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 1fe793b7e..a8b0716b3 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -45,7 +45,7 @@ if(STRATA_HIP_GFX906)endif()set(STRATA_ENABLE_CUDA ON CACHE BOOL "" FORCE)endif()-option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1030 unvalidated)" OFF)+option(STRATA_ENABLE_HIP "Build the HIP targets for wave32 AMD GPUs (gfx1100, gfx1201; gfx1012/gfx1030 unvalidated)" OFF)option(STRATA_PREFILL_MMQ "Build the optional GGML MMQ prefill path for HIP" OFF)# CUDA: MMQ prompt kernels for Q4_K / Q5_K / Q5_1 (Unsloth's UD-Q4_K_XL experts). Off by default: the engine loads# every kernel when it starts (CUDA_MODULE_LOADING=EAGER), so these took ~5 MB of VRAM - 1-3 expert slots - from every@@ -157,7 +157,7 @@ elseif(STRATA_ENABLE_CUDA)set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES})elseif(STRATA_ENABLE_HIP)set(_strata_gpu_runtime_target strata_hip_runtime)- set(_strata_gpu_blas_target roc::hipblas)+ set(_strata_gpu_blas_target ${STRATA_HIP_BLAS_TARGETS})set(_strata_gpu_include_directories ${STRATA_HIP_COMPAT_INCLUDE_DIR})endif()@@ -475,6 +475,10 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)if(STRATA_ENABLE_HIP)enable_testing()set(_strata_hip_tests)+ add_executable(hip_prefill_gemm tests/hip/prefill_gemm.cpp)+ target_link_libraries(hip_prefill_gemm PRIVATE strata_prefill strata_hip_runtime)+ add_test(NAME hip_prefill_gemm COMMAND hip_prefill_gemm)+ list(APPEND _strata_hip_tests hip_prefill_gemm)add_executable(hip_expert_cache_staging tests/hip/expert_cache_staging.cpp)target_link_libraries(hip_expert_cache_staging PRIVATE strata_engine)add_test(NAME hip_expert_cache_staging COMMAND hip_expert_cache_staging)diff --git a/cmake/hip_backend.cmake b/cmake/hip_backend.cmakeindex 2e629e60a..d59bba9a8 100644--- a/cmake/hip_backend.cmake+++ b/cmake/hip_backend.cmake@@ -11,7 +11,7 @@ endif()# report ran it (#311), the maintainers have not.set(_strata_hip_validated gfx1100 gfx1201)set(_strata_hip_community gfx1101 gfx1200)-set(_strata_hip_unvalidated gfx1102 gfx1030 gfx1031)+set(_strata_hip_unvalidated gfx1012 gfx1102 gfx1030 gfx1031)# CMake hands HIP a ';' list, but a -DCMAKE_HIP_ARCHITECTURES typed by hand (or ROCm's own Windows tooling) may use# spaces, which foreach(IN LISTS) would otherwise treat as one element.string(REPLACE " " ";" _strata_hip_norm "${CMAKE_HIP_ARCHITECTURES}")@@ -44,6 +44,13 @@ string(REPLACE ";" "," STRATA_HIP_ARCHS "${STRATA_HIP_ARCH_LIST}")enable_language(HIP)find_package(hip CONFIG REQUIRED)find_package(hipblas CONFIG REQUIRED)+# Older distro hipBLAS has no workspace API. The compatibility shim uses+# rocBLAS directly for that version; newer hipBLAS keeps its existing path.+set(STRATA_HIP_BLAS_TARGETS roc::hipblas)+if(hipblas_VERSION VERSION_LESS "1.0")+ find_package(rocblas CONFIG REQUIRED)+ list(APPEND STRATA_HIP_BLAS_TARGETS roc::rocblas)+endif()find_package(hipblaslt CONFIG QUIET)if(NOT TARGET hip::host)@@ -67,6 +74,10 @@ 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 "STRATA_HIP_ARCHS=\"${STRATA_HIP_ARCHS}\"")+option(STRATA_GFX1012_PORTABLE_DOT "Use the portable signed-byte dot control on gfx1012" OFF)+if(STRATA_GFX1012_PORTABLE_DOT)+ target_compile_definitions(strata_hip_runtime INTERFACE STRATA_GFX1012_PORTABLE_DOT=1)+endif()target_link_libraries(strata_hip_runtime INTERFACE hip::host)# The shim renames the CUDA runtime to HIP, force-included into every host and device source. On Windows the host# compiler is ROCm's clang++ too (tools/hip/build_windows.bat: CMake refuses to mix cl.exe with Clang HIP), which takesdiff --git a/include/strata/hip_compat/cublas_v2.h b/include/strata/hip_compat/cublas_v2.hindex f162474bb..879447968 100644--- a/include/strata/hip_compat/cublas_v2.h+++ b/include/strata/hip_compat/cublas_v2.h@@ -1,5 +1,45 @@#pragma once#include <hipblas/hipblas.h>+#include <hipblas/hipblas-version.h>++#if hipblasVersionMajor == 0+// Ubuntu's hipBLAS 0.54 has no workspace API or compute-type enum. Use its+// underlying rocBLAS API directly, including ownership of the real handle,+// so the engine's explicit workspace contract is preserved.+#include <rocblas/rocblas.h>+#define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r+#define CUBLAS_DEFAULT_MATH 0+#define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard+#define CUBLAS_OP_N rocblas_operation_none+#define CUBLAS_OP_T rocblas_operation_transpose+#define CUBLAS_STATUS_SUCCESS rocblas_status_success+#define CUDA_R_16BF rocblas_datatype_bf16_r+#define CUDA_R_16F rocblas_datatype_f16_r+#define CUDA_R_32F rocblas_datatype_f32_r+#define cublasCreate rocblas_create_handle+#define cublasDestroy rocblas_destroy_handle+#define cublasHandle_t rocblas_handle+#define cublasSetStream rocblas_set_stream+#define cublasSetWorkspace rocblas_set_workspace+#define cublasStatus_t rocblas_status++inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) {+ // This API has only its default arithmetic; GEMM below explicitly selects+ // FP32 accumulation. Reject any request for a different math mode.+ if (!h) return rocblas_status_invalid_handle;+ return mode == CUBLAS_DEFAULT_MATH ? rocblas_status_success : rocblas_status_invalid_value;+}+inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a,+ rocblas_operation trans_b, int m, int n, int k, const void* alpha,+ const void* a, rocblas_datatype a_type, int lda,+ const void* b, rocblas_datatype b_type, int ldb, const void* beta,+ void* c, rocblas_datatype c_type, int ldc,+ rocblas_datatype compute_type, rocblas_gemm_algo algo) {+ return rocblas_gemm_ex(h, trans_a, trans_b, m, n, k, alpha,+ a, a_type, lda, b, b_type, ldb, beta, c, c_type, ldc,+ c, c_type, ldc, compute_type, algo, 0, 0);+}+#else#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT@@ -17,3 +57,4 @@#define cublasSetStream hipblasSetStream#define cublasSetWorkspace hipblasSetWorkspace#define cublasStatus_t hipblasStatus_t+#endifdiff --git a/include/strata/hip_compat/cuda_runtime.h b/include/strata/hip_compat/cuda_runtime.hindex ccf9a9132..2359da983 100644--- a/include/strata/hip_compat/cuda_runtime.h+++ b/include/strata/hip_compat/cuda_runtime.h@@ -10,6 +10,7 @@#endif#endif#include <hip/hip_runtime.h>+#include <hip/hip_version.h>// Do not let HIP's legacy macro corrupt libstdc++ attribute names.#ifdef __noinline__#undef __noinline__@@ -39,7 +40,11 @@#define cudaEventSynchronize hipEventSynchronize#define cudaEvent_t hipEvent_t#define cudaFree hipFree+#if HIP_VERSION_MAJOR < 7+#define cudaFreeHost hipHostFree+#else#define cudaFreeHost hipFreeHost+#endif#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize#define cudaGetDevice hipGetDevice#define cudaGetDeviceCount hipGetDeviceCount@@ -54,9 +59,15 @@#define cudaGraphUpload hipGraphUpload#define cudaGraph_t hipGraph_t#define cudaHostAlloc hipHostMalloc+#if HIP_VERSION_MAJOR < 7+#define cudaHostAllocDefault hipHostMallocDefault+#define cudaHostAllocMapped hipHostMallocMapped+#define cudaHostAllocPortable hipHostMallocPortable+#else#define cudaHostAllocDefault hipHostAllocDefault#define cudaHostAllocMapped hipHostAllocMapped#define cudaHostAllocPortable hipHostAllocPortable+#endif#define cudaHostGetDevicePointer hipHostGetDevicePointer#define cudaHostRegister hipHostRegister#define cudaHostRegisterMapped hipHostRegisterMappeddiff --git a/include/strata/hip_compat/intrinsics.hpp b/include/strata/hip_compat/intrinsics.hppindex a789e38c9..ef5079cdb 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 RDNA2 / RDNA3 / RDNA4 (wave32).+// CUDA device intrinsics used by Strata kernels on supported wave32 HIP targets.// This header is included only from the HIP cuda_runtime compatibility shim.#if defined(__HIPCC__)@@ -25,6 +25,21 @@ __device__ __forceinline__ int dp4a(int a, int b, int c) {// RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same// signed x signed byte products accumulated modulo 2^32, no clamp.return __builtin_amdgcn_sdot4(a, b, c, false);+#elif defined(__gfx1012__) && !defined(STRATA_GFX1012_PORTABLE_DOT)+ // RDNA1 has no native signed dot4. SDWA selects and sign-extends byte+ // operands directly, avoiding separate shift/mask/sign-extension work.+ // Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see+ // third_party/ggml/LICENSE), same modulo-2^32 accumulation contract.+ int lo, hi;+ asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n"+ "v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n"+ "v_add3_u32 %0, %1, %2, %0\n"+ "v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n"+ "v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n"+ "v_add3_u32 %0, %1, %2, %0\n"+ // c changes before the high-byte reads; it must not alias a or b.+ : "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b));+ return c;#elseconst uint32_t ua = static_cast<uint32_t>(a);const uint32_t ub = static_cast<uint32_t>(b);@@ -84,6 +99,15 @@ __device__ __forceinline__ void require_full_wave_mask(uint32_t mask) {if (mask != 0xffffffffu) __builtin_trap();}+// Older HIP has no __syncwarp. A wave barrier alone does not order memory.+// Release/acquire fences cover the shared-memory exchange used by attention.+__device__ __forceinline__ void syncwarp(uint32_t mask = 0xffffffffu) {+ require_full_wave_mask(mask);+ __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");+ __builtin_amdgcn_wave_barrier();+ __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");+}+template <typename T>__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) {require_full_wave_mask(mask);@@ -125,6 +149,7 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) {#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__))#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__))#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate)))+#define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__))// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a// backoff hint, so use its smallest portable delay independently of CUDA cycle counts.#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1)diff --git a/include/strata/hip_compat/math_constants.h b/include/strata/hip_compat/math_constants.hnew file mode 100644index 000000000..50a086250--- /dev/null+++ b/include/strata/hip_compat/math_constants.h@@ -0,0 +1,4 @@+#pragma once+// CUDA spelling used by the attention kernels; included only in HIP builds.+#include <hip/hip_math_constants.h>+#define CUDART_INF_F HIP_INF_Fdiff --git a/tests/hip/intrinsics.cpp b/tests/hip/intrinsics.cppindex ff2b93e39..a0c7ed49d 100644--- a/tests/hip/intrinsics.cpp+++ b/tests/hip/intrinsics.cpp@@ -18,7 +18,7 @@namespace {constexpr int kLanes = 32;-constexpr int kIntegerResults = 7;+constexpr int kIntegerResults = 10;__global__ void intrinsic_probe(int* integer_results, float* float_shuffle, double* double_shuffle,unsigned* ballot, const uint32_t* dot_inputs) {@@ -37,6 +37,20 @@ __global__ void intrinsic_probe(int* integer_results, float* float_shuffle, doub__dp4a(static_cast<int>(dot_inputs[lane * 2]), static_cast<int>(dot_inputs[lane * 2 + 1]),0x7fffffff - lane);+ __shared__ int exchanged[kLanes];+ int sum = 0;+ for (int iteration = 0; iteration < 64; ++iteration) {+ exchanged[lane] = static_cast<int>(dot_inputs[lane * 2] & 255u) + iteration;+ __syncwarp();+ sum += exchanged[lane ^ 1];+ __syncwarp();+ }+ integer_results[lane * kIntegerResults + 7] = sum;+ const int input_a = static_cast<int>(dot_inputs[lane * 2]);+ const int input_b = static_cast<int>(dot_inputs[lane * 2 + 1]);+ integer_results[lane * kIntegerResults + 8] = __dp4a(input_a, input_b, input_a);+ integer_results[lane * kIntegerResults + 9] = __dp4a(input_a, input_b, input_b);+float_shuffle[lane * 4 + 0] = __shfl_xor_sync(mask, static_cast<float>(lane), 1);float_shuffle[lane * 4 + 1] = static_cast<float>(__shfl_down_sync(mask, lane, 4, 8));float_shuffle[lane * 4 + 2] = static_cast<float>(__shfl_up_sync(mask, lane, 1));@@ -153,7 +167,7 @@ int main() {CHECK(hipMemcpy(&ballot, device_ballot, sizeof(ballot), hipMemcpyDeviceToHost));constexpr uint32_t a = 0x80ff017fu, b = 0x0203fe81u;- const uint32_t expected_integer[kIntegerResults - 1] = {+ const uint32_t expected_integer[6] = {static_cast<uint32_t>(dp4a_reference(a, b, 7)),static_cast<uint32_t>(dp4a_reference(0x7f7f7f7fu, 0x7f7f7f7fu, std::numeric_limits<int>::max())),byte_sub_reference(0x00ff0102u, 0x01010103u),@@ -163,11 +177,17 @@ int main() {};bool ok = ballot == 0x55555555u;for (int lane = 0; lane < kLanes; ++lane) {- for (int i = 0; i < kIntegerResults - 1; ++i)+ for (int i = 0; i < 6; ++i)ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + i]) == expected_integer[i];- ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + kIntegerResults - 1]) ==+ ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + 6]) ==static_cast<uint32_t>(dp4a_reference(dot_inputs[lane * 2], dot_inputs[lane * 2 + 1],0x7fffffff - lane));+ ok = ok && integers[lane * kIntegerResults + 7] ==+ 64 * static_cast<int>(dot_inputs[(lane ^ 1) * 2] & 255u) + 2016;+ for (int alias = 0; alias < 2; ++alias)+ ok = ok && static_cast<uint32_t>(integers[lane * kIntegerResults + 8 + alias]) ==+ static_cast<uint32_t>(dp4a_reference(dot_inputs[lane * 2], dot_inputs[lane * 2 + 1],+ static_cast<int>(dot_inputs[lane * 2 + alias])));ok = ok && float_shuffle[lane * 4 + 0] == static_cast<float>(lane ^ 1);const int down = lane % 8 < 4 ? lane + 4 : lane;ok = ok && float_shuffle[lane * 4 + 1] == static_cast<float>(down);@@ -211,6 +231,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, byte permute, 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, shared-memory exchange, ballot and sleep");return 0;}diff --git a/tests/hip/prefill_gemm.cpp b/tests/hip/prefill_gemm.cppnew file mode 100644index 000000000..1536c89eb--- /dev/null+++ b/tests/hip/prefill_gemm.cpp@@ -0,0 +1,93 @@+// BF16/F16 prefill through the actual engine GEMM path against a CPU reference.+#include <hip/hip_runtime.h>+#include <hip/hip_bfloat16.h>+#include <hip/hip_fp16.h>+#include "strata/prefill/gemm.hpp"+#include <algorithm>+#include <cmath>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <random>+#include <vector>++#define CHECK(call) do { const auto e = (call); if (e != hipSuccess) { \+ std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(e)); std::exit(2); } } while (0)++struct Buffer {+ void* p = nullptr;+ explicit Buffer(size_t bytes) { CHECK(hipMalloc(&p, bytes)); }+ ~Buffer() { if (p) (void) hipFree(p); }+};++bool run(strata::prefill::Gemm& gemm, hipStream_t stream, bool bf16,+ int t, int n, int k, int ldy, float beta) {+ std::mt19937 rng(51012 + t + n);+ std::uniform_real_distribution<float> dist(-0.25f, 0.25f);+ std::vector<uint16_t> x((size_t)t*k), w((size_t)n*k);+ std::vector<float> xf(x.size()), wf(w.size());+ auto fill = [&](auto& bits, auto& values) {+ for (size_t i = 0; i < bits.size(); ++i) {+ if (bf16) {+ const hip_bfloat16 v(dist(rng));+ bits[i] = v.data;+ const uint32_t wide = static_cast<uint32_t>(v.data) << 16;+ std::memcpy(&values[i], &wide, 4);+ } else {+ const __half v = __float2half_rn(dist(rng));+ std::memcpy(&bits[i], &v, 2);+ values[i] = __half2float(v);+ }+ }+ };+ fill(x, xf); fill(w, wf);+ constexpr int offset = 5;+ std::vector<float> initial(offset + (size_t)t*ldy + 8, -777.25f);+ for (int r = 0; r < t; ++r) for (int c = 0; c < n; ++c)+ initial[offset + (size_t)r*ldy + c] = (r+c)%17 * 0.03125f;+ Buffer dx(x.size()*2), dw(w.size()*2), dy(initial.size()*4);+ CHECK(hipMemcpyAsync(dx.p,x.data(),x.size()*2,hipMemcpyHostToDevice,stream));+ CHECK(hipMemcpyAsync(dw.p,w.data(),w.size()*2,hipMemcpyHostToDevice,stream));+ CHECK(hipMemcpyAsync(dy.p,initial.data(),initial.size()*4,hipMemcpyHostToDevice,stream));+ if (bf16) gemm.bf16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);+ else gemm.f16((const uint16_t*)dx.p,(const uint16_t*)dw.p,(float*)dy.p+offset,t,n,k,ldy,beta);+ CHECK(hipStreamSynchronize(stream));+ std::vector<float> got(initial.size());+ CHECK(hipMemcpy(got.data(),dy.p,got.size()*4,hipMemcpyDeviceToHost));+ std::vector<bool> active(got.size());+ double diff2=0, ref2=0, maximum=0;+ bool ok=true;+ for (int r=0;r<t;++r) for (int c=0;c<n;++c) {+ const size_t j=offset+(size_t)r*ldy+c;+ active[j]=true;+ double ref=beta*initial[j];+ for (int i=0;i<k;++i) ref+=(double)xf[(size_t)r*k+i]*wf[(size_t)c*k+i];+ const double d=(double)got[j]-ref;+ ok=ok && std::isfinite(got[j]);+ diff2+=d*d; ref2+=ref*ref; maximum=std::max(maximum,std::abs(d));+ }+ for (size_t j=0;j<got.size();++j) if (!active[j]) ok=ok && got[j]==initial[j];+ const double rel=std::sqrt(diff2/std::max(ref2,1e-300));+ ok=ok && rel<1e-4 && maximum<5e-3;+ std::printf("%s %s T=%d N=%d K=%d ldy=%d beta=%.1f rel_l2=%.3g max_abs=%.3g\n",+ ok?"PASS":"FAIL",bf16?"BF16":"F16",t,n,k,ldy,beta,rel,maximum);+ return ok;+}++int main() {+ setvbuf(stdout,nullptr,_IONBF,0);+ hipStream_t stream;+ CHECK(hipStreamCreateWithFlags(&stream,hipStreamNonBlocking));+ bool ok=true;+ {+ strata::prefill::Gemm gemm;+ std::string error;+ if (!gemm.init(stream,0,error)) { std::fprintf(stderr,"%s\n",error.c_str()); return 2; }+ ok=run(gemm,stream,true,16,96,2560,96,0) && ok;+ ok=run(gemm,stream,true,17,48,2560,64,1) && ok;+ ok=run(gemm,stream,false,32,640,2560,648,0) && ok;+ ok=run(gemm,stream,false,64,2560,640,2560,1) && ok;+ }+ CHECK(hipStreamDestroy(stream));+ return ok?0:1;+}