Skip to content

Distribute and run LLMs with a single file.

Shave 9 seconds latency off tinyBLAS compilation

Justine Tunney2313ac796584
diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.c
index 371f738a..9970c813 100644
--- a/llama.cpp/ggml.c
+++ b/llama.cpp/ggml.c
@@ -1954,15 +1954,8 @@ inline static float ggml_silu_f32(float x) {
}
inline static float ggml_gelu_f32(float x) {
- // GeLU w/ 29.245772 bits of precision, and 2.3x better performance
- //
- // "I used the tanh approximation simply because the error function
- // erf was slow in tensorflow some years ago. If the exact version
- // is fast enough now and does not have numerical issues, I do not
- // see a reason to use an inexact version." -Dan Hendrycks @GitHub
- //
- // https://github.com/pytorch/pytorch/issues/39853
- return .5f * x * (1.f + erff(x / sqrtf(2)));
+ // GeLU approximation that goes slower and we seem to be stuck with.
+ return .5f * x * (1.f + tanhf(sqrtf(M_2_PI) * (x + .044715f * x * x * x)));
}
inline static float ggml_gelu_quick_f32(float x) {
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 7863148b..e0b5ceec 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -42,6 +42,7 @@ o/$(MODE)/llamafile: \
o/$(MODE)/llamafile/simple \
o/$(MODE)/llamafile/zipalign \
o/$(MODE)/llamafile/zipcheck \
+ o/$(MODE)/llamafile/tokenize \
o/$(MODE)/llamafile/addnl
################################################################################
diff --git a/llamafile/tinyblas_cpu.inc b/llamafile/tinyblas_cpu.h
similarity index 53%
rename from llamafile/tinyblas_cpu.inc
rename to llamafile/tinyblas_cpu.h
index 1e29bada..850ac507 100644
--- a/llamafile/tinyblas_cpu.inc
+++ b/llamafile/tinyblas_cpu.h
@@ -38,6 +38,8 @@
// [1] J. Tunney, ‘LLaMA Now Goes Faster on CPUs’, Mar. 2024. [Online].
// Available: https://justine.lol/matmul/. [Accessed: 29-Mar-2024].
+#pragma once
+
#include "llama.cpp/ggml-impl.h"
#include "llama.cpp/ggml-quants.h"
#include "llamafile.h"
@@ -936,658 +938,4 @@ class tinyBLAS_Q0_AVX2 {
};
#endif // __AVX2__
-template <typename TC>
-bool llamafile_sgemm_impl(long m, long n, long k, const void *A, long lda, const void *B, long ldb,
- TC *C, long ldc, int ith, int nth, int task, int Atype, int Btype,
- int precision) {
-
- switch (Atype) {
-
- case GGML_TYPE_F32: {
- if (Btype != GGML_TYPE_F32)
- return false;
-#if defined(__AVX512F__)
- if (k % 16)
- return false;
- tinyBLAS<0, 16, __m512, __m512, float, float, TC> tb{
- k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__AVX__) || defined(__AVX2__)
- if (k % 8)
- return false;
- tinyBLAS<0, 8, __m256, __m256, float, float, TC> tb{
- k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__ARM_NEON)
- if (k % 4)
- return false;
- tinyBLAS<0, 4, float32x4_t, float32x4_t, float, float, TC> tb{
- k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#else
- return false;
-#endif
- }
-
- case GGML_TYPE_BF16: {
-#if defined(__AVX512BF16__)
- if (k % 32)
- return false;
- if (Btype == GGML_TYPE_F32 && n < 2) {
- tinyBLAS<0, 32, __m512, __m512bh, ggml_bf16_t, float, TC> tb{
- k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- }
- if (Btype != GGML_TYPE_BF16)
- return false;
- tinyBLAS<0, 32, __m512, __m512bh, ggml_bf16_t, ggml_bf16_t, TC> tb{
- k, (const ggml_bf16_t *)A, lda, (const ggml_bf16_t *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__AVX512F__)
- if (k % 16)
- return false;
- tinyBLAS<0, 16, __m512, __m512, ggml_bf16_t, float, TC> tb{
- k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__AVX2__)
- if (k % 8)
- return false;
- if (Btype != GGML_TYPE_F32)
- return false;
- tinyBLAS<0, 8, __m256, __m256, ggml_bf16_t, float, TC> tb{
- k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__ARM_NEON) && !defined(_MSC_VER)
- if (k % 4)
- return false;
- if (Btype != GGML_TYPE_F32)
- return false;
- tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_bf16_t, float, TC> tb{
- k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#else
- return false;
-#endif
- }
-
- case GGML_TYPE_F16: {
-#if defined(__AVX512F__)
- if (k % 16)
- return false;
- if (Btype == GGML_TYPE_F32 && n < 2) {
- tinyBLAS<0, 16, __m512, __m512, ggml_fp16_t, float, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- }
- if (Btype != GGML_TYPE_F16)
- return false;
- tinyBLAS<0, 16, __m512, __m512, ggml_fp16_t, ggml_fp16_t, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif (defined(__AVX__) || defined(__AVX2__)) && defined(__F16C__)
- if (X86_HAVE(F16C)) {
- if (k % 8)
- return false;
- if (Btype == GGML_TYPE_F32 && n < 2) {
- tinyBLAS<0, 8, __m256, __m256, ggml_fp16_t, float, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- }
- if (Btype != GGML_TYPE_F16)
- return false;
- tinyBLAS<0, 8, __m256, __m256, ggml_fp16_t, ggml_fp16_t, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- } else {
- return false;
- }
-#elif defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(_MSC_VER)
- if (n < 2)
- // TODO(jart): Why is ggml_vec_dot_f16_unroll() so fast at matvec?
- return false;
- if (precision == GGML_PREC_F32) {
- if (k % 4)
- return false;
- if (Btype != GGML_TYPE_F32)
- return false;
- tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_fp16_t, float, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- } else {
- if (k % 8)
- return false;
- if (Btype != GGML_TYPE_F16)
- return false;
- tinyBLAS<0, 8, float16x8_t, float16x8_t, ggml_fp16_t, ggml_fp16_t, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
- }
-#elif defined(__ARM_NEON) && !defined(_MSC_VER)
- if (n < 2)
- // TODO(jart): Why is ggml_vec_dot_f16_unroll() so fast at matvec?
- return false;
- if (k % 4)
- return false;
- if (Btype != GGML_TYPE_F32)
- return false;
- tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_fp16_t, float, TC> tb{
- k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#else
- return false;
-#endif
- }
-
- case GGML_TYPE_Q8_0: {
- if (Btype != GGML_TYPE_Q8_0)
- return false;
-#if defined(__AVX2__) || defined(__AVX512F__)
- tinyBLAS_Q0_AVX2<0, block_q8_0, block_q8_0, TC> tb{
- k, (const block_q8_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__ARM_FEATURE_DOTPROD)
- tinyBLAS_Q0_ARM<0, block_q8_0, block_q8_0, TC> tb{
- k, (const block_q8_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#else
- return false;
-#endif
- }
-
- case GGML_TYPE_Q4_0: {
- if (Btype != GGML_TYPE_Q8_0)
- return false;
-#if defined(__AVX2__) || defined(__AVX512F__)
- tinyBLAS_Q0_AVX2<0, block_q4_0, block_q8_0, TC> tb{
- k, (const block_q4_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#elif defined(__ARM_FEATURE_DOTPROD)
- tinyBLAS_Q0_ARM<0, block_q4_0, block_q8_0, TC> tb{
- k, (const block_q4_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
- tb.matmul(m, n, task);
- return true;
-#else
- return false;
-#endif
- }
-
- default:
- return false;
- }
-
- (void)m;
- (void)n;
- (void)k;
- (void)A;
- (void)lda;
- (void)B;
- (void)ldb;
- (void)C;
- (void)ldc;
- (void)ith;
- (void)nth;
- (void)Atype;
- (void)Btype;
- (void)precision;
-}
-
-} // namespace
-
-/**
- * Performs optimized matrix multiplication on CPU.
- *
- * This subroutine may compute C = Aᵀ * B with column major ordering.
- * Despite its name, this isn't a generalized implementation. Work is
- * only performed when a handwritten kernel is written and available.
- * Otherwise the caller should fall back to a general matmul routine.
- *
- * For example, for single-threaded single-precision GEMM you can say
- *
- * llamafile_sgemm(m, n, k, A, lda, B, ldb, C, ldc, 0, 1,
- * GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32,
- * GGML_PREC_DEFAULT);
- *
- * @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 A is first input matrix (always transposed)
- * @param lda is row stride of `A`
- * @param B is second input matrix (never transposed)
- * @param ldb is row stride of `B`
- * @param C is input/output array of output matrices
- * @param ldc is row stride of `C`
- * @param ith is thread id (must be less than `nth`)
- * @param nth is number of threads (must be greater than zero)
- * @param Atype is GGML data type of `A`
- * @param Btype is GGML data type of `B`
- * @param Ctype is GGML data type of `C`
- * @param precision may be used to control the internal compute type
- * @return true if this function was able to service the matmul request
- */
-bool llamafile_sgemm(long m, long n, long k, const void *A, long lda, const void *B, long ldb,
- void *C, long ldc, int ith, int nth, int task, int Atype, int Btype, int Ctype,
- int precision) {
-
- assert(m >= 0);
- assert(n >= 0);
- assert(k >= 0);
- assert(lda >= k);
- assert(ldb >= k);
- assert(ldc >= m);
- assert(nth > 0);
- assert(ith < nth);
-
- switch (Ctype) {
- case GGML_TYPE_F32:
- return llamafile_sgemm_impl(m, n, k, A, lda, B, ldb, (float *)C, ldc, ith, nth, task, Atype,
- Btype, precision);
- case GGML_TYPE_F16:
- return llamafile_sgemm_impl(m, n, k, A, lda, B, ldb, (ggml_fp16_t *)C, ldc, ith, nth, task,
- Atype, Btype, precision);
- default:
- return false;
- }
-}
-
-//
-// _ _ ___ _ _ ___
-// | |_(_)_ _ _ _| _ ) | /_\ / __|
-// | _| | ' \ || | _ \ |__ / _ \\__ \.
-// \__|_|_||_\_, |___/____/_/ \_\___/
-// |__/
-//
-// MIXTURE OF EXPERTS TENSOR MULTIPLICATION
-//
-//
-// SHAPES
-//
-// - weights [cols, rows, experts]
-// - thought [cols, tasks, tokens] w/ tasks ≤ thinkers
-// - result [rows, thinkers, tokens] w/ thinkers ≤ experts
-// - plan [thinkers, tokens] w/ i32 < experts
-//
-// DEFINITION
-//
-// for thinker in range(thinkers):
-// for token in range(tokens):
-// for row in range(rows):
-// c = 0
-// for col in range(cols):
-// expert = plan[token][thinker]
-// a = weights[expert][row][col]
-// b = thought[token][thinker % tasks][col]
-// c += a * b
-// result[token][thinker][row] = c
-//
-// REGULARITIES
-//
-// - tokens can be odd
-// - thinkers is usually 2
-// - tasks is usually 1 or 2
-// - cols should be a multiple of 64
-// - rows should be a multiple of 64
-// - experts is usually 8 but could be 60
-// - tokens is always 1 for token generation
-// - tokens can be huge for prompt processing
-//
-// EXAMPLE
-//
-// mixtral 8x7b w/ 217 token prompt
-//
-// | ne*0 ne*1 ne*2 ne*3 | nb*0 nb*1 nb*2 nb*3 | type
-// =========================================================================
-// weights | 16384 6144 8 1 | 18 0x2400 0x3600000 0x1b000000 | q4_0
-// thought | 16384 2 217 1 | 4 0x10000 0x20000 0x1b20000 | f32
-// result | 6144 2 217 1 | 4 0x6000 0xc000 0xa2c000 | f32
-// plan | 2 217 1 1 | 4 0x20 0x1b20 0x1b20 | i32
-//
-
-namespace {
-class MixMul {
- public:
- MixMul(ggml_compute_params *params, const ggml_tensor *weights, const ggml_tensor *thought,
- const ggml_tensor *plan, ggml_tensor *result)
- : params(params),
- weights(weights),
- thought(thought),
- plan(plan),
- result(result),
- rows(weights->ne[1]),
- cols(weights->ne[0]),
- experts(weights->ne[2]),
- thinkers(plan->ne[0]),
- tasks(thought->ne[1]),
- tokens(thought->ne[2]),
- ldq((cols * 2 + ROW_ALIGN - 1) & -ROW_ALIGN),
- wdata_((char *)(((uintptr_t)params->wdata + MAX_ALIGN - 1) & -MAX_ALIGN)),
- allocated_(0) {
- }
-
- bool allocate_shared_memory() {
- if (!(quantized_thought_ = allocate<char>(MATRIX_ALIGN, tokens * tasks * ldq)))
- return false;
- if (!(rowptr_result_ = allocate<uintptr_t>(ROW_ALIGN, experts * tokens * thinkers)))
- return false;
- if (!(rowptr_thought_ = allocate<uintptr_t>(ROW_ALIGN, experts * tokens * thinkers)))
- return false;
- if (!(rowptr_count_ = allocate<long>(sizeof(long), experts)))
- return false;
- return true;
- }
-
- size_t get_allocated_bytes() {
- return (wdata_ - (char *)params->wdata) + allocated_;
- }
-
- bool mixmul() {
-
- // invariants
- assert(tasks <= thinkers);
- assert(thinkers <= experts);
- assert(tokens == plan->ne[1]);
- assert(rows == result->ne[0]);
- assert(cols == thought->ne[0]);
- assert(tokens == result->ne[2]);
- assert(thinkers == result->ne[1]);
-
- // dimensionality
- assert(plan->ne[2] == 1);
- assert(plan->ne[3] == 1);
- assert(result->ne[3] == 1);
- assert(weights->ne[3] == 1);
- assert(thought->ne[3] == 1);
-
- // miscellaneous
- assert(params->nth > 0);
- assert(params->ith < params->nth);
- assert(plan->type == GGML_TYPE_I32);
-
- // check nb01 is convertible to lda
- if (weights->nb[1] % ggml_type_size(weights->type))
- return false;
-
- // no support for column strides
-
- if (result->nb[0] != ggml_type_size(result->type))
- return false;
- if (thought->nb[0] != ggml_type_size(thought->type))
- return false;
- if (weights->nb[0] != ggml_type_size(weights->type))
- return false;
-
- // supported output types
- switch (result->type) {
- case GGML_TYPE_F32:
- return mixmuler<float>();
- case GGML_TYPE_F16:
- return mixmuler<ggml_fp16_t>();
- default:
- return false;
- }
- }
-
- private:
- template <typename TC>
- bool mixmuler() {
- switch (weights->type) {
-
- case GGML_TYPE_F32:
- if (thought->type != GGML_TYPE_F32)
- return false;
-#if defined(__AVX512F__)
- return mixmat<16, 1, tinyBLAS<NCB | NCC, 16, __m512, __m512, float, float, TC>, float,
- float, TC>();
-#elif defined(__AVX__) || defined(__AVX2__)
- return mixmat<8, 1, tinyBLAS<NCB | NCC, 8, __m256, __m256, float, float, TC>, float,
- float, TC>();
-#elif defined(__SSE__)
- return mixmat<4, 1, tinyBLAS<NCB | NCC, 4, __m128, __m128, float, float, TC>, float,
- float, TC>();
-#elif defined(__ARM_NEON)
- return mixmat<4, 1, tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, float, float, TC>,
- float, float, TC>();
-#else
- return false;
-#endif
-
- case GGML_TYPE_BF16:
- if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_BF16)
- return false;
-#if defined(__AVX512BF16__)
- return mixmat<32, 1,
- tinyBLAS<NCB | NCC, 32, __m512, __m512bh, ggml_bf16_t, ggml_bf16_t, TC>,
- ggml_bf16_t, ggml_bf16_t, TC>();
-#elif defined(__AVX512F__)
- return mixmat<16, 1,
- tinyBLAS<NCB | NCC, 16, __m512, __m512, ggml_bf16_t, ggml_bf16_t, TC>,
- ggml_bf16_t, ggml_bf16_t, TC>();
-#elif defined(__AVX2__)
- return mixmat<8, 1,
- tinyBLAS<NCB | NCC, 8, __m256, __m256, ggml_bf16_t, ggml_bf16_t, TC>,
- ggml_bf16_t, ggml_bf16_t, TC>();
-#elif defined(__ARM_NEON) && !defined(_MSC_VER)
- return mixmat<
- 4, 1,
- tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_bf16_t, ggml_bf16_t, TC>,
- ggml_bf16_t, ggml_bf16_t, TC>();
-#else
- return false;
-#endif
-
- case GGML_TYPE_F16:
- if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_F16)
- return false;
-#if defined(__AVX512F__)
- return mixmat<16, 1,
- tinyBLAS<NCB | NCC, 16, __m512, __m512, ggml_fp16_t, ggml_fp16_t, TC>,
- ggml_fp16_t, ggml_fp16_t, TC>();
-#elif (defined(__AVX__) || defined(__AVX2__)) && defined(__F16C__)
- if (X86_HAVE(F16C)) {
- return mixmat<8, 1,
- tinyBLAS<NCB | NCC, 8, __m256, __m256, ggml_fp16_t, ggml_fp16_t, TC>,
- ggml_fp16_t, ggml_fp16_t, TC>();
- } else {
- return false;
- }
-#elif defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(_MSC_VER)
- if (result->op_params[0] == GGML_PREC_F32) {
- return mixmat<
- 4, 1,
- tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, TC>,
- ggml_fp16_t, ggml_fp16_t, TC>();
- } else {
- return mixmat<
- 8, 1,
- tinyBLAS<NCB | NCC, 8, float16x8_t, float16x8_t, ggml_fp16_t, ggml_fp16_t, TC>,
- ggml_fp16_t, ggml_fp16_t, TC>();
- }
-#elif defined(__ARM_NEON) && !defined(_MSC_VER)
- return mixmat<
- 4, 1,
- tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, TC>,
- ggml_fp16_t, ggml_fp16_t, TC>();
-#else
- return false;
-#endif
-
- case GGML_TYPE_Q4_0:
- if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_Q8_0)
- return false;
-#if defined(__AVX2__) || defined(__AVX512F__)
- return mixmat<32, 32, tinyBLAS_Q0_AVX2<NCB | NCC, block_q4_0, block_q8_0, TC>,
- block_q4_0, block_q8_0, TC>();
-#elif defined(__ARM_FEATURE_DOTPROD)
- return mixmat<32, 32, tinyBLAS_Q0_ARM<NCB | NCC, block_q4_0, block_q8_0, TC>,
- block_q4_0, block_q8_0, TC>();
-#else
- return false;
-#endif
-
- case GGML_TYPE_Q8_0:
- if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_Q8_0)
- return false;
-#if defined(__AVX2__) || defined(__AVX512F__)
- return mixmat<32, 32, tinyBLAS_Q0_AVX2<NCB | NCC, block_q8_0, block_q8_0, TC>,
- block_q8_0, block_q8_0, TC>();
-#elif defined(__ARM_FEATURE_DOTPROD)
- return mixmat<32, 32, tinyBLAS_Q0_ARM<NCB | NCC, block_q8_0, block_q8_0, TC>,
- block_q8_0, block_q8_0, TC>();
-#else
- return false;
-#endif
-
- default:
- return false;
- }
- }
-
- template <int KN, int BS, typename BLAS, typename TA, typename TB, typename TC>
- bool mixmat() {
- if (cols % KN)
- return false;
- switch (params->type) {
- case GGML_TASK_TYPE_INIT:
- if (thought->type != ggml_type_trait<TB>::id)
- quantize_thought(ggml_type_trait<TB>::id);
- build_row_pointers(ggml_type_trait<TB>::id);
- return true;
- case GGML_TASK_TYPE_COMPUTE:
- assert(!(cols % BS));
- assert(!(weights->nb[1] % sizeof(TA)));
- for (int expert = 0; expert < experts; ++expert) {
- BLAS tb{cols / BS,
- (const TA *)((const char *)weights->data + expert * weights->nb[2]),
- (long)(weights->nb[1] / sizeof(TA)),
- (const TB *)(rowptr_thought_ + expert * tokens * thinkers),
- 0,
- (TC *)(rowptr_result_ + expert * tokens * thinkers),
- 0,
- params->ith,
- params->nth};
- tb.matmul(rows, rowptr_count_[expert], GGML_TASK_TYPE_COMPUTE);
- }
- return true;
- default:
- return true;
- }
- }
-
- void build_row_pointers(ggml_type vec_dot_type) {
- for (int expert = params->ith; expert < experts; expert += params->nth) {
- long count = 0;
- for (long token = 0; token < tokens; ++token)
- for (int thinker = 0; thinker < thinkers; ++thinker)
- if (expert == *(const int32_t *)((const char *)plan->data +
- token * plan->nb[1] + thinker * plan->nb[0])) {
- long row = count++;
- long idx = expert * thinkers * tokens + row;
- rowptr_result_[idx] =
- (uintptr_t)((char *)result->data + token * result->nb[2] +
- thinker * result->nb[1]);
- if (thought->type == vec_dot_type)
- rowptr_thought_[idx] =
- (uintptr_t)((char *)thought->data + token * thought->nb[2] +
- thinker % tasks * thought->nb[1]);
- else
- rowptr_thought_[idx] =
- (uintptr_t)((char *)quantized_thought_ + token * tasks * ldq +
- thinker % tasks * ldq);
- }
- rowptr_count_[expert] = count;
- }
- }
-
- void quantize_thought(ggml_type vec_dot_type) {
- long chore = 0;
- for (long token = 0; token < tokens; ++token)
- for (int task = 0; task < tasks; ++task)
- if (chore++ % params->nth == params->ith)
- quantize_row(quantized_thought_ + token * tasks * ldq + task * ldq,
- (const float *)((const char *)thought->data +
- token * thought->nb[2] + task * thought->nb[1]),
- vec_dot_type);
- }
-
- void quantize_row(void *dst, const float *src, ggml_type type) {
- assert((long)ggml_row_size(type, cols) <= ldq);
- switch (type) {
- case GGML_TYPE_F16:
- ggml_fp32_to_fp16_row(src, (ggml_fp16_t *)dst, cols);
- break;
- case GGML_TYPE_BF16:
- ggml_fp32_to_bf16_row(src, (ggml_bf16_t *)dst, cols);
- break;
- case GGML_TYPE_Q8_0:
- quantize_row_q8_0((const float *)src, (block_q8_0 *)dst, cols);
- break;
- default:
- GGML_UNREACHABLE();
- }
- }
-
- template <typename T>
- T *allocate(size_t align, size_t elems) {
- T *res = nullptr;
- size_t need = sizeof(T) * elems;
- size_t base = allocated_;
- base += align - 1;
- base &= -align;
- size_t toto = base + need;
- if (toto >= allocated_ && toto <= params->wsize) {
- res = (T *)(wdata_ + base);
- allocated_ = toto;
- }
- return res;
- }
-
- ggml_compute_params *const params;
- const ggml_tensor *const weights;
- const ggml_tensor *const thought;
- const ggml_tensor *const plan;
- ggml_tensor *const result;
- const long rows;
- const long cols;
- const int experts;
- const int thinkers;
- const int tasks;
- const long tokens;
- const long ldq;
-
- // variables
- char *const wdata_;
- size_t allocated_;
-
- // shared memory
- long *rowptr_count_ /*[experts]*/;
- char *quantized_thought_ /*[tokens][tasks][cols][2]*/;
- uintptr_t *rowptr_result_ /*[experts][tokens*thinkers]*/;
- uintptr_t *rowptr_thought_ /*[experts][tokens*thinkers]*/;
-};
} // namespace
-
-/**
- * Performs "mixture of experts" tensor multiplication on CPU.
- */
-bool llamafile_mixmul(ggml_compute_params *params, const ggml_tensor *weights,
- const ggml_tensor *thought, const ggml_tensor *plan, ggml_tensor *result) {
- MixMul mm{params, weights, thought, plan, result};
- return mm.allocate_shared_memory() && mm.mixmul();
-}
diff --git a/llamafile/tinyblas_cpu_mixmul.inc b/llamafile/tinyblas_cpu_mixmul.inc
new file mode 100644
index 00000000..bd35e4e1
--- /dev/null
+++ b/llamafile/tinyblas_cpu_mixmul.inc
@@ -0,0 +1,405 @@
+// -*- 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
+//
+// 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.
+
+#include "tinyblas_cpu.h"
+
+//
+// _ _ ___ _ _ ___
+// | |_(_)_ _ _ _| _ ) | /_\ / __|
+// | _| | ' \ || | _ \ |__ / _ \\__ \.
+// \__|_|_||_\_, |___/____/_/ \_\___/
+// |__/
+//
+// MIXTURE OF EXPERTS TENSOR MULTIPLICATION
+//
+//
+// SHAPES
+//
+// - weights [cols, rows, experts]
+// - thought [cols, tasks, tokens] w/ tasks ≤ thinkers
+// - result [rows, thinkers, tokens] w/ thinkers ≤ experts
+// - plan [thinkers, tokens] w/ i32 < experts
+//
+// DEFINITION
+//
+// for thinker in range(thinkers):
+// for token in range(tokens):
+// for row in range(rows):
+// c = 0
+// for col in range(cols):
+// expert = plan[token][thinker]
+// a = weights[expert][row][col]
+// b = thought[token][thinker % tasks][col]
+// c += a * b
+// result[token][thinker][row] = c
+//
+// REGULARITIES
+//
+// - tokens can be odd
+// - thinkers is usually 2
+// - tasks is usually 1 or 2
+// - cols should be a multiple of 64
+// - rows should be a multiple of 64
+// - experts is usually 8 but could be 60
+// - tokens is always 1 for token generation
+// - tokens can be huge for prompt processing
+//
+// EXAMPLE
+//
+// mixtral 8x7b w/ 217 token prompt
+//
+// | ne*0 ne*1 ne*2 ne*3 | nb*0 nb*1 nb*2 nb*3 | type
+// =========================================================================
+// weights | 16384 6144 8 1 | 18 0x2400 0x3600000 0x1b000000 | q4_0
+// thought | 16384 2 217 1 | 4 0x10000 0x20000 0x1b20000 | f32
+// result | 6144 2 217 1 | 4 0x6000 0xc000 0xa2c000 | f32
+// plan | 2 217 1 1 | 4 0x20 0x1b20 0x1b20 | i32
+//
+
+namespace {
+
+class MixMul {
+ public:
+ MixMul(ggml_compute_params *params, const ggml_tensor *weights, const ggml_tensor *thought,
+ const ggml_tensor *plan, ggml_tensor *result)
+ : params(params),
+ weights(weights),
+ thought(thought),
+ plan(plan),
+ result(result),
+ rows(weights->ne[1]),
+ cols(weights->ne[0]),
+ experts(weights->ne[2]),
+ thinkers(plan->ne[0]),
+ tasks(thought->ne[1]),
+ tokens(thought->ne[2]),
+ ldq((cols * 2 + ROW_ALIGN - 1) & -ROW_ALIGN),
+ wdata_((char *)(((uintptr_t)params->wdata + MAX_ALIGN - 1) & -MAX_ALIGN)),
+ allocated_(0) {
+ }
+
+ bool allocate_shared_memory() {
+ if (!(quantized_thought_ = allocate<char>(MATRIX_ALIGN, tokens * tasks * ldq)))
+ return false;
+ if (!(rowptr_result_ = allocate<uintptr_t>(ROW_ALIGN, experts * tokens * thinkers)))
+ return false;
+ if (!(rowptr_thought_ = allocate<uintptr_t>(ROW_ALIGN, experts * tokens * thinkers)))
+ return false;
+ if (!(rowptr_count_ = allocate<long>(sizeof(long), experts)))
+ return false;
+ return true;
+ }
+
+ size_t get_allocated_bytes() {
+ return (wdata_ - (char *)params->wdata) + allocated_;
+ }
+
+ bool mixmul() {
+
+ // invariants
+ assert(tasks <= thinkers);
+ assert(thinkers <= experts);
+ assert(tokens == plan->ne[1]);
+ assert(rows == result->ne[0]);
+ assert(cols == thought->ne[0]);
+ assert(tokens == result->ne[2]);
+ assert(thinkers == result->ne[1]);
+
+ // dimensionality
+ assert(plan->ne[2] == 1);
+ assert(plan->ne[3] == 1);
+ assert(result->ne[3] == 1);
+ assert(weights->ne[3] == 1);
+ assert(thought->ne[3] == 1);
+
+ // miscellaneous
+ assert(params->nth > 0);
+ assert(params->ith < params->nth);
+ assert(plan->type == GGML_TYPE_I32);
+
+ // check nb01 is convertible to lda
+ if (weights->nb[1] % ggml_type_size(weights->type))
+ return false;
+
+ // no support for column strides
+
+ if (result->nb[0] != ggml_type_size(result->type))
+ return false;
+ if (thought->nb[0] != ggml_type_size(thought->type))
+ return false;
+ if (weights->nb[0] != ggml_type_size(weights->type))
+ return false;
+
+ // supported output types
+ switch (result->type) {
+ case GGML_TYPE_F32:
+ return mixmuler<float>();
+ case GGML_TYPE_F16:
+ return mixmuler<ggml_fp16_t>();
+ default:
+ return false;
+ }
+ }
+
+ private:
+ template <typename TC>
+ bool mixmuler() {
+ switch (weights->type) {
+
+ case GGML_TYPE_F32:
+ if (thought->type != GGML_TYPE_F32)
+ return false;
+#if defined(__AVX512F__)
+ return mixmat<16, 1, tinyBLAS<NCB | NCC, 16, __m512, __m512, float, float, TC>, float,
+ float, TC>();
+#elif defined(__AVX__) || defined(__AVX2__)
+ return mixmat<8, 1, tinyBLAS<NCB | NCC, 8, __m256, __m256, float, float, TC>, float,
+ float, TC>();
+#elif defined(__SSE__)
+ return mixmat<4, 1, tinyBLAS<NCB | NCC, 4, __m128, __m128, float, float, TC>, float,
+ float, TC>();
+#elif defined(__ARM_NEON)
+ return mixmat<4, 1, tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, float, float, TC>,
+ float, float, TC>();
+#else
+ return false;
+#endif
+
+ case GGML_TYPE_BF16:
+ if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_BF16)
+ return false;
+#if defined(__AVX512BF16__)
+ return mixmat<32, 1,
+ tinyBLAS<NCB | NCC, 32, __m512, __m512bh, ggml_bf16_t, ggml_bf16_t, TC>,
+ ggml_bf16_t, ggml_bf16_t, TC>();
+#elif defined(__AVX512F__)
+ return mixmat<16, 1,
+ tinyBLAS<NCB | NCC, 16, __m512, __m512, ggml_bf16_t, ggml_bf16_t, TC>,
+ ggml_bf16_t, ggml_bf16_t, TC>();
+#elif defined(__AVX2__)
+ return mixmat<8, 1,
+ tinyBLAS<NCB | NCC, 8, __m256, __m256, ggml_bf16_t, ggml_bf16_t, TC>,
+ ggml_bf16_t, ggml_bf16_t, TC>();
+#elif defined(__ARM_NEON) && !defined(_MSC_VER)
+ return mixmat<
+ 4, 1,
+ tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_bf16_t, ggml_bf16_t, TC>,
+ ggml_bf16_t, ggml_bf16_t, TC>();
+#else
+ return false;
+#endif
+
+ case GGML_TYPE_F16:
+ if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_F16)
+ return false;
+#if defined(__AVX512F__)
+ return mixmat<16, 1,
+ tinyBLAS<NCB | NCC, 16, __m512, __m512, ggml_fp16_t, ggml_fp16_t, TC>,
+ ggml_fp16_t, ggml_fp16_t, TC>();
+#elif (defined(__AVX__) || defined(__AVX2__)) && defined(__F16C__)
+ if (X86_HAVE(F16C)) {
+ return mixmat<8, 1,
+ tinyBLAS<NCB | NCC, 8, __m256, __m256, ggml_fp16_t, ggml_fp16_t, TC>,
+ ggml_fp16_t, ggml_fp16_t, TC>();
+ } else {
+ return false;
+ }
+#elif defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(_MSC_VER)
+ if (result->op_params[0] == GGML_PREC_F32) {
+ return mixmat<
+ 4, 1,
+ tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, TC>,
+ ggml_fp16_t, ggml_fp16_t, TC>();
+ } else {
+ return mixmat<
+ 8, 1,
+ tinyBLAS<NCB | NCC, 8, float16x8_t, float16x8_t, ggml_fp16_t, ggml_fp16_t, TC>,
+ ggml_fp16_t, ggml_fp16_t, TC>();
+ }
+#elif defined(__ARM_NEON) && !defined(_MSC_VER)
+ return mixmat<
+ 4, 1,
+ tinyBLAS<NCB | NCC, 4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, TC>,
+ ggml_fp16_t, ggml_fp16_t, TC>();
+#else
+ return false;
+#endif
+
+ case GGML_TYPE_Q4_0:
+ if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_Q8_0)
+ return false;
+#if defined(__AVX2__) || defined(__AVX512F__)
+ return mixmat<32, 32, tinyBLAS_Q0_AVX2<NCB | NCC, block_q4_0, block_q8_0, TC>,
+ block_q4_0, block_q8_0, TC>();
+#elif defined(__ARM_FEATURE_DOTPROD)
+ return mixmat<32, 32, tinyBLAS_Q0_ARM<NCB | NCC, block_q4_0, block_q8_0, TC>,
+ block_q4_0, block_q8_0, TC>();
+#else
+ return false;
+#endif
+
+ case GGML_TYPE_Q8_0:
+ if (thought->type != GGML_TYPE_F32 && thought->type != GGML_TYPE_Q8_0)
+ return false;
+#if defined(__AVX2__) || defined(__AVX512F__)
+ return mixmat<32, 32, tinyBLAS_Q0_AVX2<NCB | NCC, block_q8_0, block_q8_0, TC>,
+ block_q8_0, block_q8_0, TC>();
+#elif defined(__ARM_FEATURE_DOTPROD)
+ return mixmat<32, 32, tinyBLAS_Q0_ARM<NCB | NCC, block_q8_0, block_q8_0, TC>,
+ block_q8_0, block_q8_0, TC>();
+#else
+ return false;
+#endif
+
+ default:
+ return false;
+ }
+ }
+
+ template <int KN, int BS, typename BLAS, typename TA, typename TB, typename TC>
+ bool mixmat() {
+ if (cols % KN)
+ return false;
+ switch (params->type) {
+ case GGML_TASK_TYPE_INIT:
+ if (thought->type != ggml_type_trait<TB>::id)
+ quantize_thought(ggml_type_trait<TB>::id);
+ build_row_pointers(ggml_type_trait<TB>::id);
+ return true;
+ case GGML_TASK_TYPE_COMPUTE:
+ assert(!(cols % BS));
+ assert(!(weights->nb[1] % sizeof(TA)));
+ for (int expert = 0; expert < experts; ++expert) {
+ BLAS tb{cols / BS,
+ (const TA *)((const char *)weights->data + expert * weights->nb[2]),
+ (long)(weights->nb[1] / sizeof(TA)),
+ (const TB *)(rowptr_thought_ + expert * tokens * thinkers),
+ 0,
+ (TC *)(rowptr_result_ + expert * tokens * thinkers),
+ 0,
+ params->ith,
+ params->nth};
+ tb.matmul(rows, rowptr_count_[expert], GGML_TASK_TYPE_COMPUTE);
+ }
+ return true;
+ default:
+ return true;
+ }
+ }
+
+ void build_row_pointers(ggml_type vec_dot_type) {
+ for (int expert = params->ith; expert < experts; expert += params->nth) {
+ long count = 0;
+ for (long token = 0; token < tokens; ++token)
+ for (int thinker = 0; thinker < thinkers; ++thinker)
+ if (expert == *(const int32_t *)((const char *)plan->data +
+ token * plan->nb[1] + thinker * plan->nb[0])) {
+ long row = count++;
+ long idx = expert * thinkers * tokens + row;
+ rowptr_result_[idx] =
+ (uintptr_t)((char *)result->data + token * result->nb[2] +
+ thinker * result->nb[1]);
+ if (thought->type == vec_dot_type)
+ rowptr_thought_[idx] =
+ (uintptr_t)((char *)thought->data + token * thought->nb[2] +
+ thinker % tasks * thought->nb[1]);
+ else
+ rowptr_thought_[idx] =
+ (uintptr_t)((char *)quantized_thought_ + token * tasks * ldq +
+ thinker % tasks * ldq);
+ }
+ rowptr_count_[expert] = count;
+ }
+ }
+
+ void quantize_thought(ggml_type vec_dot_type) {
+ long chore = 0;
+ for (long token = 0; token < tokens; ++token)
+ for (int task = 0; task < tasks; ++task)
+ if (chore++ % params->nth == params->ith)
+ quantize_row(quantized_thought_ + token * tasks * ldq + task * ldq,
+ (const float *)((const char *)thought->data +
+ token * thought->nb[2] + task * thought->nb[1]),
+ vec_dot_type);
+ }
+
+ void quantize_row(void *dst, const float *src, ggml_type type) {
+ assert((long)ggml_row_size(type, cols) <= ldq);
+ switch (type) {
+ case GGML_TYPE_F16:
+ ggml_fp32_to_fp16_row(src, (ggml_fp16_t *)dst, cols);
+ break;
+ case GGML_TYPE_BF16:
+ ggml_fp32_to_bf16_row(src, (ggml_bf16_t *)dst, cols);
+ break;
+ case GGML_TYPE_Q8_0:
+ quantize_row_q8_0((const float *)src, (block_q8_0 *)dst, cols);
+ break;
+ default:
+ GGML_UNREACHABLE();
+ }
+ }
+
+ template <typename T>
+ T *allocate(size_t align, size_t elems) {
+ T *res = nullptr;
+ size_t need = sizeof(T) * elems;
+ size_t base = allocated_;
+ base += align - 1;
+ base &= -align;
+ size_t toto = base + need;
+ if (toto >= allocated_ && toto <= params->wsize) {
+ res = (T *)(wdata_ + base);
+ allocated_ = toto;
+ }
+ return res;
+ }
+
+ ggml_compute_params *const params;
+ const ggml_tensor *const weights;
+ const ggml_tensor *const thought;
+ const ggml_tensor *const plan;
+ ggml_tensor *const result;
+ const long rows;
+ const long cols;
+ const int experts;
+ const int thinkers;
+ const int tasks;
+ const long tokens;
+ const long ldq;
+
+ // variables
+ char *const wdata_;
+ size_t allocated_;
+
+ // shared memory
+ long *rowptr_count_ /*[experts]*/;
+ char *quantized_thought_ /*[tokens][tasks][cols][2]*/;
+ uintptr_t *rowptr_result_ /*[experts][tokens*thinkers]*/;
+ uintptr_t *rowptr_thought_ /*[experts][tokens*thinkers]*/;
+};
+
+} // namespace
+
+/**
+ * Performs "mixture of experts" tensor multiplication on CPU.
+ */
+bool llamafile_mixmul(ggml_compute_params *params, const ggml_tensor *weights,
+ const ggml_tensor *thought, const ggml_tensor *plan, ggml_tensor *result) {
+ MixMul mm{params, weights, thought, plan, result};
+ return mm.allocate_shared_memory() && mm.mixmul();
+}
diff --git a/llamafile/tinyblas_cpu_amd_avx.cpp b/llamafile/tinyblas_cpu_mixmul_amd_avx.cpp
similarity index 88%
rename from llamafile/tinyblas_cpu_amd_avx.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_avx.cpp
index 75ea97e1..6efe28f9 100644
--- a/llamafile/tinyblas_cpu_amd_avx.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_avx.cpp
@@ -1,7 +1,6 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_avx
#define llamafile_mixmul llamafile_mixmul_amd_avx
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
/**
* Returns number of shared memory bytes llamafile_mixmul() needs.
diff --git a/llamafile/tinyblas_cpu_amd_avx2.cpp b/llamafile/tinyblas_cpu_mixmul_amd_avx2.cpp
similarity index 53%
rename from llamafile/tinyblas_cpu_amd_avx2.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_avx2.cpp
index 3457d3f6..16f96499 100644
--- a/llamafile/tinyblas_cpu_amd_avx2.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_avx2.cpp
@@ -1,5 +1,4 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_avx2
#define llamafile_mixmul llamafile_mixmul_amd_avx2
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_amd_avx512f.cpp b/llamafile/tinyblas_cpu_mixmul_amd_avx512f.cpp
similarity index 53%
rename from llamafile/tinyblas_cpu_amd_avx512f.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_avx512f.cpp
index e0af44fd..73df0395 100644
--- a/llamafile/tinyblas_cpu_amd_avx512f.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_avx512f.cpp
@@ -1,5 +1,4 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_avx512f
#define llamafile_mixmul llamafile_mixmul_amd_avx512f
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_amd_avxvnni.cpp b/llamafile/tinyblas_cpu_mixmul_amd_avxvnni.cpp
similarity index 53%
rename from llamafile/tinyblas_cpu_amd_avxvnni.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_avxvnni.cpp
index 84b6f608..5da12221 100644
--- a/llamafile/tinyblas_cpu_amd_avxvnni.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_avxvnni.cpp
@@ -1,5 +1,4 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_avxvnni
#define llamafile_mixmul llamafile_mixmul_amd_avxvnni
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_amd_fma.cpp b/llamafile/tinyblas_cpu_mixmul_amd_fma.cpp
similarity index 53%
rename from llamafile/tinyblas_cpu_amd_fma.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_fma.cpp
index 6e42e4d5..924b7f4b 100644
--- a/llamafile/tinyblas_cpu_amd_fma.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_fma.cpp
@@ -1,5 +1,4 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_fma
#define llamafile_mixmul llamafile_mixmul_amd_fma
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_amd_zen4.cpp b/llamafile/tinyblas_cpu_mixmul_amd_zen4.cpp
similarity index 53%
rename from llamafile/tinyblas_cpu_amd_zen4.cpp
rename to llamafile/tinyblas_cpu_mixmul_amd_zen4.cpp
index e905fe3e..0c383e46 100644
--- a/llamafile/tinyblas_cpu_amd_zen4.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_amd_zen4.cpp
@@ -1,5 +1,4 @@
#ifdef __x86_64__
-#define llamafile_sgemm llamafile_sgemm_amd_zen4
#define llamafile_mixmul llamafile_mixmul_amd_zen4
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_arm80.cpp b/llamafile/tinyblas_cpu_mixmul_arm80.cpp
similarity index 88%
rename from llamafile/tinyblas_cpu_arm80.cpp
rename to llamafile/tinyblas_cpu_mixmul_arm80.cpp
index a5268fd4..c03ecdf5 100644
--- a/llamafile/tinyblas_cpu_arm80.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_arm80.cpp
@@ -1,7 +1,6 @@
#ifdef __aarch64__
-#define llamafile_sgemm llamafile_sgemm_arm80
#define llamafile_mixmul llamafile_mixmul_arm80
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
/**
* Returns number of shared memory bytes llamafile_mixmul() needs.
diff --git a/llamafile/tinyblas_cpu_arm82.cpp b/llamafile/tinyblas_cpu_mixmul_arm82.cpp
similarity index 54%
rename from llamafile/tinyblas_cpu_arm82.cpp
rename to llamafile/tinyblas_cpu_mixmul_arm82.cpp
index 1246d825..06aba7de 100644
--- a/llamafile/tinyblas_cpu_arm82.cpp
+++ b/llamafile/tinyblas_cpu_mixmul_arm82.cpp
@@ -1,5 +1,4 @@
#ifdef __aarch64__
-#define llamafile_sgemm llamafile_sgemm_arm82
#define llamafile_mixmul llamafile_mixmul_arm82
-#include "tinyblas_cpu.inc"
+#include "tinyblas_cpu_mixmul.inc"
#endif // __aarch64__
diff --git a/llamafile/tinyblas_cpu_sgemm.inc b/llamafile/tinyblas_cpu_sgemm.inc
new file mode 100644
index 00000000..27448e7e
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm.inc
@@ -0,0 +1,314 @@
+// -*- 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
+//
+// 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.
+
+#include "tinyblas_cpu.h"
+
+//
+// _ _ ___ _ _ ___
+// | |_(_)_ _ _ _| _ ) | /_\ / __|
+// | _| | ' \ || | _ \ |__ / _ \\__ \.
+// \__|_|_||_\_, |___/____/_/ \_\___/
+// |__/
+//
+// BASIC LINEAR ALGEBRA SUBPROGRAMS
+//
+//
+// This file implements multithreaded CPU matrix multiplication for the
+// common contiguous use case C = Aᵀ * B. These kernels are designed to
+// have excellent performance[1] for matrices that fit in the CPU cache
+// without imposing any overhead such as cache filling or malloc calls.
+//
+// This implementation does not guarantee any upper bound with rounding
+// errors, which grow along with k. Our goal's to maximally exploit the
+// hardware for performance, and then use whatever resources remain for
+// improving numerical accuracy.
+//
+// [1] J. Tunney, ‘LLaMA Now Goes Faster on CPUs’, Mar. 2024. [Online].
+// Available: https://justine.lol/matmul/. [Accessed: 29-Mar-2024].
+
+namespace {
+
+template <typename TC>
+bool llamafile_sgemm_impl(long m, long n, long k, const void *A, long lda, const void *B, long ldb,
+ TC *C, long ldc, int ith, int nth, int task, int Atype, int Btype,
+ int precision) {
+
+ switch (Atype) {
+
+ case GGML_TYPE_F32: {
+ if (Btype != GGML_TYPE_F32)
+ return false;
+#if defined(__AVX512F__)
+ if (k % 16)
+ return false;
+ tinyBLAS<0, 16, __m512, __m512, float, float, TC> tb{
+ k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__AVX__) || defined(__AVX2__)
+ if (k % 8)
+ return false;
+ tinyBLAS<0, 8, __m256, __m256, float, float, TC> tb{
+ k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__ARM_NEON)
+ if (k % 4)
+ return false;
+ tinyBLAS<0, 4, float32x4_t, float32x4_t, float, float, TC> tb{
+ k, (const float *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#else
+ return false;
+#endif
+ }
+
+ case GGML_TYPE_BF16: {
+#if defined(__AVX512BF16__)
+ if (k % 32)
+ return false;
+ if (Btype == GGML_TYPE_F32 && n < 2) {
+ tinyBLAS<0, 32, __m512, __m512bh, ggml_bf16_t, float, TC> tb{
+ k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ }
+ if (Btype != GGML_TYPE_BF16)
+ return false;
+ tinyBLAS<0, 32, __m512, __m512bh, ggml_bf16_t, ggml_bf16_t, TC> tb{
+ k, (const ggml_bf16_t *)A, lda, (const ggml_bf16_t *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__AVX512F__)
+ if (k % 16)
+ return false;
+ tinyBLAS<0, 16, __m512, __m512, ggml_bf16_t, float, TC> tb{
+ k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__AVX2__)
+ if (k % 8)
+ return false;
+ if (Btype != GGML_TYPE_F32)
+ return false;
+ tinyBLAS<0, 8, __m256, __m256, ggml_bf16_t, float, TC> tb{
+ k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__ARM_NEON) && !defined(_MSC_VER)
+ if (k % 4)
+ return false;
+ if (Btype != GGML_TYPE_F32)
+ return false;
+ tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_bf16_t, float, TC> tb{
+ k, (const ggml_bf16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#else
+ return false;
+#endif
+ }
+
+ case GGML_TYPE_F16: {
+#if defined(__AVX512F__)
+ if (k % 16)
+ return false;
+ if (Btype == GGML_TYPE_F32 && n < 2) {
+ tinyBLAS<0, 16, __m512, __m512, ggml_fp16_t, float, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ }
+ if (Btype != GGML_TYPE_F16)
+ return false;
+ tinyBLAS<0, 16, __m512, __m512, ggml_fp16_t, ggml_fp16_t, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif (defined(__AVX__) || defined(__AVX2__)) && defined(__F16C__)
+ if (X86_HAVE(F16C)) {
+ if (k % 8)
+ return false;
+ if (Btype == GGML_TYPE_F32 && n < 2) {
+ tinyBLAS<0, 8, __m256, __m256, ggml_fp16_t, float, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ }
+ if (Btype != GGML_TYPE_F16)
+ return false;
+ tinyBLAS<0, 8, __m256, __m256, ggml_fp16_t, ggml_fp16_t, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ } else {
+ return false;
+ }
+#elif defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(_MSC_VER)
+ if (n < 2)
+ // TODO(jart): Why is ggml_vec_dot_f16_unroll() so fast at matvec?
+ return false;
+ if (precision == GGML_PREC_F32) {
+ if (k % 4)
+ return false;
+ if (Btype != GGML_TYPE_F32)
+ return false;
+ tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_fp16_t, float, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ } else {
+ if (k % 8)
+ return false;
+ if (Btype != GGML_TYPE_F16)
+ return false;
+ tinyBLAS<0, 8, float16x8_t, float16x8_t, ggml_fp16_t, ggml_fp16_t, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const ggml_fp16_t *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+ }
+#elif defined(__ARM_NEON) && !defined(_MSC_VER)
+ if (n < 2)
+ // TODO(jart): Why is ggml_vec_dot_f16_unroll() so fast at matvec?
+ return false;
+ if (k % 4)
+ return false;
+ if (Btype != GGML_TYPE_F32)
+ return false;
+ tinyBLAS<0, 4, float32x4_t, float32x4_t, ggml_fp16_t, float, TC> tb{
+ k, (const ggml_fp16_t *)A, lda, (const float *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#else
+ return false;
+#endif
+ }
+
+ case GGML_TYPE_Q8_0: {
+ if (Btype != GGML_TYPE_Q8_0)
+ return false;
+#if defined(__AVX2__) || defined(__AVX512F__)
+ tinyBLAS_Q0_AVX2<0, block_q8_0, block_q8_0, TC> tb{
+ k, (const block_q8_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__ARM_FEATURE_DOTPROD)
+ tinyBLAS_Q0_ARM<0, block_q8_0, block_q8_0, TC> tb{
+ k, (const block_q8_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#else
+ return false;
+#endif
+ }
+
+ case GGML_TYPE_Q4_0: {
+ if (Btype != GGML_TYPE_Q8_0)
+ return false;
+#if defined(__AVX2__) || defined(__AVX512F__)
+ tinyBLAS_Q0_AVX2<0, block_q4_0, block_q8_0, TC> tb{
+ k, (const block_q4_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#elif defined(__ARM_FEATURE_DOTPROD)
+ tinyBLAS_Q0_ARM<0, block_q4_0, block_q8_0, TC> tb{
+ k, (const block_q4_0 *)A, lda, (const block_q8_0 *)B, ldb, C, ldc, ith, nth};
+ tb.matmul(m, n, task);
+ return true;
+#else
+ return false;
+#endif
+ }
+
+ default:
+ return false;
+ }
+
+ (void)m;
+ (void)n;
+ (void)k;
+ (void)A;
+ (void)lda;
+ (void)B;
+ (void)ldb;
+ (void)C;
+ (void)ldc;
+ (void)ith;
+ (void)nth;
+ (void)Atype;
+ (void)Btype;
+ (void)precision;
+}
+
+} // namespace
+
+/**
+ * Performs optimized matrix multiplication on CPU.
+ *
+ * This subroutine may compute C = Aᵀ * B with column major ordering.
+ * Despite its name, this isn't a generalized implementation. Work is
+ * only performed when a handwritten kernel is written and available.
+ * Otherwise the caller should fall back to a general matmul routine.
+ *
+ * For example, for single-threaded single-precision GEMM you can say
+ *
+ * llamafile_sgemm(m, n, k, A, lda, B, ldb, C, ldc, 0, 1,
+ * GGML_TYPE_F32, GGML_TYPE_F32, GGML_TYPE_F32,
+ * GGML_PREC_DEFAULT);
+ *
+ * @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 A is first input matrix (always transposed)
+ * @param lda is row stride of `A`
+ * @param B is second input matrix (never transposed)
+ * @param ldb is row stride of `B`
+ * @param C is input/output array of output matrices
+ * @param ldc is row stride of `C`
+ * @param ith is thread id (must be less than `nth`)
+ * @param nth is number of threads (must be greater than zero)
+ * @param Atype is GGML data type of `A`
+ * @param Btype is GGML data type of `B`
+ * @param Ctype is GGML data type of `C`
+ * @param precision may be used to control the internal compute type
+ * @return true if this function was able to service the matmul request
+ */
+bool llamafile_sgemm(long m, long n, long k, const void *A, long lda, const void *B, long ldb,
+ void *C, long ldc, int ith, int nth, int task, int Atype, int Btype, int Ctype,
+ int precision) {
+
+ assert(m >= 0);
+ assert(n >= 0);
+ assert(k >= 0);
+ assert(lda >= k);
+ assert(ldb >= k);
+ assert(ldc >= m);
+ assert(nth > 0);
+ assert(ith < nth);
+
+ switch (Ctype) {
+ case GGML_TYPE_F32:
+ return llamafile_sgemm_impl(m, n, k, A, lda, B, ldb, (float *)C, ldc, ith, nth, task, Atype,
+ Btype, precision);
+ case GGML_TYPE_F16:
+ return llamafile_sgemm_impl(m, n, k, A, lda, B, ldb, (ggml_fp16_t *)C, ldc, ith, nth, task,
+ Atype, Btype, precision);
+ default:
+ return false;
+ }
+}
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_avx.cpp b/llamafile/tinyblas_cpu_sgemm_amd_avx.cpp
new file mode 100644
index 00000000..832f61f0
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_avx.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_avx
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_avx2.cpp b/llamafile/tinyblas_cpu_sgemm_amd_avx2.cpp
new file mode 100644
index 00000000..7550b52c
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_avx2.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_avx2
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_avx512f.cpp b/llamafile/tinyblas_cpu_sgemm_amd_avx512f.cpp
new file mode 100644
index 00000000..1386f4c5
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_avx512f.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_avx512f
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_avxvnni.cpp b/llamafile/tinyblas_cpu_sgemm_amd_avxvnni.cpp
new file mode 100644
index 00000000..0f25d5f3
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_avxvnni.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_avxvnni
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_fma.cpp b/llamafile/tinyblas_cpu_sgemm_amd_fma.cpp
new file mode 100644
index 00000000..e1ade5a7
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_fma.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_fma
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_amd_zen4.cpp b/llamafile/tinyblas_cpu_sgemm_amd_zen4.cpp
new file mode 100644
index 00000000..57f2ecba
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_amd_zen4.cpp
@@ -0,0 +1,4 @@
+#ifdef __x86_64__
+#define llamafile_sgemm llamafile_sgemm_amd_zen4
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __x86_64__
diff --git a/llamafile/tinyblas_cpu_sgemm_arm80.cpp b/llamafile/tinyblas_cpu_sgemm_arm80.cpp
new file mode 100644
index 00000000..c375a05d
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_arm80.cpp
@@ -0,0 +1,4 @@
+#ifdef __aarch64__
+#define llamafile_sgemm llamafile_sgemm_arm80
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __aarch64__
diff --git a/llamafile/tinyblas_cpu_sgemm_arm82.cpp b/llamafile/tinyblas_cpu_sgemm_arm82.cpp
new file mode 100644
index 00000000..81e77ce2
--- /dev/null
+++ b/llamafile/tinyblas_cpu_sgemm_arm82.cpp
@@ -0,0 +1,4 @@
+#ifdef __aarch64__
+#define llamafile_sgemm llamafile_sgemm_arm82
+#include "tinyblas_cpu_sgemm.inc"
+#endif // __aarch64__