Merge branch 'f-139b-old' into f-139-rel

# Conflicts:
#	setup.py
This commit is contained in:
Niko1221 committed 2026-10-04 10:12:13 +02:00
commit bd34d0d87e
65 files changed
+6759 -123

No files matched your search

+3
View File
@@ -168,6 +168,9 @@ bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer,
/// rung, so a host that sees it knows `h_x_f`/`h_ids`/`h_weights` are in place.
bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, void* stream, std::string& err, const Doorbell* db = nullptr);
/// The verify window's n tokens routed at once (see layer.cpp); bitwise per token what `moe_route` gives.
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err);
/// The finishing half: the shared expert and the combination.
///
+41
View File
@@ -1,5 +1,45 @@
#pragma once
#include <hipblas/hipblas.h>
#include <hipblas/hipblas-version.h>
#if hipblasVersionMajor == 0
// Ubuntu's hipBLAS 0.54 has no workspace API or compute-type enum. Use its
// underlying rocBLAS API directly, including ownership of the real handle,
// so the engine's explicit workspace contract is preserved.
#include <rocblas/rocblas.h>
#define CUBLAS_COMPUTE_32F rocblas_datatype_f32_r
#define CUBLAS_DEFAULT_MATH 0
#define CUBLAS_GEMM_DEFAULT rocblas_gemm_algo_standard
#define CUBLAS_OP_N rocblas_operation_none
#define CUBLAS_OP_T rocblas_operation_transpose
#define CUBLAS_STATUS_SUCCESS rocblas_status_success
#define CUDA_R_16BF rocblas_datatype_bf16_r
#define CUDA_R_16F rocblas_datatype_f16_r
#define CUDA_R_32F rocblas_datatype_f32_r
#define cublasCreate rocblas_create_handle
#define cublasDestroy rocblas_destroy_handle
#define cublasHandle_t rocblas_handle
#define cublasSetStream rocblas_set_stream
#define cublasSetWorkspace rocblas_set_workspace
#define cublasStatus_t rocblas_status
inline rocblas_status cublasSetMathMode(rocblas_handle h, int mode) {
// This API has only its default arithmetic; GEMM below explicitly selects
// FP32 accumulation. Reject any request for a different math mode.
if (!h) return rocblas_status_invalid_handle;
return mode == CUBLAS_DEFAULT_MATH ? rocblas_status_success : rocblas_status_invalid_value;
}
inline rocblas_status cublasGemmEx(rocblas_handle h, rocblas_operation trans_a,
rocblas_operation trans_b, int m, int n, int k, const void* alpha,
const void* a, rocblas_datatype a_type, int lda,
const void* b, rocblas_datatype b_type, int ldb, const void* beta,
void* c, rocblas_datatype c_type, int ldc,
rocblas_datatype compute_type, rocblas_gemm_algo algo) {
return rocblas_gemm_ex(h, trans_a, trans_b, m, n, k, alpha,
a, a_type, lda, b, b_type, ldb, beta, c, c_type, ldc,
c, c_type, ldc, compute_type, algo, 0, 0);
}
#else
#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F
#define CUBLAS_DEFAULT_MATH HIPBLAS_DEFAULT_MATH
#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
@@ -17,3 +57,4 @@
#define cublasSetStream hipblasSetStream
#define cublasSetWorkspace hipblasSetWorkspace
#define cublasStatus_t hipblasStatus_t
#endif
+11
View File
@@ -10,6 +10,7 @@
#endif
#endif
#include <hip/hip_runtime.h>
#include <hip/hip_version.h>
// Do not let HIP's legacy macro corrupt libstdc++ attribute names.
#ifdef __noinline__
#undef __noinline__
@@ -39,7 +40,11 @@
#define cudaEventSynchronize hipEventSynchronize
#define cudaEvent_t hipEvent_t
#define cudaFree hipFree
#if HIP_VERSION_MAJOR < 7
#define cudaFreeHost hipHostFree
#else
#define cudaFreeHost hipFreeHost
#endif
#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize
#define cudaGetDevice hipGetDevice
#define cudaGetDeviceCount hipGetDeviceCount
@@ -54,9 +59,15 @@
#define cudaGraphUpload hipGraphUpload
#define cudaGraph_t hipGraph_t
#define cudaHostAlloc hipHostMalloc
#if HIP_VERSION_MAJOR < 7
#define cudaHostAllocDefault hipHostMallocDefault
#define cudaHostAllocMapped hipHostMallocMapped
#define cudaHostAllocPortable hipHostMallocPortable
#else
#define cudaHostAllocDefault hipHostAllocDefault
#define cudaHostAllocMapped hipHostAllocMapped
#define cudaHostAllocPortable hipHostAllocPortable
#endif
#define cudaHostGetDevicePointer hipHostGetDevicePointer
#define cudaHostRegister hipHostRegister
#define cudaHostRegisterMapped hipHostRegisterMapped
+31 -1
View File
@@ -1,8 +1,9 @@
#pragma once
// CUDA device intrinsics used by Strata kernels that HIP does not provide on RDNA2 / RDNA3 / RDNA4 (wave32).
// CUDA device intrinsics used by Strata kernels on supported wave32 HIP targets.
// This header is included only from the HIP cuda_runtime compatibility shim.
#if defined(__HIPCC__)
#include <hip/hip_version.h>
#include <cstdint>
@@ -25,6 +26,21 @@ __device__ __forceinline__ int dp4a(int a, int b, int c) {
// RDNA2 has no sudot4 (that is gfx11+), but it has the plain signed v_dot4_i32_i8 (dot1-insts): the same
// signed x signed byte products accumulated modulo 2^32, no clamp.
return __builtin_amdgcn_sdot4(a, b, c, false);
#elif defined(__gfx1012__) && !defined(STRATA_GFX1012_PORTABLE_DOT)
// RDNA1 has no native signed dot4. SDWA selects and sign-extends byte
// operands directly, avoiding separate shift/mask/sign-extension work.
// Adapted from pinned llama.cpp ggml-cuda/common.cuh (MIT; see
// third_party/ggml/LICENSE), same modulo-2^32 accumulation contract.
int lo, hi;
asm("v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_0 src1_sel:BYTE_0\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_1 src1_sel:BYTE_1\n"
"v_add3_u32 %0, %1, %2, %0\n"
"v_mul_i32_i24 %1, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_2 src1_sel:BYTE_2\n"
"v_mul_i32_i24 %2, sext(%3), sext(%4) dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:BYTE_3 src1_sel:BYTE_3\n"
"v_add3_u32 %0, %1, %2, %0\n"
// c changes before the high-byte reads; it must not alias a or b.
: "+&v"(c), "=&v"(lo), "=&v"(hi) : "v"(a), "v"(b));
return c;
#else
const uint32_t ua = static_cast<uint32_t>(a);
const uint32_t ub = static_cast<uint32_t>(b);
@@ -84,6 +100,17 @@ __device__ __forceinline__ void require_full_wave_mask(uint32_t mask) {
if (mask != 0xffffffffu) __builtin_trap();
}
// Older HIP has no __syncwarp. A wave barrier alone does not order memory.
// Release/acquire fences cover the shared-memory exchange used by attention.
#if HIP_VERSION_MAJOR < 7
__device__ __forceinline__ void syncwarp(uint32_t mask = 0xffffffffu) {
require_full_wave_mask(mask);
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup");
}
#endif
template <typename T>
__device__ __forceinline__ T shfl_xor_sync(uint32_t mask, T value, int lane_mask, int width = 32) {
require_full_wave_mask(mask);
@@ -125,6 +152,9 @@ __device__ __forceinline__ unsigned ballot_sync(uint32_t mask, int predicate) {
#define __shfl_up_sync(...) (::strata::hip_compat::shfl_up_sync(__VA_ARGS__))
#define __shfl_sync(...) (::strata::hip_compat::shfl_sync(__VA_ARGS__))
#define __ballot_sync(mask, predicate) (::strata::hip_compat::ballot_sync((mask), (predicate)))
#if HIP_VERSION_MAJOR < 7
#define __syncwarp(...) (::strata::hip_compat::syncwarp(__VA_ARGS__))
#endif
// AMD's sleep instruction accepts only 0..15; the synchronization loops use it as a
// backoff hint, so use its smallest portable delay independently of CUDA cycle counts.
#define __nanosleep(cycles) __builtin_amdgcn_s_sleep(1)
@@ -0,0 +1,4 @@
#pragma once
// CUDA spelling used by the attention kernels; included only in HIP builds.
#include <hip/hip_math_constants.h>
#define CUDART_INF_F HIP_INF_F
+4
View File
@@ -44,6 +44,10 @@ void bf16_gemv_split(const uint16_t* x, const uint16_t* w, float* y, int64_t n_i
/// No allocations or synchronization, including when stream is null (the CUDA default stream).
void bf16_gemv_fp32_mmvf(const float* x, const uint16_t* w, float* y,
int64_t n_in, int64_t n_out, void* stream);
/// `ncols` columns at once: x is [ncols][n_in], y is [ncols][n_out]; each column bitwise equal to a
/// `bf16_gemv_fp32_mmvf` call on it.
void bf16_gemv_fp32_mmvf_cols(const float* x, const uint16_t* w, float* y, int64_t n_in, int64_t n_out, int ncols,
void* stream);
/// bf16_gemv_fp32_mmvf for n_tok (1..8) activation rows x[t * ldx], outputs y[t * ldy + j]; one launch,
/// the weight read once, every output bit-identical to its own single-row call.
void bf16_gemv_fp32_mmvf_multi(const float* x, int64_t ldx, const uint16_t* w, float* y, int64_t ldy,
+3
View File
@@ -19,6 +19,9 @@
#pragma once
#include <cstdint>
#if defined(STRATA_HIP_GFX906)
#include <cuda_runtime.h> // 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) {
+2
View File
@@ -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
+3
View File
@@ -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.
+3
View File
@@ -15,6 +15,9 @@
#pragma once
#include <cstdint>
#if defined(__HIPCC__) && defined(STRATA_HIP_GFX906) // PR #638: the gfx906 compat build only
#include <hip/hip_runtime.h>
#endif
#include "strata/kernels/rope_scaling.hpp"
@@ -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 <hipblas/hipblas.h>
#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
@@ -0,0 +1,2 @@
#pragma once
#include "strata_hip.h"
@@ -0,0 +1,2 @@
#pragma once
#include "strata_hip.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("")
@@ -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 <hip/hip_runtime.h>
#include <hip/hip_fp16.h>
#include <cstdint>
#include <cstdlib>
#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 <typename T> inline hipError_t strata_host_alloc(T** p, size_t bytes, unsigned int flags) {
return strata_host_alloc(reinterpret_cast<void**>(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<const void*>(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<const int8_t*>(&a);
const int8_t* vb = reinterpret_cast<const int8_t*>(&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<const uint8_t*>(&a);
const uint8_t* vb = reinterpret_cast<const uint8_t*>(&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
+7
View File
@@ -26,6 +26,8 @@ public:
std::string& err);
/// Y[T, N] (fp32, row stride ldy) = X[T, K] (bf16, row-major) . W[N, K]^T (bf16, row-major). `beta` = 1 adds.
/// Below sm_80 (no BF16 tensor cores): Volta converts both to FP16 and runs the FP16 tensor-core GEMM (Turing with
/// STRATA_BF16_TC=1), Pascal widens both to fp32 (cublasSgemm); see gemm.cu.
void bf16(const uint16_t* X, const uint16_t* W, float* Y, int64_t T, int64_t N, int64_t K, int64_t ldy = 0,
float beta = 0.0f);
@@ -52,6 +54,11 @@ private:
void* workspace_ = nullptr;
bool external_ = false;
void* hipblaslt_state_ = nullptr;
// below sm_80: FP16 (Pascal: fp32) copies of a BF16 product's weight and activation slice (Gemm::bf16)
uint16_t* tc_w_ = nullptr;
int64_t tc_w_elems_ = 0;
uint16_t* tc_x_ = nullptr;
int64_t tc_x_elems_ = 0;
};