diff --git a/.gitignore b/.gitignore index cb6477db..36a0ce6b 100644 --- a/.gitignore +++ b/.gitignore @@ -50,4 +50,5 @@ build-vision.bat *.done /third_party/*.zip +/.ccache/ /.rocm-win/ diff --git a/CMakeLists.txt b/CMakeLists.txt index 7e9017cf..68f636d6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -33,6 +33,18 @@ if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) endif() option(STRATA_ENABLE_CUDA "Build the CUDA targets (Phase 2+)" OFF) +# AMD gfx906 (MI50, wave64): the same .cu sources compiled as HIP through the gfx906 compat layer. The CUDA runtime and +# cuBLAS names are mapped by the headers in include/strata/platform/hip_compat/, which go first on the include path, +# and CUDA::cudart / CUDA::cublas become aliases of HIP's targets, so every CUDA target below stays as it is. This is +# separate from STRATA_ENABLE_HIP (the wave32 RDNA backend): with it on, STRATA_ENABLE_CUDA is on and +# STRATA_ENABLE_HIP stays off, so every "CUDA" branch of the tree is the one taken. +option(STRATA_HIP_GFX906 "Build the CUDA targets for AMD gfx906 through HIP (wave64 compat layer)" OFF) +if(STRATA_HIP_GFX906) + if(STRATA_ENABLE_HIP) + message(FATAL_ERROR "STRATA_HIP_GFX906 and STRATA_ENABLE_HIP are separate backends; enable only one") + 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_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 @@ -43,7 +55,7 @@ option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_ if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() -if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP) +if(STRATA_ENABLE_CUDA AND STRATA_ENABLE_HIP AND NOT STRATA_HIP_GFX906) message(FATAL_ERROR "STRATA_ENABLE_CUDA and STRATA_ENABLE_HIP are separate backends; enable only one") endif() if(STRATA_ENABLE_HIP) @@ -68,7 +80,27 @@ if(STRATA_BUILD_CONVERSATION_TESTS) add_test(NAME conversation_memory_test COMMAND conversation_memory_test) endif() -if(STRATA_ENABLE_CUDA) +if(STRATA_HIP_GFX906) + if(NOT DEFINED CMAKE_HIP_ARCHITECTURES) + set(CMAKE_HIP_ARCHITECTURES gfx906 CACHE STRING "HIP architectures" FORCE) + endif() + enable_language(HIP) + find_package(hip REQUIRED) + find_package(hipblas REQUIRED) + add_library(CUDA::cudart INTERFACE IMPORTED) + target_link_libraries(CUDA::cudart INTERFACE hip::host) + target_compile_definitions(CUDA::cudart INTERFACE STRATA_HIP_GFX906=1 __HIP_PLATFORM_AMD__=1) + target_include_directories(CUDA::cudart BEFORE INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + add_library(CUDA::cublas INTERFACE IMPORTED) + target_link_libraries(CUDA::cublas INTERFACE roc::hipblas CUDA::cudart) + set(CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + include_directories(BEFORE ${CMAKE_CURRENT_SOURCE_DIR}/include/strata/platform/hip_compat) + add_compile_definitions(STRATA_HIP_GFX906=1) + message(STATUS "Strata: HIP (gfx906 compat) enabled, arch ${CMAKE_HIP_ARCHITECTURES}") + set(_strata_gpu_runtime_target CUDA::cudart) + set(_strata_gpu_blas_target CUDA::cublas) + set(_strata_gpu_include_directories ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}) +elseif(STRATA_ENABLE_CUDA) # #585: CMake links CUDA code with the STATIC runtime by default, and the targets below also link CUDA::cudart (the # DLL's import library). MSVC with a CUDA 12.x toolkit - the experimental Pascal/Volta build - then fails with # LNK1169 (every cudart symbol defined twice); GNU ld lets it pass. That build links the shared runtime alone. The @@ -321,7 +353,7 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/kernels/cuda/native_flash_attn.cu src/kernels/cuda/native_qsa_indexer.cu src/kernels/cuda/native_qsa_score.cu - PROPERTIES COMPILE_OPTIONS "--use_fast_math") + PROPERTIES COMPILE_OPTIONS "$,,--use_fast_math>") elseif(STRATA_ENABLE_HIP) # Keep Q8_K's multiply and magic-bias rounding as separate FP32 operations on HIP; contraction to an # FMA changes tie results. The embedding gather also relies on separately rounded operations. @@ -584,8 +616,8 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(iq_multi_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME iq_multi_parity COMMAND iq_multi_parity) # the prompt path's DeltaNet recurrence: gdn_rec_kh_kernel against gdn_rec_cols_pipe_kernel, bitwise (GPU, - # synthetic, no model; --bench adds timings) - if(STRATA_ENABLE_CUDA) + # synthetic, no model; --bench adds timings). NVIDIA only: cp.async and the CUDA occupancy API (not on gfx906) + if(STRATA_ENABLE_CUDA AND NOT STRATA_HIP_GFX906) add_executable(gdn_rec_parity src/prefill/gdn_rec_parity.cu) target_link_libraries(gdn_rec_parity PRIVATE ${_strata_gpu_runtime_target}) add_test(NAME gdn_rec_parity COMMAND gdn_rec_parity) @@ -606,6 +638,9 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_link_libraries(shared_expert_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME shared_expert_parity COMMAND shared_expert_parity --selftest) + add_executable(fused_gr_bench src/kernels/fused_gr_bench.cpp) + target_include_directories(fused_gr_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(fused_gr_bench PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_executable(gr_parity src/kernels/gr_parity.cpp) target_include_directories(gr_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(gr_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) @@ -654,6 +689,12 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) target_include_directories(router_top10_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(router_top10_parity PRIVATE strata_kernels ${_strata_gpu_runtime_target}) add_test(NAME router_top10_parity COMMAND router_top10_parity --selftest) + if(STRATA_HIP_GFX906) + # the S6 router (STRATA_HIP_ROUTER_FAST=1 on gfx906) against the portable kernel, bitwise, on wave64 + add_executable(hip_router_fast tests/hip/router_fast.cpp) + target_include_directories(hip_router_fast PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(hip_router_fast PRIVATE strata_kernels ${_strata_gpu_runtime_target}) + endif() add_executable(s_gemv_parity src/kernels/s_gemv_parity.cpp) target_include_directories(s_gemv_parity PRIVATE ${_strata_gpu_include_directories}) @@ -1024,6 +1065,9 @@ if(STRATA_NATIVE_EXPERTS) add_executable(native_expert_parity src/kernels/native_expert_parity.cpp) target_include_directories(native_expert_parity PRIVATE ${_strata_gpu_include_directories}) target_link_libraries(native_expert_parity PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) + add_executable(native_expert_bench src/kernels/native_expert_bench.cpp) + target_include_directories(native_expert_bench PRIVATE ${_strata_gpu_include_directories}) + target_link_libraries(native_expert_bench PRIVATE strata_kernels strata_kernels_cpu strata_artifact ${_strata_gpu_runtime_target}) if(STRATA_BUILD_TESTS AND STRATA_ENABLE_CUDA) # Unsloth UD-Q4_K_XL's three expert pairs (and Q8_0 alone, its embedding) on synthetic ggml-quantized weights # at 2560/640: GPU and CPU experts against the float reference, GPU dequantizers against to_float. @@ -1106,3 +1150,15 @@ if(STRATA_BUILD_TESTS) add_subdirectory(tests) endif() endif() + +# ---- HIP gfx906: every CUDA source of the tree (and the ggml-cuda MMQ sources) is compiled as HIP ---- +if(STRATA_HIP_GFX906) + file(GLOB_RECURSE _strata_cu CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cu ${CMAKE_CURRENT_SOURCE_DIR}/bench/micro/*.cu + ${CMAKE_CURRENT_SOURCE_DIR}/tools/vision/*.cu) + if(_strata_mmq) + file(GLOB _strata_mmq_cu ${_strata_mmq}/*.cu ${_strata_mmq}/template-instances/*.cu) + list(APPEND _strata_cu ${_strata_mmq_cu}) + target_compile_definitions(strata_mmq PRIVATE GGML_USE_HIP) + endif() + set_source_files_properties(${_strata_cu} PROPERTIES LANGUAGE HIP) +endif() diff --git a/include/strata/kernels/dp4a.hpp b/include/strata/kernels/dp4a.hpp index cbca6a9a..e73be4d1 100644 --- a/include/strata/kernels/dp4a.hpp +++ b/include/strata/kernels/dp4a.hpp @@ -19,6 +19,9 @@ #pragma once #include +#if defined(STRATA_HIP_GFX906) +#include // gfx906: the compat layer (__forceinline__, __nanosleep, __dp4a) +#endif #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610 __device__ __forceinline__ int strata_dp4a(const int a, const int b, const int c) { diff --git a/include/strata/kernels/fused_gr.hpp b/include/strata/kernels/fused_gr.hpp index 40eff30f..b5f95fcb 100644 --- a/include/strata/kernels/fused_gr.hpp +++ b/include/strata/kernels/fused_gr.hpp @@ -49,6 +49,8 @@ constexpr int kFusedGrMaxT = 8; void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf = nullptr, int stamp_i0 = 0); +/// The bench only: the AMD latency-hidden kernels on (1) or off (0); -1 = STRATA_GR_FAST. +void fused_gr_set_fast(int on); /// The multi read's variants (#315; not main's opt-in STRATA_GR_V3 read, which sums in another order), all computing /// every output with the plain read's operations in its order, so bitwise the plain read's and the single-token /// read's: plain (0.1.31's default: the norm one block per token, the down projection on 41 blocks), split (the norm diff --git a/include/strata/kernels/iq_kernels.hpp b/include/strata/kernels/iq_kernels.hpp index 56c0d65e..2c38f6f9 100644 --- a/include/strata/kernels/iq_kernels.hpp +++ b/include/strata/kernels/iq_kernels.hpp @@ -68,6 +68,9 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long /// (native_grouped_parity checks it); kept for A/B timing. Set before graph capture; captured graphs keep theirs. void native_grouped_set_v1(bool v1); +/// The bench only: the AMD kernel layout (STRATA_EXP_MODE values; -1 = the environment's) and the phase +/// (0 all, 1 gate/up + SwiGLU + quantize, 2 down). +void native_expert_set_mode(int mode, int phase); /// `iq_mmvq` and `native_expert_grouped` decode each weight part once and apply it to every column / entry; /// true selects the older kernels that decode it again per column (STRATA_OLD_IQ_MMVQ=1 at startup). Both give /// bitwise the same results. Set before graph capture; captured graphs keep the kernels they captured. diff --git a/include/strata/kernels/mrope.hpp b/include/strata/kernels/mrope.hpp index cb1451c4..23584242 100644 --- a/include/strata/kernels/mrope.hpp +++ b/include/strata/kernels/mrope.hpp @@ -15,6 +15,9 @@ #pragma once #include +#if defined(__HIPCC__) +#include +#endif #include "strata/kernels/rope_scaling.hpp" diff --git a/include/strata/platform/hip_compat/cublas_v2.h b/include/strata/platform/hip_compat/cublas_v2.h new file mode 100644 index 00000000..fe8ea157 --- /dev/null +++ b/include/strata/platform/hip_compat/cublas_v2.h @@ -0,0 +1,26 @@ +// cublas_v2.h for a STRATA_ENABLE_HIP build: the cuBLAS names src/prefill/gemm.cu uses, on hipBLAS. +#pragma once +#include "strata_hip.h" +#ifndef HIPBLAS_V2 +#define HIPBLAS_V2 +#endif +#include + +#define cublasHandle_t hipblasHandle_t +#define cublasStatus_t hipblasStatus_t +#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS +#define cublasCreate hipblasCreate +#define cublasDestroy hipblasDestroy +#define cublasSetStream hipblasSetStream +#define cublasGemmEx hipblasGemmEx +#define CUBLAS_OP_N HIPBLAS_OP_N +#define CUBLAS_OP_T HIPBLAS_OP_T +#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT +#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F +#define CUDA_R_32F HIP_R_32F +#define CUDA_R_16F HIP_R_16F +#define CUDA_R_16BF HIP_R_16BF +// rocBLAS picks its own math and workspace; the NVIDIA-only knobs are accepted and ignored +#define CUBLAS_DEFAULT_MATH 0 +#define cublasSetMathMode(handle, mode) HIPBLAS_STATUS_SUCCESS +#define cublasSetWorkspace(handle, ptr, bytes) HIPBLAS_STATUS_SUCCESS diff --git a/include/strata/platform/hip_compat/cuda_fp16.h b/include/strata/platform/hip_compat/cuda_fp16.h new file mode 100644 index 00000000..4cd2d3c6 --- /dev/null +++ b/include/strata/platform/hip_compat/cuda_fp16.h @@ -0,0 +1,2 @@ +#pragma once +#include "strata_hip.h" diff --git a/include/strata/platform/hip_compat/cuda_runtime.h b/include/strata/platform/hip_compat/cuda_runtime.h new file mode 100644 index 00000000..4cd2d3c6 --- /dev/null +++ b/include/strata/platform/hip_compat/cuda_runtime.h @@ -0,0 +1,2 @@ +#pragma once +#include "strata_hip.h" diff --git a/include/strata/platform/hip_compat/math_constants.h b/include/strata/platform/hip_compat/math_constants.h new file mode 100644 index 00000000..b00d57b9 --- /dev/null +++ b/include/strata/platform/hip_compat/math_constants.h @@ -0,0 +1,4 @@ +// math_constants.h for a STRATA_ENABLE_HIP build: the CUDART_* constants the tree uses. +#pragma once +#define CUDART_INF_F __builtin_huge_valf() +#define CUDART_NAN_F __builtin_nanf("") diff --git a/include/strata/platform/hip_compat/strata_hip.h b/include/strata/platform/hip_compat/strata_hip.h new file mode 100644 index 00000000..b0de6c4a --- /dev/null +++ b/include/strata/platform/hip_compat/strata_hip.h @@ -0,0 +1,295 @@ +// strata_hip.h - the CUDA runtime/cuBLAS names Strata uses, mapped onto HIP/hipBLAS for AMD GPUs (gfx906). +// +// This directory is put FIRST on the include path of a STRATA_ENABLE_HIP build only; its `cuda_runtime.h`, +// `cuda_fp16.h` and `cublas_v2.h` include this header instead of the NVIDIA ones, so the engine's sources stay +// one tree. The mapping list follows llama.cpp's ggml-cuda/vendors/hip.h (MIT) where the two overlap. +// +// The warp contract: every Strata kernel is written for a 32-lane warp. gfx906 runs 64-lane wavefronts, so +// here a CUDA warp is a LOGICAL 32-lane half of a wavefront: every shuffle defaults to width 32 (a +// `__shfl_down_sync(m, v, 1)` at lane 31 must not read lane 32), `__ballot_sync` returns the 32-bit mask of the +// caller's own half, and `__syncwarp` is a wavefront barrier plus an LDS fence. That keeps every kernel's +// arithmetic, lane mapping and reduction order exactly as on NVIDIA; wave64-native rewrites of the hot kernels +// are separate, measured changes. +#pragma once + +#ifndef HIP_DISABLE_WARP_SYNC_BUILTINS +#define HIP_DISABLE_WARP_SYNC_BUILTINS 1 +#endif +#include +#include + +#include +#include + +#define STRATA_HIP_GFX906 1 + +// ---- runtime: types and constants ------------------------------------------------------------------------ +#define cudaError_t hipError_t +#define cudaSuccess hipSuccess +#define cudaErrorNotReady hipErrorNotReady +#define cudaErrorMemoryAllocation hipErrorOutOfMemory +#define cudaErrorStreamCaptureUnsupported hipErrorStreamCaptureUnsupported +#define cudaErrorPeerAccessAlreadyEnabled hipErrorPeerAccessAlreadyEnabled +#define cudaStream_t hipStream_t +#define cudaEvent_t hipEvent_t +#define cudaGraph_t hipGraph_t +#define cudaGraphExec_t hipGraphExec_t +#define cudaGraphNode_t hipGraphNode_t +#define cudaDeviceProp hipDeviceProp_t +#define cudaMemcpyKind hipMemcpyKind +#define cudaMemcpyHostToDevice hipMemcpyHostToDevice +#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost +#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice +#define cudaMemcpyDefault hipMemcpyDefault +#define cudaStreamNonBlocking hipStreamNonBlocking +#define cudaStreamCaptureModeThreadLocal hipStreamCaptureModeThreadLocal +#define cudaStreamCaptureModeRelaxed hipStreamCaptureModeRelaxed +#define cudaStreamCaptureModeGlobal hipStreamCaptureModeGlobal +#define cudaStreamCaptureStatus hipStreamCaptureStatus +#define cudaStreamCaptureStatusNone hipStreamCaptureStatusNone +#define cudaStreamCaptureStatusActive hipStreamCaptureStatusActive +#define cudaEventDisableTiming hipEventDisableTiming +#define cudaEventDefault hipEventDefault +#define cudaHostAllocDefault hipHostMallocDefault +#define cudaHostAllocPortable hipHostMallocPortable +#define cudaHostAllocMapped hipHostMallocMapped +#define cudaHostAllocWriteCombined hipHostMallocWriteCombined +#define cudaHostRegisterDefault hipHostRegisterDefault +#define cudaHostRegisterPortable hipHostRegisterPortable +#define cudaHostRegisterMapped hipHostRegisterMapped +#define cudaHostRegisterReadOnly hipHostRegisterReadOnly +#define cudaDeviceScheduleSpin hipDeviceScheduleSpin +#define cudaDeviceScheduleYield hipDeviceScheduleYield +#define cudaDeviceScheduleBlockingSync hipDeviceScheduleBlockingSync +#define cudaDeviceMapHost hipDeviceMapHost +#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize +#define cudaDevAttrMultiProcessorCount hipDeviceAttributeMultiprocessorCount +#define cudaDevAttrClockRate hipDeviceAttributeClockRate +#define cudaDevAttrComputeCapabilityMajor hipDeviceAttributeComputeCapabilityMajor +#define cudaDevAttrComputeCapabilityMinor hipDeviceAttributeComputeCapabilityMinor +#define cudaDevAttrMaxSharedMemoryPerBlockOptin hipDeviceAttributeSharedMemPerBlockOptin +#define cudaDevAttrMemoryClockRate hipDeviceAttributeMemoryClockRate +#define cudaDevAttrGlobalMemoryBusWidth hipDeviceAttributeMemoryBusWidth + +// ---- runtime: functions ---------------------------------------------------------------------------------- +#define cudaGetErrorString hipGetErrorString +#define cudaGetErrorName hipGetErrorName +#define cudaGetLastError hipGetLastError +#define cudaPeekAtLastError hipPeekAtLastError +#define cudaGetDevice hipGetDevice +#define cudaSetDevice hipSetDevice +#define cudaGetDeviceCount hipGetDeviceCount +#define cudaGetDeviceProperties hipGetDeviceProperties +// The shared-memory opt-in limit: some HIP versions report 0 for it on GCN cards; the real ceiling there is +// the plain per-block limit (64 KB of LDS on gfx906). +inline hipError_t strata_device_get_attribute(int* v, hipDeviceAttribute_t a, int dev) { + hipError_t e = hipDeviceGetAttribute(v, a, dev); + if (e == hipSuccess && a == hipDeviceAttributeSharedMemPerBlockOptin && *v <= 0) + e = hipDeviceGetAttribute(v, hipDeviceAttributeMaxSharedMemoryPerBlock, dev); + return e; +} +#define cudaDeviceGetAttribute strata_device_get_attribute +#define cudaDeviceSynchronize hipDeviceSynchronize +#define cudaDeviceCanAccessPeer hipDeviceCanAccessPeer +#define cudaDeviceEnablePeerAccess hipDeviceEnablePeerAccess +#define cudaDriverGetVersion hipDriverGetVersion +#define cudaRuntimeGetVersion hipRuntimeGetVersion +#define cudaSetDeviceFlags hipSetDeviceFlags +#define cudaMalloc hipMalloc +#define cudaFree hipFree +#define cudaMemGetInfo hipMemGetInfo +#define cudaMemcpy hipMemcpy +#define cudaMemcpyAsync hipMemcpyAsync +#define cudaMemcpyPeerAsync hipMemcpyPeerAsync +#define cudaMemcpy2DAsync hipMemcpy2DAsync +#define cudaMemset hipMemset +#define cudaMemsetAsync hipMemsetAsync +// Mapped host memory is how the GPU and the CPU talk inside a running graph (the doorbells, the CPU experts' +// results, the verify flags): a kernel spins on a word the CPU writes, and the CPU on a word the kernel writes. +// On AMD that needs FINE-GRAINED (coherent) memory - coarse-grained host memory may sit in the GPU's L2 for the +// whole kernel and the spin never sees the other side. So every mapped allocation is made coherent here. +inline hipError_t strata_host_alloc(void** p, size_t bytes, unsigned int flags) { + if (flags & hipHostMallocMapped) flags |= hipHostMallocCoherent; + return hipHostMalloc(p, bytes, flags); +} +template inline hipError_t strata_host_alloc(T** p, size_t bytes, unsigned int flags) { + return strata_host_alloc(reinterpret_cast(p), bytes, flags); +} +#define cudaHostAlloc strata_host_alloc +#define cudaMallocHost(ptr, size) hipHostMalloc(ptr, size, hipHostMallocDefault) +#define cudaFreeHost hipHostFree +#define cudaHostRegister hipHostRegister +#define cudaHostUnregister hipHostUnregister +#define cudaHostGetDevicePointer hipHostGetDevicePointer +#define cudaStreamCreate hipStreamCreate +#define cudaStreamCreateWithFlags hipStreamCreateWithFlags +#define cudaStreamDestroy hipStreamDestroy +#define cudaStreamSynchronize hipStreamSynchronize +#define cudaStreamQuery hipStreamQuery +#define cudaStreamWaitEvent hipStreamWaitEvent +#define cudaStreamBeginCapture hipStreamBeginCapture +#define cudaStreamEndCapture hipStreamEndCapture +#define cudaStreamIsCapturing hipStreamIsCapturing +#define cudaLaunchHostFunc hipLaunchHostFunc +#define cudaEventCreate hipEventCreate +#define cudaEventCreateWithFlags hipEventCreateWithFlags +#define cudaEventDestroy hipEventDestroy +#define cudaEventRecord hipEventRecord +#define cudaEventQuery hipEventQuery +#define cudaEventSynchronize hipEventSynchronize +#define cudaEventElapsedTime hipEventElapsedTime +#define cudaGraphLaunch hipGraphLaunch +#define cudaGraphUpload hipGraphUpload +#define cudaGraphDestroy hipGraphDestroy +#define cudaGraphExecDestroy hipGraphExecDestroy +#define cudaGraphGetNodes hipGraphGetNodes +#define cudaGraphNodeType hipGraphNodeType +#define cudaGraphNodeGetType hipGraphNodeGetType +#define cudaGraphNodeTypeKernel hipGraphNodeTypeKernel +#define cudaGraphNodeTypeMemcpy hipGraphNodeTypeMemcpy +#define cudaGraphNodeTypeMemset hipGraphNodeTypeMemset +#define cudaKernelNodeParams hipKernelNodeParams +#define cudaGraphKernelNodeGetParams hipGraphKernelNodeGetParams +inline hipError_t cudaFuncGetName(const char** name, const void*) { *name = nullptr; return hipErrorNotSupported; } +#define cudaFuncSetAttribute(fn, attr, val) hipFuncSetAttribute(reinterpret_cast(fn), attr, val) +#define cudaMemcpyToSymbol(sym, src, ...) hipMemcpyToSymbol(HIP_SYMBOL(sym), src, __VA_ARGS__) + +// CUDA 12 has a 3-argument cudaGraphInstantiate(exec, graph, flags) and the older 5-argument one; HIP spells +// the first hipGraphInstantiateWithFlags. Both are used in the tree. +inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, unsigned long long flags) { + return hipGraphInstantiateWithFlags(exec, graph, flags); +} +inline hipError_t cudaGraphInstantiate(hipGraphExec_t* exec, hipGraph_t graph, hipGraphNode_t* err_node, + char* log, size_t log_size) { + return hipGraphInstantiate(exec, graph, err_node, log, log_size); +} +// cudaInitDevice(dev, deviceFlags, flags): initialise a device and its scheduling flags WITHOUT making it the +// current device (CUDA's contract; the layer split relies on it - a changed current device put GPU 0's expert +// cache on GPU 1). +inline hipError_t cudaInitDevice(int device, unsigned int device_flags, unsigned int /*flags*/) { + int prev = 0; + hipError_t e = hipGetDevice(&prev); + if (e != hipSuccess) return e; + e = hipSetDevice(device); + if (e != hipSuccess) return e; + if (hipSetDeviceFlags(device_flags) != hipSuccess) (void) hipGetLastError(); // context already active + return hipSetDevice(prev); +} + +// ---- device side ----------------------------------------------------------------------------------------- +#if defined(__HIP_DEVICE_COMPILE__) || defined(__HIPCC__) + +// Logical 32-lane warps (see the header comment). The width argument, when given, wins. +#define __shfl_sync(mask, var, lane, ...) __shfl(var, lane, STRATA_SHFL_W(__VA_ARGS__)) +#define __shfl_up_sync(mask, var, delta, ...) __shfl_up(var, delta, STRATA_SHFL_W(__VA_ARGS__)) +#define __shfl_down_sync(mask, var, delta, ...) __shfl_down(var, delta, STRATA_SHFL_W(__VA_ARGS__)) +#define __shfl_xor_sync(mask, var, lanemask, ...) __shfl_xor(var, lanemask, STRATA_SHFL_W(__VA_ARGS__)) +// STRATA_SHFL_W() -> 32, STRATA_SHFL_W(w) -> w +#define STRATA_SHFL_W(...) STRATA_SHFL_W_I(dummy, ##__VA_ARGS__, STRATA_SHFL_W_GIVEN, STRATA_SHFL_W_DEFAULT)(__VA_ARGS__) +#define STRATA_SHFL_W_I(d, a, b, ...) b +#define STRATA_SHFL_W_GIVEN(w) (w) +#define STRATA_SHFL_W_DEFAULT(...) 32 +#define __all_sync(mask, pred) __all(pred) +#define __any_sync(mask, pred) __any(pred) + +static __device__ __forceinline__ unsigned int strata_ballot32(int pred) { + const unsigned long long b = __ballot(pred); + return (unsigned int) (b >> (__lane_id() & 32u)); +} +#define __ballot_sync(mask, pred) strata_ballot32(pred) +#define __activemask() ((unsigned int) (__ballot(1) >> (__lane_id() & 32u))) + +static __device__ __forceinline__ void strata_syncwarp() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront"); + __builtin_amdgcn_wave_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront"); +} +#define __syncwarp(...) strata_syncwarp() + +// __nanosleep(ns): s_sleep counts 64 clocks per unit (~40 ns at the 1.7 GHz shader clock); a spin loop only +// needs "back off a little", not an exact time. +static __device__ __forceinline__ void strata_nanosleep(unsigned int ns) { + if (ns >= 400) __builtin_amdgcn_s_sleep(8); + else __builtin_amdgcn_s_sleep(1); +} +#define __nanosleep(ns) strata_nanosleep(ns) +#define __trap() __builtin_trap() + +// __dp4a(a, b, c): signed 8-bit dot product plus accumulator; gfx906 has v_dot4_i32_i8. +static __device__ __forceinline__ int strata_dp4a(int a, int b, int c) { +#if defined(__gfx906__) || defined(__gfx908__) || defined(__gfx90a__) || defined(__gfx942__) || defined(__GFX11__) || defined(__GFX12__) + return __builtin_amdgcn_sdot4(a, b, c, false); +#else + const int8_t* va = reinterpret_cast(&a); + const int8_t* vb = reinterpret_cast(&b); + return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3]; +#endif +} +static __device__ __forceinline__ unsigned int strata_dp4a(unsigned int a, unsigned int b, unsigned int c) { + const uint8_t* va = reinterpret_cast(&a); + const uint8_t* vb = reinterpret_cast(&b); + return c + va[0] * vb[0] + va[1] * vb[1] + va[2] * vb[2] + va[3] * vb[3]; +} +#define __dp4a strata_dp4a + +// SIMD-in-a-word byte ops (CUDA semantics: __vsub4 wraps per byte, __vsubss4 saturates, __vcmp*4 give 0xff) +typedef int8_t strata_i8x4 __attribute__((ext_vector_type(4))); +typedef uint8_t strata_u8x4 __attribute__((ext_vector_type(4))); +static __device__ __forceinline__ unsigned int strata_vsub4(unsigned int a, unsigned int b) { + const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a); + const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b); + return __builtin_bit_cast(unsigned int, (strata_u8x4) (va - vb)); +} +static __device__ __forceinline__ int strata_vsubss4(int a, int b) { + const strata_i8x4 va = __builtin_bit_cast(strata_i8x4, a); + const strata_i8x4 vb = __builtin_bit_cast(strata_i8x4, b); + return __builtin_bit_cast(int, (strata_i8x4) __builtin_elementwise_sub_sat(va, vb)); +} +static __device__ __forceinline__ unsigned int strata_vcmpeq4(unsigned int a, unsigned int b) { + const strata_u8x4 va = __builtin_bit_cast(strata_u8x4, a); + const strata_u8x4 vb = __builtin_bit_cast(strata_u8x4, b); + strata_u8x4 c; +#pragma unroll + for (int i = 0; i < 4; ++i) c[i] = va[i] == vb[i] ? 0xff : 0x00; + return __builtin_bit_cast(unsigned int, c); +} +static __device__ __forceinline__ unsigned int strata_vcmpne4(unsigned int a, unsigned int b) { + return ~strata_vcmpeq4(a, b); +} +#define __vsub4(a, b) ((int) strata_vsub4((unsigned int) (a), (unsigned int) (b))) +#define __vsubss4(a, b) strata_vsubss4((int) (a), (int) (b)) +#define __vcmpeq4(a, b) strata_vcmpeq4((unsigned int) (a), (unsigned int) (b)) +#define __vcmpne4(a, b) strata_vcmpne4((unsigned int) (a), (unsigned int) (b)) + + +// __fmul_rn / __fadd_rn / __fsub_rn: on NVIDIA these are never contracted into an FMA (that is their point - the +// engine uses them where a result must match a reference bit for bit). HIP spells them as plain operators, which +// clang's default -ffp-contract=fast-honor-pragmas may fuse. The pragma keeps each one a separate rounding. +static __device__ __forceinline__ float strata_fmul_rn(float a, float b) { +#pragma clang fp contract(off) + return a * b; +} +static __device__ __forceinline__ float strata_fadd_rn(float a, float b) { +#pragma clang fp contract(off) + return a + b; +} +static __device__ __forceinline__ float strata_fsub_rn(float a, float b) { +#pragma clang fp contract(off) + return a - b; +} +#define __fmul_rn(a, b) strata_fmul_rn((a), (b)) +#define __fadd_rn(a, b) strata_fadd_rn((a), (b)) +#define __fsub_rn(a, b) strata_fsub_rn((a), (b)) + + +// __byte_perm(x, y, s): HIP's own version builds an 8-byte array and indexes it - the array lands in SCRATCH +// memory, and every IQ4 codebook lookup went through it (a 0.9 MB IQ4_NL GEMV took 290 us, ~3 GB/s). gfx906 has +// v_perm_b32, which selects bytes of {src0:src1} (src1 low) by byte selectors 0-7: the same operation, one +// instruction. CUDA reads the low 3 bits of each of the four low selector nibbles. +static __device__ __forceinline__ unsigned int strata_byte_perm(unsigned int x, unsigned int y, unsigned int s) { + const unsigned int sel = (s & 0x7u) | ((s & 0x70u) << 4) | ((s & 0x700u) << 8) | ((s & 0x7000u) << 12); + return __builtin_amdgcn_perm(y, x, sel); +} +#define __byte_perm(x, y, s) strata_byte_perm((unsigned int) (x), (unsigned int) (y), (unsigned int) (s)) + +#endif // device side diff --git a/src/core/device.cu b/src/core/device.cu index 98fc0717..fbc70307 100644 --- a/src/core/device.cu +++ b/src/core/device.cu @@ -212,7 +212,7 @@ std::string gpu_arch_problem(int ordinal) { } std::string device_code_error() { -#if defined(STRATA_USE_HIP) +#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) return ""; // gpu_arch_problem() checks the HIP architectures against STRATA_HIP_ARCHS, before this point #else // every .cu of the engine is compiled for the same CMAKE_CUDA_ARCHITECTURES, so this kernel stands for all @@ -263,7 +263,17 @@ DeviceInfo device_info(int ordinal) { // 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 checks the card against the architectures the binary was compiled for (and wave32). -#if defined(STRATA_USE_HIP) +#if defined(STRATA_HIP_GFX906) + // AMD gfx906 (the STRATA_HIP_GFX906 compat build, not STRATA_USE_HIP): the build targets one gfx arch + // (CMAKE_HIP_ARCHITECTURES, wave64); a card of another arch fails at the first kernel launch with + // hipErrorInvalidDeviceFunction. gcnArchName says which it is. + { + std::string arch(p.gcnArchName); + if (const size_t colon = arch.find(':'); colon != std::string::npos) arch.resize(colon); + d.arch = arch; + } + if (p.gcnArchName[0] != 0) d.name += std::string(" (") + p.gcnArchName + ")"; +#elif defined(STRATA_USE_HIP) d.arch = base_arch(p.gcnArchName); if (const std::string why = arch_problem(p, ordinal); !why.empty()) throw CudaError(why, -1); #else diff --git a/src/kernels/cuda/fused_gr.cu b/src/kernels/cuda/fused_gr.cu index c9d1b80d..0ef848db 100644 --- a/src/kernels/cuda/fused_gr.cu +++ b/src/kernels/cuda/fused_gr.cu @@ -712,7 +712,11 @@ int down_chunk(bool staged, int* tile_out) { // the down kernel's outputs (lo, inject_out) are strictly per-token, so the chunk boundaries are safe, and // the up kernel below still sees every token of the batch in one launch. #if defined(__HIPCC__) +#if defined(STRATA_HIP_GFX906) + const bool small_tile = false; // gfx906: 64 KiB LDS, the 2560 tile as before (8 tokens slice into launches) +#else const bool small_tile = true; // all eight tokens fit gfx1100's 64 KiB LDS at this tile +#endif #else int cc_maj = 0, cc_min = 0; cudaDeviceGetAttribute(&cc_maj, cudaDevAttrComputeCapabilityMajor, dev); @@ -811,8 +815,230 @@ int env_variant() { // per device: the variant `fused_gr_check` chose (0 = not checked yet) std::atomic g_variant[64]; + +#if defined(STRATA_HIP_GFX906) +// ---- AMD fast path (STRATA_GR_FAST, default 1; 0 = the old kernels): the same arithmetic per value in the same order, latency +// hidden. gr_norm: one block per token (as before) but a thread's 10 float4 of R / bo / w_norm are loaded +// before any is used, and xn stays in registers until rs is known (was: store, then re-read the 40 KB). +// gr_up: a warp's 8 rows of w_up and their epilogue inputs are loaded before the dots (was: one row's load chain +// after another). +constexpr int NQ = D / (THREADS * 4); // 10 float4 per thread +static_assert(D % (THREADS * 4) == 0, "whole float4 per thread"); +__global__ void __launch_bounds__(THREADS) gr_norm_fast_kernel(GrMulti m) { + __shared__ float part[WARPS][HC]; + __shared__ float s_rs[HC]; + const FusedGrArgs& a = m.a[blockIdx.x]; + float* xn = m.xn + (size_t) blockIdx.x * D; + const int t = threadIdx.x, lane = t & 31, warp = t >> 5; + float gw[HC]; +#pragma unroll + for (int c = 0; c < HC; ++c) gw[c] = a.apply ? 2.0f * sigmoidf_(a.inj_prev[c] / (float) HC) : 0.0f; + float4 r[NQ], g[NQ]; +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const int i = t * 4 + k * THREADS * 4; + r[k] = *reinterpret_cast(a.R + i); + g[k] = *reinterpret_cast(a.w_norm + i); + } + if (a.apply) { +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const int i = t * 4 + k * THREADS * 4, c = i / N, d = i - c * N; + const float4 b = *reinterpret_cast(a.bo_prev + d); + r[k].x = fmaf(b.x, gw[c], r[k].x); r[k].y = fmaf(b.y, gw[c], r[k].y); + r[k].z = fmaf(b.z, gw[c], r[k].z); r[k].w = fmaf(b.w, gw[c], r[k].w); + } + } + float ss[HC] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const int i = t * 4 + k * THREADS * 4, c = i / N; + const float sq = r[k].x * r[k].x + r[k].y * r[k].y + r[k].z * r[k].z + r[k].w * r[k].w; +#pragma unroll + for (int cc = 0; cc < HC; ++cc) if (cc == c) ss[cc] += sq; + r[k] = make_float4(r[k].x * g[k].x, r[k].y * g[k].y, r[k].z * g[k].z, r[k].w * g[k].w); + } +#pragma unroll + for (int c = 0; c < HC; ++c) { + const float v = warp_sum(ss[c]); + if (lane == 0) part[warp][c] = v; + } + __syncthreads(); + if (t < HC) { + float s = 0.0f; + for (int w = 0; w < WARPS; ++w) s += part[w][t]; + s_rs[t] = rsqrtf(s / (float) N + a.eps); + a.rs[t] = s_rs[t]; + } + __syncthreads(); +#pragma unroll + for (int k = 0; k < NQ; ++k) { + const int i = t * 4 + k * THREADS * 4; + const float sr = s_rs[i / N]; + *reinterpret_cast(xn + i) = make_float4(r[k].x * sr, r[k].y * sr, r[k].z * sr, r[k].w * sr); + } +} +// gr_up: 8 lanes per row instead of a 32-lane warp. Lane j holds the old lanes j, j+8, j+16, j+24 (and chunk +// 32+j, the old lane j's second chunk): the xor tree's stages 16 and 8 are its own adds (a + b == b + a), stages +// 4, 2, 1 are shuffles inside the 8 - the same tree, bitwise the same sum, 3 shuffles a token instead of 5 and no +// idle lanes on the tail chunks. A block's 64 rows are 2 passes of 32 groups, their weights loaded up front. +__device__ __forceinline__ float xor8(float v) { +#pragma unroll + for (int o = 4; o > 0; o >>= 1) v += __shfl_xor(v, o, 64); + return v; +} +__global__ void __launch_bounds__(THREADS) gr_up_fast_kernel(GrMulti m) { + __shared__ __align__(16) float lo[kFusedGrMaxT][LR]; + __shared__ float g[kFusedGrMaxT][HC][UPM_COLS]; + const int t = threadIdx.x, j = t & 7, grp = t >> 3; + const int T = m.T; + const int d0 = blockIdx.x * UPM_COLS; + static_assert(LR == 40 * 8 && HC * UPM_COLS == 64 && THREADS == 256, "geometry"); + uint4 w[2][5]; + float rv[2] = {0.0f, 0.0f}, wn[2] = {0.0f, 0.0f}, rsc[2] = {0.0f, 0.0f}, bo[2] = {0.0f, 0.0f}, ip[2] = {0.0f, 0.0f}; + const bool apply = j < T && m.a[j < T ? j : 0].apply; +#pragma unroll + for (int p = 0; p < 2; ++p) { + const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + const uint4* w4 = reinterpret_cast(m.a[0].w_up + (size_t) i * LR); +#pragma unroll + for (int q = 0; q < 4; ++q) w[p][q] = __ldg(w4 + j + 8 * q); + w[p][4] = __ldg(w4 + 32 + j); + if (j < T) { + const FusedGrArgs& a = m.a[j]; + rv[p] = a.R[i]; + wn[p] = a.w_norm[i]; + rsc[p] = a.rs[c]; + if (apply) { bo[p] = a.bo_prev[d0 + dd]; ip[p] = a.inj_prev[c]; } + } + } + for (int i = t; i < T * LR; i += THREADS) lo[i / LR][i % LR] = m.a[i / LR].lo[i % LR]; + __syncthreads(); +#pragma unroll + for (int p = 0; p < 2; ++p) { + const int r = grp + 32 * p, c = r / UPM_COLS, dd = r - c * UPM_COLS, i = c * N + d0 + dd; + float mine = 0.0f; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + const float* l = lo[k]; + const float p0 = dot8(w[p][0], l + j * 8) + dot8(w[p][4], l + (32 + j) * 8); // old lane j + const float p1 = dot8(w[p][1], l + (j + 8) * 8); // old lane j + 8 + const float p2 = dot8(w[p][2], l + (j + 16) * 8); // old lane j + 16 + const float p3 = dot8(w[p][3], l + (j + 24) * 8); // old lane j + 24 + const float s = xor8((p0 + p2) + (p1 + p3)); // stage 16: (j, j+16), (j+8, j+24); stage 8; then 4, 2, 1 + if (j == k) mine = s; + } + if (j < T) { + float x0 = rv[p]; + if (apply) { + x0 = fmaf(bo[p], 2.0f * sigmoidf_(ip[p] / (float) HC), x0); + m.a[j].R_out[i] = x0; + } + const float x = x0 * wn[p] * rsc[p]; + g[j][c][dd] = x * sigmoidf_(mine); + } + } + __syncthreads(); + for (int i = t; i < T * UPM_COLS; i += THREADS) { + const int k = i / UPM_COLS, col = i - k * UPM_COLS; + float s = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) s += g[k][c][col]; + m.a[k].mixed[d0 + col] = s / (float) HC; + } +} +#endif + +#if defined(STRATA_HIP_GFX906) +// ---- AMD: `gr_down_multi` split along K. The CUDA kernel is one warp per row of w_down (320 + 4 rows), 41 +// blocks: on a 60-CU gfx906 that left most of the card idle and read the 6.5 MB matrix at ~100 GB/s. Here a block +// is 8 wavefronts = 8 rows of one K-slice of 2048 (the slice of every token's xn staged in LDS once), 41 x 5 +// blocks, and a second kernel adds the 5 slice sums in a fixed order and runs the epilogue. A token's result does +// not depend on how many tokens share the window (each column is reduced on its own). +constexpr int GS_SL = 2048; // K per slice +constexpr int GS_S = D / GS_SL; // 5 slices +constexpr int GS_ROWS = LR + HC; // 324: the down rows, then the inject rows +constexpr int GS_WAVES = 8; +static_assert(D % GS_SL == 0 && GS_SL == 64 * 8 * 4, "a lane takes 4 chunks of 8 per slice"); +// the slice sums: a module-scope device array is per device by construction, and needs no allocation during a +// graph capture +__device__ float g_gr_part[GS_S * kFusedGrMaxT * GS_ROWS]; +__global__ void __launch_bounds__(GS_WAVES * 64) gr_down_split_kernel(GrMulti m) { + float* part = g_gr_part; + extern __shared__ __align__(16) float tile[]; // [T][GS_SL] + const int t = threadIdx.x, lane = t & 63, wave = t >> 6; + const int T = m.T, sl = blockIdx.y; + const bool inject_block = blockIdx.x == DOWN_BLOCKS; + const int row = inject_block ? wave : blockIdx.x * GS_WAVES + wave; + const bool active = !(inject_block && (m.a[0].w_inject == nullptr || wave >= HC)); + const uint16_t* wrow = (inject_block ? m.a[0].w_inject : m.a[0].w_down) + (size_t) (active ? row : 0) * D; + const uint4* w4 = reinterpret_cast(wrow) + sl * (GS_SL / 8); + uint4 wv[4]; + if (active) { +#pragma unroll + for (int q = 0; q < 4; ++q) wv[q] = __ldg(w4 + lane + 64 * q); + } + const float4* src4 = reinterpret_cast(m.xn); + float4* tile4 = reinterpret_cast(tile); + for (int i = t; i < T * (GS_SL / 4); i += GS_WAVES * 64) { + const int k = i / (GS_SL / 4), off = i - k * (GS_SL / 4); + tile4[i] = src4[((size_t) k * D + (size_t) sl * GS_SL) / 4 + off]; + } + __syncthreads(); + if (!active) return; + float acc[kFusedGrMaxT]; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) acc[k] = 0.0f; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int j = lane + 64 * q; +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) + if (k < T) acc[k] += dot8(wv[q], tile + k * GS_SL + j * 8); + } +#pragma unroll + for (int k = 0; k < kFusedGrMaxT; ++k) { + if (k >= T) break; + float v = acc[k]; +#pragma unroll + for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64); + if (lane == 0) part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + (inject_block ? LR + row : row)] = v; + } +} +__global__ void gr_down_finish_kernel(GrMulti m) { + const float* part = g_gr_part; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + const int k = i / GS_ROWS, r = i - k * GS_ROWS; + if (k >= m.T) return; + const bool inject = r >= LR; + if (inject && m.a[0].w_inject == nullptr) return; + float s = 0.0f; +#pragma unroll + for (int sl = 0; sl < GS_S; ++sl) s += part[((size_t) sl * kFusedGrMaxT + k) * GS_ROWS + r]; + if (inject) { + m.a[k].inject_out[r - LR] = s; + } else { + const float x = s / (float) HC; + m.a[k].lo[r] = x / (1.0f + __expf(-x)); + } +} + +#endif + } // namespace +#if defined(STRATA_HIP_GFX906) +int g_gr_fast = -1; // fused_gr_set_fast (the bench); -1 = STRATA_GR_FAST +static bool gr_fast() { + static const bool env = [] { const char* v = std::getenv("STRATA_GR_FAST"); return v ? std::atoi(v) != 0 : true; }(); + return g_gr_fast >= 0 ? g_gr_fast != 0 : env; +} +#else +int g_gr_fast = -1; +#endif +void fused_gr_set_fast(int on) { g_gr_fast = on; } + void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, void* stream, unsigned long long* stamp_buf, int stamp_i0) { if (n_tok < 1 || n_tok > kFusedGrMaxT || xn_scratch == nullptr) { @@ -875,6 +1101,28 @@ void fused_gr_read_multi(const FusedGrArgs* a, int n_tok, float* xn_scratch, voi } return; } +#if defined(STRATA_HIP_GFX906) + // gfx906: the latency-hidden norm/up (STRATA_GR_FAST) and the K-split down (STRATA_GR_SPLIT=0: the CUDA layout's read) + static const bool split_off = std::getenv("STRATA_GR_SPLIT") && std::string(std::getenv("STRATA_GR_SPLIT")) == "0"; + if (!split_off) { + const bool fast = gr_fast(); + if (fast) gr_norm_fast_kernel<<>>(m); + else gr_norm_multi_kernel<<>>(m); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0, stream); + gr_down_split_kernel<<>>( + m); + gr_down_finish_kernel<<<(unsigned) ((n_tok * GS_ROWS + 255) / 256), 256, 0, st>>>(m); + if (stamp_buf) gpu_stamp(stamp_buf, stamp_i0 + 1, stream); + if (fast) gr_up_fast_kernel<<>>(m); + else gr_up_multi_kernel<<>>(m); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "fused_gr_read_multi: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + return; + } +#endif // the default read (STRATA_GR_V3 unset): v1, or the bitwise-equal v2 / v3 this card's check accepted launch_multi(m, fused_gr_variant(), st, stamp_buf, stamp_i0); const cudaError_t e = cudaGetLastError(); diff --git a/src/kernels/cuda/iq_kernels.cu b/src/kernels/cuda/iq_kernels.cu index 15be7d59..121e5a0a 100644 --- a/src/kernels/cuda/iq_kernels.cu +++ b/src/kernels/cuda/iq_kernels.cu @@ -17,6 +17,7 @@ #include #include +#include namespace strata::kernels { namespace { @@ -40,6 +41,18 @@ __device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) { return s * 0x01010101; } __device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) { +#if defined(STRATA_HIP_GFX906) + // AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves + // of the table are looked up and the index MSB picks between them: 4 perms per 8 values. + const uint32_t* v32 = reinterpret_cast(table); + const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4; + const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u); + const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u); + const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u); + const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u); + return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)), + (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1))); +#else const uint32_t* table32 = (const uint32_t*) table; uint32_t tmp[2]; const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1)); @@ -51,6 +64,7 @@ __device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_ tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); } return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); +#endif } #define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c)) @@ -1533,6 +1547,560 @@ size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) { return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255); } + +#if defined(STRATA_HIP_GFX906) +// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above). +// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly. +// 2 (R2): a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight. +// Either way a (row, entry) sum does not depend on the window size. +template +__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) { + using F = Fmt; + float s = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 64) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs); + } +#pragma unroll + for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64); + return s; +} +template +__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane, + float& o0, float& o1) { + using F = Fmt; + float s0 = 0.0f, s1 = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + const block_q8_1* xk = x + kbx * (F::qk / 32); + const float a = F::dot(r0, xk, kbx, iqs); + const float b = F::dot(r1, xk, kbx, iqs); + s0 += a; + s1 += b; + } + o0 = warp_sum(s0); + o1 = warp_sum(s1); +} +template +__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) { + using F = Fmt; + float acc[NR]; +#pragma unroll + for (int i = 0; i < NR; ++i) acc[i] = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + const block_q8_1* xk = x + kbx * (F::qk / 32); + float d[NR]; +#pragma unroll + for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs); +#pragma unroll + for (int i = 0; i < NR; ++i) acc[i] += d[i]; + } +#pragma unroll + for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]); +} +template +__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nrow = 2 * (int) L.n_ff; + auto wrow = [&](int row) -> const uint8_t* { + const bool is_up = row >= L.n_ff; + return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row; + }; + auto put = [&](int row, int e, float v) { + const bool is_up = row >= L.n_ff; + (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v; + }; + if constexpr (MODE == 1) { + const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6); + if (row >= nrow) return; + const uint8_t* wr = wrow(row); + for (int e = e0; e < e1; ++e) { + const float v = row_dot64(wr, xq + (size_t) ent_tok[e] * xb, nb, lane); + if (lane == 0) put(row, e, v); + } + } else if constexpr (MODE == 4) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int row0 = blockIdx.x * 32 + warp; + if (row0 >= nrow) return; + const uint8_t* w[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0); + for (int e = e0; e < e1; ++e) { + float o[4]; + row_dotn(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o); + if (lane == 0) +#pragma unroll + for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]); + } + } else { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8; + if (row0 >= nrow) return; + const bool two = row1 < nrow; + const uint8_t* w0 = wrow(row0); + const uint8_t* w1 = wrow(two ? row1 : row0); + for (int e = e0; e < e1; ++e) { + float a, b; + row_dot2(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b); + if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); } + } + } +} +template +__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nrow = (int) L.n_embd; + if constexpr (MODE == 1) { + const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6); + if (r >= nrow) return; + const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row; + for (int e = e0; e < e1; ++e) { + const float v = row_dot64(wr, hq + (size_t) e * hb, nb, lane); + if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v; + } + } else if constexpr (MODE == 4) { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int r0 = blockIdx.x * 32 + warp; + if (r0 >= nrow) return; + const uint8_t* w[4]; +#pragma unroll + for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row; + for (int e = e0; e < e1; ++e) { + float o[4]; + row_dotn(w, hq + (size_t) e * hb, nb, lane, o); + if (lane == 0) +#pragma unroll + for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i]; + } + } else { + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8; + if (r0 >= nrow) return; + const bool two = r1 < nrow; + const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row; + const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row; + for (int e = e0; e < e1; ++e) { + float a, b; + row_dot2(w0, w1, hq + (size_t) e * hb, nb, lane, a, b); + if (lane == 0) { + out[(size_t) ent_dst[e] * L.n_embd + r0] = a; + if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b; + } + } + } +} +// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1 +// activations in LDS. The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the +// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector +// memory path after the weight load. Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the +// output is bitwise the mode-2 one. +template struct GridOf; +template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } }; +template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } }; +template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } }; +template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } }; // IQ4_XS: no grid + +// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to +// ~12 word ops each). m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so +// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats. +__device__ __forceinline__ int nib_mask(uint32_t n) { + const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u; + return (int) ((b << 8) - b); +} +template struct DotG; +template struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, + const uint64_t* grid) { + const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx; + const int qs_packed = get_int_b2(bq2->qs, iqs / 2); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq2->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + const int ls0 = bq2->scales[iqs / 2] & 0x0F; + const int ls1 = bq2->scales[iqs / 2] >> 4; + int sumi0 = 0, sumi1 = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300))); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + int& acc = l0 < 4 ? sumi0 : sumi1; + if constexpr (SG == 1) { + const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4); + acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc); + acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc); + acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); + } else { + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0); + const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1); + acc = ggml_cuda_dp4a(grid_l, u0, acc); + acc = ggml_cuda_dp4a(grid_h, u1, acc); + } + } + const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4; + const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} }; +template struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, + const uint32_t* grid) { + const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx; + const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* q3 = (const uint8_t*) &q3_packed; + const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2); + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]); + const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2)); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + if constexpr (SG == 1) { + const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4); + sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi); + sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi); + sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); + } else { + const int signs0 = __vcmpne4(signs & 0x08040201, 0); + const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); + const int signs1 = __vcmpne4(signs & 0x80402010, 0); + const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); + sumi = ggml_cuda_dp4a(grid_l, u0, sumi); + sumi = ggml_cuda_dp4a(grid_h, u1, sumi); + } + } + const int ls = aux32 >> 28; + sumi = (ls * sumi + sumi / 2) / 2; + const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} }; +template struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, + const uint32_t* grid) { + const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx; + const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1)); + const uint8_t* qs = (const uint8_t*) &qs_packed; + const int qh = bq3->qh[iqs / 2]; + const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2); + const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32; + int sumi = 0; +#pragma unroll + for (int l0 = 0; l0 < 8; l0 += 2) { + const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)], + grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]); + const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0); + const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1); + if constexpr (SG == 1) { + const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4); + sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi); + sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi); + sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0)); + } else { + const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000); + const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000); + const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0); + const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1); + sumi = ggml_cuda_dp4a(grid_l, u0, sumi); + sumi = ggml_cuda_dp4a(grid_h, u1, sumi); + } + } + sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F); + const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds); + return d * sumi; +} }; + +template struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs, + const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } }; + +constexpr int LDS_RB = 64; // gate/up rows per block (4 R2 passes of 16) +constexpr int LDS_NT = 4; // entries whose activations sit in LDS at once + +template +__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + float* __restrict__ gate, float* __restrict__ up) { + using GT = typename GridOf::T; + using F = Fmt; + __shared__ GT sgrid[GridOf::N]; + extern __shared__ int sx_raw[]; // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each) + const int g = blockIdx.y; + if (g >= *n_groups) return; // uniform over the block + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const GT* gsrc = GridOf::src(); + for (int i = tid; i < GridOf::N; i += 256) sgrid[i] = gsrc[i]; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nrow = 2 * (int) L.n_ff; + const block_q8_1* sx = (const block_q8_1*) sx_raw; + auto wrow = [&](int row) -> const uint8_t* { + const bool is_up = row >= L.n_ff; + return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row; + }; + auto put = [&](int row, int e, float v) { + const bool is_up = row >= L.n_ff; + (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v; + }; + for (int c0 = e0; c0 < e1; c0 += LDS_NT) { + const int cn = min(LDS_NT, e1 - c0); + __syncthreads(); + for (int j = 0; j < cn; ++j) { + const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb); + for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i]; + } + __syncthreads(); + for (int p = 0; p < LDS_RB / 16; ++p) { + const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8; + if (row0 >= nrow) break; + const bool two = row1 < nrow; + const uint8_t* w0 = wrow(row0); + const uint8_t* w1 = wrow(two ? row1 : row0); + if constexpr (TI) { // mode 7: the tokens inside the k loop - one weight load per k for all of them + auto pass = [&](auto ntc) { + constexpr int NTC = decltype(ntc)::value; + float s0[NTC], s1[NTC]; +#pragma unroll + for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32); + const float a = DotG::f(w0, xk, kbx, iqs, sgrid); + const float b = DotG::f(w1, xk, kbx, iqs, sgrid); + s0[j] += a; + s1[j] += b; + } + } +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); + if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); } + } + }; + switch (cn) { + case 1: pass(std::integral_constant{}); break; + case 2: pass(std::integral_constant{}); break; + case 3: pass(std::integral_constant{}); break; + default: pass(std::integral_constant{}); break; + } + continue; + } + for (int j = 0; j < cn; ++j) { + const block_q8_1* x = sx + (size_t) j * xb; + float s0 = 0.0f, s1 = 0.0f; + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); + const block_q8_1* xk = x + kbx * (F::qk / 32); + const float a = DotG::f(w0, xk, kbx, iqs, sgrid); + const float b = DotG::f(w1, xk, kbx, iqs, sgrid); + s0 += a; + s1 += b; + } + s0 = warp_sum(s0); + s1 = warp_sum(s1); + if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); } + } + } + } +} + +// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 - +// the same per-(row, entry) sums in the same order: bitwise the mode-2 output. +template +__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, NativeExpertLayout L, + float* __restrict__ out) { + using F = Fmt; + extern __shared__ int sh_raw[]; // LDS_NT entries x hb blocks of q8_1 + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int nrow = (int) L.n_embd; + const block_q8_1* sh = (const block_q8_1*) sh_raw; + for (int c0 = e0; c0 < e1; c0 += LDS_NT) { + const int cn = min(LDS_NT, e1 - c0); + __syncthreads(); + { + const int* src = (const int*) (hq + (size_t) c0 * hb); // the chunk's entries are contiguous + for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i]; + } + __syncthreads(); + for (int p = 0; p < LDS_RB / 16; ++p) { + const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8; + if (r0 >= nrow) break; + const bool two = r1 < nrow; + const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row; + const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row; + auto pass = [&](auto ntc) { + constexpr int NTC = decltype(ntc)::value; + float s0[NTC], s1[NTC]; +#pragma unroll + for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32); + const float a = F::dot(w0, xk, kbx, iqs); + const float b = F::dot(w1, xk, kbx, iqs); + s0[j] += a; + s1[j] += b; + } + } +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); + if (lane == 0) { + out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a; + if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b; + } + } + }; + switch (cn) { + case 1: pass(std::integral_constant{}); break; + case 2: pass(std::integral_constant{}); break; + case 3: pass(std::integral_constant{}); break; + default: pass(std::integral_constant{}); break; + } + } + } +} + +// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue. A block takes h rows +// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so +// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it - +// bitwise the separate kernels' hq, two launches fewer per call. +template +__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, NativeExpertLayout L, + block_q8_1* __restrict__ hq) { + using GT = typename GridOf::T; + using F = Fmt; + __shared__ GT sgrid[GridOf::N]; + __shared__ float res[LDS_NT][64]; + extern __shared__ int sx_raw[]; + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const GT* gsrc = GridOf::src(); + for (int i = tid; i < GridOf::N; i += 256) sgrid[i] = gsrc[i]; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + const int r0 = blockIdx.x * 32; + const block_q8_1* sx = (const block_q8_1*) sx_raw; + auto wrow = [&](int i) -> const uint8_t* { // i < 32: gate row r0 + i, else up row r0 + i - 32 + return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row; + }; + for (int c0 = e0; c0 < e1; c0 += LDS_NT) { + const int cn = min(LDS_NT, e1 - c0); + __syncthreads(); + for (int j = 0; j < cn; ++j) { + const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb); + for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i]; + } + __syncthreads(); + for (int p = 0; p < 4; ++p) { + const int i0 = p * 16 + warp, i1 = i0 + 8; + const uint8_t* w0 = wrow(i0); + const uint8_t* w1 = wrow(i1); + auto pass = [&](auto ntc) { + constexpr int NTC = decltype(ntc)::value; + float s0[NTC], s1[NTC]; +#pragma unroll + for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; } + for (int k = lane; k < nb * F::ipb; k += 32) { + const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb); +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32); + const float a = DotG::f(w0, xk, kbx, iqs, sgrid); + const float b = DotG::f(w1, xk, kbx, iqs, sgrid); + s0[j] += a; + s1[j] += b; + } + } +#pragma unroll + for (int j = 0; j < NTC; ++j) { + const float a = warp_sum(s0[j]), b = warp_sum(s1[j]); + if (lane == 0) { res[j][i0] = a; res[j][i1] = b; } + } + }; + switch (cn) { + case 1: pass(std::integral_constant{}); break; + case 2: pass(std::integral_constant{}); break; + case 3: pass(std::integral_constant{}); break; + default: pass(std::integral_constant{}); break; + } + } + __syncthreads(); + if (warp < cn) { // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry + const float gg = res[warp][lane], uu = res[warp][32 + lane]; + const float xi = (gg / (1.0f + __expf(-gg))) * uu; + float amax = fabsf(xi), sum = xi; +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o)); + sum += __shfl_xor_sync(0xffffffffu, sum, o); + } + const float d = amax / 127.0f; + const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); + block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x; + y->qs[lane] = q; + if (lane == 0) y->ds = make_half2(d, sum); + } + } +} + +int g_exp_mode = -1; // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, default 7 +int exp_mode() { + static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : 7; }(); + return g_exp_mode >= 0 ? g_exp_mode : m; +} +#endif +int g_exp_phase = 0; // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only + +void native_expert_set_mode(int mode, int phase) { +#if defined(STRATA_HIP_GFX906) + g_exp_mode = mode; +#else + (void) mode; +#endif + g_exp_phase = phase; +} + namespace { bool g_grouped_v1 = env_on("STRATA_GROUPED_V1"); } // namespace @@ -1555,15 +2123,74 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long const bool v1 = g_grouped_v1; const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups; const dim3 ggu((unsigned) ((2 * L.n_ff + GU_ROWS - 1) / GU_ROWS), (unsigned) gy); +#if defined(STRATA_HIP_GFX906) + const int em0 = exp_mode(); +#endif +#if defined(STRATA_HIP_GFX906) + const bool fused_gu = em0 == 8 && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) && + L.n_ff % 32 == 0; + if (fused_gu && g_exp_phase != 2) { + const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups); + const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); + switch (L.gu_type) { + case 18: native_gu_fused_kernel<18><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; + case 21: native_gu_fused_kernel<21><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; + case 23: native_gu_fused_kernel<23><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; + default: native_gu_fused_kernel<22><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break; + } + check("native_expert_grouped/gu fused"); + } + if (g_exp_phase != 2 && !fused_gu) { +#else + if (g_exp_phase != 2) { +#endif +#if defined(STRATA_HIP_GFX906) + const bool lds_gu = (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && (L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23); + if (lds_gu) { + const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); + const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1); + switch (L.gu_type) { + case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + } + } else { + const int em = exp_mode() >= 5 ? 2 : exp_mode(); + const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); +#define STRATA_GU_AMD(T) \ + case T: if (em == 1) native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \ + else if (em == 4) native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \ + else native_gu_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; + if (em == 1 || em == 2 || em == 4) { + switch (L.gu_type) { + STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23) + STRATA_GU_AMD(29) STRATA_GU_AMD(42) + default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); + } + } else +#undef STRATA_GU_AMD +#endif switch (L.gu_type) { #define STRATA_GU(T) case T: launch_gu(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break; STRATA_GU_FMTS(STRATA_GU) #undef STRATA_GU default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1); } +#if defined(STRATA_HIP_GFX906) + } +#endif check("native_expert_grouped/gu"); const long long nh = (long long) cap_entries * L.n_ff; - if (v1) { +#if defined(STRATA_HIP_GFX906) + // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass + // kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1 + static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED"); + const bool sw_v1 = v1 || !sw_fused; +#else + const bool sw_v1 = v1; +#endif + if (sw_v1) { swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh); quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh); } else { @@ -1571,7 +2198,32 @@ void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long (int) L.n_ff, hq); } check("native_expert_grouped/swiglu"); + } + if (g_exp_phase == 1) return; const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) gy); +#if defined(STRATA_HIP_GFX906) + if ((em0 == 7 || em0 == 8) && (L.d_type == 20 || L.d_type == 42)) { + const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups); + const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1); + if (L.d_type == 20) native_down_lds_kernel<20><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + else native_down_lds_kernel<42><<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); + check("native_expert_grouped/down"); + return; + } + const int em = exp_mode() >= 5 ? 2 : exp_mode(); + const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups); +#define STRATA_D_AMD(T) \ + case T: if (em == 1) native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ + else if (em == 4) native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ + else native_down_amd_kernel<<>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; + if (em == 1 || em == 2 || em == 4) { + switch (L.d_type) { + STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42) + default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1); + } + } else +#undef STRATA_D_AMD +#endif switch (L.d_type) { #define STRATA_DOWN(T) case T: launch_down(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break; STRATA_D_FMTS(STRATA_DOWN) diff --git a/src/kernels/cuda/native_mmvq.cu b/src/kernels/cuda/native_mmvq.cu index 84748179..c17862e2 100644 --- a/src/kernels/cuda/native_mmvq.cu +++ b/src/kernels/cuda/native_mmvq.cu @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -418,6 +419,17 @@ __device__ __align__(4) int8_t iq4nl_values[16] = { }; __device__ __forceinline__ int2 iq4_table_lookup(int q4) { +#if defined(STRATA_HIP_GFX906) + // AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values + const uint32_t* v32 = reinterpret_cast(iq4nl_values); + const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4; + const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u); + const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u); + const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u); + const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u); + return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)), + (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1))); +#else const uint32_t* table32 = reinterpret_cast(iq4nl_values); uint32_t tmp[2]; const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1); @@ -429,6 +441,7 @@ __device__ __forceinline__ int2 iq4_table_lookup(int q4) { tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift); } return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531)); +#endif } // Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock, @@ -1099,6 +1112,77 @@ void launch_check() { } } + +#if defined(STRATA_HIP_GFX906) +// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the +// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane +// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per +// 2 KB row spent most of its time being launched and joined. The SAME kernel serves every column count 1..8, so a +// column's sums do not depend on how many columns (verify tokens) ride along. STRATA_MMVQ_WAVE=0: the CUDA layout. +bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0"; +template +__launch_bounds__(256) +__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x, + float* __restrict__ y, int n_in, int n_out) { + constexpr int BPIW = 64 / F::T; + static_assert(64 % F::T == 0, "a block's threads must tile the wavefront"); + const int lane = int(threadIdx.x) & 63; + const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R; + if (row0 >= n_out) return; + const int blocks_per_row = n_in / F::DIV; + const int x_stride = n_in / Q8K; + const int kqs = F::kqs(lane); + float tmp[NCOLS][R] = {}; + for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) { + const int kby = kbx * F::KBY; +#pragma unroll + for (int i = 0; i < R; ++i) { + if (row0 + i < n_out) { + const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs); +#pragma unroll + for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs); + } + } + } +#pragma unroll + for (int j = 0; j < NCOLS; ++j) +#pragma unroll + for (int i = 0; i < R; ++i) { + float v = tmp[j][i]; +#pragma unroll + for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64); + if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v; + } +} +template +void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) { + const auto* w = static_cast(weights); + const auto* x = static_cast(x_q8_1); + constexpr int R = 1; + const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R)); + native_mmvq_wave_kernel<<>>(w, x, y, n_in, n_out); +} +template +void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { + const auto s = static_cast(stream); + switch (ncols) { + case 1: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 2: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 3: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 4: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 5: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 6: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 7: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + case 8: wave_launch_n(weights, x_q8_1, y, n_in, n_out, s); break; + default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8"); + } +} +#define STRATA_WAVE_MMVQ(...) \ + if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; } +#else +#define STRATA_WAVE_MMVQ(...) +#endif + template void small_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) { @@ -1108,6 +1192,7 @@ void small_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(SmallTraits) if (ncols > 1) { launch_multi>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1172,6 +1257,7 @@ void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(Q5KTraits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1212,6 +1298,7 @@ void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(Q20Traits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1251,6 +1338,7 @@ void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(Q3KTraits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1290,6 +1378,7 @@ void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(IQ4XSTraits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1329,6 +1418,7 @@ void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(Q4KTraits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); @@ -1368,6 +1458,7 @@ void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y, validate_pointer(x_q8_1); validate_pointer(y); validate_stream(stream); + STRATA_WAVE_MMVQ(Q6KTraits) if (ncols > 1) { launch_multi(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); diff --git a/src/kernels/cuda/qsa_prompt_attn.cu b/src/kernels/cuda/qsa_prompt_attn.cu index 8062176c..9b481929 100644 --- a/src/kernels/cuda/qsa_prompt_attn.cu +++ b/src/kernels/cuda/qsa_prompt_attn.cu @@ -1412,6 +1412,9 @@ bool qsa_prompt_attn_batch(const float* q, const QsaAttnPools& pools, const int3 // no cp.async, so it runs the v1 kernel (launch<1>, same accuracy, another summation order). An older card // keeps the old kernel. // #371: the compute capability with its minor - sm_70 (V100) has no m16n8k8 (the kernels trap below sm_75) +#if defined(STRATA_HIP_GFX906) + return false; // gfx906: the tensor-core and WMMA kernels are not for it; the FP32 kernel runs +#endif static int cc[64] = {}; int dev = 0; if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; } diff --git a/src/kernels/cuda/router_top10.cu b/src/kernels/cuda/router_top10.cu index f23a63d7..720cec67 100644 --- a/src/kernels/cuda/router_top10.cu +++ b/src/kernels/cuda/router_top10.cu @@ -186,6 +186,83 @@ __global__ void router_top10_kernel(const float* __restrict__ logits, int n_toke } } + +#if defined(STRATA_HIP_GFX906) +// AMD (wave64): the same routing in ONE wavefront per token. The block-wide kernel above spends its time in +// barriers - 10 selection passes with two __syncthreads each over 8 logical warps - not in arithmetic (43 us per +// token on gfx906). Here every lane holds up to RW_PER probabilities in registers and each pass is a 64-lane +// butterfly argmax: no LDS round trip, no block barrier. Bit-identical to the kernel above: fmaxf trees are +// exact, the exponentials and the (float) products are the same expressions, the sum stays one serial ascending +// scan, and the argmax keeps the lowest index on a tie (a total order, so the butterfly's association is free). +constexpr int RW_PER = 8; // n_expert <= 64 * 8 +__global__ void __launch_bounds__(64) router_top10_wave_kernel(const float* __restrict__ logits, int n_tokens, + int n_expert, int k, int* __restrict__ ids, + float* __restrict__ weights) { + __shared__ double s_ex[64 * RW_PER]; + __shared__ double s_sum; + const int t = blockIdx.x; + if (t >= n_tokens) return; + const int lane = threadIdx.x; + const float* l = logits + (size_t) t * n_expert; + float lv[RW_PER]; + float mx = -INFINITY; +#pragma unroll + for (int j = 0; j < RW_PER; ++j) { + const int e = lane + 64 * j; + lv[j] = e < n_expert ? l[e] : -INFINITY; + mx = fmaxf(mx, lv[j]); + } +#pragma unroll + for (int off = 32; off > 0; off >>= 1) mx = fmaxf(mx, __shfl_xor(mx, off, 64)); +#pragma unroll + for (int j = 0; j < RW_PER; ++j) { + const int e = lane + 64 * j; + if (e < n_expert) s_ex[e] = exp((double) lv[j] - (double) mx); + } + __syncthreads(); + if (lane == 0) { + double sum = 0.0; + for (int e = 0; e < n_expert; ++e) sum += s_ex[e]; + s_sum = sum; + } + __syncthreads(); + const float inv = (float) (1.0 / s_sum); + float p[RW_PER]; +#pragma unroll + for (int j = 0; j < RW_PER; ++j) { + const int e = lane + 64 * j; + p[j] = e < n_expert ? (float) (s_ex[e] * inv) : -INFINITY; + } + unsigned taken = 0; + for (int i = 0; i < k; ++i) { + float bv = -INFINITY; + int bi = n_expert; +#pragma unroll + for (int j = 0; j < RW_PER; ++j) { + const int e = lane + 64 * j; + if (e >= n_expert || (taken >> j & 1u)) continue; + if (p[j] > bv || (p[j] == bv && e < bi)) { bv = p[j]; bi = e; } + } +#pragma unroll + for (int off = 32; off > 0; off >>= 1) { + const float ov = __shfl_xor(bv, off, 64); + const int oi = __shfl_xor(bi, off, 64); + if (ov > bv || (ov == bv && oi < bi)) { bv = ov; bi = oi; } + } + if (bi >= n_expert) break; + if ((bi & 63) == lane) taken |= 1u << (bi >> 6); + if (lane == 0) { ids[(size_t) t * k + i] = bi; weights[(size_t) t * k + i] = bv; } + } + if (lane == 0) { + double s = 0.0; + for (int i = 0; i < k; ++i) s += (double) weights[(size_t) t * k + i]; + const double sc = fmax(s, 6.103515625e-05); // 2**-14 + for (int i = 0; i < k; ++i) + weights[(size_t) t * k + i] = (float) ((double) weights[(size_t) t * k + i] / sc); + } +} +#endif // STRATA_HIP_GFX906 + #if defined(__HIPCC__) // ---- S6, AMD: the same router, BIT-IDENTICAL, without its serial parts. Measured on RDNA4 (gfx1201) the kernel // above took 39 us per call in decode (16% of the GPU's decode time): the ascending double sum is 512 dependent FP64 @@ -346,7 +423,13 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i void* stream) { #if defined(__HIPCC__) { +#if defined(STRATA_HIP_GFX906) + // gfx906 (wave64): the one-wavefront kernel below stays the default; the S6 kernel is wave32-shaped and only + // runs here on request (STRATA_HIP_ROUTER_FAST=1) until it is measured on this card + static const bool old = std::getenv("STRATA_HIP_ROUTER_FAST") == nullptr; +#else static const bool old = std::getenv("STRATA_HIP_ROUTER_OLD") != nullptr; +#endif if (!old && n_tokens > 0 && n_expert > 64 && n_expert <= 512 && k > 0 && k <= 32) { launch_generic(logits, n_tokens, n_expert, k, ids, weights, stream, 1); const cudaError_t e = cudaGetLastError(); @@ -375,6 +458,19 @@ void router_top10(const float* logits, int n_tokens, int n_expert, int k, int* i RT_MAX_THREADS * 64); std::exit(1); } +#if defined(STRATA_HIP_GFX906) + if (n_expert <= 64 * RW_PER && !std::getenv("STRATA_ROUTER_BLOCK")) { + router_top10_wave_kernel<<<(unsigned) n_tokens, 64, 0, (cudaStream_t) stream>>>(logits, n_tokens, n_expert, k, + ids, weights); + const cudaError_t e = cudaGetLastError(); + if (e != cudaSuccess) { + std::fprintf(stderr, "router_top10 launch: %s\n", cudaGetErrorString(e)); + std::exit(1); + } + if (stream == nullptr && cudaDeviceSynchronize() != cudaSuccess) std::exit(1); + return; + } +#endif int threads = n_expert < RT_MAX_THREADS ? n_expert : RT_MAX_THREADS; threads = (threads + 31) & ~31; // at least one full warp, for the reductions // the selection's taken-mask, then n_expert doubles for the exponentials, then n_expert floats for the diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 7908ce40..e81d211f 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -545,7 +545,9 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i // a GPU timestamp (ns, %globaltimer) into buf[i] - the verify window's stage profiler namespace { __global__ void gpu_stamp_kernel(unsigned long long* buf, int i) { unsigned long long t; -#if defined(__HIPCC__) +#if defined(STRATA_HIP_GFX906) + t = wall_clock64() * 40ull; // gfx906: the wall clock runs at 25 MHz (hipDeviceAttributeWallClockRate) -> ns +#elif defined(__HIPCC__) t = wall_clock64() * 10ull; // gfx10.3 / gfx11 / gfx12: a constant 100 MHz counter, in ns #else asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); diff --git a/src/kernels/fused_gr_bench.cpp b/src/kernels/fused_gr_bench.cpp new file mode 100644 index 00000000..b7b8452f --- /dev/null +++ b/src/kernels/fused_gr_bench.cpp @@ -0,0 +1,116 @@ +// src/kernels/fused_gr_bench.cpp - fused_gr_read_multi: the AMD fast kernels (STRATA_GR_FAST) against the old +// ones, bit for bit on every output (lo, rs, inject, mixed, the in-place R), and each one's time. +// +// build/fused_gr_bench [iters] [T min] [T max] +#include "strata/kernels/fused_gr.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace K = strata::kernels; + +static uint16_t bf16(float x) { + uint32_t u; + std::memcpy(&u, &x, 4); + return (uint16_t) ((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + const int iters = argc > 1 ? std::atoi(argv[1]) : 500; + const int t_lo = argc > 2 ? std::atoi(argv[2]) : 1, t_hi = argc > 3 ? std::atoi(argv[3]) : 6; + const int N = 2560, HC = 4, D = N * HC, LR = 320, TM = K::kFusedGrMaxT; + std::mt19937 rng(7); + std::normal_distribution nd(0.f, 1.f); + auto fill = [&](std::vector& v, float sc) { for (auto& x : v) x = sc * nd(rng); }; + std::vector R((size_t) TM * D), bo((size_t) TM * N), inj((size_t) TM * HC), wn(D); + fill(R, 1.0f); fill(bo, 0.5f); fill(inj, 1.0f); fill(wn, 0.3f); + for (auto& x : wn) x += 1.0f; + std::vector wd((size_t) LR * D), wu((size_t) D * LR), wi((size_t) HC * D); + for (auto& x : wd) x = bf16(0.02f * nd(rng)); + for (auto& x : wu) x = bf16(0.05f * nd(rng)); + for (auto& x : wi) x = bf16(0.02f * nd(rng)); + float *dR, *dbo, *dinj, *dwn, *dxn, *dlo, *drs, *dio, *dmix; + uint16_t *dwd, *dwu, *dwi; + cudaMalloc((void**) &dR, R.size() * 4); + cudaMalloc((void**) &dbo, bo.size() * 4); + cudaMalloc((void**) &dinj, inj.size() * 4); + cudaMalloc((void**) &dwn, wn.size() * 4); + cudaMalloc((void**) &dxn, (size_t) TM * D * 4); + cudaMalloc((void**) &dlo, (size_t) TM * LR * 4); + cudaMalloc((void**) &drs, (size_t) TM * HC * 4); + cudaMalloc((void**) &dio, (size_t) TM * HC * 4); + cudaMalloc((void**) &dmix, (size_t) TM * N * 4); + cudaMalloc((void**) &dwd, wd.size() * 2); + cudaMalloc((void**) &dwu, wu.size() * 2); + cudaMalloc((void**) &dwi, wi.size() * 2); + cudaMemcpy(dbo, bo.data(), bo.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dinj, inj.data(), inj.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dwn, wn.data(), wn.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dwd, wd.data(), wd.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(dwu, wu.data(), wu.size() * 2, cudaMemcpyHostToDevice); + cudaMemcpy(dwi, wi.data(), wi.size() * 2, cudaMemcpyHostToDevice); + cudaStream_t s; + cudaStreamCreate(&s); + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + int failures = 0; + for (int T = t_lo; T <= t_hi; ++T) + for (int apply = 0; apply < 2; ++apply) + for (int inject = 0; inject < 2; ++inject) { + K::FusedGrArgs a[TM]; + for (int t = 0; t < T; ++t) { + a[t].R = dR + (size_t) t * D; a[t].R_out = dR + (size_t) t * D; a[t].apply = apply; + a[t].bo_prev = dbo + (size_t) t * N; a[t].inj_prev = dinj + (size_t) t * HC; + a[t].w_norm = dwn; a[t].w_down = dwd; a[t].w_up = dwu; a[t].w_inject = inject ? dwi : nullptr; + a[t].lo = dlo + (size_t) t * LR; a[t].rs = drs + (size_t) t * HC; + a[t].inject_out = dio + (size_t) t * HC; a[t].mixed = dmix + (size_t) t * N; + } + std::vector out[2]; + for (int f = 0; f < 2; ++f) { + cudaMemcpy(dR, R.data(), R.size() * 4, cudaMemcpyHostToDevice); + cudaMemset(dlo, 0xff, (size_t) TM * LR * 4); + cudaMemset(drs, 0xff, (size_t) TM * HC * 4); + cudaMemset(dio, 0xff, (size_t) TM * HC * 4); + cudaMemset(dmix, 0xff, (size_t) TM * N * 4); + K::fused_gr_set_fast(f); + K::fused_gr_read_multi(a, T, dxn, s); + cudaStreamSynchronize(s); + auto& o = out[f]; + o.resize((size_t) TM * (D + LR + HC + HC + N)); + float* p = o.data(); + cudaMemcpy(p, dR, (size_t) TM * D * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * D; + cudaMemcpy(p, dlo, (size_t) TM * LR * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * LR; + cudaMemcpy(p, drs, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC; + cudaMemcpy(p, dio, (size_t) TM * HC * 4, cudaMemcpyDeviceToHost); p += (size_t) TM * HC; + cudaMemcpy(p, dmix, (size_t) TM * N * 4, cudaMemcpyDeviceToHost); + } + const bool same = std::memcmp(out[0].data(), out[1].data(), out[0].size() * 4) == 0; + double us[2] = {1e30, 1e30}; + for (int round = 0; round < 3; ++round) + for (int f = 0; f < 2; ++f) { + K::fused_gr_set_fast(f); + for (int i = 0; i < 20; ++i) K::fused_gr_read_multi(a, T, dxn, s); + cudaEventRecord(e0, s); + for (int i = 0; i < iters; ++i) K::fused_gr_read_multi(a, T, dxn, s); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + us[f] = std::fmin(us[f], 1e3 * ms / iters); + } + std::printf("T %d apply %d inject %d | old %6.1f us fast %6.1f us | %s\n", T, apply, inject, us[0], us[1], + same ? "bitwise equal" : "DIFFERS"); + if (!same) ++failures; + } + std::printf("fused_gr_bench: %d differing\n", failures); + return failures ? 1 : 0; +} diff --git a/src/kernels/native_expert_bench.cpp b/src/kernels/native_expert_bench.cpp new file mode 100644 index 00000000..7f16e220 --- /dev/null +++ b/src/kernels/native_expert_bench.cpp @@ -0,0 +1,170 @@ +// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against +// another, bit for bit, and each one's time. +// +// build/native_expert_bench [iters] +// +// Modes are STRATA_EXP_MODE values. A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit +// in L2); its entries read distinct tokens of an 8-token window. The output must be bitwise equal to the +// reference mode's: the verify window's text depends on it. +#include "strata/artifact/gguf_reader.hpp" +#include "strata/kernels/cpu/native_expert.hpp" +#include "strata/kernels/iq_kernels.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; +namespace K = strata::kernels; + +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + if (argc < 7) { + std::fprintf(stderr, "usage: native_expert_bench [iters]\n"); + return 2; + } + strata::GgufFile gguf(argv[1]); + std::vector layers; + { + std::stringstream ss(argv[2]); + std::string t; + while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str())); + } + const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]); + const int iters = argc > 7 ? std::atoi(argv[7]) : 200; + const int NTOK = 8; + if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; } + const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL; // Flash-Next's expert geometry + int failures = 0; + cudaStream_t s; + cudaStreamCreate(&s); + cudaEvent_t e0, e1; + cudaEventCreate(&e0); + cudaEventCreate(&e1); + for (int l : layers) { + const strata::TensorInfo* t[3] = {}; + const char* roles[3] = {"gate", "up", "down"}; + for (const auto& ti : gguf.tensors()) + for (int r = 0; r < 3; ++r) + if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti; + if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; } + cpu::NativeFmt f; + std::string err; + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; + } + cpu::NativeFmt ff; // the full expert's geometry, for strides into the GGUF + if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) { + std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue; + } + const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off; + const size_t drow = dsz / H, drow_full = dsz_full / H; + std::vector blobs((size_t) G * f.bytes); + for (int g = 0; g < G; ++g) { + const size_t E = (size_t) ((g * 37 + 5) % 256); + uint8_t* b = blobs.data() + (size_t) g * f.bytes; + std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off); + std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off); + for (int64_t r = 0; r < H; ++r) + std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow); + } + std::mt19937 rng(17 + l); + std::normal_distribution nd(0.f, 1.f); + std::vector x((size_t) NTOK * H); + for (auto& v : x) v = nd(rng); + const int NE = G * T; + std::vector ptr(G); + std::vector start(G + 1), dst(NE), tok(NE); + const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF); + uint8_t* dblob; + void *dx, *dxq, *dscr; + float* dout; + unsigned long long* dptr; + int32_t *dstart, *dn, *ddst, *dtok; + cudaMalloc((void**) &dblob, blobs.size()); + cudaMalloc(&dx, x.size() * 4); + cudaMalloc(&dxq, (size_t) NTOK * H / 32 * 36); + cudaMalloc(&dscr, K::native_expert_scratch_bytes(NE, FF)); + cudaMalloc((void**) &dout, (size_t) NE * H * 4); + cudaMalloc((void**) &dptr, (size_t) G * 8); + cudaMalloc((void**) &dstart, (size_t) (G + 1) * 4); + cudaMalloc((void**) &dn, 4); + cudaMalloc((void**) &ddst, (size_t) NE * 4); + cudaMalloc((void**) &dtok, (size_t) NE * 4); + for (int g = 0; g < G; ++g) { + ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes); + start[g] = g * T; + for (int j = 0; j < T; ++j) { + dst[g * T + j] = g * T + j; + tok[g * T + j] = (g * 3 + j) % NTOK; + } + } + start[G] = NE; + cudaMemcpy(dblob, blobs.data(), blobs.size(), cudaMemcpyHostToDevice); + cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dptr, ptr.data(), (size_t) G * 8, cudaMemcpyHostToDevice); + cudaMemcpy(dstart, start.data(), (size_t) (G + 1) * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dn, &G, 4, cudaMemcpyHostToDevice); + cudaMemcpy(ddst, dst.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); + cudaMemcpy(dtok, tok.data(), (size_t) NE * 4, cudaMemcpyHostToDevice); + K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s); + auto run = [&](int m, int phase) { + K::native_expert_set_mode(m, phase); + K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s); + }; + std::vector ref((size_t) NE * H), got((size_t) NE * H); + cudaMemsetAsync(dout, 0xff, got.size() * 4, s); + run(mref, 0); + cudaMemcpyAsync(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost, s); + cudaMemsetAsync(dout, 0xff, got.size() * 4, s); + run(mode, 0); + cudaMemcpyAsync(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost, s); + if (cudaStreamSynchronize(s) != cudaSuccess) { std::printf("layer %d: CUDA error\n", l); return 1; } + size_t ndiff = 0; + double worst = 0; + for (size_t i = 0; i < ref.size(); ++i) + if (std::memcmp(&ref[i], &got[i], 4) != 0) { + ++ndiff; + worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6)); + } + auto time = [&](int m, int phase) { + for (int i = 0; i < 10; ++i) run(m, phase); + cudaEventRecord(e0, s); + for (int i = 0; i < iters; ++i) run(m, phase); + cudaEventRecord(e1, s); + cudaEventSynchronize(e1); + float ms = 0; + cudaEventElapsedTime(&ms, e0, e1); + return 1e3 * ms / iters; + }; + const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz; + double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}}; + for (int round = 0; round < 3; ++round) // interleaved, the minimum: the clocks wander between runs + for (int k = 0; k < 2; ++k) + for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p)); + std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s)" + " | mode %d: all %7.1f us gu %7.1f us (%3.0f GB/s) down %6.1f us (%3.0f GB/s) | %s\n", + l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T, + mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3, + mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3, + ndiff ? "DIFFERS" : "bitwise equal"); + if (ndiff) { + std::printf(" %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst); + ++failures; + } + K::native_expert_set_mode(-1, 0); + cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr); + cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok); + } + std::printf("native_expert_bench: %d differing\n", failures); + return failures ? 1 : 0; +} diff --git a/src/prefill/moe_fused.cu b/src/prefill/moe_fused.cu index b5f9a1c8..19d1c949 100644 --- a/src/prefill/moe_fused.cu +++ b/src/prefill/moe_fused.cu @@ -364,6 +364,11 @@ const DevInfo& dev_info() { DevInfo& d = g_dev[dev & 31]; if (d.done) return d; d.done = true; +#if defined(STRATA_HIP_GFX906) + // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and + // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) + return d; +#else int major = 0, minor = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev); @@ -385,6 +390,7 @@ const DevInfo& dev_info() { cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel, THREADS, smem_bytes(false)); if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0; // does not fit this card: the MMQ path cudaGetLastError(); +#endif return d; } diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 52476c87..b2d99086 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -516,6 +516,7 @@ struct DevInfo { std::mutex g_mu; DevInfo g_dev[32]; +#if !defined(STRATA_HIP_GFX906) template bool setup_ww(int& occ) { cudaFuncAttributes fa{}; if (cudaFuncGetAttributes(&fa, native_kernel) != cudaSuccess || fa.ptxVersion < 80) return false; @@ -530,6 +531,7 @@ template bool setup_ww(int& occ) { return true; } template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } +#endif const DevInfo& dev_info() { int dev = 0; @@ -538,6 +540,11 @@ const DevInfo& dev_info() { DevInfo& d = g_dev[dev & 31]; if (d.done) return d; d.done = true; +#if defined(STRATA_HIP_GFX906) + // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and + // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs) + return d; +#else int major = 0; cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); @@ -548,6 +555,7 @@ const DevInfo& dev_info() { setup_one(occ) && setup_one(occ); d.occ = d.ok ? occ : 1; cudaGetLastError(); +#endif return d; } diff --git a/src/program/generate.cpp b/src/program/generate.cpp index b9a4440c..6c6945be 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2963,6 +2963,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: GPU %d: %s, compute capability %d.%d%s\n", dev, name, strata::cc_major_of(p.major), strata::cc_minor_of(p.minor), strata::emulated_cc() ? " (STRATA_EMULATE_CC: a test mode, the card is emulated)" : ""); +#if !defined(STRATA_HIP_GFX906) // a CUDA toolkit mismatch; the gfx906 HIP build has no CUDART_VERSION { // #542: a build whose libcudart is older than its headers (a CUDA 13 kit with a dangling libcudart.so that // CMake resolved to the system's CUDA 12 one) reads cudaDeviceProp shifted - silently, and slowly int rt = 0; @@ -2973,6 +2974,7 @@ int main(int argc, char** argv) { "toolkit>, with its libcudart.so present) (#542)\n", CUDART_VERSION / 1000, CUDART_VERSION % 1000 / 10, rt / 1000, rt % 1000 / 10); } +#endif #endif const std::string e = strata::core::device_code_error(); if (!e.empty()) {