Skip to content

Distribute and run LLMs with a single file.

Improve accuracy and performance of tinyBLAS

Justine Tunney9c53c272650b
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 3e907432..dcc5e014 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -44,7 +44,7 @@ o/$(MODE)/llamafile: \
o/$(MODE)/llamafile/%.o: llamafile/%.cu llamafile/BUILD.mk
@mkdir -p $(@D)
- build/cudacc -g -O3 -march=native -ffast-math --use_fast_math -c -o $@ $<
+ build/cudacc -g -O3 -march=native -c -o $@ $<
o/$(MODE)/llamafile/tinyblas_test: \
o/$(MODE)/llamafile/tinyblas_test.o \
@@ -57,6 +57,9 @@ o/$(MODE)/llamafile/cudaprops: \
o/$(MODE)/llamafile/tester.o
build/cudacc -g -o $@ $^ -lcublas
+o/$(MODE)/llamafile/pick_a_warp_kernel: private LDFLAGS += -fopenmp
+o/$(MODE)/llamafile/pick_a_warp_kernel.o: private CFLAGS += -fopenmp
+
.PHONY: o/$(MODE)/llamafile/check
o/$(MODE)/llamafile/check: \
o/$(MODE)/llamafile/tinyblas_test.runs
diff --git a/llamafile/cuda.h b/llamafile/cuda.h
index b9791b6e..70c71bb8 100644
--- a/llamafile/cuda.h
+++ b/llamafile/cuda.h
@@ -57,12 +57,15 @@
#define cudaGetDevice hipGetDevice
#define cudaDeviceReset hipDeviceReset
#define cublasGemmEx hipblasGemmEx_v2
+#define cublasGemmStridedBatchedEx hipblasGemmStridedBatchedEx_v2
#define CUDA_R_16F HIP_R_16F
#define CUDA_R_32F HIP_R_32F
+#define CUDA_R_64F HIP_R_64F
#define CUBLAS_OP_N HIPBLAS_OP_N
#define CUBLAS_OP_T HIPBLAS_OP_T
#define CUBLAS_COMPUTE_16F HIPBLAS_COMPUTE_16F
#define CUBLAS_COMPUTE_32F HIPBLAS_COMPUTE_32F
+#define CUBLAS_COMPUTE_64F HIPBLAS_COMPUTE_64F
#define CUBLAS_COMPUTE_32F_FAST_16F HIPBLAS_COMPUTE_32F_FAST_16F
#define CUBLAS_GEMM_DEFAULT HIPBLAS_GEMM_DEFAULT
#define CUBLAS_STATUS_SUCCESS HIPBLAS_STATUS_SUCCESS
diff --git a/llamafile/flt.h b/llamafile/flt.h
index ea0cc607..50b96c57 100644
--- a/llamafile/flt.h
+++ b/llamafile/flt.h
@@ -18,14 +18,6 @@
namespace flt {
-inline int toint(float f) {
- union {
- float f;
- unsigned i;
- } u = {f};
- return u.i;
-}
-
inline int toint(half f) {
union {
half f;
@@ -34,42 +26,79 @@ inline int toint(half f) {
return u.i;
}
-inline int signbit(float f) {
- return toint(f) & (-2147483647 - 1);
+inline unsigned toint(float f) {
+ union {
+ float f;
+ unsigned i;
+ } u = {f};
+ return u.i;
}
-inline int signbit(half f) {
- return toint(f) & 0x8000;
+inline bool isnan(half f) {
+ return (toint(f) & 0x7fff) > 0x7c00;
}
-inline int isnan(float f) {
+inline bool isnan(float f) {
return (toint(f) & 0x7fffffff) > 0x7f800000;
}
-inline int isnan(half f) {
- return (toint(f) & 0x7fff) > 0x7c00;
+inline bool isinf(half f) {
+ return (toint(f) & 0x7fff) == 0x7c00;
}
-inline int isinf(float f) {
+inline bool isinf(float f) {
return (toint(f) & 0x7fffffff) == 0x7f800000;
}
-inline int isinf(half f) {
- return (toint(f) & 0x7fff) == 0x7c00;
+inline int signbit(half f) {
+ return toint(f) & 0x8000;
}
-inline int isnormal(float f) {
- int expo = toint(f) & 0x7f800000;
- return expo && expo != 0x7f800000;
+inline unsigned signbit(float f) {
+ return toint(f) & 0x80000000u;
}
-inline int isnormal(half f) {
+inline bool isnormal(half f) {
int expo = toint(f) & 0x7c00;
return expo && expo != 0x7c00;
}
-template <typename T> inline int isdenormal(T f) {
+inline bool isnormal(float f) {
+ int expo = toint(f) & 0x7f800000;
+ return expo && expo != 0x7f800000;
+}
+
+template <typename T> inline bool isdenormal(T f) {
return f && !isnormal(f) && !isnan(f) && !isinf(f);
}
+inline float normalize(float f) {
+ union {
+ float f;
+ unsigned u;
+ } fb;
+ fb.f = f;
+ unsigned sign = (fb.u >> 31) & 1;
+ unsigned exponent = (fb.u >> 23) & 0xFF;
+ unsigned mantissa = fb.u & 0x7FFFFF;
+ if (exponent == 0xFF) {
+ // Special case: Infinity or NaN
+ return f;
+ }
+ if (exponent == 0) {
+ // Denormalized number
+ while ((mantissa & 0x800000) == 0) {
+ mantissa <<= 1;
+ exponent--;
+ }
+ exponent++;
+ mantissa &= 0x7FFFFF;
+ } else {
+ // Normalized number
+ mantissa |= 0x800000;
+ }
+ fb.u = (sign << 31) | (exponent << 23) | mantissa;
+ return fb.f;
+}
+
} // namespace flt
diff --git a/llamafile/gemm.h b/llamafile/gemm.h
index 09473156..bdd88a19 100644
--- a/llamafile/gemm.h
+++ b/llamafile/gemm.h
@@ -44,27 +44,53 @@ void gemm(bool aT, bool bT, //
for (int j = 0; j < n; ++j) {
T d = 0;
for (int l = 0; l < k; ++l) {
- T a = aT ? A[lda * i + l] : A[lda * l + i];
- T b = bT ? B[ldb * l + j] : B[ldb * j + l];
+ T a = A[aT ? lda * i + l : lda * l + i];
+ T b = B[bT ? ldb * l + j : ldb * j + l];
d = std::fma(a, b, d);
}
- T c = C[ldc * j + i];
- C[ldc * j + i] = std::fma(alpha, d, beta * c);
+ if (beta) {
+ T c = C[ldc * j + i];
+ C[ldc * j + i] = std::fma(alpha, d, beta * c);
+ } else {
+ C[ldc * j + i] = alpha * d;
+ }
}
}
-// multiplies matrix on cpu with row major ordering
+// multiplies matrices on cpu with column major ordering
//
-// k×m * n×k → n×m
-// m×k * n×k → n×m if aᵀ
-// k×m * k×n → n×m if bᵀ
-// m×k * k×n → n×m if aᵀ and bᵀ
+// m×k * k×n → m×n
+// k×m * k×n → m×n if aᵀ
+// m×k * n×k → m×n if bᵀ
+// k×m * n×k → m×n if aᵀ and bᵀ
//
template <typename T, typename TA, typename TB, typename TC>
-void gemmrm(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
- gemm(bT, aT, n, m, k, alpha, B, ldb, A, lda, beta, C, ldc);
+void gsbe(bool aT, bool bT, //
+ int m, int n, int k, T alpha, //
+ const TA *A, int lda, long long sta, //
+ const TB *B, int ldb, long long stb, T beta, //
+ TC *C, int ldc, long long stc, int batches) {
+ assert(m >= 0 && n >= 0 && k >= 0);
+ assert(lda >= std::max(1, aT ? k : m));
+ assert(ldb >= std::max(1, bT ? n : k));
+ assert(ldc >= std::max(1, m));
+ assert(1ll * lda * (aT ? m : k) <= INT_MAX);
+ assert(1ll * ldb * (bT ? k : n) <= INT_MAX);
+ assert(std::max(0ll, stc) >= std::min(1ll * ldc * n, stc * 2));
+ for (int z = 0; z < batches; ++z)
+ for (int i = 0; i < m; ++i)
+ for (int j = 0; j < n; ++j) {
+ T d = 0;
+ for (int l = 0; l < k; ++l) {
+ T a = A[sta * z + (aT ? lda * i + l : lda * l + i)];
+ T b = B[stb * z + (bT ? ldb * l + j : ldb * j + l)];
+ d = std::fma(a, b, d);
+ }
+ if (beta) {
+ T c = C[stc * z + ldc * j + i];
+ C[stc * z + ldc * j + i] = std::fma(alpha, d, beta * c);
+ } else {
+ C[stc * z + ldc * j + i] = alpha * d;
+ }
+ }
}
diff --git a/llamafile/naive.h b/llamafile/naive.h
index 1cf2dd39..b52e4067 100644
--- a/llamafile/naive.h
+++ b/llamafile/naive.h
@@ -38,22 +38,51 @@ namespace naive {
namespace {
template <typename T, typename TA, typename TB, typename TC>
-__global__ void kernel(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
+__global__ void GEMM(bool aT, bool bT, //
+ int m, int n, int k, T alpha, //
+ const TA *A, int lda, //
+ const TB *B, int ldb, T beta, //
+ TC *C, int ldc) {
const int i = blockIdx.x * blockDim.x + threadIdx.x;
const int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i < m && j < n) {
T d = 0;
for (int l = 0; l < k; ++l) {
- T a = aT ? A[lda * i + l] : A[lda * l + i];
- T b = bT ? B[ldb * l + j] : B[ldb * j + l];
+ T a = A[aT ? lda * i + l : lda * l + i];
+ T b = B[bT ? ldb * l + j : ldb * j + l];
d += a * b;
}
- T c = C[ldc * j + i];
- C[ldc * j + i] = alpha * d + beta * c;
+ if (beta) {
+ T c = C[ldc * j + i];
+ C[ldc * j + i] = alpha * d + beta * c;
+ } else {
+ C[ldc * j + i] = alpha * d;
+ }
+ }
+}
+
+template <typename T, typename TA, typename TB, typename TC>
+__global__ void GSBE(bool aT, bool bT, //
+ int m, int n, int k, T alpha, //
+ const TA *A, int lda, long long sta, //
+ const TB *B, int ldb, long long stb, T beta, //
+ TC *C, int ldc, long long stc) {
+ const int z = blockIdx.z;
+ const int i = blockIdx.x * blockDim.x + threadIdx.x;
+ const int j = blockIdx.y * blockDim.y + threadIdx.y;
+ if (i < m && j < n) {
+ T d = 0;
+ for (int l = 0; l < k; ++l) {
+ T a = A[sta * z + (aT ? lda * i + l : lda * l + i)];
+ T b = B[stb * z + (bT ? ldb * l + j : ldb * j + l)];
+ d += a * b;
+ }
+ if (beta) {
+ T c = C[stc * z + ldc * j + i];
+ C[stc * z + ldc * j + i] = alpha * d + beta * c;
+ } else {
+ C[stc * z + ldc * j + i] = alpha * d;
+ }
}
}
@@ -75,7 +104,28 @@ cudaError_t gemm(cudaStream_t stream, //
TC *C, int ldc) {
dim3 threads(32, 32);
dim3 blocks(CEIL_DIV(m, 32), CEIL_DIV(n, 32));
- kernel<<<blocks, threads, 0, stream>>>(aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
+ GEMM<<<blocks, threads, 0, stream>>>(aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
+ return cudaGetLastError();
+}
+
+// multiplies matrices on gpu with column major ordering
+//
+// m×k * k×n → m×n
+// k×m * k×n → m×n if aᵀ
+// m×k * n×k → m×n if bᵀ
+// k×m * n×k → m×n if aᵀ and bᵀ
+//
+template <typename T, typename TA, typename TB, typename TC>
+cudaError_t gsbe(cudaStream_t stream, //
+ bool aT, bool bT, //
+ int m, int n, int k, T alpha, //
+ const TA *A, int lda, long long sta, //
+ const TB *B, int ldb, long long stb, T beta, //
+ TC *C, int ldc, long long stc, int batches) {
+ dim3 threads(32, 32);
+ dim3 blocks(CEIL_DIV(m, 32), CEIL_DIV(n, 32), batches);
+ GSBE<<<blocks, threads, 0, stream>>>(aT, bT, m, n, k, alpha, A, lda, sta, B, ldb, stb, beta, C,
+ ldc, stc);
return cudaGetLastError();
}
diff --git a/llamafile/pick_a_warp_kernel.c b/llamafile/pick_a_warp_kernel.c
index 315f94d0..d965d3f1 100644
--- a/llamafile/pick_a_warp_kernel.c
+++ b/llamafile/pick_a_warp_kernel.c
@@ -1,5 +1,5 @@
-// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;coding:utf-8 -*-
-// vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
+// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
//
// Copyright 2024 Mozilla Foundation
//
@@ -17,109 +17,145 @@
// clang-format off
#include <stdio.h>
+#include <string.h>
#include <stdlib.h>
+#include <stdatomic.h>
// this program prints legal template args for tinyBLAS matmul_warp2d()
//
// make o//llamafile/pick_a_warp_kernel
-// o//llamafile/pick_a_warp_kernel | sort
+// o//llamafile/pick_a_warp_kernel
//
// note that the sizes generated are in row major order, as used by the
// warp kernel implementation which is the opposite of the tinyBLAS API
-const int VECTOR = 16;
+#define SRC 2
+#define BANK 8
// run o//llamafile/cudaprops to get these values for your gpu
-const int warpSize = 32;
-const int regsPerBlock = 65536;
-const int maxThreadsPerBlock = 1024;
-const int sharedMemPerBlock = 49152;
-const int warpsPerMultiprocessor = 48;
-const int regsPerMultiprocessor = 65536;
-const int sharedMemPerMultiprocessor = 65536;
-const int maxThreadsPerMultiProcessor = 2048;
+#define regsPerBlock 65536
+#define sharedMemPerBlock 65536 // 49152
+#define warpSize 32
+#define cudaSharedOverhead 1024
+#define maxThreadsPerBlock 1024
+#define regsPerMultiprocessor 65536
+#define sharedMemPerMultiprocessor 65536
+#define maxThreadsPerMultiProcessor 2048
#define MIN(X, Y) ((Y) > (X) ? (X) : (Y))
-
-#define INTEGER(VAR, START, STOP) \
- int VAR = START; \
- VAR <= STOP; \
- VAR++
-
-#define TWOPOW(VAR, START, STOP) \
- int VAR = START; \
- VAR <= STOP; \
- VAR <<= 1
+#define ROUNDUP(X, K) (((X) + (K) - 1) & -(K))
+#define ARRAYLEN(A) (sizeof(A) / sizeof(*(A)))
+
+#define INTEGER(VAR, START, STOP) \
+ int VAR = START; \
+ VAR <= STOP; \
+ VAR++
+
+#define TWOPOW(VAR, START, STOP) \
+ int VAR = START; \
+ VAR <= STOP; \
+ VAR *= 2
+
+#define STRINGS 100000
+char *strings[STRINGS];
+atomic_int lock;
+int results;
+
+static const int kNumbers[] = {
+ 1, 2, 4, 8, 12, 14, 16,
+ 18, 20, 22, 24, 26, 28, 30,
+ 32, 64, 128, 256,
+};
+
+int cmp(const void *x, const void *y) {
+ return strcmp(*(const char *const *)x,
+ *(const char *const *)y);
+}
int main(int argc, char *argv[]) {
- for (TWOPOW(BM, 1, 256))
- for (TWOPOW(BN, 1, 128))
- for (TWOPOW(BK, 1, 64))
- for (TWOPOW(WM, 1, 256))
- for (TWOPOW(WN, 1, 256))
- for (INTEGER(WNI, 1, 8))
- for (TWOPOW(TM, 2, 16))
- for (TWOPOW(TN, 2, 16))
- for (TWOPOW(TT, warpSize, maxThreadsPerBlock)) {
- int warps, VE, WMI, SRC;
-
- // make sure there's a solution for each word size
- // for resource calculation we assume fp16 because
- // that's the data type we use most but since it's
- // possible to have f32 output type in practice we
- // should only choose a kernel with >= 2 occupancy
- for (SRC = 4; SRC >= 2; SRC >>= 1) {
- warps = TT / warpSize;
- WMI = (WM * WN) / (warpSize * TM * TN * WNI);
- VE = VECTOR / SRC;
- if (warps > warpsPerMultiprocessor) goto nope;
- if (BN % WN || BM % WM) goto nope;
- if ((BN / WN) * (BM / WM) != warps) goto nope;
- if (BN % (VECTOR * TN)) goto nope;
- if (BM % (VECTOR * TM)) goto nope;
- if ((BM * BK) % (VE * TT)) goto nope;
- if ((BN * BK) % (VE * TT)) goto nope;
- if ((WM % WMI) || (WN % WNI)) goto nope;
- if ((WM * WN) % (warpSize * TM * TN * WNI)) goto nope;
- if (!((WM * WN) / (warpSize * TM * TN * WNI))) goto nope;
-
- // with LLMs the m dimension is the most wild of
- // the three, since its size is often determined
- // by user input. as a result, it has a habit of
- // being small and also not aligned on a 2 power
- if (BM > BN) goto nope;
-
- // cargo culting boehm
- if (WM < WN) goto nope;
-
- // seems slightly better
- if (TN > TM) goto nope;
- }
-
- int regs = ((WMI * TM) + (WNI * TN) + (WMI * TM * WNI * TN)) * TT; // in 32-bit words
- int shared = ((BK * BM) + (BK * BN)) * SRC; // in bytes
- if (shared > sharedMemPerBlock) goto nope;
- if (regs > regsPerBlock) goto nope;
-
- int occupants = MIN(regsPerMultiprocessor / regs,
- MIN(warpsPerMultiprocessor / warps,
- sharedMemPerMultiprocessor / shared));
- if (occupants < 2) goto nope; // so there's room for sgemm float
- int occupancy = ((regs * occupants / (double)regsPerMultiprocessor) +
- (shared * occupants / (double)sharedMemPerMultiprocessor)) / 2 * 100 + .5;
- if (occupancy < 85) goto nope; // not worth printing
-
- long long score = (long long) // our goal in scoring is as follows (bigger is better)
- BK * TM * TN * // - maximize outer product's algorithmic advantage
- occupants * // - minimize resource usage
- TT * // - maximize concurrency
- WM * WN; // - maximum warp engage
-
- printf("%012lld constexpr int TT=%4d, BM=%3d, BN=%3d, BK=%3d, WM=%3d, "
- "WN=%3d, WNI=%d, TM=%2d, TN=%3d, REGS=%7d, SHARED=%7d; // %2d occupants (%d%%)\n",
- score, TT, BM, BN, BK, WM, WN, WNI, TM, TN, regs, shared, occupants, occupancy);
-
- nope:
- (void)0;
- }
+#pragma omp parallel for collapse(4)
+ for (int iBM = 0; iBM < ARRAYLEN(kNumbers); ++iBM)
+ for (int iBN = 0; iBN < ARRAYLEN(kNumbers); ++iBN)
+ for (int iBK = 0; iBK < ARRAYLEN(kNumbers); ++iBK)
+ for (int iWM = 0; iWM < ARRAYLEN(kNumbers); ++iWM)
+ for (int iWN = 0; iWN < ARRAYLEN(kNumbers); ++iWN)
+ for (int TM = 1; TM <= 8; TM<<=1)
+ for (int TN = 1; TN <= 8; TN<<=1)
+ for (int WNI = 1; WNI <= 8; ++WNI)
+ for (int TT = warpSize; TT <= 128/* maxThreadsPerBlock */; TT += warpSize) {
+ int BM = kNumbers[iBM];
+ int BN = kNumbers[iBN];
+ int BK = kNumbers[iBK];
+ int WN = kNumbers[iWN];
+ int WM = kNumbers[iWM];
+
+ // with LLMs the m dimension is the most wild of
+ // the three, since its size is often determined
+ // by user input. as a result, it has a habit of
+ // being small and also not aligned on a 2 power
+ if (BM > BN) continue;
+
+ // cargo culting boehm
+ if (WM < WN) continue;
+
+ // seems slightly better
+ if (TN > TM) continue;
+
+ // make warp tiles fit evenly in blocks
+ if (BN % WN) continue;
+ if (BM % WM) continue;
+
+ // not worth bothering
+ if (TM * TN < 24) continue;
+
+ // banking possible
+ if (BK % BANK) continue;
+ if (BN % BANK) continue;
+ if ((BM * BK) % (BANK * TT)) continue;
+ if ((BN * BK) % (BANK * TT)) continue;
+
+ // plan out warp tiles for each thread
+ int WARPS = TT / warpSize;
+ if ((BN / WN) * (BM / WM) != WARPS) continue;
+ int WMI = (WM * WN) / (warpSize * TM * TN * WNI);
+ if (!((WM * WN) / (warpSize * TM * TN * WNI))) continue;
+ if ((WM % WMI) || (WN % WNI)) continue;
+ if ((WM * WN) % (warpSize * TM * TN * WNI)) continue;
+
+ // compute number of bytes of shared memory required per block
+ int SMEM = (BK * BM) + (BK * BN); // in words
+ if (SMEM * 4 > sharedMemPerBlock) continue;
+ SMEM *= SRC; // now in bytes
+
+ // compute number of words used for thread local storage
+ int REGS = ROUNDUP(((WMI * TM) + (WNI * TN) + (WMI * TM * WNI * TN)) * warpSize, 256) * (TT / warpSize);
+ if (REGS > regsPerBlock) continue;
+
+ int occupants = MIN(regsPerMultiprocessor / REGS,
+ MIN(maxThreadsPerMultiProcessor / TT,
+ sharedMemPerMultiprocessor / (SMEM + cudaSharedOverhead)));
+ if (occupants < 2) continue; // so there's room for sgemm float
+ int occupancy = ((REGS * occupants / (double)regsPerMultiprocessor) +
+ (SMEM * occupants / (double)sharedMemPerMultiprocessor)) / 2 * 100 + .5;
+
+ int score = occupancy;
+
+ int n = 256;
+ char *s = malloc(256);
+ snprintf(s, n, "%07d constexpr int TT = %3d, BM = %3d, BN = %3d, BK = %3d, WM = %3d, "
+ "WN = %3d, WNI = %d, TM = %2d, TN = %3d; // %5d REGS, %5d SMEM, %2d occupants (%d%%)",
+ score, TT, BM, BN, BK, WM, WN, WNI, TM, TN, REGS, SMEM, occupants, occupancy);
+
+ while (atomic_exchange_explicit(&lock, 1, memory_order_acquire));
+ if (results == STRINGS) exit(7);
+ strings[results++] = s;
+ atomic_store_explicit(&lock, 0, memory_order_release);
+ }
+
+ int printed = MIN(results, 500);
+ qsort(strings, results, sizeof(char *), cmp);
+ for (int i = results - printed; i < results; ++i)
+ puts(strings[i]);
+
+ fprintf(stderr, "note: printed %d of the %d legal kernels that exist\n", printed, results);
}
diff --git a/llamafile/tester.cu b/llamafile/tester.cu
index 1e8fc1d7..f0f5c0f9 100644
--- a/llamafile/tester.cu
+++ b/llamafile/tester.cu
@@ -110,7 +110,8 @@ long long micros(void) {
const char *msg) {
int id = -1;
(void)cudaGetDevice(&id);
- fprintf(stderr, "CUDA error: %s\n", msg);
+ fprintf(stderr, "CUDA error: %s%s%s%s\n", msg, is_self_testing ? " (" : "",
+ is_self_testing ? is_self_testing : "", is_self_testing ? ")" : "");
fprintf(stderr, " current device: %d, in function %s at %s:%d\n", id, func, file, line);
fprintf(stderr, " %s\n", stmt);
(void)cudaDeviceReset();
@@ -118,7 +119,7 @@ long long micros(void) {
}
void test_matmul(std::function<void(int m, int n, int k, int l, float alpha, float beta)> f) {
- static const int kDims[] = {1, 2, 23, 65, 63, 64, 2048, 512, 127, 129, 128, 16};
+ static const int kDims[] = {1, 2, 23, 65, 63, 64, 1024, 512, 127, 129, 128, 16};
static const float kAlphas[] = {1, .1};
static const float kBetas[] = {0, .1};
static const int kLeads[] = {0, 1};
diff --git a/llamafile/tester.h b/llamafile/tester.h
index fac71894..a6661ea0 100644
--- a/llamafile/tester.h
+++ b/llamafile/tester.h
@@ -18,6 +18,7 @@
#include "cuda.h"
#include "flt.h"
+#include "gemm.h"
#include "macros.h"
#include "naive.h"
#include "tinyblas.h"
@@ -27,6 +28,7 @@
#include <cstdio>
#include <cstdlib>
#include <functional>
+#include <limits>
#include <mutex>
//
@@ -44,13 +46,28 @@
// this file contains tools for testing matrix multiplication, measuring
// errors, and visualizing what went wrong in using ansi terminal codes.
-#define ITERATIONS 30
+#define ITERATIONS 20
#define TOMBSTONE 1.666f
#ifdef __HIP__
#define cublas hipblas
#endif
+struct ErrorReport {
+ long long worst;
+ double avg;
+ double sad;
+ int infs;
+ int flips;
+ int zeroes;
+ int denormals;
+ int nans;
+ double worsta;
+ double worstb;
+ unsigned long long worstabin;
+ unsigned long long worstbbin;
+};
+
extern const int kPageSize;
extern std::recursive_mutex g_log_lock;
extern thread_local const char *is_self_testing;
@@ -106,75 +123,10 @@ template <typename T> struct cuda_memory {
}
};
-template <typename T>
-void verify(double tol, int m, int n, const T *A, int lda, const T *B, int ldb) {
- T worst_x = 0;
- T worst_y = 0;
- int worst_i = 0;
- int worst_j = 0;
- long long nans = 0;
- long long infs = 0;
- long long worst = 0;
- long long flips = 0;
- long long diffsum = 0;
- long long denormals = 0;
- long long hamhist[32] = {0};
- for (int i = 0; i < m; i++)
- for (int j = 0; j < n; j++) {
- T x = A[lda * j + i];
- T y = B[ldb * j + i];
- long long xi = flt::toint(x);
- long long yi = flt::toint(y);
- long long d = std::abs(xi - yi);
- if (flt::isnormal(x) && flt::isnormal(y) && flt::signbit(x) == flt::signbit(y)) {
- diffsum += d;
- if (d > worst) {
- worst = d;
- worst_x = x;
- worst_y = y;
- worst_i = i;
- worst_j = j;
- }
- }
- nans -= flt::isnan(x);
- nans += flt::isnan(y);
- infs -= flt::isinf(x);
- infs += flt::isinf(y);
- flips += flt::signbit(x) != flt::signbit(y);
- denormals -= flt::isdenormal(x);
- denormals += flt::isdenormal(y);
- ++hamhist[hamming(xi, yi)];
- }
- double avg = static_cast<double>(diffsum) / (m * n);
- if (worst > tol || nans || flips > m * n * .01) {
- std::unique_lock<std::recursive_mutex> lock(g_log_lock);
- fprintf(stderr, "error: %d×%d matrix difference exceeds tolerance\n", m, n);
- fprintf(stderr, " worst element at index (%d, %d)\n", worst_i, worst_j);
- fprintf(stderr, " difference %14e (%lld ulp)\n",
- std::fabs(static_cast<double>(worst_x) - static_cast<double>(worst_y)), worst);
- fprintf(stderr, " expected %14e (%x)\n", static_cast<double>(worst_x),
- flt::toint(worst_x));
- fprintf(stderr, " actual %14e (%x)\n", static_cast<double>(worst_y),
- flt::toint(worst_y));
- fprintf(stderr, " average %14g ulp\n", avg);
- fprintf(stderr, " denormals %14lld elements\n", denormals);
- fprintf(stderr, " flips %14lld elements\n", flips);
- fprintf(stderr, " nans %14lld elements\n", nans);
- fprintf(stderr, " infs %14lld elements\n", infs);
- for (int i = 0; i < 32; ++i)
- if (hamhist[i])
- fprintf(stderr, " hamhist%-2d %14lld elements\n", i, hamhist[i]);
- fflush(stderr);
- (void)cudaDeviceReset();
- _Exit(1);
- }
-}
-
-template <typename T>
-void diff(int m, int n, int k, const T *Wan, int lda, const T *Got, int ldb, double *out_avg,
- double *out_sad, double *out_worst, int *out_infs, int *out_flips, int *out_zeroes,
- int *out_denormals, int *out_nans) {
+template <typename T> ErrorReport diff(int m, int n, const T *Wan, int lda, const T *Got, int ldb) {
double sad = 0;
+ double worsta = 0;
+ double worstb = 0;
long long ulp = 0;
long long worst = 0;
int infs = 0;
@@ -184,6 +136,8 @@ void diff(int m, int n, int k, const T *Wan, int lda, const T *Got, int ldb, dou
int wan_nans = 0;
int denormals = 0;
int considered = 0;
+ unsigned long long worstabin = 0;
+ unsigned long long worstbbin = 0;
if (m && n) {
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j) {
@@ -201,13 +155,19 @@ void diff(int m, int n, int k, const T *Wan, int lda, const T *Got, int ldb, dou
denormals -= flt::isdenormal(x);
denormals += flt::isdenormal(y);
flips += flt::signbit(x) != flt::signbit(y);
- long long xi = flt::toint(x);
- long long yi = flt::toint(y);
- if (flt::isnormal(x) && flt::isnormal(y) &&
- flt::signbit(x) == flt::signbit(y)) {
+ long long xi = flt::toint(flt::normalize(x));
+ long long yi = flt::toint(flt::normalize(y));
+ if (flt::signbit(x) == flt::signbit(y)) {
++considered;
- ulp += std::abs(xi - yi);
- worst = std::max(worst, std::abs(xi - yi));
+ long long bad = std::abs(xi - yi);
+ ulp += bad;
+ if (bad > worst) {
+ worst = bad;
+ worsta = x;
+ worstb = y;
+ worstabin = xi;
+ worstbbin = yi;
+ }
sad += std::fabs(static_cast<double>(x) - static_cast<double>(y));
}
}
@@ -217,15 +177,20 @@ void diff(int m, int n, int k, const T *Wan, int lda, const T *Got, int ldb, dou
if (wan_nans)
fprintf(stderr, "WARNING: want array has %d NaNs!\n", wan_nans);
}
- int ops_per_element = k + 2;
- *out_avg = static_cast<double>(ulp) / considered / ops_per_element;
- *out_worst = static_cast<double>(worst) / ops_per_element;
- *out_nans = got_nans + wan_nans;
- *out_sad = sad / considered;
- *out_denormals = denormals;
- *out_zeroes = zeroes;
- *out_flips = flips;
- *out_infs = infs;
+ ErrorReport errors;
+ errors.nans = got_nans + wan_nans;
+ errors.avg = ulp / considered;
+ errors.sad = sad / considered;
+ errors.denormals = denormals;
+ errors.zeroes = zeroes;
+ errors.worst = worst;
+ errors.flips = flips;
+ errors.infs = infs;
+ errors.worsta = worsta;
+ errors.worstb = worstb;
+ errors.worstabin = worstabin;
+ errors.worstbbin = worstbbin;
+ return errors;
}
template <typename T>
@@ -262,13 +227,15 @@ void show(FILE *f, int max, int m, int n, const T *A, int lda, const T *B, int l
}
template <typename T>
-void misfit(FILE *f, int max, int m, int n, const T *A, int lda, const T *B, int ldb,
- const char *file, int line, double avg, double sad, double worst, int infs, int flips,
- int zeroes, int denormals, int nans) {
- fprintf(f, "%s:%d: matrix errors exceed tolerance %s\n", file, line,
- is_self_testing ? is_self_testing : "");
- fprintf(f, " %g ulp (sad=%g nans=%d infs=%d flips=%d zeroes=%d denormals=%d)\n", worst,
- sad, nans, infs, flips, zeroes, denormals);
+void misfit(FILE *f, int max, int m, int n, int k, const T *A, int lda, const T *B, int ldb,
+ const char *file, int line, double tol, ErrorReport &errors) {
+ fprintf(f, "%s:%d: worst matrix error exceeds k=%d tolerance of %g ulp %s\n", file, line, k,
+ tol * sqrt(k), is_self_testing ? is_self_testing : "");
+ fprintf(f,
+ " %lld ulp - %g (%llx) vs. %g (%llx)\n"
+ " sad=%g nans=%d infs=%d flips=%d zeroes=%d denormals=%d\n",
+ errors.worst, errors.worsta, errors.worstabin, errors.worstb, errors.worstbbin,
+ errors.sad, errors.nans, errors.infs, errors.flips, errors.zeroes, errors.denormals);
fprintf(f, "want\n");
show(f, max, m, n, A, lda, B, ldb);
fprintf(f, "got\n");
@@ -282,25 +249,23 @@ void check(double tol, //
const T *A, int lda, //
const T *B, int ldb, //
const char *file, int line) {
- double avg, sad, worst;
- int nans, infs, flips, zeroes, denormals;
assert(lda >= std::max(1, m));
assert(ldb >= std::max(1, m));
- diff(m, n, k, A, lda, B, ldb, &avg, &sad, &worst, &infs, &flips, &zeroes, &denormals, &nans);
- if (!nans && worst <= tol && flips < m * n * .01) {
+ ErrorReport errors = diff(m, n, A, lda, B, ldb);
+ if (!errors.nans && errors.worst <= tol * sqrt(k) && errors.flips < m * n * .01) {
if (!is_self_testing)
- printf(" %g ulp (sad=%g nans=%d infs=%d flips=%d zeroes=%d "
- "denormals=%d)\n",
- worst, sad, nans, infs, flips, zeroes, denormals);
+ printf(" %lld ulp - %g (%llx) vs. %g (%llx)\n"
+ " sad=%g nans=%d infs=%d flips=%d zeroes=%d denormals=%d\n",
+ errors.worst, errors.worsta, errors.worstabin, errors.worstb, errors.worstbbin,
+ errors.sad, errors.nans, errors.infs, errors.flips, errors.zeroes,
+ errors.denormals);
} else {
std::unique_lock<std::recursive_mutex> lock(g_log_lock);
- misfit(stderr, 16, m, n, A, lda, B, ldb, file, line, avg, sad, worst, infs, flips, zeroes,
- denormals, nans);
+ misfit(stderr, 16, m, n, k, A, lda, B, ldb, file, line, tol, errors);
const char *path = "/tmp/wompwomp.log";
FILE *f = fopen(path, "w");
if (f) {
- misfit(f, 10000, m, n, A, lda, B, ldb, file, line, avg, sad, worst, infs, flips, zeroes,
- denormals, nans);
+ misfit(f, 10000, m, n, k, A, lda, B, ldb, file, line, tol, errors);
fclose(f);
fprintf(stderr, "see also %s\n", path);
}
@@ -370,17 +335,21 @@ void check(double tol, //
#define RUN(x) \
printf(" \r\n%s\n", #x); \
- x
+ x; \
+ printf(" \r")
[[noreturn]] void cuda_die(const char *, const char *, const char *, int, const char *);
-template <typename T> struct cuda_data_type;
-template <> struct cuda_data_type<half> {
+template <typename T> struct cublas_data_type;
+template <> struct cublas_data_type<half> {
static constexpr cudaDataType_t id = CUDA_R_16F;
};
-template <> struct cuda_data_type<float> {
+template <> struct cublas_data_type<float> {
static constexpr cudaDataType_t id = CUDA_R_32F;
};
+template <> struct cublas_data_type<double> {
+ static constexpr cudaDataType_t id = CUDA_R_64F;
+};
template <typename T> struct cublas_compute_type;
template <> struct cublas_compute_type<half> {
@@ -389,6 +358,9 @@ template <> struct cublas_compute_type<half> {
template <> struct cublas_compute_type<float> {
static constexpr cublasComputeType_t id = CUBLAS_COMPUTE_32F;
};
+template <> struct cublas_compute_type<double> {
+ static constexpr cublasComputeType_t id = CUBLAS_COMPUTE_64F;
+};
template <typename T> struct tinyblas_data_type;
template <> struct tinyblas_data_type<half> {
@@ -406,12 +378,65 @@ template <> struct tinyblas_compute_type<float> {
static constexpr tinyblasComputeType_t id = TINYBLAS_COMPUTE_32F;
};
-template <typename T, typename TA, typename TB, typename TC>
+// multiplies matrix with column major ordering
+//
+// m×k * k×n → m×n
+// k×m * k×n → m×n if aᵀ
+// m×k * n×k → m×n if bᵀ
+// k×m * n×k → m×n if aᵀ and bᵀ
+//
+template <typename WORD, typename SRC, typename DST>
+void gemmref(bool aT, bool bT, //
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, //
+ const SRC *B, int ldb, WORD beta, //
+ DST *C, int ldc) {
+ cudaStream_t stream;
+ assert(m >= 0 && n >= 0 && k >= 0);
+ assert(lda >= std::max(1, aT ? k : m));
+ assert(ldb >= std::max(1, bT ? n : k));
+ assert(ldc >= std::max(1, m));
+ CUDA_OR_DIE(cudaSetDevice(0));
+ CUDA_OR_DIE(cudaStreamCreate(&stream));
+ BENCH_CUDA(
+ CUDA_OR_DIE(naive::gemm(stream, aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc)));
+ CUDA_OR_DIE(cudaStreamSynchronize(stream));
+ CUDA_OR_DIE(cudaStreamDestroy(stream));
+}
+
+// multiplies matrix with column major ordering
+//
+// m×k * k×n → m×n
+// k×m * k×n → m×n if aᵀ
+// m×k * n×k → m×n if bᵀ
+// k×m * n×k → m×n if aᵀ and bᵀ
+//
+template <typename WORD, typename SRC, typename DST>
+void gsberef(bool aT, bool bT, //
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, long long sta, //
+ const SRC *B, int ldb, long long stb, WORD beta, //
+ DST *C, int ldc, long long stc, int batches) {
+ cudaStream_t stream;
+ assert(m >= 0 && n >= 0 && k >= 0);
+ assert(lda >= std::max(1, aT ? k : m));
+ assert(ldb >= std::max(1, bT ? n : k));
+ assert(ldc >= std::max(1, m));
+ assert(std::max(0ll, stc) >= std::min(1ll * ldc * n, stc * 2));
+ CUDA_OR_DIE(cudaSetDevice(0));
+ CUDA_OR_DIE(cudaStreamCreate(&stream));
+ BENCH_CUDA(CUDA_OR_DIE(naive::gsbe(stream, aT, bT, m, n, k, alpha, A, lda, sta, B, ldb, stb,
+ beta, C, ldc, stc, batches)));
+ CUDA_OR_DIE(cudaStreamSynchronize(stream));
+ CUDA_OR_DIE(cudaStreamDestroy(stream));
+}
+
+template <typename WORD, typename SRC, typename DST>
void cublas(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, //
+ const SRC *B, int ldb, WORD beta, //
+ DST *C, int ldc) {
cudaStream_t stream;
cublasHandle_t blas;
assert(m >= 0 && n >= 0 && k >= 0);
@@ -429,28 +454,49 @@ void cublas(bool aT, bool bT, //
CUBLAS_OR_DIE(cublasSetStream(blas, stream));
BENCH_CUDA(CUBLAS_OR_DIE(cublasGemmEx(
blas, aT ? CUBLAS_OP_T : CUBLAS_OP_N, bT ? CUBLAS_OP_T : CUBLAS_OP_N, m, n, k, &alpha, A,
- cuda_data_type<TA>::id, lda, B, cuda_data_type<TB>::id, ldb, &beta, C,
- cuda_data_type<TC>::id, ldc, cublas_compute_type<T>::id, CUBLAS_GEMM_DEFAULT)));
+ cublas_data_type<SRC>::id, lda, B, cublas_data_type<SRC>::id, ldb, &beta, C,
+ cublas_data_type<DST>::id, ldc, cublas_compute_type<WORD>::id, CUBLAS_GEMM_DEFAULT)));
CUDA_OR_DIE(cudaStreamSynchronize(stream));
CUDA_OR_DIE(cudaStreamDestroy(stream));
CUBLAS_OR_DIE(cublasDestroy(blas));
}
-template <typename T, typename TA, typename TB, typename TC>
-void cublasrm(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
- cublas(bT, aT, n, m, k, alpha, B, ldb, A, lda, beta, C, ldc);
+template <typename WORD, typename SRC, typename DST>
+void cublasGSBE(bool aT, bool bT, //
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, long long sta, //
+ const SRC *B, int ldb, long long stb, WORD beta, //
+ DST *C, int ldc, long long stc, int batches) {
+ cudaStream_t stream;
+ cublasHandle_t blas;
+ assert(m >= 0 && n >= 0 && k >= 0);
+ assert(lda >= std::max(1, aT ? k : m));
+ assert(ldb >= std::max(1, bT ? n : k));
+ assert(ldc >= std::max(1, m));
+ CUDA_OR_DIE(cudaSetDevice(0));
+ CUBLAS_OR_DIE(cublasCreate(&blas));
+ CUDA_OR_DIE(cudaStreamCreate(&stream));
+ CUBLAS_OR_DIE(cublasSetMathMode(blas, CUBLAS_DEFAULT_MATH));
+#ifdef __HIP__
+ CUBLAS_OR_DIE(hipblasSetAtomicsMode(blas, HIPBLAS_ATOMICS_NOT_ALLOWED));
+#endif
+ CUBLAS_OR_DIE(cublasSetStream(blas, stream));
+ BENCH_CUDA(CUBLAS_OR_DIE(cublasGemmStridedBatchedEx(
+ blas, aT ? CUBLAS_OP_T : CUBLAS_OP_N, bT ? CUBLAS_OP_T : CUBLAS_OP_N, m, n, k, &alpha, A,
+ cublas_data_type<SRC>::id, lda, sta, B, cublas_data_type<SRC>::id, ldb, stb, &beta, C,
+ cublas_data_type<DST>::id, ldc, stc, batches, cublas_compute_type<WORD>::id,
+ CUBLAS_GEMM_DEFAULT)));
+ CUDA_OR_DIE(cudaStreamSynchronize(stream));
+ CUDA_OR_DIE(cudaStreamDestroy(stream));
+ CUBLAS_OR_DIE(cublasDestroy(blas));
}
-template <typename T, typename TA, typename TB, typename TC>
+template <typename WORD, typename SRC, typename DST>
void tinyblas(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, //
+ const SRC *B, int ldb, WORD beta, //
+ DST *C, int ldc) {
cudaStream_t stream;
tinyblasHandle_t blas;
assert(m >= 0 && n >= 0 && k >= 0);
@@ -463,44 +509,35 @@ void tinyblas(bool aT, bool bT, //
TINYBLAS_OR_DIE(tinyblasSetStream(blas, stream));
BENCH_CUDA(TINYBLAS_OR_DIE(tinyblasGemmEx(
blas, aT ? TINYBLAS_OP_T : TINYBLAS_OP_N, bT ? TINYBLAS_OP_T : TINYBLAS_OP_N, m, n, k,
- &alpha, A, tinyblas_data_type<TA>::id, lda, B, tinyblas_data_type<TB>::id, ldb, &beta, C,
- tinyblas_data_type<TC>::id, ldc, tinyblas_compute_type<T>::id, TINYBLAS_GEMM_DEFAULT)));
+ &alpha, A, tinyblas_data_type<SRC>::id, lda, B, tinyblas_data_type<SRC>::id, ldb, &beta, C,
+ tinyblas_data_type<DST>::id, ldc, tinyblas_compute_type<WORD>::id, TINYBLAS_GEMM_DEFAULT)));
CUDA_OR_DIE(cudaStreamSynchronize(stream));
CUDA_OR_DIE(cudaStreamDestroy(stream));
TINYBLAS_OR_DIE(tinyblasDestroy(blas));
}
-template <typename T, typename TA, typename TB, typename TC>
-void tinyblasrm(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
- tinyblas(bT, aT, n, m, k, alpha, B, ldb, A, lda, beta, C, ldc);
-}
-
-// multiplies matrix on gpu with column major ordering
-//
-// m×k * k×n → m×n
-// k×m * k×n → m×n if aᵀ
-// m×k * n×k → m×n if bᵀ
-// k×m * n×k → m×n if aᵀ and bᵀ
-//
-template <typename T, typename TA, typename TB, typename TC>
-void gemmref(bool aT, bool bT, //
- int m, int n, int k, T alpha, //
- const TA *A, int lda, //
- const TB *B, int ldb, T beta, //
- TC *C, int ldc) {
+template <typename WORD, typename SRC, typename DST>
+void tinyblasGSBE(bool aT, bool bT, //
+ int m, int n, int k, WORD alpha, //
+ const SRC *A, int lda, long long sta, //
+ const SRC *B, int ldb, long long stb, WORD beta, //
+ DST *C, int ldc, long long stc, int batches) {
cudaStream_t stream;
+ tinyblasHandle_t blas;
assert(m >= 0 && n >= 0 && k >= 0);
assert(lda >= std::max(1, aT ? k : m));
assert(ldb >= std::max(1, bT ? n : k));
assert(ldc >= std::max(1, m));
CUDA_OR_DIE(cudaSetDevice(0));
+ TINYBLAS_OR_DIE(tinyblasCreate(&blas));
CUDA_OR_DIE(cudaStreamCreate(&stream));
- BENCH_CUDA(
- CUDA_OR_DIE(naive::gemm(stream, aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc)));
+ TINYBLAS_OR_DIE(tinyblasSetStream(blas, stream));
+ BENCH_CUDA(TINYBLAS_OR_DIE(tinyblasGemmStridedBatchedEx(
+ blas, aT ? TINYBLAS_OP_T : TINYBLAS_OP_N, bT ? TINYBLAS_OP_T : TINYBLAS_OP_N, m, n, k,
+ &alpha, A, tinyblas_data_type<SRC>::id, lda, sta, B, tinyblas_data_type<SRC>::id, ldb, stb,
+ &beta, C, tinyblas_data_type<DST>::id, ldc, stc, batches, tinyblas_compute_type<WORD>::id,
+ TINYBLAS_GEMM_DEFAULT)));
CUDA_OR_DIE(cudaStreamSynchronize(stream));
CUDA_OR_DIE(cudaStreamDestroy(stream));
+ TINYBLAS_OR_DIE(tinyblasDestroy(blas));
}
diff --git a/llamafile/tinyblas.cu b/llamafile/tinyblas.cu
index d44fb6b2..7894cedf 100644
--- a/llamafile/tinyblas.cu
+++ b/llamafile/tinyblas.cu
@@ -65,10 +65,20 @@
#define KERNEL __launch_bounds__(THREAD_COUNT)
#define CEIL_DIV(M, N) (((M) + (N) - 1) / (N))
+#define IGNORE_BETA 1
+#define IGNORE_ALPHA 2
+#define ASSUME_A_OP_N 4
+#define ASSUME_B_OP_T 8
+#define ASSUME_M_SAFE 16
+#define ASSUME_N_SAFE 32
+#define ASSUME_K_SAFE 64
+#define ASSUME_A_OP_T 128
+#define ASSUME_B_OP_N 256
+
////////////////////////////////////////////////////////////////////////////////////////////////////
// tinyBLAS block tiling outer product GEMM kernel
-template <int BM, int BN, int TM, int TN, typename WORD, typename SRC, typename DST>
+template <int CONFIG, int BM, int BN, int TM, int TN, typename WORD, typename SRC, typename DST>
static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperation_t transb, int m,
int n, int k, WORD alpha, const SRC *A, int lda, const SRC *B,
int ldb, WORD beta, DST *C, int ldc) {
@@ -81,6 +91,10 @@ static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperat
static_assert((BK * BM * sizeof(SRC)) + (BK * BN * sizeof(SRC)) <= 65536,
"you're almost almost certainly using too much shared memory");
+ constexpr bool msafe = !!(CONFIG & ASSUME_M_SAFE);
+ constexpr bool nsafe = !!(CONFIG & ASSUME_N_SAFE);
+ constexpr bool ksafe = !!(CONFIG & ASSUME_K_SAFE);
+
const int th = threadIdx.x;
const int ii = blockIdx.x * BM;
const int jj = blockIdx.y * BN;
@@ -92,18 +106,29 @@ static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperat
WORD At[TM];
WORD Bt[TN];
- WORD Cs[TM * TN] = {0};
+ WORD Ct[TM * TN] = {0};
+
+ if (CONFIG & ASSUME_A_OP_T)
+ transa = TINYBLAS_OP_T;
+ if (CONFIG & ASSUME_A_OP_N)
+ transa = TINYBLAS_OP_N;
+ if (CONFIG & ASSUME_B_OP_N)
+ transb = TINYBLAS_OP_N;
+ if (CONFIG & ASSUME_B_OP_T)
+ transb = TINYBLAS_OP_T;
for (int ll = 0; ll < k; ll += BK) {
- for (int i = 0; i < BM; ++i)
- As[BM * th + i] = 0;
- for (int i = 0; i < BM && ll + th < k && ii + i < m; ++i)
+ if (!ksafe || !msafe)
+ for (int i = 0; i < BM; ++i)
+ As[BM * th + i] = 0;
+ for (int i = 0; i < BM && (ll + th < k || ksafe) && (ii + i < m || msafe); ++i)
As[BM * th + i] = A[transa ? lda * (ii + i) + (ll + th) : lda * (ll + th) + (ii + i)];
- for (int j = 0; j < BN; ++j)
- Bs[BN * th + j] = 0;
- for (int j = 0; j < BN && ll + th < k && jj + j < n; ++j)
+ if (!ksafe || !nsafe)
+ for (int j = 0; j < BN; ++j)
+ Bs[BN * th + j] = 0;
+ for (int j = 0; j < BN && (ll + th < k || ksafe) && (jj + j < n || nsafe); ++j)
Bs[BN * th + j] = B[transb ? ldb * (ll + th) + (jj + j) : ldb * (jj + j) + (ll + th)];
__syncthreads();
@@ -117,7 +142,7 @@ static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperat
WORD a = At[j];
for (int h = 0; h < TN; ++h) {
WORD b = Bt[h];
- Cs[TN * j + h] += a * b;
+ Ct[TN * j + h] += a * b;
}
}
}
@@ -125,29 +150,29 @@ static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperat
__syncthreads();
}
- if (alpha != (WORD)1)
- for (int i = 0; i < TM * TN; ++i)
- Cs[i] *= alpha;
-
- for (int j = 0; j < TN && jj + tj + j < n; ++j)
- for (int i = 0; i < TM && ii + ti + i < m; ++i)
- if (beta) {
- WORD c = C[ldc * (jj + tj + j) + (ii + ti + i)];
- C[ldc * (jj + tj + j) + (ii + ti + i)] = c * beta + Cs[TN * i + j];
+ for (int j = 0; j < TN && (jj + tj + j < n || nsafe); ++j)
+ for (int i = 0; i < TM && (ii + ti + i < m || msafe); ++i) {
+ WORD r, d = Ct[TN * i + j];
+ if ((CONFIG & IGNORE_BETA) || !beta) {
+ if (CONFIG & IGNORE_ALPHA)
+ r = d;
+ else
+ r = alpha * d;
} else {
- C[ldc * (jj + tj + j) + (ii + ti + i)] = Cs[TN * i + j];
+ WORD c = C[ldc * (jj + tj + j) + (ii + ti + i)];
+ if (CONFIG & IGNORE_ALPHA)
+ r = beta * c + d;
+ else
+ r = alpha * d + beta * c;
}
+ C[ldc * (jj + tj + j) + (ii + ti + i)] = r;
+ }
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// tinyBLAS warp block tiling outer product GEMM kernel
-enum Mode {
- GENERAL,
- SIMPLE,
-};
-
-template <enum Mode MODE, int BM, int BN, int BK, int WM, int WN, int WNI, int TM, int TN, int TT,
+template <int CONFIG, int BM, int BN, int BK, int WM, int WN, int WNI, int TM, int TN, int TT,
typename WORD, typename SRC, typename DST>
static __device__ void matmul_warp2d(tinyblasOperation_t aT, //
tinyblasOperation_t bT, //
@@ -156,6 +181,7 @@ static __device__ void matmul_warp2d(tinyblasOperation_t aT, //
const SRC *B, int ldb, WORD beta, //
DST *C, int ldc) {
+ const SRC zero = 0;
const int warpIdx = threadIdx.x / WARPSIZE;
const int warpCol = warpIdx % (BN / WN);
const int warpRow = warpIdx / (BN / WN);
@@ -164,22 +190,26 @@ static __device__ void matmul_warp2d(tinyblasOperation_t aT, //
constexpr int WMI = (WM * WN) / (WARPSIZE * TM * TN * WNI);
constexpr int WSUBM = WM / WMI;
constexpr int WSUBN = WN / WNI;
- constexpr int VE = sizeof(float4) / sizeof(SRC);
+ constexpr int BANK = 16;
+
+ constexpr bool msafe = !!(CONFIG & ASSUME_M_SAFE);
+ constexpr bool nsafe = !!(CONFIG & ASSUME_N_SAFE);
+ constexpr bool ksafe = !!(CONFIG & ASSUME_K_SAFE);
const int threadIdxInWarp = threadIdx.x % WARPSIZE;
const int threadColInWarp = threadIdxInWarp % (WSUBN / TN);
const int threadRowInWarp = threadIdxInWarp / (WSUBN / TN);
- // want to tune these magnums?
+ // want to tune these magic numbers?
// use llamafile/pick_a_warp_kernel.c
static_assert(!(BN % WN) && !(BM % WM), "");
- static_assert((BN / WN) * (BM / WM) == WARPS, "");
- static_assert(!((WM * WN) % (WARPSIZE * TM * TN * WNI)), "");
- static_assert(BN % (sizeof(float4) * TN) == 0, "");
- static_assert(BM % (sizeof(float4) * TM) == 0, "");
static_assert(!(WM % WMI) && !(WN % WNI), "");
- static_assert(!((BM * BK) % (VE * TT)), "");
- static_assert(!((BN * BK) % (VE * TT)), "");
+ static_assert((BN / WN) * (BM / WM) == WARPS, "");
+ static_assert((WM * WN) % (WARPSIZE * TM * TN * WNI) == 0, "");
+ static_assert((BM * BK) % (BANK * TT) == 0, "");
+ static_assert((BN * BK) % (BANK * TT) == 0, "");
+ static_assert(BK % BANK == 0, "");
+ static_assert(BN % BANK == 0, "");
__shared__ SRC As[BK * BM];
__shared__ SRC Bs[BK * BN];
@@ -188,26 +218,37 @@ static __device__ void matmul_warp2d(tinyblasOperation_t aT, //
WORD Br[WNI * TN] = {0};
WORD Cr[WMI * TM * WNI * TN] = {0};
- for (int bkIdx = 0; bkIdx < k; bkIdx += BK) {
+ if (CONFIG & ASSUME_A_OP_T)
+ aT = TINYBLAS_OP_T;
+ if (CONFIG & ASSUME_A_OP_N)
+ aT = TINYBLAS_OP_N;
+ if (CONFIG & ASSUME_B_OP_N)
+ bT = TINYBLAS_OP_N;
+ if (CONFIG & ASSUME_B_OP_T)
+ bT = TINYBLAS_OP_T;
+
+ for (int ll = 0; ll < k; ll += BK) {
- for (int h = 0; h < BM; h += (TT * VE) / BK)
- for (int v = 0; v < VE; ++v) {
- int l = bkIdx + threadIdx.x % (BK / VE) * VE + v;
- int i = blockIdx.y * BM + threadIdx.x / (BK / VE) + h;
- As[BM * (threadIdx.x % (BK / VE) * VE + v) + (threadIdx.x / (BK / VE) + h)] =
- aT && MODE <= GENERAL
- ? ((MODE == SIMPLE ? i < m : (l < k && i < m)) ? A[lda * l + i] : (SRC)0)
- : ((MODE == SIMPLE ? i < m : (l < k && i < m)) ? A[lda * i + l] : (SRC)0);
+ for (int h = 0; h < BM; h += (TT * BANK) / BK)
+ for (int v = 0; v < BANK; ++v) {
+ int l = ll + threadIdx.x % (BK / BANK) * BANK + v;
+ int i = blockIdx.y * BM + threadIdx.x / (BK / BANK) + h;
+ As[BM * (threadIdx.x % (BK / BANK) * BANK + v) + (threadIdx.x / (BK / BANK) + h)] =
+ (((i < m || msafe) && //
+ (l < k || ksafe))
+ ? A[!aT ? lda * i + l : lda * l + i]
+ : zero);
}
- for (int h = 0; h < BK; h += TT / (BN / VE))
- for (int v = 0; v < VE; ++v) {
- int l = bkIdx + threadIdx.x / (BN / VE) + h;
- int j = blockIdx.x * BN + threadIdx.x % (BN / VE) * VE + v;
- Bs[BN * (threadIdx.x / (BN / VE) + h) + (threadIdx.x % (BN / VE) * VE + v)] =
- bT || MODE >= SIMPLE
- ? (MODE == SIMPLE || (l < k && j < n) ? B[ldb * j + l] : (SRC)0)
- : (MODE == SIMPLE || (l < k && j < n) ? B[ldb * l + j] : (SRC)0);
+ for (int h = 0; h < BK; h += TT / (BN / BANK))
+ for (int v = 0; v < BANK; ++v) {
+ int l = ll + threadIdx.x / (BN / BANK) + h;
+ int j = blockIdx.x * BN + threadIdx.x % (BN / BANK) * BANK + v;
+ Bs[BN * (threadIdx.x / (BN / BANK) + h) + (threadIdx.x % (BN / BANK) * BANK + v)] =
+ (((j < n || nsafe) && //
+ (l < k || ksafe))
+ ? B[bT ? ldb * j + l : ldb * l + j]
+ : zero);
}
__syncthreads();
@@ -232,24 +273,29 @@ static __device__ void matmul_warp2d(tinyblasOperation_t aT, //
__syncthreads();
}
- for (int wSubRowIdx = 0; wSubRowIdx < WMI; ++wSubRowIdx)
- for (int wSubColIdx = 0; wSubColIdx < WNI; ++wSubColIdx)
- for (int resIdxM = 0; resIdxM < TM; resIdxM += 1)
- for (int resIdxN = 0; resIdxN < TN; resIdxN += 1) {
- int row = (BM * blockIdx.y + WM * warpRow) + (WSUBM * wSubRowIdx) +
- (threadRowInWarp * TM + resIdxM);
- int col = (BN * blockIdx.x + WN * warpCol) + (WSUBN * wSubColIdx) +
- (threadColInWarp * TN + resIdxN);
- if (MODE == SIMPLE) {
- if (row < m)
- C[ldc * row + col] = Cr[(WNI * TN) * (TM * wSubRowIdx + resIdxM) +
- TN * wSubColIdx + resIdxN];
- } else {
- if (row < m && col < n)
- C[ldc * row + col] =
- alpha * Cr[(WNI * TN) * (TM * wSubRowIdx + resIdxM) +
- TN * wSubColIdx + resIdxN] +
- beta * (WORD)C[ldc * row + col];
+ for (int ii = 0; ii < WMI; ++ii)
+ for (int jj = 0; jj < WNI; ++jj)
+ for (int i = 0; i < TM; i += 1)
+ for (int j = 0; j < TN; j += 1) {
+ int row = (BM * blockIdx.y + WM * warpRow) + (WSUBM * ii) +
+ (threadRowInWarp * TM + i);
+ int col = (BN * blockIdx.x + WN * warpCol) + (WSUBN * jj) +
+ (threadColInWarp * TN + j);
+ if ((row < m || msafe) && (col < n || nsafe)) {
+ WORD r, d = Cr[(WNI * TN) * (TM * ii + i) + (TN * jj + j)];
+ if ((CONFIG & IGNORE_BETA) || !beta) {
+ if (CONFIG & IGNORE_ALPHA)
+ r = d;
+ else
+ r = alpha * d;
+ } else {
+ WORD c = C[ldc * row + col];
+ if (CONFIG & IGNORE_ALPHA)
+ r = beta * c + d;
+ else
+ r = alpha * d + beta * c;
+ }
+ C[ldc * row + col] = r;
}
}
}
@@ -334,6 +380,8 @@ const char *tinyblasGetStatusString(tinyblasStatus_t err) {
return "Not supported";
case TINYBLAS_STATUS_EXECUTION_FAILED:
return "Execution failed";
+ case TINYBLAS_STATUS_DIMENSION_OVERLAP:
+ return "Dimension overlap";
case TINYBLAS_STATUS_DIMENSION_OVERFLOW:
return "Dimension overflow";
default:
@@ -357,7 +405,8 @@ const char *tinyblasGetStatusString(tinyblasStatus_t err) {
* @param lda is row stride of `A`
* @param B is input array of second matrix
* @param ldb is row stride of `B`
- * @param beta points to scalar that's multiplied against existing output
+ * @param beta points to scalar that's multiplied against the existing
+ * output, but this multiplication only happens if beta is nonzero
* @param C is input/output array of output matrix
* @param ldc is row stride of `C`
*/
@@ -370,7 +419,7 @@ tinyblasStatus_t tinyblasSgemm(tinyblasHandle_t handle, tinyblasOperation_t tran
TINYBLAS_GEMM_DEFAULT);
}
-template <enum Mode MODE, int BM, int BN, int BK, int WM, int WN, int WNI, int TM, int TN, int TT,
+template <int CONFIG, int BM, int BN, int BK, int WM, int WN, int WNI, int TM, int TN, int TT,
typename WORD, typename SRC, typename DST>
static __global__ void __launch_bounds__(TT) tinyblasGE_entry(tinyblasOperation_t aT, //
tinyblasOperation_t bT, //
@@ -378,8 +427,8 @@ static __global__ void __launch_bounds__(TT) tinyblasGE_entry(tinyblasOperation_
const SRC *A, int lda, //
const SRC *B, int ldb, //
WORD beta, DST *C, int ldc) {
- matmul_warp2d<MODE, BM, BN, BK, WM, WN, WNI, TM, TN, TT>(aT, bT, m, n, k, alpha, A, lda, B, ldb,
- beta, C, ldc);
+ matmul_warp2d<CONFIG, BM, BN, BK, WM, WN, WNI, TM, TN, TT>(aT, bT, m, n, k, alpha, A, lda, B,
+ ldb, beta, C, ldc);
}
template <typename WORD, typename SRC, typename DST>
@@ -387,18 +436,22 @@ static tinyblasStatus_t tinyblasGE_launcher(tinyblasHandle_t handle, tinyblasOpe
tinyblasOperation_t bT, int m, int n, int k, WORD alpha,
const SRC *A, int lda, const SRC *B, int ldb, WORD beta,
DST *C, int ldc) {
- const int TT = 256, BM = 128, BN = 64, BK = 64, WM = 128, WN = 8, WNI = 1, TM = 8, TN = 4;
- dim3 maxblocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN));
- if (!aT && bT && !(n % BN) && !(k % BK) && alpha == (WORD)1 && beta == (WORD)0) {
- dim3 blocks(CEIL_DIV(n, BN), CEIL_DIV(m, BM));
- tinyblasGE_entry<SIMPLE, BM, BN, BK, WM, WN, WNI, TM, TN, TT>
+ constexpr int TT = 256, BM = 128, BN = 64, BK = 64, WM = 128, WN = 8, WNI = 1, TM = 8, TN = 4;
+ dim3 blocks(CEIL_DIV(n, BN), CEIL_DIV(m, BM));
+ if ((beta == 0 && //
+ alpha == 1 && //
+ n % BN == 0 && //
+ k % BK == 0 && //
+ aT == TINYBLAS_OP_N && //
+ bT == TINYBLAS_OP_T)) {
+ constexpr int CONFIG = IGNORE_BETA | IGNORE_ALPHA | ASSUME_A_OP_N | ASSUME_B_OP_T |
+ ASSUME_N_SAFE | ASSUME_K_SAFE;
+ tinyblasGE_entry<CONFIG, BM, BN, BK, WM, WN, WNI, TM, TN, TT>
<<<blocks, TT, 0, handle->stream>>>(aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C,
ldc);
} else {
- dim3 blocks(CEIL_DIV(n, BN), CEIL_DIV(m, BM));
- tinyblasGE_entry<GENERAL, BM, BN, BK, WM, WN, WNI, TM, TN, TT>
- <<<blocks, TT, 0, handle->stream>>>(aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C,
- ldc);
+ tinyblasGE_entry<0, BM, BN, BK, WM, WN, WNI, TM, TN, TT><<<blocks, TT, 0, handle->stream>>>(
+ aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);
}
if (cudaGetLastError() != cudaSuccess)
return TINYBLAS_STATUS_EXECUTION_FAILED;
@@ -431,7 +484,8 @@ static tinyblasStatus_t tinyblasGE_launch(tinyblasHandle_t handle, tinyblasOpera
* @param B is input array of second matrix
* @param Btype is data type of `C`
* @param ldb is row stride of `B`
- * @param beta points to scalar that's multiplied against existing output
+ * @param beta points to scalar that's multiplied against the existing
+ * output, but this multiplication only happens if beta is nonzero
* @param C is input/output array of output matrix
* @param Ctype is data type of `C`
* @param ldc is row stride of `C`
@@ -528,9 +582,8 @@ static __global__ void KERNEL tinyblasGBE_entry(tinyblasOperation_t transa,
WORD alpha, const SRC *const Aarray[], int lda,
const SRC *const Barray[], int ldb, WORD beta,
DST *const Carray[], int ldc, int batchCount) {
- for (int z = blockIdx.z; z < batchCount; z += gridDim.z)
- matmul_block2d<BM, BN, TM, TN>(transa, transb, m, n, k, alpha, Aarray[z], lda, Barray[z],
- ldb, beta, Carray[z], ldc);
+ matmul_block2d<0, BM, BN, TM, TN>(transa, transb, m, n, k, alpha, Aarray[blockIdx.z], lda,
+ Barray[blockIdx.z], ldb, beta, Carray[blockIdx.z], ldc);
}
template <typename WORD, typename SRC, typename DST>
@@ -539,19 +592,45 @@ static tinyblasStatus_t tinyblasGBE_launch(tinyblasHandle_t handle, tinyblasOper
WORD alpha, const SRC *const *Aarray, int lda,
const SRC *const *Barray, int ldb, WORD beta,
DST *const *Carray, int ldc, int batchCount) {
- constexpr int BC = 32;
constexpr int BM = 32;
constexpr int BN = 32;
constexpr int TM = 2;
constexpr int TN = 8;
- dim3 maxblocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN), BC);
- tinyblasGBE_entry<BM, BN, TM, TN><<<maxblocks, THREAD_COUNT, 0, handle->stream>>>(
+ dim3 blocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN), batchCount);
+ tinyblasGBE_entry<BM, BN, TM, TN><<<blocks, THREAD_COUNT, 0, handle->stream>>>(
transa, transb, m, n, k, alpha, Aarray, lda, Barray, ldb, beta, Carray, ldc, batchCount);
if (cudaGetLastError() != cudaSuccess)
return TINYBLAS_STATUS_EXECUTION_FAILED;
return TINYBLAS_STATUS_SUCCESS;
}
+/**
+ * Multiplies matrices.
+ *
+ * This is a column major GEMM subroutine for computing C = α*A*B + β*C.
+ *
+ * @param handle was created by tinyblasCreate()
+ * @param transa if `A` should be transposed
+ * @param transb if `B` should be transposed
+ * @param m is rows in `A` and `C`
+ * @param n is cols in `B` and `C`
+ * @param k is cols in `A` and rows in `B`
+ * @param alpha points to scalar that's multiplied against input
+ * @param A is input array of device memory pointing to first matrices
+ * @param Atype is data type of `C`
+ * @param lda is row stride of `A`
+ * @param B is input array of device memory pointing to second matrices
+ * @param Btype is data type of `C`
+ * @param ldb is row stride of `B`
+ * @param beta points to scalar that's multiplied against the existing
+ * output, but this multiplication only happens if beta is nonzero
+ * @param C is input/output array of output matrices
+ * @param Ctype is data type of `C`
+ * @param ldc is row stride of `C`
+ * @param batchCount is number of elements in `A`, `B`, and `C`
+ * @param computeType is data type of `alpha`, `beta`, and dot product
+ * @param algo specifies algorithm to use
+ */
tinyblasStatus_t tinyblasGemmBatchedEx(tinyblasHandle_t handle, tinyblasOperation_t transa,
tinyblasOperation_t transb, int m, int n, int k,
const void *alpha, const void *const Aarray[],
@@ -637,16 +716,16 @@ tinyblasStatus_t tinyblasGemmBatchedEx(tinyblasHandle_t handle, tinyblasOperatio
}
}
-template <int BM, int BN, int TM, int TN, typename SRC, typename DST, typename WORD>
+template <int CONFIG, int BM, int BN, int TM, int TN, typename SRC, typename DST, typename WORD>
static __global__ void KERNEL tinyblasGSBE_entry(tinyblasOperation_t transa,
tinyblasOperation_t transb, int m, int n, int k,
WORD alpha, const SRC *A, int lda,
long long strideA, const SRC *B, int ldb,
long long strideB, WORD beta, DST *C, int ldc,
long long strideC, int batchCount) {
- matmul_block2d<BM, BN, TM, TN>(transa, transb, m, n, k, alpha, A + blockIdx.z * strideA, lda,
- B + blockIdx.z * strideB, ldb, beta, C + blockIdx.z * strideC,
- ldc);
+ matmul_block2d<CONFIG, BM, BN, TM, TN>(transa, transb, m, n, k, alpha, A + strideA * blockIdx.z,
+ lda, B + strideB * blockIdx.z, ldb, beta,
+ C + strideC * blockIdx.z, ldc);
}
template <typename WORD, typename SRC, typename DST>
@@ -655,20 +734,63 @@ static tinyblasStatus_t tinyblasGSBE_launch(tinyblasHandle_t handle, tinyblasOpe
WORD alpha, const SRC *A, int lda, long long strideA,
const SRC *B, int ldb, long long strideB, WORD beta,
DST *C, int ldc, long long strideC, int batchCount) {
- constexpr int BC = 32;
constexpr int BM = 32;
constexpr int BN = 32;
constexpr int TM = 2;
constexpr int TN = 8;
- dim3 maxblocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN), BC);
- tinyblasGSBE_entry<BM, BN, TM, TN><<<maxblocks, THREAD_COUNT, 0, handle->stream>>>(
- transa, transb, m, n, k, alpha, A, lda, strideA, B, ldb, strideB, beta, C, ldc, strideC,
- batchCount);
+ constexpr int BK = THREAD_COUNT;
+ dim3 blocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN), batchCount);
+ if ((beta == 0 && //
+ alpha == 1 && //
+ m % BM == 0 && //
+ k % BK == 0 && //
+ transa == TINYBLAS_OP_T && //
+ transb == TINYBLAS_OP_N)) {
+ constexpr int CONFIG = IGNORE_BETA | IGNORE_ALPHA | ASSUME_A_OP_T | ASSUME_B_OP_N |
+ ASSUME_M_SAFE | ASSUME_K_SAFE;
+ tinyblasGSBE_entry<CONFIG, BM, BN, TM, TN><<<blocks, THREAD_COUNT, 0, handle->stream>>>(
+ transa, transb, m, n, k, alpha, A, lda, strideA, B, ldb, strideB, beta, C, ldc, strideC,
+ batchCount);
+ } else {
+ tinyblasGSBE_entry<0, BM, BN, TM, TN><<<blocks, THREAD_COUNT, 0, handle->stream>>>(
+ transa, transb, m, n, k, alpha, A, lda, strideA, B, ldb, strideB, beta, C, ldc, strideC,
+ batchCount);
+ }
if (cudaGetLastError() != cudaSuccess)
return TINYBLAS_STATUS_EXECUTION_FAILED;
return TINYBLAS_STATUS_SUCCESS;
}
+/**
+ * Multiplies matrices.
+ *
+ * This is a column major GEMM subroutine for computing C = α*A*B + β*C.
+ *
+ * @param handle was created by tinyblasCreate()
+ * @param transa if `A` should be transposed
+ * @param transb if `B` should be transposed
+ * @param m is rows in `A` and `C`
+ * @param n is cols in `B` and `C`
+ * @param k is cols in `A` and rows in `B`
+ * @param alpha points to scalar that's multiplied against input
+ * @param A is input array of first matrices
+ * @param Atype is data type of `C`
+ * @param lda is row stride of `A`
+ * @param strideA is distance between matrices in `A`
+ * @param B is input array of second matrices
+ * @param Btype is data type of `C`
+ * @param ldb is row stride of `B`
+ * @param strideB is distance between matrices in `B`
+ * @param beta points to scalar that's multiplied against the existing
+ * output, but this multiplication only happens if beta is nonzero
+ * @param C is input/output array of output matrices
+ * @param Ctype is data type of `C`
+ * @param ldc is row stride of `C`
+ * @param strideC is distance between matrices in `C`, which must not overlap
+ * @param batchCount is number of matrices to multiply
+ * @param computeType is data type of `alpha`, `beta`, and dot product
+ * @param algo specifies algorithm to use
+ */
tinyblasStatus_t tinyblasGemmStridedBatchedEx(tinyblasHandle_t handle, //
tinyblasOperation_t transa, //
tinyblasOperation_t transb, //
@@ -693,6 +815,8 @@ tinyblasStatus_t tinyblasGemmStridedBatchedEx(tinyblasHandle_t handle, //
return TINYBLAS_STATUS_INVALID_VALUE;
if (ldc < std::max(1, m))
return TINYBLAS_STATUS_INVALID_VALUE;
+ if (std::max(0ll, strideC) < std::min(1ll * ldc * n, strideC * 2))
+ return TINYBLAS_STATUS_DIMENSION_OVERLAP;
if (1ll * lda * ((transa ? k : m) - 1) + ((transa ? m : k) - 1) > INT_MAX)
return TINYBLAS_STATUS_DIMENSION_OVERFLOW;
if (1ll * ldb * ((transb ? n : k) - 1) + ((transb ? k : n) - 1) > INT_MAX)
diff --git a/llamafile/tinyblas.h b/llamafile/tinyblas.h
index 38c02db0..1f9169d6 100644
--- a/llamafile/tinyblas.h
+++ b/llamafile/tinyblas.h
@@ -27,6 +27,7 @@ typedef enum tinyblasStatus {
TINYBLAS_STATUS_INVALID_VALUE,
TINYBLAS_STATUS_NOT_SUPPORTED,
TINYBLAS_STATUS_EXECUTION_FAILED,
+ TINYBLAS_STATUS_DIMENSION_OVERLAP,
TINYBLAS_STATUS_DIMENSION_OVERFLOW,
} tinyblasStatus_t;
diff --git a/llamafile/tinyblas_test.cu b/llamafile/tinyblas_test.cu
index 10c4e10b..6bf23a74 100644
--- a/llamafile/tinyblas_test.cu
+++ b/llamafile/tinyblas_test.cu
@@ -18,9 +18,9 @@
#include "gemm.h"
#include "tester.h"
-void checkTinyblasWorksHHHS() {
- double TOLERANCE = 1;
+double TOLERANCE = 1;
+void checkTinyblasWorksHHHS() {
float alpha = 1;
float beta = 0;
int m = 4096;
@@ -35,11 +35,11 @@ void checkTinyblasWorksHHHS() {
cuda_memory<half> G{ldc * n};
randomize(k, m, A.p, lda);
randomize(k, n, B.p, ldb);
- cublas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ cublas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
broadcast(m, n, C.p, ldc, TOMBSTONE);
broadcast(m, n, G.p, ldc, TOMBSTONE);
- gemmref(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
test_matmul([&](int m, int n, int k, int l, float alpha, float beta) {
@@ -54,15 +54,13 @@ void checkTinyblasWorksHHHS() {
randomize(k, n, B.p, ldb);
broadcast(m, n, G.p, ldc, TOMBSTONE);
broadcast(m, n, C.p, ldc, TOMBSTONE);
- gemmref(false, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(false, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(0, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(0, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
});
}
void checkTinyblasWorksHHSS() {
- double TOLERANCE = 1;
-
float alpha = 1;
float beta = 0;
int m = 4096;
@@ -77,11 +75,11 @@ void checkTinyblasWorksHHSS() {
cuda_memory<float> G{ldc * n};
randomize(k, m, A.p, lda);
randomize(k, n, B.p, ldb);
- cublas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ cublas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
broadcast(m, n, G.p, ldc, TOMBSTONE);
broadcast(m, n, C.p, ldc, TOMBSTONE);
- gemmref(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
test_matmul([&](int m, int n, int k, int l, float alpha, float beta) {
@@ -96,15 +94,13 @@ void checkTinyblasWorksHHSS() {
randomize(k, n, B.p, ldb);
broadcast(m, n, G.p, ldc, TOMBSTONE);
broadcast(m, n, C.p, ldc, TOMBSTONE);
- gemmref(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
});
}
void checkTinyblasWorksSSSS() {
- double TOLERANCE = 1;
-
float alpha = 1;
float beta = 0;
int m = 4096;
@@ -119,11 +115,11 @@ void checkTinyblasWorksSSSS() {
cuda_memory<float> G{ldc * n};
randomize(k, m, A.p, lda);
randomize(k, n, B.p, ldb);
- cublas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ cublas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
broadcast(m, n, C.p, ldc, TOMBSTONE);
broadcast(m, n, G.p, ldc, TOMBSTONE);
- gemmref(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
test_matmul([&](int m, int n, int k, int l, float alpha, float beta) {
@@ -138,8 +134,8 @@ void checkTinyblasWorksSSSS() {
randomize(k, n, B.p, ldb);
broadcast(m, n, G.p, ldc, TOMBSTONE);
broadcast(m, n, C.p, ldc, TOMBSTONE);
- gemmref(false, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(false, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(0, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(0, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);
});
}
@@ -157,16 +153,40 @@ void try_size(int m, int n, int k) {
cuda_memory<half> G{ldc * n};
randomize(k, m, A.p, lda);
randomize(k, n, B.p, ldb);
- cublas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ cublas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
broadcast(m, n, C.p, ldc, TOMBSTONE);
broadcast(m, n, G.p, ldc, TOMBSTONE);
- gemmref(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
- tinyblas(true, false, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
+ gemmref(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, G.p, ldc);
+ tinyblas(1, 0, m, n, k, alpha, A.p, lda, B.p, ldb, beta, C.p, ldc);
CHECK(1, m, n, k, G.p, ldc, C.p, ldc);
}
+void test_gsbe() {
+ test_matmul([&](int m, int n, int k, int l, float alpha, float beta) {
+ int lda = k;
+ int ldb = k;
+ int ldc = m;
+ cuda_memory<float> A{lda * m};
+ cuda_memory<float> B{ldb * n};
+ cuda_memory<float> C{ldc * n * 2};
+ cuda_memory<float> G{ldc * n * 2};
+ randomize(k, m, A.p, lda);
+ randomize(k, n, B.p, ldb);
+ broadcast(m, n, C.p + 0 * ldc * n, ldc, TOMBSTONE);
+ broadcast(m, n, G.p + 0 * ldc * n, ldc, TOMBSTONE);
+ broadcast(m, n, C.p + 1 * ldc * n, ldc, TOMBSTONE);
+ broadcast(m, n, G.p + 1 * ldc * n, ldc, TOMBSTONE);
+ gsberef(1, 0, m, n, k, alpha, A.p, lda, 0, B.p, ldb, 0, beta, G.p, ldc, ldc * n, 2);
+ tinyblasGSBE(1, 0, m, n, k, alpha, A.p, lda, 0, B.p, ldb, 0, beta, C.p, ldc, ldc * n, 2);
+ CHECK(TOLERANCE, m, n, k, G.p + 0 * ldc * n, ldc, C.p + 0 * ldc * n, ldc);
+ CHECK(TOLERANCE, m, n, k, G.p + 0 * ldc * n, ldc, C.p + 0 * ldc * n, ldc);
+ CHECK(TOLERANCE, m, n, k, G.p + 1 * ldc * n, ldc, C.p + 1 * ldc * n, ldc);
+ CHECK(TOLERANCE, m, n, k, G.p + 1 * ldc * n, ldc, C.p + 1 * ldc * n, ldc);
+ });
+}
+
int main(int argc, char *argv[]) {
- try_size(512, 512, 512);
+
try_size(5760, 1, 128); // mistral 7b
try_size(128, 1, 5696); // mistral 7b
try_size(14336, 512, 4096); // mistral 7b
@@ -176,6 +196,8 @@ int main(int argc, char *argv[]) {
try_size(1024, 1024, 1024);
try_size(2048, 2048, 2048);
try_size(32000, 512, 4096);
+
+ RUN(test_gsbe());
RUN(checkTinyblasWorksSSSS());
RUN(checkTinyblasWorksHHSS());
RUN(checkTinyblasWorksHHHS());