Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Use warp tiling for tinyblasGemmEx()
Justine Tunneycdc09c35f9dd
diff --git a/llamafile/cuda.h b/llamafile/cuda.hindex b9066f82..08ba0112 100644--- a/llamafile/cuda.h+++ b/llamafile/cuda.h@@ -6,6 +6,8 @@#include <cublas_v2.h>#include <cuda_fp16.h>#include <cuda_runtime.h>+#define __shfl(var, srcLane, warpSize) __shfl_sync(-1u, var, srcLane, warpSize)+#define __shfl_down(var, srcLane, warpSize) __shfl_down_sync(-1u, var, srcLane, warpSize)#else#include <hip/hip_fp16.h>#include <hip/hip_runtime.h>diff --git a/llamafile/cudaprops.cu b/llamafile/cudaprops.cuindex 1578b8b3..b19aeedc 100644--- a/llamafile/cudaprops.cu+++ b/llamafile/cudaprops.cu@@ -15,66 +15,8 @@// See the License for the specific language governing permissions and// limitations under the License.-#include "cuda.h"#include "tester.h"-#include <iostream>--#ifdef __HIP__-#define VENDOR "AMD"-#else-#define VENDOR "NVIDIA"-#endif--namespace {--void show_cuda_device(int idev) {- cudaDeviceProp dp;- CUDA_OR_DIE(cudaSetDevice(idev));- CUDA_OR_DIE(cudaGetDeviceProperties(&dp, idev));-- fprintf(stderr,- "\n" VENDOR " %s\n"- "\t%.2f Ghz\n"- "\t%g GB VRAM\n"- "\t%d CPUs\n"- "\tcompute_%d\n",- dp.name, dp.clockRate * 1e-6, dp.totalGlobalMem / 1073741824., dp.multiProcessorCount,- dp.major * 10 + dp.minor);--#define SHOW(s) std::cout << #s << " = " << dp.s << std::endl;-- SHOW(warpSize);- SHOW(regsPerBlock);- SHOW(regsPerMultiprocessor);- SHOW(multiProcessorCount);- SHOW(memoryBusWidth);- SHOW(memoryClockRate);- SHOW(sharedMemPerBlock);- SHOW(sharedMemPerMultiprocessor);- SHOW(totalConstMem);- SHOW(maxThreadsPerBlock);- SHOW(maxThreadsPerMultiProcessor);- SHOW(maxThreadsDim[0]);- SHOW(maxThreadsDim[1]);- SHOW(maxThreadsDim[2]);- SHOW(asyncEngineCount);- SHOW(managedMemory);- SHOW(concurrentManagedAccess);- SHOW(directManagedMemAccessFromHost);- SHOW(globalL1CacheSupported);- SHOW(hostNativeAtomicSupported);- // SHOW(hostRegisterReadOnlySupported);- // SHOW(hostRegisterSupported);- SHOW(integrated);- SHOW(l2CacheSize);-}--} // namespaceint main() {- int device_count;- CUDA_OR_DIE(cudaGetDeviceCount(&device_count));- for (int idev = 0; idev < device_count; ++idev) {- show_cuda_device(idev);- }+ show_cuda_devices();}diff --git a/llamafile/naive.h b/llamafile/naive.hindex 730f9f46..1cf2dd39 100644--- a/llamafile/naive.h+++ b/llamafile/naive.h@@ -73,9 +73,9 @@ cudaError_t gemm(cudaStream_t stream, //const TA *A, int lda, //const TB *B, int ldb, T beta, //TC *C, int ldc) {- dim3 blockDim(32, 32);- dim3 gridDim(CEIL_DIV(m, 32), CEIL_DIV(n, 32));- kernel<<<gridDim, blockDim, 0, stream>>>(aT, bT, m, n, k, alpha, A, lda, B, ldb, beta, C, 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);return cudaGetLastError();}diff --git a/llamafile/pick_a_warp_kernel.c b/llamafile/pick_a_warp_kernel.cnew file mode 100644index 00000000..315f94d0--- /dev/null+++ b/llamafile/pick_a_warp_kernel.c@@ -0,0 +1,125 @@+// -*- 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+//+// Copyright 2024 Mozilla Foundation+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.+// clang-format off++#include <stdio.h>+#include <stdlib.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+//+// 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;++// 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 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++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;+ }+}diff --git a/llamafile/tester.cu b/llamafile/tester.cuindex f4e12698..1e8fc1d7 100644--- a/llamafile/tester.cu+++ b/llamafile/tester.cu@@ -20,11 +20,18 @@#include <algorithm>#include <atomic>#include <ctime>+#include <iostream>#ifndef _WIN32#include <unistd.h>#else-#include "windows.h"+#include <windows.h>+#endif++#ifdef __HIP__+#define VENDOR "AMD"+#else+#define VENDOR "NVIDIA"#endifstd::recursive_mutex g_log_lock;@@ -111,7 +118,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, 77, 15, 2048, 512, 127, 129, 128, 16};+ static const int kDims[] = {1, 2, 23, 65, 63, 64, 2048, 512, 127, 129, 128, 16};static const float kAlphas[] = {1, .1};static const float kBetas[] = {0, .1};static const int kLeads[] = {0, 1};@@ -149,6 +156,53 @@ void test_matmul(std::function<void(int m, int n, int k, int l, float alpha, flo}}+void show_cuda_device(int idev) {+ cudaDeviceProp dp;+ CUDA_OR_DIE(cudaSetDevice(idev));+ CUDA_OR_DIE(cudaGetDeviceProperties(&dp, idev));+ fprintf(stderr,+ "\n" VENDOR " %s\n"+ "\t%.2f Ghz\n"+ "\t%g GB VRAM\n"+ "\t%d CPUs\n"+ "\tcompute_%d\n",+ dp.name, dp.clockRate * 1e-6, dp.totalGlobalMem / 1073741824., dp.multiProcessorCount,+ dp.major * 10 + dp.minor);+#define SHOW(s) std::cout << #s << " = " << dp.s << std::endl;+ SHOW(warpSize);+ SHOW(regsPerBlock);+ SHOW(regsPerMultiprocessor);+ SHOW(multiProcessorCount);+ SHOW(memoryBusWidth);+ SHOW(memoryClockRate);+ SHOW(sharedMemPerBlock);+ SHOW(sharedMemPerMultiprocessor);+ SHOW(totalConstMem);+ SHOW(maxThreadsPerBlock);+ SHOW(maxThreadsPerMultiProcessor);+ SHOW(maxThreadsDim[0]);+ SHOW(maxThreadsDim[1]);+ SHOW(maxThreadsDim[2]);+ SHOW(asyncEngineCount);+ SHOW(managedMemory);+ SHOW(concurrentManagedAccess);+ SHOW(directManagedMemAccessFromHost);+ SHOW(globalL1CacheSupported);+ SHOW(hostNativeAtomicSupported);+ // SHOW(hostRegisterReadOnlySupported);+ // SHOW(hostRegisterSupported);+ SHOW(integrated);+ SHOW(l2CacheSize);+}++void show_cuda_devices() {+ int device_count;+ CUDA_OR_DIE(cudaGetDeviceCount(&device_count));+ for (int idev = 0; idev < device_count; ++idev) {+ show_cuda_device(idev);+ }+}+static int cuda_tester_init() {CUDA_OR_DIE(cudaSetDevice(0));#ifdef __HIP__diff --git a/llamafile/tester.h b/llamafile/tester.hindex 1d672496..fac71894 100644--- a/llamafile/tester.h+++ b/llamafile/tester.h@@ -47,6 +47,10 @@#define ITERATIONS 30#define TOMBSTONE 1.666f+#ifdef __HIP__+#define cublas hipblas+#endif+extern const int kPageSize;extern std::recursive_mutex g_log_lock;extern thread_local const char *is_self_testing;@@ -59,6 +63,8 @@ int rand32(void);long long micros(void);void *cudaMallocManagedOrDie(size_t);void cudaFreeOrDie(void *);+void show_cuda_device(int);+void show_cuda_devices();void test_matmul(std::function<void(int, int, int, int, float, float)>);template <typename T> void randomize(T *A, int n) {@@ -140,7 +146,7 @@ void verify(double tol, int m, int n, const T *A, int lda, const T *B, int ldb)++hamhist[hamming(xi, yi)];}double avg = static_cast<double>(diffsum) / (m * n);- if (avg > tol || nans) {+ 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);@@ -261,9 +267,8 @@ void misfit(FILE *f, int max, int m, int n, const T *A, int lda, const T *B, intint 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 (worst=%g sad=%g nans=%d infs=%d flips=%d zeroes=%d denormals=%d)\n",- avg, worst, sad, nans, infs, flips, zeroes, denormals);+ fprintf(f, " %g ulp (sad=%g nans=%d infs=%d flips=%d zeroes=%d denormals=%d)\n", worst,+ sad, nans, infs, flips, zeroes, denormals);fprintf(f, "want\n");show(f, max, m, n, A, lda, B, ldb);fprintf(f, "got\n");@@ -282,11 +287,11 @@ void check(double tol, //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 && avg <= tol) {+ if (!nans && worst <= tol && flips < m * n * .01) {if (!is_self_testing)- printf(" %g ulp (worst=%g sad=%g nans=%d infs=%d flips=%d zeroes=%d "+ printf(" %g ulp (sad=%g nans=%d infs=%d flips=%d zeroes=%d ""denormals=%d)\n",- avg, worst, sad, nans, infs, flips, zeroes, denormals);+ worst, sad, nans, infs, flips, zeroes, 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,@@ -417,6 +422,10 @@ void cublas(bool aT, bool bT, //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(cublasSetMathMode(blas, CUBLAS_DEFAULT_MATH));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,@@ -495,19 +504,3 @@ void gemmref(bool aT, bool bT, //CUDA_OR_DIE(cudaStreamSynchronize(stream));CUDA_OR_DIE(cudaStreamDestroy(stream));}--// multiplies matrix on gpu with row 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ᵀ-//-template <typename T, typename TA, typename TB, typename TC>-void gemmrefrm(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) {- gemmref(bT, aT, n, m, k, alpha, B, ldb, A, lda, beta, C, ldc);-}diff --git a/llamafile/tinyblas.cu b/llamafile/tinyblas.cuindex f595461e..6488781a 100644--- a/llamafile/tinyblas.cu+++ b/llamafile/tinyblas.cu@@ -17,6 +17,34 @@#include "tinyblas.h"+//+// _ _ ___ _ _ ___+// | |_(_)_ _ _ _| _ ) | /_\ / __|+// | _| | ' \ || | _ \ |__ / _ \\__ \.+// \__|_|_||_\_, |___/____/_/ \_\___/+// |__/+//+// BASIC LINEAR ALGEBRA SUBPROGRAMS+//+//+// In this file you'll find GPU subroutines implementing general matrix+// multiplication, that are API compatible with NVIDIA's cuBLAS library+// and nearly as fast[1] too. This is important because how can we call+// our software open source if it spends most of its time inside NVIDIA+// proprietary blobs like cuBLAS? tinyBLAS provides a free, open, libre+// alternative to cuBLAS that's orders of a magnitude tinier (cuBLAS is+// a 500mb DSO) and goes fast enough that you won't sacrifice much. AMD+// users might even prefer tinyBLAS, since outperforming hipBLAS is not+// very difficult for large matrices. tinyBLAS also has better accuracy+// too, since hipBLAS uses tricks that cause sign flips, and denormals.+//+// TODO(jart): make tinyBLAS go fast for skinny matrices+//+// [1] S. Boehm, ‘How to Optimize a CUDA Matmul Kernel for cuBLAS-like+// Performance’, 2022. [Online]. Available:+// https://siboehm.com/articles/22/CUDA-MMM. [Accessed:+// 05-Mar-2024].+#include <algorithm>#include <cstdlib>#include <type_traits>@@ -32,81 +60,13 @@#define cudaGetLastError hipGetLastError#endif-//-// _ _ ___ _ _ ___-// | |_(_)_ _ _ _| _ ) | /_\ / __|-// | _| | ' \ || | _ \ |__ / _ \\__ \.-// \__|_|_||_\_, |___/____/_/ \_\___/-// |__/-//-// BASIC LINEAR ALGEBRA SUBPROGRAMS-//-+#define WARPSIZE 32#define THREAD_COUNT ((BM * BN) / (TM * TN))#define KERNEL __launch_bounds__(THREAD_COUNT)#define CEIL_DIV(M, N) (((M) + (N) - 1) / (N))-struct tinyblasContext {- cudaStream_t stream;-};--tinyblasStatus_t tinyblasCreate(tinyblasHandle_t *out_handle) {- tinyblasHandle_t handle;- if ((handle = (tinyblasHandle_t)malloc(sizeof(struct tinyblasContext)))) {- *out_handle = handle;- return TINYBLAS_STATUS_SUCCESS;- } else {- return TINYBLAS_STATUS_ALLOC_FAILED;- }-}--tinyblasStatus_t tinyblasDestroy(tinyblasHandle_t handle) {- free(handle);- return TINYBLAS_STATUS_SUCCESS;-}--tinyblasStatus_t tinyblasSetStream(tinyblasHandle_t handle, void *stream) {- handle->stream = (cudaStream_t)stream;- return TINYBLAS_STATUS_SUCCESS;-}--tinyblasStatus_t tinyblasGetStream(tinyblasHandle_t handle, void **out_stream) {- *out_stream = handle->stream;- return TINYBLAS_STATUS_SUCCESS;-}--tinyblasStatus_t tinyblasSgemm(tinyblasHandle_t handle, //- tinyblasOperation_t transa, //- tinyblasOperation_t transb, //- int m, int n, int k, //- const float *alpha, //- const float *A, int lda, //- const float *B, int ldb, //- const float *beta, //- float *C, int ldc) {- return tinyblasGemmEx(handle, transa, transb, m, n, k, alpha, A, TINYBLAS_R_32F, lda, B,- TINYBLAS_R_32F, ldb, beta, C, TINYBLAS_R_32F, ldc, TINYBLAS_COMPUTE_32F,- TINYBLAS_GEMM_DEFAULT);-}--const char *tinyblasGetStatusString(tinyblasStatus_t err) {- switch (err) {- case TINYBLAS_STATUS_SUCCESS:- return "Success";- case TINYBLAS_STATUS_ALLOC_FAILED:- return "Alloc failed";- case TINYBLAS_STATUS_INVALID_VALUE:- return "Invalid value";- case TINYBLAS_STATUS_NOT_SUPPORTED:- return "Not supported";- case TINYBLAS_STATUS_EXECUTION_FAILED:- return "Execution failed";- case TINYBLAS_STATUS_DIMENSION_OVERFLOW:- return "Dimension overflow";- default:- return "Unknown error";- }-}+////////////////////////////////////////////////////////////////////////////////////////////////////+// tinyBLAS block tiling outer product GEMM kerneltemplate <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,@@ -179,31 +139,306 @@ static __device__ void matmul_block2d(tinyblasOperation_t transa, tinyblasOperat}}-template <int BM, int BN, int TM, int TN, typename WORD, typename SRC, typename DST>-static __global__ void KERNEL tinyblasGE_entry(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) {- matmul_block2d<BM, BN, TM, TN>(transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);+////////////////////////////////////////////////////////////////////////////////////////////////////+// 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,+ typename WORD, typename SRC, typename DST>+static __device__ void matmul_warp2d(tinyblasOperation_t aT, //+ 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 warpIdx = threadIdx.x / WARPSIZE;+ const int warpCol = warpIdx % (BN / WN);+ const int warpRow = warpIdx / (BN / WN);++ constexpr int WARPS = TT / WARPSIZE;+ 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);++ const int threadIdxInWarp = threadIdx.x % WARPSIZE;+ const int threadColInWarp = threadIdxInWarp % (WSUBN / TN);+ const int threadRowInWarp = threadIdxInWarp / (WSUBN / TN);++ // want to tune these magnums?+ // 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)), "");++ __shared__ SRC As[BK * BM];+ __shared__ SRC Bs[BK * BN];++ WORD Ar[WMI * TM] = {0};+ WORD Br[WNI * TN] = {0};+ WORD Cr[WMI * TM * WNI * TN] = {0};++ for (int bkIdx = 0; bkIdx < k; bkIdx += 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 < 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);+ }++ __syncthreads();++ for (int l = 0; l < BK; ++l) {+ for (int ii = 0; ii < WMI; ++ii)+ for (int i = 0; i < TM; ++i)+ Ar[TM * ii + i] =+ As[BM * l + WM * warpRow + WSUBM * ii + TM * threadRowInWarp + i];+ for (int jj = 0; jj < WNI; ++jj)+ for (int j = 0; j < TN; ++j)+ Br[TN * jj + j] =+ Bs[BN * l + WN * warpCol + WSUBN * jj + TN * threadColInWarp + j];+ for (int ii = 0; ii < WMI; ++ii)+ for (int jj = 0; jj < WNI; ++jj)+ for (int i = 0; i < TM; ++i)+ for (int j = 0; j < TN; ++j)+ Cr[(WNI * TN) * (TM * ii + i) + (TN * jj) + j] +=+ Ar[TM * ii + i] * Br[TN * jj + j];+ }++ __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];+ }+ }+}++////////////////////////////////////////////////////////////////////////////////////////////////////+// tinyBLAS canonical cuBLAS-like interface++struct tinyblasContext {+ cudaStream_t stream;+};++/**+ * Creates new tinyBLAS handle.+ *+ * Before calling tinyBLAS GEMM functions a handle must first be+ * created, using this function. It should be freed later, using+ * tinyblasDestroy(). After a handle is created the caller needs+ * tinyblasSetStream() to specify the CUDA stream.+ *+ * @param out_handle receives pointer to newly created handle+ * @return TINYBLAS_STATUS_SUCCESS on success otherwise error+ */+tinyblasStatus_t tinyblasCreate(tinyblasHandle_t *out_handle) {+ tinyblasHandle_t handle;+ if ((handle = (tinyblasHandle_t)malloc(sizeof(struct tinyblasContext)))) {+ *out_handle = handle;+ return TINYBLAS_STATUS_SUCCESS;+ } else {+ return TINYBLAS_STATUS_ALLOC_FAILED;+ }+}++/**+ * Destroys tinyBLAS handle.+ *+ * @param handle is pointer to handle created by tinyblasCreate()+ * @return TINYBLAS_STATUS_SUCCESS on success otherwise error+ */+tinyblasStatus_t tinyblasDestroy(tinyblasHandle_t handle) {+ free(handle);+ return TINYBLAS_STATUS_SUCCESS;+}++/**+ * Associates CUDA handle with tinyBLAS handle.+ *+ * The provided stream will be used when tinyBLAS launches kernels.+ *+ * @param handle is pointer to handle created by tinyblasCreate()+ * @param stream is pointer to stream created by cudaStreamCreate()+ * @return TINYBLAS_STATUS_SUCCESS on success otherwise error+ */+tinyblasStatus_t tinyblasSetStream(tinyblasHandle_t handle, void *stream) {+ handle->stream = (cudaStream_t)stream;+ return TINYBLAS_STATUS_SUCCESS;+}++/**+ * Gets CUDA stream associated with tinyBLAS handle.+ *+ * @param handle is pointer to handle created by tinyblasCreate()+ * @param out_stream receives pointer to any cudaStream_t object+ * @return TINYBLAS_STATUS_SUCCESS on success otherwise error+ */+tinyblasStatus_t tinyblasGetStream(tinyblasHandle_t handle, void **out_stream) {+ *out_stream = handle->stream;+ return TINYBLAS_STATUS_SUCCESS;+}++/**+ * Returns string describing tinyBLAS status code.+ */+const char *tinyblasGetStatusString(tinyblasStatus_t err) {+ switch (err) {+ case TINYBLAS_STATUS_SUCCESS:+ return "Success";+ case TINYBLAS_STATUS_ALLOC_FAILED:+ return "Alloc failed";+ case TINYBLAS_STATUS_INVALID_VALUE:+ return "Invalid value";+ case TINYBLAS_STATUS_NOT_SUPPORTED:+ return "Not supported";+ case TINYBLAS_STATUS_EXECUTION_FAILED:+ return "Execution failed";+ case TINYBLAS_STATUS_DIMENSION_OVERFLOW:+ return "Dimension overflow";+ default:+ return "Unknown error";+ }+}++/**+ * Performs single-precision general matrix multiplication.+ *+ * 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 matrix+ * @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 C is input/output array of output matrix+ * @param ldc is row stride of `C`+ */+tinyblasStatus_t tinyblasSgemm(tinyblasHandle_t handle, tinyblasOperation_t transa,+ tinyblasOperation_t transb, int m, int n, int k, const float *alpha,+ const float *A, int lda, const float *B, int ldb, const float *beta,+ float *C, int ldc) {+ return tinyblasGemmEx(handle, transa, transb, m, n, k, alpha, A, TINYBLAS_R_32F, lda, B,+ TINYBLAS_R_32F, ldb, beta, C, TINYBLAS_R_32F, ldc, TINYBLAS_COMPUTE_32F,+ 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,+ typename WORD, typename SRC, typename DST>+static __global__ void __launch_bounds__(TT) tinyblasGE_entry(tinyblasOperation_t aT, //+ 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) {+ 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);}template <typename WORD, typename SRC, typename DST>-static tinyblasStatus_t tinyblasGE_launch(tinyblasHandle_t handle, 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) {- constexpr int BM = 48;- constexpr int BN = 32;- constexpr int TM = 3;- constexpr int TN = 8;+static tinyblasStatus_t tinyblasGE_launcher(tinyblasHandle_t handle, tinyblasOperation_t aT,+ 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) {+ constexpr int TT = 256, BM = 128, BN = 128, BK = 64, WM = 64, WN = 32, WNI = 1, TM = 8, TN = 4,+ REGS = 21504, SHARED = 16384; // THE BEASTdim3 maxblocks(CEIL_DIV(m, BM), CEIL_DIV(n, BN));- tinyblasGE_entry<BM, BN, TM, TN><<<maxblocks, THREAD_COUNT, 0, handle->stream>>>(- transa, transb, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc);+ 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>+ <<<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);+ }if (cudaGetLastError() != cudaSuccess)return TINYBLAS_STATUS_EXECUTION_FAILED;return TINYBLAS_STATUS_SUCCESS;}+template <typename WORD, typename SRC, typename DST>+static tinyblasStatus_t tinyblasGE_launch(tinyblasHandle_t handle, tinyblasOperation_t aT,+ 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) {+ return tinyblasGE_launcher(handle, bT, aT, n, m, k, alpha, B, ldb, A, lda, beta, C, ldc);+}++/**+ * Performs extended general matrix multiplication.+ *+ * 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 matrix+ * @param Atype is data type of `C`+ * @param lda is row stride of `A`+ * @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 C is input/output array of output matrix+ * @param Ctype is data type of `C`+ * @param ldc is row stride of `C`+ * @param computeType is data type of `alpha`, `beta`, and dot product+ * @param algo specifies algorithm to use+ */tinyblasStatus_t tinyblasGemmEx(tinyblasHandle_t handle, //tinyblasOperation_t transa, //tinyblasOperation_t transb, //@@ -230,6 +465,8 @@ tinyblasStatus_t tinyblasGemmEx(tinyblasHandle_t handle, //return TINYBLAS_STATUS_DIMENSION_OVERFLOW;if (1ll * ldc * (n - 1) + (m - 1) > INT_MAX)return TINYBLAS_STATUS_DIMENSION_OVERFLOW;+ if (algo != TINYBLAS_GEMM_DEFAULT)+ return TINYBLAS_STATUS_INVALID_VALUE;if (Atype != Btype)return TINYBLAS_STATUS_NOT_SUPPORTED;@@ -316,20 +553,14 @@ static tinyblasStatus_t tinyblasGBE_launch(tinyblasHandle_t handle, tinyblasOperreturn TINYBLAS_STATUS_SUCCESS;}-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[], tinyblasDataType_t Atype,- int lda, //+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[],+ tinyblasDataType_t Atype, int lda,const void *const Barray[], tinyblasDataType_t Btype,- int ldb, //- const void *beta, //- void *const Carray[], tinyblasDataType_t Ctype, int ldc, //- int batchCount, //- tinyblasComputeType_t computeType, //- tinyblasGemmAlgo_t algo) {+ int ldb, const void *beta, void *const Carray[],+ tinyblasDataType_t Ctype, int ldc, int batchCount,+ tinyblasComputeType_t computeType, tinyblasGemmAlgo_t algo) {if (m < 0 || n < 0 || k < 0)return TINYBLAS_STATUS_INVALID_VALUE;@@ -345,6 +576,8 @@ tinyblasStatus_t tinyblasGemmBatchedEx(tinyblasHandle_t handle, //return TINYBLAS_STATUS_DIMENSION_OVERFLOW;if (1ll * ldc * (n - 1) + (m - 1) > INT_MAX)return TINYBLAS_STATUS_DIMENSION_OVERFLOW;+ if (algo != TINYBLAS_GEMM_DEFAULT)+ return TINYBLAS_STATUS_INVALID_VALUE;if (Atype != Btype)return TINYBLAS_STATUS_NOT_SUPPORTED;@@ -467,6 +700,8 @@ tinyblasStatus_t tinyblasGemmStridedBatchedEx(tinyblasHandle_t handle, //return TINYBLAS_STATUS_DIMENSION_OVERFLOW;if (1ll * ldc * (n - 1) + (m - 1) > INT_MAX)return TINYBLAS_STATUS_DIMENSION_OVERFLOW;+ if (algo != TINYBLAS_GEMM_DEFAULT)+ return TINYBLAS_STATUS_INVALID_VALUE;if (Atype != Btype)return TINYBLAS_STATUS_NOT_SUPPORTED;diff --git a/llamafile/tinyblas_test.cu b/llamafile/tinyblas_test.cuindex e49a1704..a02b01f5 100644--- a/llamafile/tinyblas_test.cu+++ b/llamafile/tinyblas_test.cu@@ -17,98 +17,8 @@#include "tester.h"-void checkTinyblasWorksHHHH() {- double TOLERANCE = .5;-- {- half alpha = 1;- half beta = 0;- int m = 577;- int n = 577;- int k = 64;- int lda = k;- int ldb = k;- int ldc = m;- cuda_memory<half> A{lda * m};- cuda_memory<half> B{ldb * n};- cuda_memory<half> C{ldc * n};- 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);- broadcast(m, n, C.p, ldc, TOMBSTONE);- broadcast(m, n, G.p, ldc, TOMBSTONE);- gemmref<float>(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);- CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);- }-- {- half alpha = 1;- half beta = 0;- int m = 4096;- int n = 1024;- int k = 2048;- int lda = k;- int ldb = k;- int ldc = m;- cuda_memory<half> A{lda * m};- cuda_memory<half> B{ldb * n};- cuda_memory<half> C{ldc * n};- 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);- broadcast(m, n, C.p, ldc, TOMBSTONE);- broadcast(m, n, G.p, ldc, TOMBSTONE);- gemmref<float>(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);- CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);- }-- {- half alpha = 1;- half beta = 0;- int m = 4096;- int n = 1024;- int k = 577;- int lda = k;- int ldb = k;- int ldc = m;- cuda_memory<half> A{lda * m};- cuda_memory<half> B{ldb * n};- cuda_memory<half> C{ldc * n};- 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);- broadcast(m, n, C.p, ldc, TOMBSTONE);- broadcast(m, n, G.p, ldc, TOMBSTONE);- gemmref<float>(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);- CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);- }-- test_matmul([&](int m, int n, int k, int l, half alpha, half beta) {- int lda = m + l;- int ldb = k + l;- int ldc = m + l;- cuda_memory<half> A{lda * k};- cuda_memory<half> B{ldb * n};- cuda_memory<half> C{ldc * n};- cuda_memory<half> G{ldc * n};- randomize(m, k, A.p, lda);- randomize(k, n, B.p, ldb);- broadcast(m, n, G.p, ldc, TOMBSTONE);- broadcast(m, n, C.p, ldc, TOMBSTONE);- gemmref<float>(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);- CHECK(TOLERANCE, m, n, k, G.p, ldc, C.p, ldc);- });-}-void checkTinyblasWorksHHHS() {- double TOLERANCE = .5;+ double TOLERANCE = 1;float alpha = 1;float beta = 0;@@ -150,7 +60,7 @@ void checkTinyblasWorksHHHS() {}void checkTinyblasWorksHHSS() {- double TOLERANCE = .5;+ double TOLERANCE = 1;float alpha = 1;float beta = 0;@@ -192,7 +102,7 @@ void checkTinyblasWorksHHSS() {}void checkTinyblasWorksSSSS() {- double TOLERANCE = .5;+ double TOLERANCE = 1;float alpha = 1;float beta = 0;@@ -233,15 +143,10 @@ void checkTinyblasWorksSSSS() {});}-int main(int argc, char *argv[]) {-- is_self_testing = "hi";-+void try_size(int m, int n, int k) {+ printf("\n");float alpha = 1;float beta = 0;- int m = 48;- int n = 32;- int k = 64;int lda = k;int ldb = k;int ldc = m;@@ -253,14 +158,21 @@ int main(int argc, char *argv[]) {randomize(k, n, B.p, ldb);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);+ cublas(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);- CHECK(0, m, n, k, G.p, ldc, C.p, ldc);-- if (1)- return 0;+ CHECK(1, m, n, k, G.p, ldc, C.p, ldc);+}- RUN(checkTinyblasWorksHHHH());+int main(int argc, char *argv[]) {+ try_size(5760, 1, 128); // mistral 7b+ try_size(128, 1, 5696); // mistral 7b+ try_size(14336, 512, 4096); // mistral 7b+ try_size(128, 128, 128);+ try_size(256, 256, 256);+ try_size(512, 512, 512);+ try_size(1024, 1024, 1024);+ try_size(2048, 2048, 2048);+ try_size(32000, 512, 4096);RUN(checkTinyblasWorksSSSS());RUN(checkTinyblasWorksHHSS());RUN(checkTinyblasWorksHHHS());