mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-23 11:17:36 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
239242322d | ||
|
|
30ec35ae2e | ||
|
|
87f816e87f | ||
|
|
1d3aad2fd8 | ||
|
|
325914defd | ||
|
|
1094646c1f | ||
|
|
27d0a1fc73 | ||
|
|
b6d5ce4bc9 | ||
|
|
1f3ea67fbf | ||
|
|
a0677c341b | ||
|
|
2359d27a36 | ||
|
|
51fc2f90e2 | ||
|
|
03813c56e4 | ||
|
|
46f4da2174 | ||
|
|
4663f9ca8a | ||
|
|
969d733317 | ||
|
|
a8f8294c45 |
@@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0;
|
||||
imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0;
|
||||
|
||||
const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA);
|
||||
if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY &&
|
||||
gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) {
|
||||
const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx);
|
||||
imatrix.stats_schema.resize(n_schema);
|
||||
for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); }
|
||||
} else {
|
||||
if (schema_idx != -1) {
|
||||
LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str());
|
||||
}
|
||||
|
||||
imatrix.stats_schema = {
|
||||
"sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance",
|
||||
};
|
||||
}
|
||||
|
||||
const std::string in_sum_suffix{ ".in_sum" };
|
||||
const std::string in_sum2_suffix{ ".in_sum2" };
|
||||
const std::string counts_suffix{ ".counts" };
|
||||
const std::string stats_suffix{ ".stats" };
|
||||
|
||||
struct sum_tensors {
|
||||
struct ggml_tensor * in_sum = nullptr;
|
||||
struct ggml_tensor * in_sum2 = nullptr;
|
||||
struct ggml_tensor * counts = nullptr;
|
||||
struct ggml_tensor * stats = nullptr;
|
||||
};
|
||||
|
||||
std::map<std::string, sum_tensors> sums_counts_for;
|
||||
@@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
sums_counts_for[std::move(name)].in_sum2 = cur;
|
||||
} else if (string_remove_suffix(name, counts_suffix)) {
|
||||
sums_counts_for[std::move(name)].counts = cur;
|
||||
} else if (string_remove_suffix(name, stats_suffix)) {
|
||||
sums_counts_for[std::move(name)].stats = cur;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
const struct ggml_tensor * in_sum = sc.second.in_sum;
|
||||
const struct ggml_tensor * in_sum2 = sc.second.in_sum2;
|
||||
const struct ggml_tensor * counts = sc.second.counts;
|
||||
const struct ggml_tensor * stats = sc.second.stats;
|
||||
|
||||
if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) {
|
||||
LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
|
||||
@@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
e.activations[j] = ((const float *) in_sum->data)[j];
|
||||
}
|
||||
}
|
||||
|
||||
if (stats && stats->type == GGML_TYPE_F32) {
|
||||
const int64_t n_stats = ggml_nelements(stats);
|
||||
e.stats.resize(n_stats);
|
||||
for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; }
|
||||
}
|
||||
}
|
||||
|
||||
gguf_free(ctx_gguf);
|
||||
|
||||
@@ -15,11 +15,13 @@ struct common_imatrix_entry {
|
||||
std::vector<float> sums;
|
||||
std::vector<float> activations;
|
||||
std::vector<int64_t> counts;
|
||||
std::vector<float> stats;
|
||||
};
|
||||
|
||||
struct common_imatrix {
|
||||
std::map<std::string, common_imatrix_entry> entries;
|
||||
std::vector<std::string> datasets;
|
||||
std::vector<std::string> stats_schema;
|
||||
int32_t chunk_count = 0;
|
||||
int32_t chunk_size = 0;
|
||||
int32_t n_layer_nextn = 0;
|
||||
|
||||
@@ -995,6 +995,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
|
||||
|
||||
**GPU-specific**
|
||||
|
||||
- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
|
||||
|
||||
```bash
|
||||
export GGML_OPENVINO_DEVICE=GPU
|
||||
export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
|
||||
export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
|
||||
mkdir -p $GGML_OPENVINO_SPILL_DIR
|
||||
./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
|
||||
--spec-type draft-dflash --spec-draft-n-max 4
|
||||
```
|
||||
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
|
||||
- `-sm tensor` is not supported.
|
||||
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
|
||||
|
||||
@@ -2292,6 +2292,15 @@ extern "C" {
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * sinks);
|
||||
|
||||
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
|
||||
|
||||
// Add table[indices[key, query], head, query] to the mask, in F32.
|
||||
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
|
||||
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * table,
|
||||
struct ggml_tensor * indices);
|
||||
|
||||
// TODO: needs to be adapted to ggml_flash_attn_ext
|
||||
GGML_API struct ggml_tensor * ggml_flash_attn_back(
|
||||
struct ggml_context * ctx,
|
||||
|
||||
@@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
|
||||
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
|
||||
|
||||
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GGML_ASSERT(ggml_backend_dev_is_meta(dev));
|
||||
const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context;
|
||||
return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(),
|
||||
|
||||
@@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
return true;
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
{
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
if (op->src[5] != nullptr) {
|
||||
// K/V row lists and indexed bias are not supported
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
#ifdef ASCEND_310P
|
||||
|
||||
@@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b
|
||||
}
|
||||
|
||||
static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const struct ggml_tensor * src0 = op->src[0];
|
||||
const struct ggml_tensor * src1 = op->src[1];
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ if (NOT TARGET kleidiai)
|
||||
endif()
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:/WX->)
|
||||
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:/WX-;/w>")
|
||||
else()
|
||||
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error>)
|
||||
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error;-w>")
|
||||
endif()
|
||||
|
||||
@@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * sinks = dst->src[4];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
const ggml_tensor * bias_table = dst->src[6];
|
||||
const ggml_tensor * bias_indices = dst->src[7];
|
||||
|
||||
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
|
||||
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
|
||||
@@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
const int64_t rv2 = neq2/nev2;
|
||||
const int64_t rv3 = neq3/nev3;
|
||||
|
||||
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
|
||||
|
||||
// parallelize by q rows using ggml_vec_dot_f32
|
||||
|
||||
float scale = 1.0f;
|
||||
@@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
|
||||
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
|
||||
|
||||
// bias rows of this query and head, queries of all streams are flattened
|
||||
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
|
||||
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
|
||||
|
||||
// online softmax / attention
|
||||
// loop over n_kv and n_head_kv
|
||||
// ref: https://arxiv.org/pdf/2112.05682.pdf
|
||||
|
||||
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
|
||||
const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
|
||||
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
|
||||
if (bias) {
|
||||
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
|
||||
mv += bias[bins[ic]];
|
||||
}
|
||||
mv *= slope;
|
||||
if (mv == -INFINITY) {
|
||||
continue;
|
||||
}
|
||||
@@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
|
||||
|
||||
const ggml_tensor * bias_table = dst->src[6];
|
||||
const ggml_tensor * bias_indices = dst->src[7];
|
||||
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
|
||||
|
||||
int ir = ir0;
|
||||
while (ir < ir1) {
|
||||
// q indices for the start of this tile
|
||||
@@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
|
||||
bool can_skip = true;
|
||||
for (int tq = 0; tq < tile_rows; tq++) {
|
||||
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
|
||||
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
|
||||
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
|
||||
for (int tk = 0; tk < kv_tile; tk++) {
|
||||
mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
|
||||
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
|
||||
if (bias) {
|
||||
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
|
||||
m += bias[bins[ic + tk]];
|
||||
}
|
||||
mask32[tq * KV_TILE_SZ + tk] = slope * m;
|
||||
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
|
||||
can_skip = false;
|
||||
}
|
||||
|
||||
@@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
#endif// FLASH_ATTN_AVAILABLE
|
||||
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
|
||||
@@ -607,13 +607,13 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
|
||||
float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w)));
|
||||
amax = warp_reduce_max<8>(amax);
|
||||
|
||||
const float d_inv = 127.0f / amax;
|
||||
const float d_inv = amax == 0.0f ? 0.0f : 127.0f / amax;
|
||||
char4 q;
|
||||
q.x = roundf(xi.x*d_inv);
|
||||
q.y = roundf(xi.y*d_inv);
|
||||
q.z = roundf(xi.z*d_inv);
|
||||
q.w = roundf(xi.w*d_inv);
|
||||
const float d = 1.0f / d_inv;
|
||||
const float d = amax == 0.0f ? 0.0f : 1.0f / d_inv;
|
||||
|
||||
// as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+
|
||||
[[maybe_unused]] float sum = 0.0f;
|
||||
|
||||
@@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] &&
|
||||
(op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] &&
|
||||
(op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr &&
|
||||
!ggml_flash_attn_ext_has_indexed_bias(op) &&
|
||||
ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) {
|
||||
float max_bias = 0.0f;
|
||||
float logit_softcap = 0.0f;
|
||||
|
||||
@@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn(
|
||||
return false;
|
||||
}
|
||||
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
if (op->src[5] != nullptr) {
|
||||
// K/V row lists and indexed bias are not supported
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ set(METALLIB_KERNEL_SOURCES
|
||||
kernels/mul_mv.metal
|
||||
kernels/mul_mv_mma.metal
|
||||
kernels/mul_mm.metal
|
||||
kernels/mul_mm_tensor.metal
|
||||
kernels/quantize.metal
|
||||
kernels/softmax.metal
|
||||
kernels/norm.metal
|
||||
@@ -223,21 +224,21 @@ else()
|
||||
|
||||
# the tensor API kernels go in a separate metallib, loaded only where supported
|
||||
if (GGML_METAL_HAS_TENSOR_LIB)
|
||||
set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor.air")
|
||||
set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor_tensor.air")
|
||||
# the tensor API needs OS 26+
|
||||
set(XC_FLAGS_TENSOR ${XC_FLAGS} -mtargetos=${GGML_METAL_TARGET_OS}26.0${METAL_TARGET_SIM})
|
||||
add_custom_command(
|
||||
OUTPUT ${AIR_MM_TENSOR}
|
||||
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm.metal -o ${AIR_MM_TENSOR}
|
||||
DEPENDS kernels/mul_mm.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h
|
||||
COMMENT "Compiling kernels/mul_mm.metal (tensor API)"
|
||||
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm_tensor.metal -o ${AIR_MM_TENSOR}
|
||||
DEPENDS kernels/mul_mm_tensor.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h
|
||||
COMMENT "Compiling kernels/mul_mm_tensor.metal (tensor API)"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
set(AIR_FA_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/fa_tensor_tensor.air")
|
||||
add_custom_command(
|
||||
OUTPUT ${AIR_FA_TENSOR}
|
||||
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR}
|
||||
COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR}
|
||||
DEPENDS kernels/fa_tensor.metal kernels/common.h ${METALLIB_COMMON} ggml-metal-impl.h
|
||||
COMMENT "Compiling kernels/fa_tensor.metal (tensor API)"
|
||||
VERBATIM
|
||||
|
||||
@@ -974,7 +974,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
|
||||
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
|
||||
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
|
||||
|
||||
const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor;
|
||||
const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib));
|
||||
|
||||
const bool has_tensor = props_dev->has_tensor;
|
||||
|
||||
const bool prec_bf16 = props_dev->has_bfloat &&
|
||||
ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 &&
|
||||
(has_tensor ? tsrc0 == GGML_TYPE_F32 : tsrc0 != GGML_TYPE_BF16);
|
||||
|
||||
const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32;
|
||||
|
||||
const bool bc_out = has_tensor
|
||||
? (op->ne[0] % NRA != 0 || op->ne[1] % NRB != 0)
|
||||
@@ -986,7 +994,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
|
||||
const int16_t r2 = (int16_t) (ne12 / op->src[0]->ne[2]);
|
||||
const int16_t r3 = (int16_t) (ne13 / op->src[0]->ne[3]);
|
||||
|
||||
snprintf(base, 256, "kernel_mul_mm_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
|
||||
const bool use_tensor = has_tensor && !prec_f32;
|
||||
|
||||
const char * infix = use_tensor ? "_tensor" : "";
|
||||
const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : "");
|
||||
snprintf(base, 256, "kernel_mul_mm%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
|
||||
snprintf(name, 256, "%s_bci=%d_bco=%d_ne12=%d_ne13=%d_r2=%d_r3=%d",
|
||||
base, bc_inp, bc_out, ne12, ne13, r2, r3);
|
||||
|
||||
@@ -1006,7 +1018,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
|
||||
ggml_metal_cv_free(cv);
|
||||
}
|
||||
|
||||
if (has_tensor) {
|
||||
if (use_tensor) {
|
||||
res.nr0 = NRA;
|
||||
res.nr1 = NRB;
|
||||
|
||||
@@ -1016,7 +1028,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta
|
||||
res.nr0 = 64;
|
||||
res.nr1 = 32;
|
||||
|
||||
res.smem = bc_out ? 8192 : (4096 + 2048);
|
||||
res.smem = prec_f32 ? 12288 : (bc_out ? 8192 : (4096 + 2048));
|
||||
}
|
||||
|
||||
res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
|
||||
@@ -1305,9 +1317,21 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m
|
||||
const ggml_type tsrc0 = op->src[0]->type;
|
||||
const ggml_type tsrc1 = op->src[1]->type;
|
||||
|
||||
const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib));
|
||||
|
||||
const bool prec_bf16 = props_dev->has_bfloat &&
|
||||
ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 &&
|
||||
tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4;
|
||||
|
||||
const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32;
|
||||
|
||||
const bool bc_inp = op->src[0]->ne[0] % 32 != 0;
|
||||
|
||||
snprintf(base, 256, "kernel_mul_mm_id_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1));
|
||||
const bool use_tensor = props_dev->has_tensor && !prec_f32;
|
||||
|
||||
const char * infix = use_tensor ? "_tensor" : "";
|
||||
const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : "");
|
||||
snprintf(base, 256, "kernel_mul_mm_id%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix);
|
||||
snprintf(name, 256, "%s_bci=%d", base, bc_inp);
|
||||
|
||||
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
|
||||
@@ -1321,7 +1345,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m
|
||||
ggml_metal_cv_free(cv);
|
||||
}
|
||||
|
||||
res.smem = 8192;
|
||||
res.smem = prec_f32 ? 12288 : 8192;
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -129,6 +129,7 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi
|
||||
X(MUL_MV, mul_mv) \
|
||||
X(MUL_MV_MMA, mul_mv_mma) \
|
||||
X(MUL_MM, mul_mm) \
|
||||
X(MUL_MM_TENSOR, mul_mm_tensor) \
|
||||
X(QUANTIZE, quantize) \
|
||||
X(SOFTMAX, softmax) \
|
||||
X(NORM, norm) \
|
||||
@@ -1510,14 +1511,16 @@ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t
|
||||
}
|
||||
}
|
||||
|
||||
static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_tensor) {
|
||||
static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_bfloat) {
|
||||
GGML_ASSERT(op->op == GGML_OP_MUL_MAT || op->op == GGML_OP_MUL_MAT_ID);
|
||||
|
||||
const enum ggml_prec prec = ggml_prec_get_src(op, 1);
|
||||
|
||||
if (prec == GGML_PREC_F32) {
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
if (prec == GGML_PREC_BF16) {
|
||||
return has_tensor && op->op == GGML_OP_MUL_MAT && op->src[0]->type != GGML_TYPE_F32;
|
||||
return has_bfloat && op->src[1]->type == GGML_TYPE_F32;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1744,6 +1747,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
|
||||
case GGML_OP_ROLL:
|
||||
return ggml_is_contiguous(op->src[0]);
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
// K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice
|
||||
if (op->src[5] != NULL) {
|
||||
const struct ggml_tensor * kv_rows = op->src[5];
|
||||
@@ -1907,7 +1913,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
|
||||
case GGML_OP_SOLVE_TRI:
|
||||
return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32;
|
||||
case GGML_OP_MUL_MAT:
|
||||
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) {
|
||||
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) {
|
||||
return false;
|
||||
}
|
||||
// the FWHT kernels read an F16 source directly; every other F16 src1 path
|
||||
@@ -1920,7 +1926,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te
|
||||
has_simdgroup_reduction, op, true,
|
||||
ggml_metal_op_mul_mat_use_mm(op, has_simdgroup_mm));
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) {
|
||||
if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) {
|
||||
return false;
|
||||
}
|
||||
return ggml_metal_supports_mul_mat_op(
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
#include "ggml-metal-ops.h"
|
||||
#include "ggml-metal-tuning.h"
|
||||
|
||||
#include <TargetConditionals.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
@@ -653,6 +655,13 @@ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgrap
|
||||
ggml_metal_graph_optimize(ctx, cgraph);
|
||||
}
|
||||
|
||||
// iOS can stop a command buffer that runs for more than a few seconds, so split the graph into shorter ones there
|
||||
#if TARGET_OS_IPHONE
|
||||
#define GGML_METAL_DEFAULT_N_CB 8
|
||||
#else
|
||||
#define GGML_METAL_DEFAULT_N_CB 1
|
||||
#endif // TARGET_OS_IPHONE
|
||||
|
||||
static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
|
||||
GGML_ASSERT(ggml_backend_is_metal(backend));
|
||||
|
||||
@@ -704,7 +713,7 @@ ggml_backend_t ggml_backend_metal_init(void) {
|
||||
/* .context = */ ctx,
|
||||
};
|
||||
|
||||
ggml_backend_metal_set_n_cb(backend, 1);
|
||||
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
|
||||
|
||||
return backend;
|
||||
}
|
||||
@@ -799,7 +808,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t
|
||||
/* .context = */ ctx,
|
||||
};
|
||||
|
||||
ggml_backend_metal_set_n_cb(backend, 1);
|
||||
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
|
||||
|
||||
return backend;
|
||||
|
||||
|
||||
@@ -124,3 +124,46 @@ template<> inline float4 elu_approx<float4>(float4 x) {
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
template <typename T> struct value_type;
|
||||
template <> struct value_type<float4x4> { typedef float type; };
|
||||
template <> struct value_type<half4x4> { typedef half type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type<bfloat4x4> { typedef bfloat type; };
|
||||
#endif
|
||||
|
||||
template <typename T> struct value_type_4x4;
|
||||
template <> struct value_type_4x4<float> { typedef float4x4 type; };
|
||||
template <> struct value_type_4x4<half> { typedef half4x4 type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type_4x4<bfloat> { typedef bfloat4x4 type; };
|
||||
#endif
|
||||
|
||||
template <typename T> struct value_type_2x4;
|
||||
template <> struct value_type_2x4<float> { typedef float2x4 type; };
|
||||
template <> struct value_type_2x4<half> { typedef half2x4 type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type_2x4<bfloat> { typedef bfloat2x4 type; };
|
||||
#endif
|
||||
|
||||
template <typename T> struct value_type_8x8;
|
||||
template <> struct value_type_8x8<float> { typedef simdgroup_float8x8 type; };
|
||||
template <> struct value_type_8x8<half> { typedef simdgroup_half8x8 type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type_8x8<bfloat> { typedef simdgroup_bfloat8x8 type; };
|
||||
#endif
|
||||
|
||||
template <typename T> struct value_type_4;
|
||||
template <> struct value_type_4<float> { typedef float4 type; };
|
||||
template <> struct value_type_4<half> { typedef half4 type; };
|
||||
template <> struct value_type_4<int32_t> { typedef int4 type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type_4<bfloat> { typedef bfloat4 type; };
|
||||
#endif
|
||||
|
||||
template <typename T> struct value_type_2;
|
||||
template <> struct value_type_2<float> { typedef float2 type; };
|
||||
template <> struct value_type_2<half> { typedef half2 type; };
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template <> struct value_type_2<bfloat> { typedef bfloat2 type; };
|
||||
#endif
|
||||
|
||||
@@ -393,7 +393,7 @@ void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg
|
||||
uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3);
|
||||
dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4);
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
reg[i/4][i%4] = dl * (q[i] & mask) - ml;
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - ml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,7 +422,7 @@ void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg
|
||||
dl *= coef;
|
||||
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml);
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - (h[i] & m ? 0 : ml));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,7 +446,7 @@ void dequantize_q4_K(device const block_q4_K * xb, short il, thread type4x4 & re
|
||||
|
||||
const ushort mask = il < 2 ? 0x0F : 0xF0;
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
reg[i/4][i%4] = dl * (q[i] & mask) - ml;
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * (q[i] & mask) - ml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,7 +469,7 @@ void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg
|
||||
const ushort mask = il<2 ? 0x0F : 0xF0;
|
||||
const float qh_val = il<2 ? 16.f : 256.f;
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml;
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,10 +499,10 @@ void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg
|
||||
const uint32_t low = (ql[2*i] | (uint32_t)(ql[2*i+1] << 16)) & kmask2;
|
||||
const uint32_t high = (qh[2*i] | (uint32_t)(qh[2*i+1] << 16)) & kmask1;
|
||||
const uint32_t q = ((high << shl_h) >> shr_h) | (low >> shr_l);
|
||||
reg[i][0] = dl0 * ((half)(q & 0xFF)) - ml;
|
||||
reg[i][1] = dl1 * ((float)(q & 0xFF00)) - ml;
|
||||
reg[i][2] = dl2 * ((float)(q & 0xFF0000)) - ml;
|
||||
reg[i][3] = dl3 * ((float)(q & 0xFF000000)) - ml;
|
||||
reg[i][0] = (typename value_type<type4x4>::type) (dl0 * ((half)(q & 0xFF)) - ml);
|
||||
reg[i][1] = (typename value_type<type4x4>::type) (dl1 * ((float)(q & 0xFF00)) - ml);
|
||||
reg[i][2] = (typename value_type<type4x4>::type) (dl2 * ((float)(q & 0xFF0000)) - ml);
|
||||
reg[i][3] = (typename value_type<type4x4>::type) (dl3 * ((float)(q & 0xFF000000)) - ml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,12 +522,12 @@ void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x
|
||||
constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]);
|
||||
uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
|
||||
}
|
||||
grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]);
|
||||
signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
|
||||
reg[2+i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -543,12 +543,12 @@ void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4
|
||||
constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511));
|
||||
uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
|
||||
reg[i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
|
||||
}
|
||||
grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511));
|
||||
signs = ksigns_iq2xs[q2[2*il+1] >> 9];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f);
|
||||
reg[2+i/4][i%4] = (typename value_type<type4x4>::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -567,15 +567,15 @@ void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x
|
||||
constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]);
|
||||
uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
|
||||
reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
|
||||
reg[0][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f));
|
||||
reg[1][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f));
|
||||
}
|
||||
grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]);
|
||||
grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]);
|
||||
signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127];
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f);
|
||||
reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f);
|
||||
reg[2][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f));
|
||||
reg[3][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -593,14 +593,14 @@ void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 &
|
||||
constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256)));
|
||||
constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256)));
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]);
|
||||
reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]);
|
||||
reg[0][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]));
|
||||
reg[1][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]));
|
||||
}
|
||||
grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256)));
|
||||
grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256)));
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]);
|
||||
reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]);
|
||||
reg[2][i] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]));
|
||||
reg[3][i] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,8 +618,8 @@ void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 &
|
||||
constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300)));
|
||||
constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300)));
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]);
|
||||
reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]);
|
||||
reg[i/4+0][i%4] = (typename value_type<type4x4>::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]));
|
||||
reg[i/4+2][i%4] = (typename value_type<type4x4>::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -637,10 +637,10 @@ void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 &
|
||||
constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700)));
|
||||
constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700)));
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[0][i] = dl * (grid1[i] & 0xf) + ml;
|
||||
reg[1][i] = dl * (grid1[i] >> 4) + ml;
|
||||
reg[2][i] = dl * (grid2[i] & 0xf) + ml;
|
||||
reg[3][i] = dl * (grid2[i] >> 4) + ml;
|
||||
reg[0][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] & 0xf) + ml);
|
||||
reg[1][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] >> 4) + ml);
|
||||
reg[2][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] & 0xf) + ml);
|
||||
reg[3][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] >> 4) + ml);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -664,10 +664,10 @@ void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 &
|
||||
constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700)));
|
||||
constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700)));
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
reg[0][i] = dl * (grid1[i] & 0xf) + ml1;
|
||||
reg[1][i] = dl * (grid1[i] >> 4) + ml1;
|
||||
reg[2][i] = dl * (grid2[i] & 0xf) + ml2;
|
||||
reg[3][i] = dl * (grid2[i] >> 4) + ml2;
|
||||
reg[0][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] & 0xf) + ml1);
|
||||
reg[1][i] = (typename value_type<type4x4>::type) (dl * (grid1[i] >> 4) + ml1);
|
||||
reg[2][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] & 0xf) + ml2);
|
||||
reg[3][i] = (typename value_type<type4x4>::type) (dl * (grid2[i] >> 4) + ml2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,10 +679,10 @@ void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4
|
||||
thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f;
|
||||
reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
|
||||
reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
|
||||
reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
|
||||
reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
|
||||
reg[i][0] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[0]]);
|
||||
reg[i][1] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[1]]);
|
||||
reg[i][2] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[2]]);
|
||||
reg[i][3] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[3]]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -712,10 +712,10 @@ void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4
|
||||
thread const uint8_t * q8 = (thread const uint8_t *)&aux32;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f;
|
||||
reg[i][0] = d * kvalues_iq4nl_f[q8[0]];
|
||||
reg[i][1] = d * kvalues_iq4nl_f[q8[1]];
|
||||
reg[i][2] = d * kvalues_iq4nl_f[q8[2]];
|
||||
reg[i][3] = d * kvalues_iq4nl_f[q8[3]];
|
||||
reg[i][0] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[0]]);
|
||||
reg[i][1] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[1]]);
|
||||
reg[i][2] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[2]]);
|
||||
reg[i][3] = (typename value_type<type4x4>::type) (d * kvalues_iq4nl_f[q8[3]]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,28 +17,17 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT +
|
||||
// ref: https://arxiv.org/pdf/2307.08691.pdf
|
||||
template<
|
||||
typename q_t, // query types in shared memory
|
||||
typename q4_t,
|
||||
typename q8x8_t,
|
||||
typename k_t, // key types in shared memory
|
||||
typename k4x4_t,
|
||||
typename k8x8_t,
|
||||
typename v_t, // value types in shared memory
|
||||
typename v4x4_t,
|
||||
typename v8x8_t,
|
||||
typename qk_t, // Q*K types
|
||||
typename qk8x8_t,
|
||||
typename s_t, // soft-max types
|
||||
typename s2_t,
|
||||
typename s8x8_t,
|
||||
typename o_t, // attention accumulation types
|
||||
typename o4_t,
|
||||
typename o8x8_t,
|
||||
typename kd4x4_t, // key type in device memory
|
||||
short nl_k,
|
||||
void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &),
|
||||
void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4<k_t>::type &),
|
||||
typename vd4x4_t, // value type in device memory
|
||||
short nl_v,
|
||||
void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &),
|
||||
void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4<v_t>::type &),
|
||||
short DK, // K head size
|
||||
short DV, // V head size
|
||||
short Q, // queries per threadgroup
|
||||
@@ -58,6 +47,18 @@ void kernel_flash_attn_ext_impl(
|
||||
uint3 tgpig,
|
||||
ushort tiisg,
|
||||
ushort sgitg) {
|
||||
using q4_t = typename value_type_4 <q_t>::type;
|
||||
using q8x8_t = typename value_type_8x8 <q_t>::type;
|
||||
using k4x4_t = typename value_type_4x4 <k_t>::type;
|
||||
using k8x8_t = typename value_type_8x8 <k_t>::type;
|
||||
using v4x4_t = typename value_type_4x4 <v_t>::type;
|
||||
using v8x8_t = typename value_type_8x8 <v_t>::type;
|
||||
using qk8x8_t = typename value_type_8x8<qk_t>::type;
|
||||
using s2_t = typename value_type_2 <s_t>::type;
|
||||
using s8x8_t = typename value_type_8x8 <s_t>::type;
|
||||
using o4_t = typename value_type_4 <o_t>::type;
|
||||
using o8x8_t = typename value_type_8x8 <o_t>::type;
|
||||
|
||||
const ushort iq3 = tgpig[2];
|
||||
const ushort iq2 = tgpig[1];
|
||||
const ushort iq1 = tgpig[0]*Q;
|
||||
@@ -656,28 +657,17 @@ void kernel_flash_attn_ext_impl(
|
||||
|
||||
template<
|
||||
typename q_t, // query types in shared memory
|
||||
typename q4_t,
|
||||
typename q8x8_t,
|
||||
typename k_t, // key types in shared memory
|
||||
typename k4x4_t,
|
||||
typename k8x8_t,
|
||||
typename v_t, // value types in shared memory
|
||||
typename v4x4_t,
|
||||
typename v8x8_t,
|
||||
typename qk_t, // Q*K types
|
||||
typename qk8x8_t,
|
||||
typename s_t, // soft-max types
|
||||
typename s2_t,
|
||||
typename s8x8_t,
|
||||
typename o_t, // attention accumulation types
|
||||
typename o4_t,
|
||||
typename o8x8_t,
|
||||
typename kd4x4_t, // key type in device memory
|
||||
short nl_k,
|
||||
void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &),
|
||||
void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4<k_t>::type &),
|
||||
typename vd4x4_t, // value type in device memory
|
||||
short nl_v,
|
||||
void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &),
|
||||
void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4<v_t>::type &),
|
||||
short DK, // K head size
|
||||
short DV, // V head size
|
||||
short Q = OP_FLASH_ATTN_EXT_NQPSG, // queries per threadgroup
|
||||
@@ -696,7 +686,7 @@ kernel void kernel_flash_attn_ext(
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
#define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C
|
||||
#define FWD_TMPL q_t, k_t, v_t, qk_t, s_t, o_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C
|
||||
#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg
|
||||
switch (FC_flash_attn_ext_nsg) {
|
||||
// note: disabled cases to reduce library load time
|
||||
|
||||
@@ -6,31 +6,28 @@
|
||||
// template to be able to explore different combinations
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -3,31 +3,28 @@
|
||||
#include "fa_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
half, half4x4, simdgroup_half8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_BF \
|
||||
bfloat, bfloat4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
bfloat, bfloat4x4, simdgroup_bfloat8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
half, half4, simdgroup_half8x8
|
||||
//float, float4, simdgroup_float8x8
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
bfloat, \
|
||||
float, \
|
||||
float, \
|
||||
half
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half, half4, simdgroup_half8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, float4x4, simdgroup_float8x8, \
|
||||
float, simdgroup_float8x8, \
|
||||
float, float2, simdgroup_float8x8, \
|
||||
float, float4, simdgroup_float8x8
|
||||
//half, half4, simdgroup_half8x8
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext<FA_TYPES, half4x4, 1, dequantize_f16, half4x4, 1, dequantize_f16, 64, 64>) flash_attn_ext_t;
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_AT
|
||||
// ref: https://arxiv.org/pdf/2307.08691.pdf
|
||||
template<
|
||||
typename T, // Q, K, V and P types
|
||||
typename T4,
|
||||
short DK, // K head size
|
||||
short DV, // V head size
|
||||
short Q = OP_FLASH_ATTN_EXT_TENSOR_NQPSG, // queries per threadgroup
|
||||
@@ -29,6 +28,8 @@ kernel void kernel_flash_attn_ext_tensor(
|
||||
uint3 tgpig [[threadgroup_position_in_grid]],
|
||||
ushort tiisg [[thread_index_in_simdgroup]],
|
||||
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
|
||||
using T4 = typename value_type_4<T>::type;
|
||||
|
||||
constexpr short NW = N_SIMDWIDTH;
|
||||
constexpr short NT = NW*NSG;
|
||||
constexpr short NQ = Q/NSG;
|
||||
@@ -279,20 +280,20 @@ kernel void kernel_flash_attn_ext_tensor(
|
||||
co.store(td);
|
||||
}
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_tensor<half, half4, 64, 64>) flash_attn_ext_tensor_t;
|
||||
typedef decltype(kernel_flash_attn_ext_tensor<half, 64, 64>) flash_attn_ext_tensor_t;
|
||||
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 64, 64>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 128, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 192, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 256, 256>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, half4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 64, 64>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 128, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 192, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 256, 256>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<half, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 64, 64>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 128, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 192, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 256, 256>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, bfloat4, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 64, 64>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 128, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 192, 128>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 256, 256>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 512, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor<bfloat, 576, 512, OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE>;
|
||||
|
||||
#endif // GGML_METAL_HAS_TENSOR
|
||||
|
||||
@@ -15,19 +15,18 @@ constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EX
|
||||
constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]];
|
||||
constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]];
|
||||
template<
|
||||
typename q4_t, // query types in shared memory
|
||||
typename k4_t, // key types in shared memory
|
||||
typename v4_t, // value types in shared memory
|
||||
typename q_t, // query types in shared memory
|
||||
typename k_t, // key types in shared memory
|
||||
typename v_t, // value types in shared memory
|
||||
typename qk_t, // Q*K types
|
||||
typename s_t, // soft-max types
|
||||
typename s4_t,
|
||||
typename o4_t, // attention accumulation types
|
||||
typename o_t, // attention accumulation types
|
||||
typename kd4_t, // key type in device memory
|
||||
short nl_k,
|
||||
void (*deq_k_t4)(device const kd4_t *, short, thread k4_t &),
|
||||
void (*deq_k_t4)(device const kd4_t *, short, thread typename value_type_4<k_t>::type &),
|
||||
typename vd4_t, // value type in device memory
|
||||
short nl_v,
|
||||
void (*deq_v_t4)(device const vd4_t *, short, thread v4_t &),
|
||||
void (*deq_v_t4)(device const vd4_t *, short, thread typename value_type_4<v_t>::type &),
|
||||
short DK, // K head size
|
||||
short DV, // V head size
|
||||
short NE = 4, // head elements per thread
|
||||
@@ -48,6 +47,12 @@ kernel void kernel_flash_attn_ext_vec(
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
using q4_t = typename value_type_4<q_t>::type;
|
||||
using k4_t = typename value_type_4<k_t>::type;
|
||||
using v4_t = typename value_type_4<v_t>::type;
|
||||
using s4_t = typename value_type_4<s_t>::type;
|
||||
using o4_t = typename value_type_4<o_t>::type;
|
||||
|
||||
static_assert(DK % 32 == 0, "DK must be divisible by 32");
|
||||
static_assert(DV % 32 == 0, "DV must be divisible by 32");
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
#include "fa_vec_common.metal"
|
||||
|
||||
#define FA_TYPES \
|
||||
half4, \
|
||||
half4, \
|
||||
half4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
half, \
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
#define FA_TYPES_F32 \
|
||||
half4, \
|
||||
float4, \
|
||||
float4, \
|
||||
float, \
|
||||
float, float4, \
|
||||
float4
|
||||
half, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float, \
|
||||
float
|
||||
|
||||
typedef decltype(kernel_flash_attn_ext_vec<FA_TYPES, half4, 1, dequantize_f16_t4, half4, 1, dequantize_f16_t4, 128, 128, 4>) flash_attn_ext_vec_t;
|
||||
|
||||
|
||||
@@ -465,6 +465,8 @@ kernel void kernel_count_equal(
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort3 ntg[[threads_per_threadgroup]]) {
|
||||
using T4 = typename value_type_4<T>::type;
|
||||
|
||||
const short NSG = FC_count_equal_nsg;
|
||||
|
||||
const int i3 = tgpig.z;
|
||||
@@ -913,12 +915,14 @@ constant bool FC_top_k_mask_has_extra [[function_constant(FC_TOP_K_MASK + 2)]];
|
||||
constant bool FC_top_k_mask_vec [[function_constant(FC_TOP_K_MASK + 3)]];
|
||||
|
||||
// the fill runs before the scatter, both are fully parallel over the whole dst and over the picks of one row
|
||||
template <typename T, typename T4>
|
||||
template <typename T>
|
||||
kernel void kernel_top_k_mask_fill(
|
||||
constant ggml_metal_kargs_top_k_mask & args,
|
||||
device char * dst,
|
||||
uint tid[[thread_position_in_grid]],
|
||||
uint ntot[[threads_per_grid]]) {
|
||||
using T4 = typename value_type_4<T>::type;
|
||||
|
||||
const T ninf = T(-INFINITY);
|
||||
|
||||
if (FC_top_k_mask_vec) {
|
||||
@@ -934,14 +938,14 @@ kernel void kernel_top_k_mask_fill(
|
||||
}
|
||||
}
|
||||
|
||||
typedef decltype(kernel_top_k_mask_fill<half, half4>) kernel_top_k_mask_fill_h_t;
|
||||
typedef decltype(kernel_top_k_mask_fill<float, float4>) kernel_top_k_mask_fill_f_t;
|
||||
typedef decltype(kernel_top_k_mask_fill<half>) kernel_top_k_mask_fill_h_t;
|
||||
typedef decltype(kernel_top_k_mask_fill<float>) kernel_top_k_mask_fill_f_t;
|
||||
|
||||
template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill<half, half4>;
|
||||
template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill<float, float4>;
|
||||
template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill<half>;
|
||||
template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill<float>;
|
||||
|
||||
// one threadgroup per row: copy the mask cells of the live picks and of the extra cells over the fill
|
||||
template <typename T, typename T4>
|
||||
template <typename T>
|
||||
kernel void kernel_top_k_mask(
|
||||
constant ggml_metal_kargs_top_k_mask & args,
|
||||
device const char * mask,
|
||||
@@ -953,6 +957,8 @@ kernel void kernel_top_k_mask(
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
uint3 tpitg[[thread_position_in_threadgroup]],
|
||||
uint3 ntg_max[[threads_per_threadgroup]]) {
|
||||
using T4 = typename value_type_4<T>::type;
|
||||
|
||||
const int i1 = tgpig.x;
|
||||
const int i2 = tgpig.y;
|
||||
const int i3 = tgpig.z;
|
||||
@@ -997,8 +1003,8 @@ kernel void kernel_top_k_mask(
|
||||
}
|
||||
}
|
||||
|
||||
typedef decltype(kernel_top_k_mask<half, half4>) kernel_top_k_mask_h_t;
|
||||
typedef decltype(kernel_top_k_mask<float, float4>) kernel_top_k_mask_f_t;
|
||||
typedef decltype(kernel_top_k_mask<half>) kernel_top_k_mask_h_t;
|
||||
typedef decltype(kernel_top_k_mask<float>) kernel_top_k_mask_f_t;
|
||||
|
||||
template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask<half, half4>;
|
||||
template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask<float, float4>;
|
||||
template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask<half>;
|
||||
template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask<float>;
|
||||
|
||||
@@ -1,157 +1,20 @@
|
||||
#include "common.h"
|
||||
#include "dequantize.h"
|
||||
|
||||
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
|
||||
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
|
||||
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
|
||||
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
|
||||
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
|
||||
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
|
||||
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
|
||||
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
|
||||
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
|
||||
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
|
||||
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
|
||||
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
|
||||
constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]];
|
||||
|
||||
// each block_q contains 16*nl weights
|
||||
#ifdef GGML_METAL_HAS_TENSOR
|
||||
template<
|
||||
typename SA, typename SA_4x4, typename SA_8x8,
|
||||
typename SB, typename SB_2x4, typename SB_8x8,
|
||||
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread SA_4x4 &),
|
||||
typename T0, typename T0_4x4, typename T1, typename T1_2x4>
|
||||
kernel void kernel_mul_mm(
|
||||
constant ggml_metal_kargs_mul_mm & args,
|
||||
device const char * srcA,
|
||||
device const char * srcB,
|
||||
device char * dst,
|
||||
threadgroup char * shmem [[threadgroup(0)]],
|
||||
uint3 tgpig [[threadgroup_position_in_grid]],
|
||||
ushort tiitg [[thread_index_in_threadgroup]],
|
||||
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
|
||||
(void) sgitg;
|
||||
|
||||
// Matrix dimensions: A(M,K) x B(K,N) -> C(M,N)
|
||||
const int K = args.ne00;
|
||||
const int M = args.ne0;
|
||||
const int N = args.ne1;
|
||||
|
||||
// Batch dimension handling
|
||||
const int im = tgpig.z;
|
||||
const int i12 = im % FC_mul_mm_ne12;
|
||||
const int i13 = im / FC_mul_mm_ne12;
|
||||
|
||||
// Batch offsets for srcA and srcB
|
||||
const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03;
|
||||
|
||||
// Tile dimensions
|
||||
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
|
||||
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
|
||||
|
||||
// Tile offsets in output matrix
|
||||
const int ra = tgpig.y * NRA;
|
||||
const int rb = tgpig.x * NRB;
|
||||
|
||||
// Threadgroup memory for dequantized A tile only
|
||||
threadgroup SA * sa = (threadgroup SA *)(shmem);
|
||||
|
||||
// Work-item count for A loading
|
||||
constexpr int A_WORK_ITEMS = NRA * N_MM_NK;
|
||||
constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
|
||||
|
||||
// tA wraps threadgroup memory
|
||||
auto tA = tensor(sa, dextents<int32_t, 2>(N_MM_NK_TOTAL, NRA));
|
||||
|
||||
// tB wraps device memory directly
|
||||
device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13);
|
||||
const int strideB = args.nb11 / sizeof(T1);
|
||||
auto tB = tensor(ptrB, dextents<int32_t, 2>(K, N), array<int, 2>({1, strideB}));
|
||||
|
||||
// Configure matmul operation
|
||||
// note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static
|
||||
// N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/27064
|
||||
mpp::tensor_ops::matmul2d<
|
||||
mpp::tensor_ops::matmul2d_descriptor(
|
||||
NRB, NRA, static_cast<int>(dynamic_extent), false, true, true,
|
||||
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
|
||||
execution_simdgroups<N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y>> mm;
|
||||
|
||||
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
|
||||
|
||||
// Accumulate partial results over K dimension
|
||||
for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) {
|
||||
// === PHASE 1: Dequantization of A into threadgroup memory ===
|
||||
for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) {
|
||||
const int row = work / N_MM_NK;
|
||||
const int k_chunk = work % N_MM_NK;
|
||||
const int k_pos = loop_k + k_chunk * 16;
|
||||
const short k_base = k_chunk * 16;
|
||||
|
||||
// Bounds check: skip device read if row is out of matrix bounds
|
||||
if (ra + row < M) {
|
||||
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
|
||||
// Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4).
|
||||
// MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd,
|
||||
// nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned.
|
||||
// Mirrors the legacy kernel's existing guard.
|
||||
device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0;
|
||||
}
|
||||
} else {
|
||||
const int block_idx = k_pos / (16 * nl);
|
||||
const short il = (k_pos / 16) % nl;
|
||||
|
||||
device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0);
|
||||
|
||||
SA_4x4 temp_a;
|
||||
dequantize_func(row_ptr + block_idx, il, temp_a);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
// Zero-pad A for K positions beyond valid range (handles partial K iterations)
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Zero-pad rows beyond matrix bounds
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
// === PHASE 2: Tensor matmul ===
|
||||
// Clamp the K extent of both operand tensors to the remaining valid K range so
|
||||
// the dynamic-K op never reads past the K extent of src1 (or the staged A tile).
|
||||
const int kExt = min(N_MM_NK_TOTAL, K - loop_k);
|
||||
|
||||
auto tAv = tensor(sa, dextents<int32_t, 2>(kExt, NRA), array<int, 2>({1, N_MM_NK_TOTAL}));
|
||||
auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents<int32_t, 2>(kExt, N - rb), array<int, 2>({1, strideB}));
|
||||
|
||||
mm.run(tBv, tAv, cT);
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
}
|
||||
|
||||
// Store result tile to output matrix (with batch offset)
|
||||
// a slice is not used because its byte offset is int32 and wraps at 2 GiB
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/28748
|
||||
const int tileM = min(NRA, M - ra);
|
||||
const int tileN = min(NRB, N - rb);
|
||||
|
||||
device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra;
|
||||
|
||||
auto tD = tensor(dstTile, dextents<int32_t, 2>(tileM, tileN), array<int, 2>({1, M}));
|
||||
cT.store(tD);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
template<
|
||||
typename S0, typename S0_4x4, typename S0_8x8,
|
||||
typename S1, typename S1_2x4, typename S1_8x8,
|
||||
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &),
|
||||
typename T0, typename T0_4x4, typename T1, typename T1_2x4>
|
||||
typename S0, typename S1,
|
||||
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &),
|
||||
typename T0, typename T1>
|
||||
kernel void kernel_mul_mm(
|
||||
constant ggml_metal_kargs_mul_mm & args,
|
||||
device const char * src0,
|
||||
@@ -162,8 +25,12 @@ kernel void kernel_mul_mm(
|
||||
ushort tiitg[[thread_index_in_threadgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
|
||||
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
|
||||
threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096);
|
||||
using S0_4x4 = typename value_type_4x4<S0>::type;
|
||||
using S0_8x8 = typename value_type_8x8<S0>::type;
|
||||
using S1_2x4 = typename value_type_2x4<S1>::type;
|
||||
using S1_8x8 = typename value_type_8x8<S1>::type;
|
||||
using T0_4x4 = typename value_type_4x4<T0>::type;
|
||||
using T1_2x4 = typename value_type_2x4<T1>::type;
|
||||
|
||||
constexpr int NR0 = 64;
|
||||
constexpr int NR1 = 32;
|
||||
@@ -172,6 +39,9 @@ kernel void kernel_mul_mm(
|
||||
constexpr int NL0 = NK/16;
|
||||
constexpr int NL1 = NK/8;
|
||||
|
||||
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
|
||||
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
|
||||
|
||||
const int im = tgpig.z;
|
||||
const int r0 = tgpig.y*NR0;
|
||||
const int r1 = tgpig.x*NR1;
|
||||
@@ -362,7 +232,6 @@ kernel void kernel_mul_mm(
|
||||
}
|
||||
}
|
||||
|
||||
#endif // GGML_METAL_HAS_TENSOR
|
||||
|
||||
template<short ne20> // n_expert_used
|
||||
kernel void kernel_mul_mm_id_map0(
|
||||
@@ -544,8 +413,7 @@ template [[host_name("kernel_mul_mm_id_map0_ne20_10")]] kernel kernel_mul_mm_id_
|
||||
template [[host_name("kernel_mul_mm_id_map0_ne20_16")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<16>;
|
||||
template [[host_name("kernel_mul_mm_id_map0_ne20_22")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<22>;
|
||||
|
||||
// TODO: refactor into two seperate functions to avoid ifdef branching: with and without tensor support
|
||||
template<typename S0, typename S0_4x4, typename S0_8x8, typename S1, typename S1_2x4, typename S1_8x8, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &), typename T0, typename T0_4x4, typename T1, typename T1_2x4>
|
||||
template<typename S0, typename S1, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &), typename T0, typename T1>
|
||||
kernel void kernel_mul_mm_id(
|
||||
constant ggml_metal_kargs_mul_mm_id & args,
|
||||
device const char * src0,
|
||||
@@ -558,12 +426,12 @@ kernel void kernel_mul_mm_id(
|
||||
ushort tiitg[[thread_index_in_threadgroup]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
|
||||
threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096);
|
||||
|
||||
#ifdef GGML_METAL_HAS_TENSOR
|
||||
threadgroup float * sc = (threadgroup float *)(shmem);
|
||||
#endif
|
||||
using S0_4x4 = typename value_type_4x4<S0>::type;
|
||||
using S0_8x8 = typename value_type_8x8<S0>::type;
|
||||
using S1_2x4 = typename value_type_2x4<S1>::type;
|
||||
using S1_8x8 = typename value_type_8x8<S1>::type;
|
||||
using T0_4x4 = typename value_type_4x4<T0>::type;
|
||||
using T1_2x4 = typename value_type_2x4<T1>::type;
|
||||
|
||||
constexpr int NR0 = 64;
|
||||
constexpr int NR1 = 32;
|
||||
@@ -572,6 +440,10 @@ kernel void kernel_mul_mm_id(
|
||||
constexpr int NL0 = NK/16;
|
||||
constexpr int NL1 = NK/8;
|
||||
|
||||
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
|
||||
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
|
||||
|
||||
|
||||
const int tile = tgpig.x; // entry tile, described by the prepass
|
||||
const int r0 = tgpig.y*NR0;
|
||||
|
||||
@@ -608,23 +480,10 @@ kernel void kernel_mul_mm_id(
|
||||
// skip the upper half of the token tile when the expert did not fill it
|
||||
constexpr short NR1H = NR1/2;
|
||||
|
||||
#ifndef GGML_METAL_HAS_TENSOR
|
||||
S0_8x8 ma[4];
|
||||
S1_8x8 mb[2];
|
||||
|
||||
simdgroup_float8x8 mc[8];
|
||||
#else
|
||||
auto tA = tensor<threadgroup S0, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(NK, NR0));
|
||||
|
||||
// sb is [NR1][NK] row-major
|
||||
auto tB0 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(NK, NR1H));
|
||||
auto tB1 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb + NR1H*NK, dextents<int32_t, 2>(NK, NR1H));
|
||||
|
||||
mpp::tensor_ops::matmul2d<
|
||||
mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
|
||||
execution_simdgroups<4>> mm;
|
||||
|
||||
#endif
|
||||
|
||||
const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31
|
||||
|
||||
@@ -645,20 +504,14 @@ kernel void kernel_mul_mm_id(
|
||||
|
||||
const bool has_hi = nr1 > NR1H;
|
||||
|
||||
#ifndef GGML_METAL_HAS_TENSOR
|
||||
for (short i = 0; i < 8; i++){
|
||||
mc[i] = make_filled_simdgroup_matrix<float, 8>(0.f);
|
||||
}
|
||||
|
||||
// simdgroups 2,3 own rows NR1H..NR1-1
|
||||
const bool sg_active = has_hi || sgitg < 2;
|
||||
#else
|
||||
auto cT0 = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB0), float>();
|
||||
auto cT1 = mm.get_destination_cooperative_tensor<decltype(tA), decltype(tB1), float>();
|
||||
#endif
|
||||
|
||||
for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) {
|
||||
#ifndef GGML_METAL_HAS_TENSOR
|
||||
// load data and store to threadgroup memory
|
||||
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
@@ -728,66 +581,6 @@ kernel void kernel_mul_mm_id(
|
||||
|
||||
*(threadgroup S1_2x4 *)(sb + 64*ib + 8*ly) = (S1_2x4)(*((device T1_2x4 *) y));
|
||||
}
|
||||
#else
|
||||
// load data and store to threadgroup memory
|
||||
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
// no need for dequantization
|
||||
for (short i = 0; i < 16; i++) {
|
||||
const short sx = 2*il0 + i/8;
|
||||
const short sy = (tiitg/NL0)/8;
|
||||
|
||||
const short lx = i%8;
|
||||
const short ly = (tiitg/NL0)%8;
|
||||
//const short lx = (tiitg/NL0)%8;
|
||||
//const short ly = i%8;
|
||||
|
||||
*(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0;
|
||||
}
|
||||
} else {
|
||||
S0_4x4 temp_a;
|
||||
dequantize_func(x, il, temp_a);
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
const short sx = 2*il0 + i/8;
|
||||
const short sy = (tiitg/NL0)/8;
|
||||
|
||||
const short lx = i%8;
|
||||
const short ly = (tiitg/NL0)%8;
|
||||
//const short lx = (tiitg/NL0)%8;
|
||||
//const short ly = i%8;
|
||||
|
||||
*(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4];
|
||||
}
|
||||
}
|
||||
|
||||
if (FC_mul_mm_bc_inp) {
|
||||
for (short i = 0; i < 8; ++i) {
|
||||
const short sx = (tiitg%NL1);
|
||||
const short sy = (tiitg/NL1)/8;
|
||||
|
||||
const short lx = i;
|
||||
const short ly = (tiitg/NL1)%8;
|
||||
//const short lx = (tiitg/NL1)%8;
|
||||
//const short ly = i;
|
||||
|
||||
*(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0;
|
||||
}
|
||||
} else {
|
||||
const short sx = (tiitg%NL1);
|
||||
const short sy = (tiitg/NL1)/8;
|
||||
|
||||
//const short lx = i;
|
||||
const short ly = (tiitg/NL1)%8;
|
||||
//const short lx = (tiitg/NL1)%8;
|
||||
//const short ly = i;
|
||||
|
||||
*(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y));
|
||||
}
|
||||
#endif
|
||||
|
||||
il = (il + 2 < nl) ? il + 2 : il % 2;
|
||||
x = (il < 2) ? x + (2 + nl - 1)/nl : x;
|
||||
@@ -796,7 +589,6 @@ kernel void kernel_mul_mm_id(
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
#ifndef GGML_METAL_HAS_TENSOR
|
||||
if (sg_active) {
|
||||
// load matrices from threadgroup memory and conduct outer products
|
||||
threadgroup const S0 * lsma = (sa + 4*64*(sgitg%2));
|
||||
@@ -825,32 +617,11 @@ kernel void kernel_mul_mm_id(
|
||||
lsmb += 4*64;
|
||||
}
|
||||
}
|
||||
#else
|
||||
auto sA = tA.slice(0, 0);
|
||||
auto sB0 = tB0.slice(0, 0);
|
||||
|
||||
mm.run(sB0, sA, cT0);
|
||||
|
||||
if (has_hi) {
|
||||
auto sB1 = tB1.slice(0, 0);
|
||||
|
||||
mm.run(sB1, sA, cT1);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// block is smaller than 64x32, we should avoid writing data outside of the matrix
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
#ifdef GGML_METAL_HAS_TENSOR
|
||||
auto tC0 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(NR0, NR1H));
|
||||
cT0.store(tC0);
|
||||
|
||||
if (has_hi) {
|
||||
auto tC1 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc + NR1H*NR0, dextents<int32_t, 2>(NR0, NR1H));
|
||||
cT1.store(tC1);
|
||||
}
|
||||
#else
|
||||
if (sg_active) {
|
||||
threadgroup float * temp_str = ((threadgroup float *) shmem) + 32*(sgitg&1) + (16*(sgitg >> 1))*NR0;
|
||||
|
||||
@@ -858,7 +629,6 @@ kernel void kernel_mul_mm_id(
|
||||
simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*NR0*(i/4), NR0, 0, false);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
@@ -886,133 +656,249 @@ kernel void kernel_mul_mm_id(
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// matrix-matrix multiplication
|
||||
//
|
||||
|
||||
typedef decltype(kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>) mul_mm_t;
|
||||
typedef decltype(kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_t;
|
||||
|
||||
template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, half4x4, 1, dequantize_f16, half, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, bfloat, bfloat2x4>;
|
||||
template [[host_name("kernel_mul_mm_f32_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, float, float2x4>;
|
||||
|
||||
template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, half, half2x4>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_f16_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, half4x4, 1, dequantize_f16, half, float>;
|
||||
template [[host_name("kernel_mul_mm_q1_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_f32_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_f16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, half4x4, 1, dequantize_f16, half, float>;
|
||||
template [[host_name("kernel_mul_mm_q1_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_bf16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm<float, float, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, float4x4, 1, dequantize_f32, float, half>;
|
||||
template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, half4x4, 1, dequantize_f16, half, half>;
|
||||
template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
|
||||
template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
|
||||
|
||||
//
|
||||
// indirect matrix-matrix multiplication
|
||||
//
|
||||
|
||||
typedef decltype(kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>) mul_mm_id;
|
||||
typedef decltype(kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_id;
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, half4x4, 1, dequantize_f16, half, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
#else
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, float, float2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, float4x4, 1, dequantize_f32, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, half4x4, 1, dequantize_f16, half, half4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q1_0, 8, dequantize_q1_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_0, 4, dequantize_q2_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0, float, float4x4, half, half2x4>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat, bfloat2x4, simdgroup_bfloat8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
|
||||
#else
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_mxfp4, 2, dequantize_mxfp4, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_f32_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float4x4, half, half2x4>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half4x4, simdgroup_half8x8, half, half2x4, simdgroup_half8x8, block_tq2_0, QK_NL, dequantize_tq2_0, float, float4x4, half, half2x4>;
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_f16_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, half4x4, 1, dequantize_f16, half, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
#endif
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_f32_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_f16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, half4x4, 1, dequantize_f16, half, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_bf16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id<float, float, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
#endif
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, float4x4, 1, dequantize_f32, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, half4x4, 1, dequantize_f16, half, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
#else
|
||||
template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
|
||||
|
||||
@@ -0,0 +1,537 @@
|
||||
#include "common.h"
|
||||
#include "dequantize.h"
|
||||
|
||||
#ifdef GGML_METAL_HAS_TENSOR
|
||||
|
||||
constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]];
|
||||
constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]];
|
||||
constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]];
|
||||
constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]];
|
||||
constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]];
|
||||
constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]];
|
||||
constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]];
|
||||
|
||||
// each block_q contains 16*nl weights
|
||||
template<
|
||||
typename SA, typename SB,
|
||||
typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<SA>::type &),
|
||||
typename T0, typename T1>
|
||||
kernel void kernel_mul_mm_tensor(
|
||||
constant ggml_metal_kargs_mul_mm & args,
|
||||
device const char * srcA,
|
||||
device const char * srcB,
|
||||
device char * dst,
|
||||
threadgroup char * shmem [[threadgroup(0)]],
|
||||
uint3 tgpig [[threadgroup_position_in_grid]],
|
||||
ushort tiitg [[thread_index_in_threadgroup]],
|
||||
ushort sgitg [[simdgroup_index_in_threadgroup]]) {
|
||||
using SA_4x4 = typename value_type_4x4<SA>::type;
|
||||
using SA_8x8 = typename value_type_8x8<SA>::type;
|
||||
using SB_2x4 = typename value_type_2x4<SB>::type;
|
||||
using SB_8x8 = typename value_type_8x8<SB>::type;
|
||||
using T0_4x4 = typename value_type_4x4<T0>::type;
|
||||
using T1_2x4 = typename value_type_2x4<T1>::type;
|
||||
|
||||
(void) sgitg;
|
||||
|
||||
// Matrix dimensions: A(M,K) x B(K,N) -> C(M,N)
|
||||
const int K = args.ne00;
|
||||
const int M = args.ne0;
|
||||
const int N = args.ne1;
|
||||
|
||||
// Batch dimension handling
|
||||
const int im = tgpig.z;
|
||||
const int i12 = im % FC_mul_mm_ne12;
|
||||
const int i13 = im / FC_mul_mm_ne12;
|
||||
|
||||
// Batch offsets for srcA and srcB
|
||||
const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03;
|
||||
|
||||
// Tile dimensions
|
||||
constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X;
|
||||
constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y;
|
||||
|
||||
// Tile offsets in output matrix
|
||||
const int ra = tgpig.y * NRA;
|
||||
const int rb = tgpig.x * NRB;
|
||||
|
||||
// Threadgroup memory for dequantized A tile only
|
||||
threadgroup SA * sa = (threadgroup SA *)(shmem);
|
||||
|
||||
// Work-item count for A loading
|
||||
constexpr int A_WORK_ITEMS = NRA * N_MM_NK;
|
||||
constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y;
|
||||
|
||||
// tA wraps threadgroup memory
|
||||
auto tA = tensor(sa, dextents<int32_t, 2>(N_MM_NK_TOTAL, NRA));
|
||||
|
||||
// tB wraps device memory directly
|
||||
device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13);
|
||||
const int strideB = args.nb11 / sizeof(T1);
|
||||
auto tB = tensor(ptrB, dextents<int32_t, 2>(K, N), array<int, 2>({1, strideB}));
|
||||
|
||||
// Configure matmul operation
|
||||
// note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static
|
||||
// N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/27064
|
||||
mpp::tensor_ops::matmul2d<
|
||||
mpp::tensor_ops::matmul2d_descriptor(
|
||||
NRB, NRA, static_cast<int>(dynamic_extent), false, true, true,
|
||||
mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
|
||||
execution_simdgroups<N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y>> mm;
|
||||
|
||||
auto cT = mm.get_destination_cooperative_tensor<decltype(tB), decltype(tA), float>();
|
||||
|
||||
// Accumulate partial results over K dimension
|
||||
for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) {
|
||||
// === PHASE 1: Dequantization of A into threadgroup memory ===
|
||||
for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) {
|
||||
const int row = work / N_MM_NK;
|
||||
const int k_chunk = work % N_MM_NK;
|
||||
const int k_pos = loop_k + k_chunk * 16;
|
||||
const short k_base = k_chunk * 16;
|
||||
|
||||
// Bounds check: skip device read if row is out of matrix bounds
|
||||
if (ra + row < M) {
|
||||
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
|
||||
// Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4).
|
||||
// MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd,
|
||||
// nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned.
|
||||
// Mirrors the legacy kernel's existing guard.
|
||||
device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0;
|
||||
}
|
||||
} else {
|
||||
const int block_idx = k_pos / (16 * nl);
|
||||
const short il = (k_pos / 16) % nl;
|
||||
|
||||
device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0);
|
||||
|
||||
SA_4x4 temp_a;
|
||||
dequantize_func(row_ptr + block_idx, il, temp_a);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
// Zero-pad A for K positions beyond valid range (handles partial K iterations)
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Zero-pad rows beyond matrix bounds
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
// === PHASE 2: Tensor matmul ===
|
||||
// Clamp the K extent of both operand tensors to the remaining valid K range so
|
||||
// the dynamic-K op never reads past the K extent of src1 (or the staged A tile).
|
||||
const int kExt = min(N_MM_NK_TOTAL, K - loop_k);
|
||||
|
||||
auto tAv = tensor(sa, dextents<int32_t, 2>(kExt, NRA), array<int, 2>({1, N_MM_NK_TOTAL}));
|
||||
auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents<int32_t, 2>(kExt, N - rb), array<int, 2>({1, strideB}));
|
||||
|
||||
mm.run(tBv, tAv, cT);
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
}
|
||||
|
||||
// Store result tile to output matrix (with batch offset)
|
||||
// a slice is not used because its byte offset is int32 and wraps at 2 GiB
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/28748
|
||||
const int tileM = min(NRA, M - ra);
|
||||
const int tileN = min(NRB, N - rb);
|
||||
|
||||
device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra;
|
||||
|
||||
auto tD = tensor(dstTile, dextents<int32_t, 2>(tileM, tileN), array<int, 2>({1, M}));
|
||||
cT.store(tD);
|
||||
}
|
||||
|
||||
template<typename S0, typename S1, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4<S0>::type &), typename T0, typename T1>
|
||||
kernel void kernel_mul_mm_id_tensor(
|
||||
constant ggml_metal_kargs_mul_mm_id & args,
|
||||
device const char * src0,
|
||||
device const char * src1,
|
||||
device const char * htpe,
|
||||
device const char * hids,
|
||||
device char * dst,
|
||||
threadgroup char * shmem [[threadgroup(0)]],
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
ushort tiitg[[thread_index_in_threadgroup]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
using S0_4x4 = typename value_type_4x4<S0>::type;
|
||||
using S0_8x8 = typename value_type_8x8<S0>::type;
|
||||
using S1_2x4 = typename value_type_2x4<S1>::type;
|
||||
using S1_8x8 = typename value_type_8x8<S1>::type;
|
||||
using T0_4x4 = typename value_type_4x4<T0>::type;
|
||||
using T1_2x4 = typename value_type_2x4<T1>::type;
|
||||
|
||||
constexpr int NR0 = 64;
|
||||
constexpr int NR1 = 32;
|
||||
|
||||
constexpr int NK = 32;
|
||||
constexpr int NL0 = NK/16;
|
||||
constexpr int NL1 = NK/8;
|
||||
|
||||
threadgroup S0 * sa = (threadgroup S0 *)(shmem);
|
||||
threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0));
|
||||
|
||||
threadgroup float * sc = (threadgroup float *)(shmem);
|
||||
|
||||
const int tile = tgpig.x; // entry tile, described by the prepass
|
||||
const int r0 = tgpig.y*NR0;
|
||||
|
||||
device const uint32_t * tpe_u32 = (device const uint32_t *) (htpe);
|
||||
device const int32_t * ids_i32 = (device const int32_t *) (hids);
|
||||
|
||||
// the prepass emits one (expert, first entry, valid rows) descriptor per tile that has
|
||||
// work - the grid is sized by a static upper bound, so the tail early exits
|
||||
if (tile >= (int) tpe_u32[0]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int im = tpe_u32[1 + 3*tile]; // expert
|
||||
const int idb = tpe_u32[1 + 3*tile + 1]; // first entry of this tile in hids
|
||||
|
||||
// number of entries in this tile, always <= NR1
|
||||
const short nr1 = (short) ((tpe_u32[1 + 3*tile + 2] < NR1) ? tpe_u32[1 + 3*tile + 2] : NR1);
|
||||
|
||||
// if this block is of 64x32 shape or smaller
|
||||
const short nr0 = (args.ne0 - r0 < NR0) ? (args.ne0 - r0) : NR0;
|
||||
|
||||
// a thread shouldn't load data outside of the matrix
|
||||
const short lr0 = ((short)tiitg/NL0) < nr0 ? ((short)tiitg/NL0) : nr0 - 1; // 0 .. 63
|
||||
|
||||
const short il0 = (tiitg % NL0);
|
||||
|
||||
const short i13 = 0;
|
||||
|
||||
const uint64_t offset0 = im*args.nb02 + i13*args.nb03;
|
||||
const short offset1 = il0/nl;
|
||||
|
||||
const short iy = 8*(tiitg % NL1);
|
||||
|
||||
// skip the upper half of the token tile when the expert did not fill it
|
||||
constexpr short NR1H = NR1/2;
|
||||
|
||||
auto tA = tensor<threadgroup S0, dextents<int32_t, 2>, tensor_inline>(sa, dextents<int32_t, 2>(NK, NR0));
|
||||
|
||||
// sb is [NR1][NK] row-major
|
||||
auto tB0 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb, dextents<int32_t, 2>(NK, NR1H));
|
||||
auto tB1 = tensor<threadgroup S1, dextents<int32_t, 2>, tensor_inline>(sb + NR1H*NK, dextents<int32_t, 2>(NK, NR1H));
|
||||
|
||||
mpp::tensor_ops::matmul2d<
|
||||
mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate),
|
||||
execution_simdgroups<4>> mm;
|
||||
|
||||
|
||||
const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31
|
||||
|
||||
short il = il0;
|
||||
|
||||
const int id = ids_i32[idb + lr1];
|
||||
|
||||
const short i11 = (id % args.ne20) % args.ne11;
|
||||
const int i12 = (id / args.ne20);
|
||||
|
||||
device const block_q * x = (device const block_q *)(src0 + args.nb01*(r0 + lr0) + offset0) + offset1;
|
||||
|
||||
device const T1 * y = (device const T1 *)(src1
|
||||
+ args.nb13*i13
|
||||
+ args.nb12*i12
|
||||
+ args.nb11*i11
|
||||
+ args.nb10*iy);
|
||||
|
||||
const bool has_hi = nr1 > NR1H;
|
||||
|
||||
auto cT0 = mm.get_destination_cooperative_tensor<decltype(tB0), decltype(tA), float>();
|
||||
auto cT1 = mm.get_destination_cooperative_tensor<decltype(tB1), decltype(tA), float>();
|
||||
|
||||
for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) {
|
||||
// load data and store to threadgroup memory
|
||||
if (is_same<T0_4x4, block_q>::value && FC_mul_mm_bc_inp) {
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
// no need for dequantization
|
||||
for (short i = 0; i < 16; i++) {
|
||||
const short sx = 2*il0 + i/8;
|
||||
const short sy = (tiitg/NL0)/8;
|
||||
|
||||
const short lx = i%8;
|
||||
const short ly = (tiitg/NL0)%8;
|
||||
//const short lx = (tiitg/NL0)%8;
|
||||
//const short ly = i%8;
|
||||
|
||||
*(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0;
|
||||
}
|
||||
} else {
|
||||
S0_4x4 temp_a;
|
||||
dequantize_func(x, il, temp_a);
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
FOR_UNROLL (short i = 0; i < 16; i++) {
|
||||
const short sx = 2*il0 + i/8;
|
||||
const short sy = (tiitg/NL0)/8;
|
||||
|
||||
const short lx = i%8;
|
||||
const short ly = (tiitg/NL0)%8;
|
||||
//const short lx = (tiitg/NL0)%8;
|
||||
//const short ly = i%8;
|
||||
|
||||
*(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4];
|
||||
}
|
||||
}
|
||||
|
||||
if (FC_mul_mm_bc_inp) {
|
||||
for (short i = 0; i < 8; ++i) {
|
||||
const short sx = (tiitg%NL1);
|
||||
const short sy = (tiitg/NL1)/8;
|
||||
|
||||
const short lx = i;
|
||||
const short ly = (tiitg/NL1)%8;
|
||||
//const short lx = (tiitg/NL1)%8;
|
||||
//const short ly = i;
|
||||
|
||||
*(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0;
|
||||
}
|
||||
} else {
|
||||
const short sx = (tiitg%NL1);
|
||||
const short sy = (tiitg/NL1)/8;
|
||||
|
||||
//const short lx = i;
|
||||
const short ly = (tiitg/NL1)%8;
|
||||
//const short lx = (tiitg/NL1)%8;
|
||||
//const short ly = i;
|
||||
|
||||
*(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y));
|
||||
}
|
||||
|
||||
il = (il + 2 < nl) ? il + 2 : il % 2;
|
||||
x = (il < 2) ? x + (2 + nl - 1)/nl : x;
|
||||
|
||||
y += NK;
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
auto sA = tA.slice(0, 0);
|
||||
auto sB0 = tB0.slice(0, 0);
|
||||
|
||||
mm.run(sB0, sA, cT0);
|
||||
|
||||
if (has_hi) {
|
||||
auto sB1 = tB1.slice(0, 0);
|
||||
|
||||
mm.run(sB1, sA, cT1);
|
||||
}
|
||||
}
|
||||
|
||||
// block is smaller than 64x32, we should avoid writing data outside of the matrix
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
auto tC0 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc, dextents<int32_t, 2>(NR0, NR1H));
|
||||
cT0.store(tC0);
|
||||
|
||||
if (has_hi) {
|
||||
auto tC1 = tensor<threadgroup float, dextents<int32_t, 2>, tensor_inline>(sc + NR1H*NR0, dextents<int32_t, 2>(NR0, NR1H));
|
||||
cT1.store(tC1);
|
||||
}
|
||||
|
||||
threadgroup_barrier(mem_flags::mem_threadgroup);
|
||||
|
||||
for (short j = sgitg; j < nr1; j += 4) {
|
||||
const int id = ids_i32[idb + j];
|
||||
|
||||
const short ide = id % args.ne20;
|
||||
const int idt = id / args.ne20;
|
||||
|
||||
device float * D = (device float *) dst + r0 + (uint64_t) ide*args.ne0 + (uint64_t) idt*args.ne1*args.ne0;
|
||||
device float4 * D4 = (device float4 *) D;
|
||||
|
||||
threadgroup float * C = (threadgroup float *) shmem + j*NR0;
|
||||
threadgroup float4 * C4 = (threadgroup float4 *) C;
|
||||
|
||||
int i = tiisg;
|
||||
for (; i < nr0/4; i += 32) {
|
||||
*(D4 + i) = *(C4 + i);
|
||||
}
|
||||
|
||||
i = (4*(nr0/4)) + tiisg;
|
||||
for (; i < nr0; i += 32) {
|
||||
*(D + i) = *(C + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// matrix-matrix multiplication
|
||||
//
|
||||
|
||||
typedef decltype(kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_tensor_t;
|
||||
|
||||
template [[host_name("kernel_mul_mm_tensor_f32_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_f16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, half4x4, 1, dequantize_f16, half, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_tensor_f32_f32_prec_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_tensor_bf16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_bf16_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, bfloat>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_tensor_q1_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q6_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq3_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq1_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq1_m_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq4_nl_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq4_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_tensor_tq2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
template [[host_name("kernel_mul_mm_tensor_f32_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, float4x4, 1, dequantize_f32, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_f16_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, half4x4, 1, dequantize_f16, half, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q1_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q5_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_q6_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq3_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq2_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq1_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq1_m_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq4_nl_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_iq4_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_tensor_tq2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
|
||||
|
||||
//
|
||||
// indirect matrix-matrix multiplication
|
||||
//
|
||||
|
||||
typedef decltype(kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, float>) mul_mm_id_tensor_t;
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f32_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, half4x4, 1, dequantize_f16, half, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_tensor_bf16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, bfloat4x4, 1, dequantize_bf16, bfloat, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
#else
|
||||
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, float>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f32_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, float4x4, 1, dequantize_f32, float, float>;
|
||||
#endif
|
||||
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f16_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, half4x4, 1, dequantize_f16, half, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q1_0, 8, dequantize_q1_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q2_0, 4, dequantize_q2_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_0, 2, dequantize_q4_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_1, 2, dequantize_q4_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_0, 2, dequantize_q5_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_1, 2, dequantize_q5_1, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q8_0, 2, dequantize_q8_0, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q2_K, QK_NL, dequantize_q2_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q3_K, QK_NL, dequantize_q3_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q4_K, QK_NL, dequantize_q4_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q5_K, QK_NL, dequantize_q5_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_q6_K, QK_NL, dequantize_q6_K, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq3_s, QK_NL, dequantize_iq3_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq2_s, QK_NL, dequantize_iq2_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq1_s, QK_NL, dequantize_iq1_s, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq1_m, QK_NL, dequantize_iq1_m, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq4_nl, 2, dequantize_iq4_nl, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, float>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, bfloat, block_tq2_0, QK_NL, dequantize_tq2_0, float, float>;
|
||||
#endif
|
||||
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f32_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, float4x4, 1, dequantize_f32, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_f16_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, half4x4, 1, dequantize_f16, half, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q1_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q1_0, 8, dequantize_q1_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_0, 4, dequantize_q2_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_0, 2, dequantize_q4_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_1, 2, dequantize_q4_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_0, 2, dequantize_q5_0, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_1, 2, dequantize_q5_1, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q8_0, 2, dequantize_q8_0, float, half>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<bfloat, bfloat, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
#else
|
||||
template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_mxfp4, 2, dequantize_mxfp4, float, half>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q2_K, QK_NL, dequantize_q2_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q3_K, QK_NL, dequantize_q3_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q4_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q4_K, QK_NL, dequantize_q4_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q5_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q5_K, QK_NL, dequantize_q5_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_q6_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_q6_K, QK_NL, dequantize_q6_K, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xxs, QK_NL, dequantize_iq2_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_xs, QK_NL, dequantize_iq2_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_xxs, QK_NL, dequantize_iq3_xxs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq3_s, QK_NL, dequantize_iq3_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq2_s, QK_NL, dequantize_iq2_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_s, QK_NL, dequantize_iq1_s, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq1_m, QK_NL, dequantize_iq1_m, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_nl, 2, dequantize_iq4_nl, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_iq4_xs, QK_NL, dequantize_iq4_xs, float, half>;
|
||||
template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor<half, half, block_tq2_0, QK_NL, dequantize_tq2_0, float, half>;
|
||||
|
||||
#endif // GGML_METAL_HAS_TENSOR
|
||||
@@ -1046,7 +1046,7 @@ template [[host_name("kernel_mul_mv_bf16_bf16")]] kernel mul_mv_t_t kernel_mul_m
|
||||
template [[host_name("kernel_mul_mv_f32_bf16")]] kernel mul_mv_t_t kernel_mul_mv_t_t<float, bfloat>;
|
||||
#endif
|
||||
|
||||
template<typename T0, typename T04, typename T1, typename T14, short NR0, typename args_t>
|
||||
template<typename T0, typename T1, short NR0, typename args_t>
|
||||
void kernel_mul_mv_t_t_4_impl(
|
||||
args_t args,
|
||||
device const char * src0,
|
||||
@@ -1056,6 +1056,9 @@ void kernel_mul_mv_t_t_4_impl(
|
||||
uint3 tgpig,
|
||||
ushort tiisg,
|
||||
ushort sgitg) {
|
||||
using T04 = typename value_type_4<T0>::type;
|
||||
using T14 = typename value_type_4<T1>::type;
|
||||
|
||||
const short NSG = FC_mul_mv_nsg;
|
||||
|
||||
constexpr short NW = N_SIMDWIDTH;
|
||||
@@ -1129,7 +1132,7 @@ void kernel_mul_mv_t_t_4_impl(
|
||||
helper_mv_reduce_and_write<NR0>(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem);
|
||||
}
|
||||
|
||||
template<typename T0, typename T04, typename T1, typename T14, typename args_t>
|
||||
template<typename T0, typename T1, typename args_t>
|
||||
void kernel_mul_mv_t_t_4_disp(
|
||||
args_t args,
|
||||
device const char * src0,
|
||||
@@ -1140,14 +1143,14 @@ void kernel_mul_mv_t_t_4_disp(
|
||||
ushort tiisg,
|
||||
ushort sgitg) {
|
||||
switch (args.nr0) {
|
||||
//case 1: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 1, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
case 2: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 2, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
//case 3: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 3, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
//case 4: kernel_mul_mv_t_t_4_impl<T0, T04, T1, T14, 4, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
//case 1: kernel_mul_mv_t_t_4_impl<T0, T1, 1, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
case 2: kernel_mul_mv_t_t_4_impl<T0, T1, 2, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
//case 3: kernel_mul_mv_t_t_4_impl<T0, T1, 3, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
//case 4: kernel_mul_mv_t_t_4_impl<T0, T1, 4, args_t>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break;
|
||||
};
|
||||
}
|
||||
|
||||
template<typename T0, typename T04, typename T1, typename T14>
|
||||
template<typename T0, typename T1>
|
||||
kernel void kernel_mul_mv_t_t_4(
|
||||
constant ggml_metal_kargs_mul_mv & args,
|
||||
device const char * src0,
|
||||
@@ -1157,18 +1160,18 @@ kernel void kernel_mul_mv_t_t_4(
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
ushort tiisg[[thread_index_in_simdgroup]],
|
||||
ushort sgitg[[simdgroup_index_in_threadgroup]]) {
|
||||
kernel_mul_mv_t_t_4_disp<T0, T04, T1, T14, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
|
||||
kernel_mul_mv_t_t_4_disp<T0, T1, constant ggml_metal_kargs_mul_mv &>(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg);
|
||||
}
|
||||
|
||||
typedef decltype(kernel_mul_mv_t_t_4<half, half4, half, half4>) mul_mv_t_t_4;
|
||||
typedef decltype(kernel_mul_mv_t_t_4<half, half>) mul_mv_t_t_4;
|
||||
|
||||
template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float4, float, float4>;
|
||||
template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half4, float, float4>;
|
||||
template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half4, half, half4>;
|
||||
template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float>;
|
||||
template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, float>;
|
||||
template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<half, half>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat4, float, float4>;
|
||||
template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat4, bfloat, bfloat4>;
|
||||
template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, float4, bfloat, bfloat4>;
|
||||
template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, float>;
|
||||
template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<bfloat, bfloat>;
|
||||
template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4<float, bfloat>;
|
||||
#endif
|
||||
|
||||
template<typename T0, typename T1, typename args_t>
|
||||
@@ -3389,17 +3392,17 @@ kernel void kernel_mul_mv_id(
|
||||
|
||||
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>) kernel_mul_mv_id_t;
|
||||
|
||||
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float4, float, float4>>>) kernel_mul_mv_id_4_t;
|
||||
typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float>>>) kernel_mul_mv_id_4_t;
|
||||
|
||||
template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<float, float>>>;
|
||||
template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<half, float>>>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mv_id_bf16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_disp<bfloat, float>>>;
|
||||
#endif
|
||||
template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float4, float, float4>>>;
|
||||
template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<half, half4, float, float4>>>;
|
||||
template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<float, float>>>;
|
||||
template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<half, float>>>;
|
||||
#if defined(GGML_METAL_HAS_BF16)
|
||||
template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<bfloat, bfloat4, float, float4>>>;
|
||||
template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_t_t_4_disp<bfloat, float>>>;
|
||||
#endif
|
||||
|
||||
template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q8_0_f32_impl<N_R0_Q8_0>>>;
|
||||
|
||||
@@ -12662,8 +12662,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
|
||||
case GGML_OP_MEAN:
|
||||
return op->src[0]->type == GGML_TYPE_F32;
|
||||
case GGML_OP_FLASH_ATTN_EXT: {
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
if (op->src[5] != nullptr) {
|
||||
// K/V row lists and indexed bias are not supported
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
|
||||
@@ -13,6 +13,8 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
|
||||
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
|
||||
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
|
||||
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
|
||||
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
|
||||
| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. |
|
||||
| `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. |
|
||||
| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. |
|
||||
| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. |
|
||||
@@ -29,6 +31,12 @@ GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
|
||||
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
|
||||
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
|
||||
|
||||
# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call
|
||||
GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op
|
||||
|
||||
# Graph key and tensor shapes when an inference throws
|
||||
GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG
|
||||
|
||||
# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
|
||||
@@ -74,6 +82,7 @@ These options are off by default. They are not validated for general use: some h
|
||||
| `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. |
|
||||
| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
|
||||
| `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
|
||||
| `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. |
|
||||
| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. |
|
||||
| `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. |
|
||||
| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. |
|
||||
|
||||
@@ -45,6 +45,10 @@ std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const gg
|
||||
}
|
||||
|
||||
std::optional<ExtraQuantType> ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) {
|
||||
GGML_UNUSED(tensor);
|
||||
return ggml_openvino_get_npu_requant_type();
|
||||
const ExtraQuantType type = ggml_openvino_get_npu_requant_type();
|
||||
// a group must fit within a row
|
||||
if (type == ExtraQuantType::Q4_0_128 && tensor->ne[0] % 128 != 0) {
|
||||
return ExtraQuantType::Q4_0_C;
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <map>
|
||||
@@ -31,10 +33,27 @@
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
static std::set<std::string> collect_graph_output_names(const ggml_cgraph * cgraph) {
|
||||
std::set<std::string> outputs;
|
||||
for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
|
||||
auto * node = cgraph->nodes[node_n];
|
||||
if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
|
||||
outputs.insert(node->name);
|
||||
}
|
||||
}
|
||||
return outputs;
|
||||
}
|
||||
|
||||
bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const {
|
||||
if (m_built_output_names.empty()) {
|
||||
return true; // no snapshot (naive / test decoders): nothing to compare against
|
||||
}
|
||||
return collect_graph_output_names(cgraph) == m_built_output_names;
|
||||
}
|
||||
|
||||
GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
|
||||
ModelParams & model_params,
|
||||
ComputeParams & compute_params,
|
||||
@@ -64,6 +83,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
|
||||
|
||||
validate_cgraph();
|
||||
|
||||
m_built_output_names = collect_graph_output_names(cgraph);
|
||||
|
||||
set_input_output();
|
||||
compute_node_dynamic_dims();
|
||||
compute_model_inputs();
|
||||
@@ -79,6 +100,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
|
||||
|
||||
void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
|
||||
m_cgraph = cgraph;
|
||||
m_built_output_names = collect_graph_output_names(cgraph);
|
||||
m_model_inputs.clear();
|
||||
m_model_outputs.clear();
|
||||
m_node_info_list.clear();
|
||||
@@ -694,45 +716,6 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
|
||||
op_case = 1;
|
||||
break;
|
||||
}
|
||||
if (node->src[0]->op == GGML_OP_VIEW) {
|
||||
auto * src = node->src[0];
|
||||
if (ggml_nelements(node) != ggml_nelements(src)) {
|
||||
// throw std::runtime_error("Unsupported VIEW case");
|
||||
}
|
||||
op_case = 0;
|
||||
if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) {
|
||||
op_case = 0;
|
||||
}
|
||||
}
|
||||
{
|
||||
auto * src = node->src[0];
|
||||
if (ggml_nelements(node) != ggml_nelements(src)) {
|
||||
// Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1.
|
||||
// Typical pattern:
|
||||
// src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3]
|
||||
// dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3]
|
||||
if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 &&
|
||||
node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) {
|
||||
op_case = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
// General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing.
|
||||
int diff_count = 0;
|
||||
for (int i = 0; i < GGML_MAX_DIMS; i++) {
|
||||
if (node->ne[i] != src->ne[i]) {
|
||||
diff_count++;
|
||||
}
|
||||
// if node ne[i] > src ne[i], case = 0
|
||||
if (node->ne[i] > src->ne[i]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (diff_count >= 1) {
|
||||
op_case = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_OP_RMS_NORM: {
|
||||
@@ -744,7 +727,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
|
||||
// pre-scaled, and the norm then scales its eps to match; 4: it is not.
|
||||
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4;
|
||||
} else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
|
||||
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2;
|
||||
// packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not.
|
||||
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2;
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -897,13 +881,10 @@ std::optional<int> extract_layer_from_name(const std::string & name) {
|
||||
return std::nullopt;
|
||||
}
|
||||
pos1 += 2;
|
||||
size_t pos2 = name.find(' ', pos1);
|
||||
if (pos2 == std::string::npos) {
|
||||
pos2 = name.length();
|
||||
if (pos1 >= name.size() || !std::isdigit(static_cast<unsigned char>(name[pos1]))) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string layer_str = name.substr(pos1, pos2 - pos1);
|
||||
int layer = std::stoi(layer_str);
|
||||
return layer;
|
||||
return std::stoi(name.substr(pos1));
|
||||
}
|
||||
|
||||
// Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a
|
||||
@@ -1202,7 +1183,11 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
}
|
||||
|
||||
ggml_tensor * cache_k = cache_k_view->src[0];
|
||||
int layer = extract_layer_from_name(cache_k->name).value();
|
||||
const auto layer_opt = extract_layer_from_name(cache_k->name);
|
||||
if (!layer_opt) {
|
||||
continue;
|
||||
}
|
||||
const int layer = *layer_opt;
|
||||
|
||||
// Classified by the pre-pass above, which groups layers by mask tensor identity. The
|
||||
// mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name.
|
||||
@@ -1372,7 +1357,9 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
|
||||
}
|
||||
if (is_conv || is_gdn) {
|
||||
compute_params.s_copy_active_slot_len = (int) dest_view->ne[1];
|
||||
// One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv
|
||||
// states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned.
|
||||
compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1573,7 +1560,10 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
|
||||
else {
|
||||
input_shape = ov::PartialShape{get_shape(input)};
|
||||
}
|
||||
if (dynamic_dim_index != -1 && m_model_is_splitted) {
|
||||
// A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are
|
||||
// fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes
|
||||
// dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails).
|
||||
if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) {
|
||||
input_shape[3 - dynamic_dim_index] = -1;
|
||||
}
|
||||
if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE &&
|
||||
@@ -1985,7 +1975,9 @@ void GgmlOvDecoder::compute_model_outputs() {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (input_use_count == cur_node_use_count) {
|
||||
// op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused
|
||||
// ADD + RMS_NORM + MUL, so every non-in-place node is a model output there
|
||||
if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) {
|
||||
cur_node = nullptr;
|
||||
}
|
||||
}
|
||||
@@ -2774,11 +2766,14 @@ size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const {
|
||||
}
|
||||
|
||||
void GgmlOvDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const {
|
||||
// One copy for the whole walk: translators only read the decoder, and a copy per node costs a full
|
||||
// copy of the node list for every node.
|
||||
auto decoder = std::make_shared<GgmlOvDecoder>(*this);
|
||||
for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) {
|
||||
if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) {
|
||||
continue;
|
||||
}
|
||||
node_visitor(std::make_shared<GgmlOvDecoder>(*this), node_idx);
|
||||
node_visitor(decoder, node_idx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2851,6 +2846,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_embd_2d(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
self(self, src);
|
||||
}
|
||||
}
|
||||
@@ -2921,10 +2920,22 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
|
||||
break;
|
||||
}
|
||||
|
||||
// A VIEW that does not change the shape is a pass-through for dynamic-dim purposes.
|
||||
if (is_same_shape(node->src[0], node)) {
|
||||
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
|
||||
break;
|
||||
}
|
||||
// Use stride-based matching: the stride of a VIEW dimension directly
|
||||
// encodes which source dimension it indexes into, so it uniquely
|
||||
// identifies the dynamic dim even when two dims share the same size.
|
||||
m_node_dynamic_dims[node] = -1;
|
||||
if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
|
||||
// The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these
|
||||
// VIEW names (get_output_names), not the packed [attention | state] the strides describe.
|
||||
m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
|
||||
break;
|
||||
}
|
||||
if (m_node_dynamic_dims[node->src[0]] != -1) {
|
||||
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
|
||||
auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
|
||||
|
||||
@@ -458,6 +458,11 @@ public:
|
||||
void update_io(ggml_cgraph * cgraph);
|
||||
bool is_bound_to(const ggml_cgraph * cgraph) const;
|
||||
|
||||
// Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is
|
||||
// only (n_nodes, first/last node name), which cannot see a change in which tensors are marked
|
||||
// as outputs, and the compiled model's Results are fixed at compile time.
|
||||
bool has_same_graph_io(const ggml_cgraph * cgraph) const;
|
||||
|
||||
static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE;
|
||||
}
|
||||
@@ -501,6 +506,16 @@ public:
|
||||
(tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY);
|
||||
}
|
||||
|
||||
// A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the
|
||||
// target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the
|
||||
// other seeds match it) and the token count differs between the prompt pass and the shorter
|
||||
// draft blocks, so its token dim must stay dynamic.
|
||||
static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE &&
|
||||
tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 &&
|
||||
op->op == GGML_OP_MUL_MAT && tensor == op->src[1];
|
||||
}
|
||||
|
||||
static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) ||
|
||||
(op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]);
|
||||
@@ -759,6 +774,8 @@ private:
|
||||
std::map<std::string, std::shared_ptr<ov::Node>> m_model_weights;
|
||||
std::map<std::string, ggml_tensor *> m_model_outputs;
|
||||
std::set<std::string> m_model_output_names;
|
||||
// The output set the compiled model was built from, for has_same_graph_io().
|
||||
std::set<std::string> m_built_output_names;
|
||||
std::vector<NodeInfo> m_node_info_list;
|
||||
std::map<ggml_tensor *, int> m_node_dynamic_dims;
|
||||
std::set<const ggml_tensor *> m_kvcache_4d;
|
||||
|
||||
@@ -179,6 +179,9 @@ constexpr env_var env_vars[] = {
|
||||
{"GGML_OPENVINO_RELEASE_WEIGHTS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_REDUCE_COMPILE_MEM", env_type::BOOL},
|
||||
{"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT},
|
||||
{"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL},
|
||||
{"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL},
|
||||
@@ -543,6 +546,14 @@ std::string ggml_openvino_config_overrides_in_use() {
|
||||
return value ? std::string(name) + "=" + value : std::string();
|
||||
}
|
||||
|
||||
bool ggml_openvino_manual_gqa_enabled() {
|
||||
// set: a positive value enables it, 0 disables it; unset: on GPU only
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu();
|
||||
}
|
||||
|
||||
bool ggml_openvino_gdn_prescale_enabled() {
|
||||
// float value, so not getenv_int: "64.0" must enable it. Unset means on.
|
||||
const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_GDN_Q_SCALE", nullptr);
|
||||
@@ -997,6 +1008,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
|
||||
const bool sym128_all = is_opt("q4_sym128_all");
|
||||
const bool asym64_all = is_opt("q4_asym64_all");
|
||||
const bool asym64 = is_opt("q4_asym64");
|
||||
// A group of 64 must fit within each row; other widths keep channel-wise INT8.
|
||||
auto group64 = [tensor](ExtraQuantType type) {
|
||||
return tensor->ne[0] % 64 == 0 ? type : ExtraQuantType::Q8_0_C;
|
||||
};
|
||||
|
||||
// TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens.
|
||||
// Q4_1_64 experts let the plugin fuse the MoE into MOECompressed.
|
||||
@@ -1021,8 +1036,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
|
||||
return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C;
|
||||
}
|
||||
if (tensor->type == GGML_TYPE_Q5_0) {
|
||||
//return ExtraQuantType::Q4_0_128;
|
||||
return ExtraQuantType::Q4_0_64;
|
||||
return group64(ExtraQuantType::Q4_0_64);
|
||||
}
|
||||
// MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side
|
||||
// equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4
|
||||
@@ -1031,10 +1045,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
|
||||
// (704/64 = 11) and 128 does not.
|
||||
if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
|
||||
if (sym128 || sym128_all) {
|
||||
return ExtraQuantType::Q4_0_64;
|
||||
return group64(ExtraQuantType::Q4_0_64);
|
||||
}
|
||||
if (asym64 || asym64_all) {
|
||||
return ExtraQuantType::Q4_1_64;
|
||||
return group64(ExtraQuantType::Q4_1_64);
|
||||
}
|
||||
// TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the
|
||||
// plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy
|
||||
@@ -1049,7 +1063,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
|
||||
// avoids the broken layout and restores correct output.
|
||||
// Opt out with GGML_OPENVINO_REQUANT_KQUANT=native.
|
||||
if (ggml_openvino_is_gpu() && !is_opt("native")) {
|
||||
return ExtraQuantType::Q4_0_64;
|
||||
return group64(ExtraQuantType::Q4_0_64);
|
||||
}
|
||||
}
|
||||
switch (tensor->type) {
|
||||
|
||||
@@ -206,6 +206,9 @@ bool ggml_openvino_is_gpu();
|
||||
// Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1)
|
||||
bool ggml_openvino_shape_from_mask_enabled();
|
||||
|
||||
// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default)
|
||||
bool ggml_openvino_manual_gqa_enabled();
|
||||
|
||||
// GDN q pre-scale for eligible graphs on the NPU static path. On by default;
|
||||
// GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off.
|
||||
bool ggml_openvino_gdn_prescale_enabled();
|
||||
@@ -242,6 +245,7 @@ size_t ggml_openvino_max_alloc_size(const std::string & device);
|
||||
// release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS.
|
||||
// released: true once release has run (used to fail-fast on post-release recompile).
|
||||
void ggml_openvino_register_weight_buffer(void * data, size_t size);
|
||||
void ggml_openvino_unregister_weight_buffer(const void * data);
|
||||
void ggml_openvino_release_weight_buffers();
|
||||
bool ggml_openvino_weight_buffers_released();
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <openvino/core/type/element_type.hpp>
|
||||
@@ -99,14 +100,20 @@ struct ggml_backend_openvino_buffer_context {
|
||||
|
||||
// Used for re-allocation on device for kvcache
|
||||
void * data_prev = nullptr;
|
||||
// data is in the weight buffer registry
|
||||
bool weight_registered = false;
|
||||
|
||||
// One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer
|
||||
// buffer and an allocated buffer must never share one.
|
||||
static size_t next_buffer_id() {
|
||||
static std::atomic<size_t> next_id{1};
|
||||
return next_id.fetch_add(1);
|
||||
}
|
||||
|
||||
ggml_backend_openvino_buffer_context(int device, void * external_data, size_t size) :
|
||||
device(device),
|
||||
name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
|
||||
id([]() {
|
||||
static std::atomic<size_t> next_id{1};
|
||||
return next_id.fetch_add(1);
|
||||
}()),
|
||||
id(next_buffer_id()),
|
||||
data(external_data),
|
||||
size(size),
|
||||
is_remote(false),
|
||||
@@ -117,10 +124,7 @@ struct ggml_backend_openvino_buffer_context {
|
||||
ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) :
|
||||
device(device),
|
||||
name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
|
||||
id([]() {
|
||||
static std::atomic<size_t> next_id{1};
|
||||
return next_id.fetch_add(1);
|
||||
}()),
|
||||
id(next_buffer_id()),
|
||||
data(nullptr),
|
||||
size(size),
|
||||
is_remote(is_remote) {
|
||||
@@ -260,6 +264,10 @@ struct ggml_backend_openvino_buffer_context {
|
||||
delete pair.second;
|
||||
}
|
||||
tensor_extras.clear();
|
||||
// a later release must not madvise memory this buffer no longer owns
|
||||
if (weight_registered) {
|
||||
ggml_openvino_unregister_weight_buffer(data);
|
||||
}
|
||||
if (kv_on_demand) {
|
||||
ggml_openvino_kv_storage_unregister(data, size);
|
||||
}
|
||||
@@ -321,6 +329,17 @@ void ggml_openvino_register_weight_buffer(void * data, size_t size) {
|
||||
reg.buffers.emplace_back(data, size);
|
||||
}
|
||||
|
||||
void ggml_openvino_unregister_weight_buffer(const void * data) {
|
||||
if (data == nullptr) {
|
||||
return;
|
||||
}
|
||||
auto & reg = ov_weight_registry();
|
||||
std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(),
|
||||
[data](const std::pair<void *, size_t> & b) { return b.first == data; }),
|
||||
reg.buffers.end());
|
||||
}
|
||||
|
||||
bool ggml_openvino_weight_buffers_released() {
|
||||
auto & reg = ov_weight_registry();
|
||||
std::lock_guard<std::mutex> lock(reg.mutex);
|
||||
@@ -378,21 +397,53 @@ static bool is_self_contained_mmap_enabled() {
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
|
||||
}
|
||||
|
||||
// Stores extra as the tensor's extra, deleting the one it replaces
|
||||
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
|
||||
ggml_tensor * tensor,
|
||||
ggml_openvino_extra_base * extra) {
|
||||
auto it = ctx->tensor_extras.find(tensor);
|
||||
if (it != ctx->tensor_extras.end() && it->second != extra) {
|
||||
delete it->second;
|
||||
}
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
}
|
||||
|
||||
// Replaces the buffer's context with a new allocation of the same size and moves tensor->data to it. The old
|
||||
// allocation is freed first, so the two never take memory at the same time. Returns false when the new
|
||||
// allocation fails.
|
||||
static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
|
||||
ggml_backend_openvino_buffer_context *& ctx,
|
||||
ggml_tensor * tensor,
|
||||
bool is_remote,
|
||||
bool lazy) {
|
||||
const int device = ctx->device;
|
||||
const size_t size = ctx->size;
|
||||
const size_t offset = (char *) tensor->data - (char *) ctx->data;
|
||||
delete ctx;
|
||||
ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy);
|
||||
buffer->context = ctx;
|
||||
if (ctx->data == nullptr) {
|
||||
return false;
|
||||
}
|
||||
tensor->data = (char *) ctx->data + offset;
|
||||
return true;
|
||||
}
|
||||
|
||||
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache)
|
||||
if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() &&
|
||||
!is_stateful_enabled()) {
|
||||
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
|
||||
// decoding feature buffers (llama_context::layer_inp_dev / h_nextn_dev): every graph reads or writes the whole
|
||||
// buffer, so in host memory the plugin copies it to the device and back on every inference.
|
||||
const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 ||
|
||||
strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0;
|
||||
if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) {
|
||||
GGML_ASSERT(ctx->tensor_extras.empty());
|
||||
auto device = ctx->device;
|
||||
auto size = ctx->size;
|
||||
auto * data_prev = ctx->data;
|
||||
delete ctx;
|
||||
ctx = new ggml_backend_openvino_buffer_context(device, size, true);
|
||||
buffer->context = ctx;
|
||||
tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
|
||||
if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) {
|
||||
return GGML_STATUS_ALLOC_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
// On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor
|
||||
@@ -401,14 +452,10 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
|
||||
if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() &&
|
||||
tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) {
|
||||
if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) {
|
||||
auto device = ctx->device;
|
||||
auto size = ctx->size;
|
||||
auto * data_prev = ctx->data;
|
||||
delete ctx;
|
||||
ctx = new ggml_backend_openvino_buffer_context(device, size, false, true);
|
||||
if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, false, true)) {
|
||||
return GGML_STATUS_ALLOC_FAILED;
|
||||
}
|
||||
ctx->kv_on_demand = true;
|
||||
buffer->context = ctx;
|
||||
tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
|
||||
}
|
||||
if (ctx->kv_on_demand) {
|
||||
ggml_openvino_kv_storage_register(tensor->data, tensor->nb[1], tensor->ne[1]);
|
||||
@@ -431,12 +478,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
|
||||
if (ggml_openvino_tensor_extra * extra =
|
||||
ggml_openvino_create_tensor_extra(tensor, ctx->is_remote,
|
||||
ggml_openvino_get_available_devices()[ctx->device])) {
|
||||
auto it = ctx->tensor_extras.find(tensor);
|
||||
if (it != ctx->tensor_extras.end()) {
|
||||
delete it->second;
|
||||
}
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
return GGML_STATUS_SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -451,12 +493,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
|
||||
ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(
|
||||
tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device]);
|
||||
if (extra != nullptr) {
|
||||
auto it = ctx->tensor_extras.find(tensor);
|
||||
if (it != ctx->tensor_extras.end()) {
|
||||
delete it->second;
|
||||
}
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -644,8 +681,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
// }
|
||||
}
|
||||
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
|
||||
// Register the host buffer so its pages can be dropped after the GPU
|
||||
// plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS).
|
||||
@@ -661,6 +697,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
"multi-model runs.");
|
||||
}
|
||||
ggml_openvino_register_weight_buffer(ctx->data, ctx->size);
|
||||
ctx->weight_registered = true;
|
||||
}
|
||||
|
||||
if (!ctx->external_memory) {
|
||||
@@ -700,12 +737,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
return;
|
||||
}
|
||||
|
||||
auto it = ctx->tensor_extras.find(tensor);
|
||||
if (it != ctx->tensor_extras.end()) {
|
||||
delete it->second;
|
||||
}
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1087,15 +1119,8 @@ void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_ext
|
||||
GGML_ASSERT(tensor->buffer != nullptr);
|
||||
GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer));
|
||||
|
||||
auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
|
||||
|
||||
auto it = ctx->tensor_extras.find(tensor);
|
||||
if (it != ctx->tensor_extras.end()) {
|
||||
delete it->second;
|
||||
}
|
||||
|
||||
ctx->tensor_extras[tensor] = extra;
|
||||
tensor->extra = extra;
|
||||
ggml_openvino_set_extra(static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context), tensor,
|
||||
extra);
|
||||
}
|
||||
|
||||
bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) {
|
||||
@@ -1837,7 +1862,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
case GGML_OP_DIV: {
|
||||
// The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path
|
||||
// and produce infs for per-channel scale vectors. Keep those DIVs on CPU
|
||||
// until the fused GPU kernel is reliable. (falied case llama-arch-test mpt)
|
||||
// until the fused GPU kernel is reliable (failing case: test-llama-archs, mpt).
|
||||
// Only a weight divisor is such a scale; at one token an activation divisor has the same shape
|
||||
// (qwen2moe's shared-expert sigmoid, silu(x) / x).
|
||||
if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] &&
|
||||
@@ -1898,11 +1923,14 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
memcpy(&max_bias, (const float *) op_params + 1, sizeof(float));
|
||||
memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float));
|
||||
|
||||
// Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid
|
||||
// accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid
|
||||
// affecting non-gemma3n models such as Llama-3.2.
|
||||
// Keep gemma3n flash-attn pattern on CPU to avoid accuracy drift in the OpenVINO path.
|
||||
// Restrict by scale=1.0 to avoid affecting non-gemma3n models such as Llama-3.2.
|
||||
if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) {
|
||||
return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"};
|
||||
return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"};
|
||||
}
|
||||
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return {false, "FLASH_ATTN_EXT with indexed bias is not supported"};
|
||||
}
|
||||
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
@@ -1948,7 +1976,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
return {false, "CPY with BF16 src[1] type is not supported"};
|
||||
}
|
||||
if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) {
|
||||
return {false, "CPY with BF16 is not supported is not supported on NPU"};
|
||||
return {false, "CPY with BF16 is not supported on NPU"};
|
||||
}
|
||||
// CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend.
|
||||
if (ggml_is_quantized(op->type)) {
|
||||
@@ -2063,12 +2091,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
// return true;
|
||||
// }
|
||||
const char * reason = nullptr;
|
||||
if (op->src[2]->op == GGML_OP_PERMUTE) {
|
||||
// a VIEW of the PERMUTE (v with padded heads) is still a permuted v
|
||||
const ggml_tensor * v_src = op->src[2]->op == GGML_OP_VIEW ? op->src[2]->src[0] : op->src[2];
|
||||
if (v_src->op == GGML_OP_PERMUTE) {
|
||||
reason = "GATED_DELTA_NET with PERMUTE src2 is not supported";
|
||||
}
|
||||
else if (op->src[3]->ne[0] != 1) {
|
||||
// kda (per-key-dimension gating) not supported by fused GatedDeltaNet op
|
||||
reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported";
|
||||
else if (op->src[3]->ne[0] != 1 && (op->op_params[0] > 1 || ggml_openvino_gdn_native_state_enabled()) &&
|
||||
!ov::frontend::ggml::op::gdn_per_key_gate_supported()) {
|
||||
reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state "
|
||||
"snapshots or the native state layout";
|
||||
}
|
||||
else if (op->op_params[0] > 1) {
|
||||
if (ggml_openvino_is_static()) {
|
||||
@@ -2084,12 +2115,6 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_OP_SSM_CONV: {
|
||||
// qwen3next is numerically unstable with OpenVINO SSM_CONV.
|
||||
// Keep this op on CPU until the OpenVINO implementation is fixed.
|
||||
// return true;
|
||||
break;
|
||||
}
|
||||
case GGML_OP_SSM_SCAN: {
|
||||
// SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state
|
||||
if (op->src[3]->ne[0] != 1) {
|
||||
@@ -2292,9 +2317,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
|
||||
if (!supported) {
|
||||
return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"};
|
||||
}
|
||||
// if (has_view_op_input(op)) {
|
||||
// return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"};
|
||||
// }
|
||||
if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) {
|
||||
// triggers bug in ov gpu
|
||||
return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"};
|
||||
@@ -2347,16 +2369,114 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
|
||||
return {true, ""};
|
||||
}
|
||||
|
||||
// Report what supports_op() accepts and rejects, so a graph that silently falls back to another
|
||||
// backend can be diagnosed. Every op rejected here becomes a graph split; if nothing is rejected,
|
||||
// the whole graph runs on OpenVINO.
|
||||
//
|
||||
// Gated by GGML_OPENVINO_LOG_SUPPORTS_OP:
|
||||
// 1 one summary at exit listing every distinct op kind and verdict -- start here
|
||||
// 2 additionally log every individual call, with the tensor name and shape
|
||||
//
|
||||
// This wraps the decision function instead of instrumenting it, so all of its return paths are
|
||||
// covered -- including the several that reject without logging a reason of their own, and any
|
||||
// added later.
|
||||
//
|
||||
// The summary is reported at exit rather than on each op's first occurrence, because the earliest
|
||||
// calls happen before the log handler emits anything: with level 2 the first line to actually
|
||||
// appear already reads "call 1244". A first-occurrence line would therefore be silently dropped
|
||||
// for exactly the ops that are only ever seen early. Counting is unaffected, so the summary is the
|
||||
// reliable view; treat the level-2 stream as a sample, not a complete trace.
|
||||
namespace {
|
||||
|
||||
struct supports_op_tally {
|
||||
std::mutex mutex;
|
||||
// key: "<op>:ok" / "<op>:no" -> number of calls
|
||||
std::map<std::string, size_t> counts;
|
||||
|
||||
// Report totals once, at exit. Registered lazily so a run with the knob off costs nothing.
|
||||
// atexit runs while the ggml log callback is still valid, which static destruction does not
|
||||
// guarantee.
|
||||
void arm_summary() {
|
||||
static std::once_flag armed;
|
||||
std::call_once(armed, [] {
|
||||
std::atexit([] {
|
||||
auto & self = instance();
|
||||
std::lock_guard<std::mutex> lock(self.mutex);
|
||||
|
||||
size_t n_accept_kinds = 0;
|
||||
size_t n_reject_kinds = 0;
|
||||
GGML_LOG_WARN("ov-supports-op: ---- summary (distinct op kinds, with call counts) ----\n");
|
||||
for (const auto & [key, count] : self.counts) {
|
||||
const bool ok = key.size() > 3 && key.compare(key.size() - 3, 3, ":ok") == 0;
|
||||
ok ? ++n_accept_kinds : ++n_reject_kinds;
|
||||
GGML_LOG_WARN("ov-supports-op: %-8s %-24s %zu call(s)\n", ok ? "ACCEPT" : "REJECT",
|
||||
key.substr(0, key.size() - 3).c_str(), count);
|
||||
}
|
||||
if (n_reject_kinds == 0) {
|
||||
GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, 0 rejected"
|
||||
" -- every op was supported, so no split originated here\n",
|
||||
n_accept_kinds);
|
||||
} else {
|
||||
GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, %zu REJECTED"
|
||||
" -- each rejected kind forces a graph split\n",
|
||||
n_accept_kinds, n_reject_kinds);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
static supports_op_tally & instance() {
|
||||
static supports_op_tally tally;
|
||||
return tally;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
|
||||
if (!res.is_supported) {
|
||||
const bool supported = res.is_supported;
|
||||
if (!supported) {
|
||||
static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0;
|
||||
if (log_unsupported) {
|
||||
GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n",
|
||||
op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str());
|
||||
}
|
||||
}
|
||||
return res.is_supported;
|
||||
|
||||
static const int log_level = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SUPPORTS_OP");
|
||||
if (log_level <= 0) {
|
||||
return supported;
|
||||
}
|
||||
|
||||
// Name the op the way ggml does: UNARY and GLU carry their real identity in a sub-enum, so
|
||||
// logging only "UNARY" would merge SILU with everything else.
|
||||
std::string op_desc = ggml_op_name(op->op);
|
||||
if (op->op == GGML_OP_UNARY) {
|
||||
op_desc += std::string("/") + ggml_unary_op_name(ggml_get_unary_op(op));
|
||||
} else if (op->op == GGML_OP_GLU) {
|
||||
op_desc += std::string("/") + ggml_glu_op_name(ggml_get_glu_op(op));
|
||||
}
|
||||
|
||||
// The scheduler calls supports_op() on every graph build and may do so from several threads,
|
||||
// so the tally needs a lock. Keyed on op identity *and* verdict, because the same op can be
|
||||
// accepted at one shape and rejected at another (e.g. a quantized 3-D src).
|
||||
auto & tally = supports_op_tally::instance();
|
||||
tally.arm_summary();
|
||||
|
||||
size_t count;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(tally.mutex);
|
||||
count = ++tally.counts[op_desc + (supported ? ":ok" : ":no")];
|
||||
}
|
||||
|
||||
if (log_level >= 2) {
|
||||
GGML_LOG_WARN("ov-supports-op: %-6s %-22s name='%s' type=%s ne=[%ld,%ld,%ld,%ld] (call %zu)\n",
|
||||
supported ? "ACCEPT" : "REJECT", op_desc.c_str(), op->name, ggml_type_name(op->type),
|
||||
(long) op->ne[0], (long) op->ne[1], (long) op->ne[2], (long) op->ne[3], count);
|
||||
}
|
||||
|
||||
return supported;
|
||||
}
|
||||
|
||||
static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
|
||||
|
||||
@@ -154,19 +154,22 @@ void extract_q4_1_data(const ggml_tensor * tensor,
|
||||
});
|
||||
} else {
|
||||
auto * zp = static_cast<uint8_t *>(zp_arr.data());
|
||||
ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
|
||||
float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
|
||||
float min = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
|
||||
scales[i] = ov::float16(scale);
|
||||
// zp = -min / scale (bias = min, so zp = -bias/scale)
|
||||
uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0;
|
||||
// Pack two 4-bit zero points per byte
|
||||
if (i % 2 == 0) {
|
||||
zp[i / 2] = zp_val & 0x0F; // Lower nibble
|
||||
} else {
|
||||
zp[i / 2] |= (zp_val << 4); // Upper nibble
|
||||
const size_t n_blocks = scales_arr.get_size();
|
||||
// One iteration per zero point byte: the two blocks that share a byte are packed together, so no two
|
||||
// threads write the same byte.
|
||||
ov::parallel_for((n_blocks + 1) / 2, [&](size_t pair) {
|
||||
uint8_t packed = 0;
|
||||
for (size_t i = 2 * pair; i < std::min(2 * pair + 2, n_blocks); i++) {
|
||||
float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
|
||||
float min =
|
||||
static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
|
||||
scales[i] = ov::float16(scale);
|
||||
// zp = -min / scale (bias = min, so zp = -bias/scale), in the u4 range
|
||||
const uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 15L) : 0;
|
||||
packed |= (i % 2 == 0) ? zp_val : (uint8_t) (zp_val << 4);
|
||||
unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
|
||||
}
|
||||
unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
|
||||
zp[pair] = packed;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -259,7 +262,7 @@ void extract_q5_1_data(const ggml_tensor * tensor,
|
||||
float min = static_cast<float>(ov::float16::from_bits(read_u16(block + 2)));
|
||||
scales[i] = ov::float16(scale);
|
||||
// zp = -min / scale (dequant: (w - zp) * s == w*s + min)
|
||||
zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0;
|
||||
zp[i] = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 255L) : 0;
|
||||
unpack_block(block, weights + i * qk);
|
||||
});
|
||||
}
|
||||
@@ -378,7 +381,9 @@ void extract_q4_k_data(const ggml_tensor * tensor,
|
||||
bias_f16[i * 8 + j] = ov::float16(-min_vals[j]);
|
||||
} else {
|
||||
// zp = min / scale (since bias = -min and zp = -bias/scale)
|
||||
uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0;
|
||||
uint8_t zp_val = (scale_vals[j] != 0.0f) ?
|
||||
(uint8_t) std::clamp(std::lround(min_vals[j] / scale_vals[j]), 0L, 15L) :
|
||||
0;
|
||||
// Pack two 4-bit zero points per byte
|
||||
size_t idx = i * 8 + j;
|
||||
if (idx % 2 == 0) {
|
||||
|
||||
@@ -186,6 +186,7 @@ static const char * cache_settings[] = {
|
||||
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
|
||||
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
|
||||
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
|
||||
"GGML_OPENVINO_ROPE_F32_ANGLE",
|
||||
};
|
||||
|
||||
void ggml_openvino_model_cache_init() {
|
||||
@@ -368,7 +369,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
|
||||
// Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive.
|
||||
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
|
||||
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
|
||||
h = fnv1a_u64(h, 8);
|
||||
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
|
||||
h = fnv1a_u64(h, 9);
|
||||
h = fnv1a(h, graph_signature.data(), graph_signature.size());
|
||||
for (const char * name : cache_settings) {
|
||||
const char * value = ggml_openvino_getenv_str(name, "");
|
||||
@@ -548,8 +550,10 @@ static bool read_weights_hash(const std::string & path, uint64_t & hash) {
|
||||
std::string key, value;
|
||||
while (meta >> key >> value) {
|
||||
if (key == "hash") {
|
||||
hash = std::stoull(value, nullptr, 16);
|
||||
return true;
|
||||
// a damaged record counts as no hash, so the caller rewrites the file
|
||||
char * end = nullptr;
|
||||
hash = std::strtoull(value.c_str(), &end, 16);
|
||||
return end != value.c_str() && *end == '\0';
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
#include "ggml.h"
|
||||
|
||||
#include <openvino/frontend/exception.hpp>
|
||||
#include <openvino/op/concat.hpp>
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <openvino/op/reshape.hpp>
|
||||
#include <openvino/op/topk.hpp>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace op {
|
||||
|
||||
// GGML_OP_ARGMAX: src0 is a matrix [ne0, ne1]; the result is a 1-D I32 tensor of ne1 entries
|
||||
// holding, for each row, the index of the maximum along ne0. ggml shapes arrive reversed here, so
|
||||
// ne0 is the last OV axis and ne1 is axis 2. TopK(k=1, axis=last, MAX) yields exactly that index,
|
||||
// then reshape to the [1,1,1,ne1] layout the decoder expects for a 1-D ggml output.
|
||||
//
|
||||
// Note ggml's argmax returns the FIRST maximum on a tie, while TopK's tie-breaking is not specified
|
||||
// to match. Ties on real logits are vanishingly rare and none were observed, but the two are not
|
||||
// proven equivalent.
|
||||
OutputVector translate_argmax(const NodeContext & context) {
|
||||
num_inputs_check(context, 1, 1);
|
||||
|
||||
auto input = process_view_input_new(context, 0);
|
||||
|
||||
auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
|
||||
auto topk = std::make_shared<ov::op::v11::TopK>(input,
|
||||
k,
|
||||
3,
|
||||
ov::op::v11::TopK::Mode::MAX,
|
||||
ov::op::v11::TopK::SortType::SORT_VALUES,
|
||||
context.get_output_type(),
|
||||
false);
|
||||
|
||||
// ne1 is the dynamic row count, so build the target shape at runtime.
|
||||
auto leading = ov::op::v0::Constant::create(ov::element::i64, {3}, {1, 1, 1});
|
||||
auto rows = get_dimensions(input.get_node_shared_ptr(), {2});
|
||||
auto target_shape = std::make_shared<ov::op::v0::Concat>(OutputVector{leading, rows}, 0);
|
||||
auto res = std::make_shared<ov::op::v1::Reshape>(topk->output(1), target_shape, false);
|
||||
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
} // namespace op
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -182,13 +182,7 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
// Manual GQA attention: enabled by default on GPU in stateless mode.
|
||||
// Set GGML_OPENVINO_MANUAL_GQA_ATTN to a positive value (e.g. 1) to force-enable,
|
||||
// or to 0 to force-disable. Unset falls back to the device-based default.
|
||||
static const bool manual_gqa_enabled = []() {
|
||||
const char * env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
|
||||
if (env != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu();
|
||||
}();
|
||||
static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
|
||||
// The manual path reshapes Q, K, V and the output with one head size; models whose K/V head sizes differ
|
||||
// from Q's (e.g. MLA) take the SDPA path.
|
||||
const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3];
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <numeric>
|
||||
#include <openvino/core/model.hpp>
|
||||
#include <openvino/op/add.hpp>
|
||||
#include <openvino/op/broadcast.hpp>
|
||||
#include <openvino/op/concat.hpp>
|
||||
@@ -29,6 +30,7 @@
|
||||
#include <openvino/op/maximum.hpp>
|
||||
#include <openvino/op/minimum.hpp>
|
||||
#include <openvino/op/multiply.hpp>
|
||||
#include <openvino/op/parameter.hpp>
|
||||
#include <openvino/op/range.hpp>
|
||||
#include <openvino/op/reduce_mean.hpp>
|
||||
#include <openvino/op/reshape.hpp>
|
||||
@@ -52,6 +54,31 @@ namespace op {
|
||||
|
||||
static OutputVector translate_gated_delta_net_ref(const NodeContext & context);
|
||||
|
||||
// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin
|
||||
// without a per-key kernel leaves the node out of query_model
|
||||
bool gdn_per_key_gate_supported() {
|
||||
static const bool supported = [] {
|
||||
ov::ParameterVector params;
|
||||
auto param = [¶ms](const ov::Shape & shape) {
|
||||
params.push_back(std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape));
|
||||
return params.back();
|
||||
};
|
||||
std::shared_ptr<ov::Node> gdn;
|
||||
try {
|
||||
gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(param({1, 1, 1, 2}), param({1, 1, 1, 2}),
|
||||
param({1, 1, 1, 2}), param({1, 1, 2, 2}),
|
||||
param({1, 1, 1, 2}), param({1, 1, 1}));
|
||||
} catch (const ov::Exception &) {
|
||||
return false;
|
||||
}
|
||||
const auto model = std::make_shared<ov::Model>(gdn->outputs(), params);
|
||||
return ov_singleton_core()
|
||||
.query_model(model, ggml_openvino_get_device_name())
|
||||
.count(gdn->get_friendly_name()) != 0;
|
||||
}();
|
||||
return supported;
|
||||
}
|
||||
|
||||
static bool match_gdn_l2_norm(const Output<Node> & normalized, Output<Node> & input, float & eps) {
|
||||
// Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE.
|
||||
const auto scale = ov::as_type_ptr<ov::op::v1::Multiply>(normalized.get_node_shared_ptr());
|
||||
@@ -379,23 +406,36 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v]
|
||||
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
|
||||
|
||||
// Fused GatedDeltaNet op only supports scalar gate (kda=0).
|
||||
// Fall back to reference implementation for per-key-dimension gating.
|
||||
// if (kda) {
|
||||
// return translate_gated_delta_net_ref(context);
|
||||
// }
|
||||
// g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as
|
||||
// a rank-4 gate
|
||||
const bool kda = context.get_input_shape(3)[3] != 1;
|
||||
if (kda && !gdn_per_key_gate_supported()) {
|
||||
// the reference loop reads and writes the state in the ggml layout, one state per call
|
||||
FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 &&
|
||||
!ggml_openvino_gdn_native_state_enabled(),
|
||||
"GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 "
|
||||
"gate for recurrent caches, state snapshots or the native state layout");
|
||||
return translate_gated_delta_net_ref(context);
|
||||
}
|
||||
|
||||
// const int64_t B = v_shape[0];
|
||||
// const int64_t T = v_shape[1];
|
||||
const int64_t H_v = v_shape[2];
|
||||
const int64_t S_v = v_shape[3];
|
||||
const int64_t H_k = q_shape[2];
|
||||
const int64_t snapshot_count = context.get_output_op_params()[0];
|
||||
// const int64_t S_k = q_shape[3];
|
||||
|
||||
// v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed
|
||||
// in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider
|
||||
// row, goes through the generic view resolution, which already returns [B, T, H_v, S_v].
|
||||
const bool v_is_view = context.get_view_input_size(2) > 0;
|
||||
bool v_packed_heads = true;
|
||||
if (v_is_view) {
|
||||
const auto v_stride = context.get_view_input_stride(2, 0); // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1]
|
||||
v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3];
|
||||
}
|
||||
|
||||
auto q = context.get_input(0);
|
||||
auto k = context.get_input(1);
|
||||
auto v = process_view_input(context, 2, H_v * S_v, 3);
|
||||
auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2);
|
||||
auto g = context.get_input(3);
|
||||
auto beta = context.get_input(4);
|
||||
auto state = context.get_input(5);
|
||||
@@ -424,7 +464,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
k = std::make_shared<ov::op::v0::Tile>(k, repeats);
|
||||
}
|
||||
|
||||
if (context.get_view_input_size(2)) {
|
||||
if (v_is_view && v_packed_heads) {
|
||||
// Same as l2_norm case 1
|
||||
v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
|
||||
auto v_shape = context.get_input_shape(2).to_shape();
|
||||
@@ -443,7 +483,9 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
|
||||
}
|
||||
|
||||
g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
|
||||
if (!kda) {
|
||||
g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
|
||||
}
|
||||
beta = std::make_shared<ov::op::v0::Squeeze>(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
|
||||
|
||||
if (context.has_input("chunk_valid_len")) {
|
||||
@@ -453,7 +495,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
// state equal to the state after the last real token. Attention output at those positions
|
||||
// is garbage but never read.
|
||||
const auto & g_ps = g.get_partial_shape();
|
||||
FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(),
|
||||
FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(),
|
||||
"GATED_DELTA_NET pad masking requires a static token dimension");
|
||||
const int64_t n_tokens = g_ps[1].get_length();
|
||||
std::vector<int64_t> positions(n_tokens);
|
||||
@@ -464,8 +506,12 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
auto mask = std::make_shared<ov::op::v0::Unsqueeze>(
|
||||
std::make_shared<ov::op::v0::Convert>(valid, g.get_element_type()),
|
||||
ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{0, 2}));
|
||||
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
|
||||
beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
|
||||
if (kda) {
|
||||
mask = std::make_shared<ov::op::v0::Unsqueeze>(mask,
|
||||
ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
|
||||
}
|
||||
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
|
||||
}
|
||||
|
||||
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
|
||||
@@ -540,6 +586,8 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co
|
||||
|
||||
static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
num_inputs_check(context, 6, 6);
|
||||
FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"),
|
||||
"GATED_DELTA_NET reference loop does not support padded prefill chunks");
|
||||
|
||||
// Inputs (OV shapes are reversed from ggml):
|
||||
// ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B]
|
||||
@@ -559,8 +607,8 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
|
||||
auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
|
||||
|
||||
// The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token.
|
||||
const int64_t B = v_shape[0];
|
||||
const int64_t T = v_shape[1];
|
||||
const int64_t H_v = v_shape[2];
|
||||
const int64_t S_v = v_shape[3];
|
||||
const int64_t H_k = q_shape[2];
|
||||
@@ -599,14 +647,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
|
||||
auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);
|
||||
|
||||
auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
|
||||
auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
|
||||
q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);
|
||||
k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);
|
||||
}
|
||||
|
||||
// Merge batch and head dims: [B*H_v, T, S_v]
|
||||
auto merge_bh = [&](const ov::Output<ov::Node> & x, int64_t last_dim) {
|
||||
auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, T, last_dim});
|
||||
auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, -1, last_dim});
|
||||
return std::make_shared<ov::op::v1::Reshape>(x, shape, false);
|
||||
};
|
||||
|
||||
@@ -682,7 +730,9 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},
|
||||
ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});
|
||||
|
||||
auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{T});
|
||||
auto vm_shape = std::make_shared<ov::op::v3::ShapeOf>(v_m, ov::element::i64);
|
||||
auto trip_count =
|
||||
std::make_shared<ov::op::v8::Gather>(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
|
||||
auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});
|
||||
|
||||
auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
|
||||
@@ -709,7 +759,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
// attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major
|
||||
|
||||
// attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten
|
||||
auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
|
||||
auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
|
||||
auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);
|
||||
auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213); // [B, T, H_v, S_v]
|
||||
|
||||
@@ -729,7 +779,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
|
||||
// Concat [attn | state] and reshape to final output
|
||||
auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);
|
||||
auto out_shape =
|
||||
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, T * B + S_v * B, S_v * H_v});
|
||||
ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, -1, S_v * H_v});
|
||||
auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);
|
||||
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
|
||||
@@ -30,6 +30,10 @@ OutputVector translate_reshape(const NodeContext & context) {
|
||||
std::shared_ptr<ov::Node> new_shape_node;
|
||||
switch (op_case) {
|
||||
case 0:
|
||||
// keep the tracked dynamic dim, e.g. the tokens of a reshape that only adds a trailing 1 (see translate_cont)
|
||||
if (context.get_op_dynamic_dim() != -1) {
|
||||
shape[3 - context.get_op_dynamic_dim()] = -1;
|
||||
}
|
||||
break;
|
||||
case 1:
|
||||
case 9:
|
||||
|
||||
@@ -34,7 +34,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
|
||||
input_node = context.get_input(0);
|
||||
} else if (op_case == 1) {
|
||||
input_node = process_view_input_new(context, 0);
|
||||
} else if (op_case == 2 || op_case == 3) {
|
||||
} else if (op_case == 2 || op_case == 5) {
|
||||
auto ssm_state_size = context.get_ssm_state_size();
|
||||
// The GDN op packs [attn | new_state] along the row axis; the state occupies the last
|
||||
// ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep
|
||||
@@ -83,7 +83,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
|
||||
float eps;
|
||||
memcpy(&eps, context.get_output_op_params(), sizeof(float));
|
||||
|
||||
if (op_case == 3 && ggml_openvino_gdn_prescale_enabled()) {
|
||||
if ((op_case == 3 || op_case == 5) && ggml_openvino_gdn_prescale_enabled()) {
|
||||
// input is the GDN output pre-scaled by ggml_openvino_gdn_q_scale(): rms_norm(s*x, s*s*eps) == rms_norm(x, eps)
|
||||
const float q_scale = ggml_openvino_gdn_q_scale();
|
||||
eps *= q_scale * q_scale;
|
||||
|
||||
@@ -118,16 +118,41 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
|
||||
if (data.get_element_type() != context.get_output_type()) {
|
||||
data = std::make_shared<v0::Convert>(data, context.get_output_type());
|
||||
}
|
||||
Output<Node> rows = std::make_shared<v1::Reshape>(process_view_input_new(context, 1), i64_const({-1}), false);
|
||||
auto row_ids = process_view_input_new(context, 1);
|
||||
Output<Node> rows = std::make_shared<v1::Reshape>(row_ids, i64_const({-1}), false);
|
||||
if (rows.get_element_type() != ov::element::i64) {
|
||||
rows = std::make_shared<v0::Convert>(rows, ov::element::i64);
|
||||
}
|
||||
|
||||
auto axis = v0::Constant::create(ov::element::i64, {}, {2});
|
||||
auto buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
|
||||
Output<Node> buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
|
||||
Output<Node> base_shape_of = std::make_shared<v3::ShapeOf>(base, ov::element::i64);
|
||||
Output<Node> existing;
|
||||
|
||||
// Every write copies the whole buffer, so fold this one into the previous column write when both use the same
|
||||
// rows (DFlash writes every target layer at the same batch rows): splice into its rows and scatter once
|
||||
auto rows_source = [](Output<Node> r) {
|
||||
if (ov::as_type_ptr<v0::Convert>(r.get_node_shared_ptr())) {
|
||||
r = r.get_node()->input_value(0);
|
||||
}
|
||||
return ov::as_type_ptr<v1::Reshape>(r.get_node_shared_ptr()) ? r.get_node()->input_value(0) : Output<Node>();
|
||||
};
|
||||
auto prev_res = ov::as_type_ptr<v1::Reshape>(base.get_node_shared_ptr());
|
||||
auto prev = prev_res ? ov::as_type_ptr<v3::ScatterUpdate>(prev_res->get_input_node_shared_ptr(0)) : nullptr;
|
||||
if (prev && rows_source(prev->input_value(1)) == row_ids &&
|
||||
prev->input_value(2).get_partial_shape().rank().is_static() &&
|
||||
prev->input_value(2).get_partial_shape()[3] == row_size) {
|
||||
buffer = prev->input_value(0);
|
||||
rows = prev->input_value(1);
|
||||
existing = prev->input_value(2);
|
||||
base_shape_of = prev_res->input_value(1);
|
||||
}
|
||||
|
||||
Output<Node> updates = data;
|
||||
if (width < row_size) {
|
||||
auto existing = std::make_shared<v8::Gather>(buffer, rows, axis);
|
||||
if (!existing.get_node_shared_ptr()) {
|
||||
existing = std::make_shared<v8::Gather>(buffer, rows, axis);
|
||||
}
|
||||
auto col_axis = i64_const({3});
|
||||
OutputVector parts;
|
||||
if (col_begin > 0) {
|
||||
@@ -142,7 +167,7 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
|
||||
updates = std::make_shared<v0::Concat>(parts, 3);
|
||||
}
|
||||
auto updated = std::make_shared<v3::ScatterUpdate>(buffer, rows, updates, axis);
|
||||
auto res = std::make_shared<v1::Reshape>(updated, std::make_shared<v3::ShapeOf>(base, ov::element::i64), false);
|
||||
auto res = std::make_shared<v1::Reshape>(updated, base_shape_of, false);
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
|
||||
#include <openvino/op/broadcast.hpp>
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <openvino/op/divide.hpp>
|
||||
#include <openvino/op/gather.hpp>
|
||||
#include <openvino/op/loop.hpp>
|
||||
#include <openvino/op/matmul.hpp>
|
||||
#include <openvino/op/scatter_update.hpp>
|
||||
#include <openvino/op/shape_of.hpp>
|
||||
#include <openvino/op/subtract.hpp>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace op {
|
||||
|
||||
// GGML SOLVE_TRI: solve Ax = B for lower-triangular A via forward substitution.
|
||||
// Currently only lower, right, non-unitriangular variant is implemented.
|
||||
//
|
||||
// ggml layout: A [n, n, B1, B2], B [k, n, B1, B2] → X [k, n, B1, B2]
|
||||
// OV layout: A [B2, B1, n, n], B [B2, B1, n, k] → X [B2, B1, n, k]
|
||||
//
|
||||
// Forward substitution row i:
|
||||
// x[i] = (b[i] - sum_{t<i} A[i,t]*x[t]) / A[i,i]
|
||||
//
|
||||
// Implemented as an OV Loop op iterating n times with a carried X accumulator.
|
||||
// Key insight: A is lower-triangular and X starts as zeros, so the full matmul
|
||||
// A_row_i @ X_partial = sum_{t<i} A[i,t]*x[t] exactly (upper triangle of A
|
||||
// is zero; unfilled rows of X are zero).
|
||||
OutputVector translate_solve_tri(const NodeContext & context) {
|
||||
num_inputs_check(context, 2, 2);
|
||||
|
||||
auto A = context.get_input(0); // [B2, B1, n, n]
|
||||
auto B = context.get_input(1); // [B2, B1, n, k]
|
||||
|
||||
auto A_shape = context.get_input_shape(0).to_shape();
|
||||
int64_t n = static_cast<int64_t>(A_shape[2]);
|
||||
|
||||
// Initial X: zeros with shape of B
|
||||
auto B_shape_node = std::make_shared<ov::op::v3::ShapeOf>(B, ov::element::i64);
|
||||
auto zero_f32 = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f});
|
||||
auto X_init = std::make_shared<ov::op::v3::Broadcast>(zero_f32, B_shape_node);
|
||||
|
||||
// --- Loop body parameters ---
|
||||
// body_iter: iteration counter injected by the Loop op (i64, shape {1})
|
||||
auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
|
||||
auto body_X = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
|
||||
auto body_A = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
|
||||
auto body_B_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
|
||||
|
||||
auto c_axis2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(2)});
|
||||
auto c_axis3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(3)});
|
||||
auto c_axis2_scalar = ov::op::v0::Constant::create(ov::element::i64, {}, {int64_t(2)});
|
||||
|
||||
// b_i = B[..., i, :] [B2, B1, 1, k]
|
||||
auto b_i = std::make_shared<ov::op::v8::Gather>(body_B_p, body_iter, c_axis2);
|
||||
|
||||
// A_row_i = A[..., i, :] [B2, B1, 1, n]
|
||||
auto A_row_i = std::make_shared<ov::op::v8::Gather>(body_A, body_iter, c_axis2);
|
||||
|
||||
// sum_i = A_row_i @ X [B2, B1, 1, k]
|
||||
// (lower-tri zeros + unfilled-X zeros make this equal to the partial sum)
|
||||
auto sum_i = std::make_shared<ov::op::v0::MatMul>(A_row_i, body_X, false, false);
|
||||
|
||||
// diag_i = A[..., i, i] [B2, B1, 1, 1]
|
||||
auto diag_i = std::make_shared<ov::op::v8::Gather>(A_row_i, body_iter, c_axis3);
|
||||
|
||||
// x_i = (b_i - sum_i) / diag_i [B2, B1, 1, k]
|
||||
auto x_i = std::make_shared<ov::op::v1::Divide>(
|
||||
std::make_shared<ov::op::v1::Subtract>(b_i, sum_i), diag_i);
|
||||
|
||||
// X_updated: scatter x_i into body_X at row i along axis 2
|
||||
auto X_updated = std::make_shared<ov::op::v3::ScatterUpdate>(body_X, body_iter, x_i, c_axis2_scalar);
|
||||
|
||||
auto body_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
|
||||
|
||||
auto body = std::make_shared<ov::Model>(
|
||||
ov::OutputVector{body_cond, X_updated},
|
||||
ov::ParameterVector{body_iter, body_X, body_A, body_B_p});
|
||||
|
||||
// --- Assemble Loop ---
|
||||
auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{n});
|
||||
auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
|
||||
|
||||
auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
|
||||
loop->set_function(body);
|
||||
// iter_counter_body_param_idx=0 (body_iter), exec_condition_body_result_idx=0 (body_cond)
|
||||
loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});
|
||||
|
||||
// Carried state: X feeds back from X_updated each iteration
|
||||
loop->set_merged_input(body_X, X_init, X_updated);
|
||||
// Invariant inputs passed through unchanged
|
||||
loop->set_invariant_input(body_A, A);
|
||||
loop->set_invariant_input(body_B_p, B);
|
||||
|
||||
// Final output: value of X_updated after the last iteration
|
||||
auto X_final = loop->get_iter_value(X_updated, -1);
|
||||
|
||||
return rename_outputs_with_suffix({X_final}, context.get_name());
|
||||
}
|
||||
|
||||
} // namespace op
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -57,6 +57,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
|
||||
{"GGML_OP_SQR", op::translate_sqr },
|
||||
{"GGML_OP_SQRT", op::translate_sqrt },
|
||||
{"GGML_OP_SOFT_MAX", op::translate_soft_max },
|
||||
{"GGML_OP_ARGMAX", op::translate_argmax },
|
||||
{"GGML_OP_ARGSORT", op::translate_argsort },
|
||||
{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},
|
||||
{"GGML_OP_TRANSPOSE", op::translate_transpose },
|
||||
@@ -102,7 +103,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
|
||||
{"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net },
|
||||
{"GGML_OP_REPEAT", op::translate_repeat },
|
||||
{"GGML_OP_CUMSUM", op::translate_cumsum },
|
||||
{"GGML_OP_FILL", op::translate_fill },
|
||||
{"GGML_OP_DIAG", op::translate_diag },
|
||||
{"GGML_OP_TRI", op::translate_tri },
|
||||
{"GGML_OP_SET", op::translate_set },
|
||||
@@ -115,8 +115,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
|
||||
{"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d },
|
||||
{"GGML_OP_CONV_TRANSPOSE_2D", op::translate_conv_transpose_2d },
|
||||
{"GGML_OP_CONV_3D", op::translate_conv_3d },
|
||||
// solve_tri has accuracy issues on GPU
|
||||
// {"GGML_OP_SOLVE_TRI", op::translate_solve_tri },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu);
|
||||
GGML_OP_CONVERTER(translate_glu_geglu_quick);
|
||||
GGML_OP_CONVERTER(translate_set_rows);
|
||||
GGML_OP_CONVERTER(translate_cpy);
|
||||
GGML_OP_CONVERTER(translate_argmax);
|
||||
GGML_OP_CONVERTER(translate_argsort);
|
||||
GGML_OP_CONVERTER(translate_top_k);
|
||||
GGML_OP_CONVERTER(translate_flash_attn_ext);
|
||||
@@ -51,16 +52,16 @@ GGML_OP_CONVERTER(translate_pad);
|
||||
GGML_OP_CONVERTER(translate_ssm_conv);
|
||||
GGML_OP_CONVERTER(translate_ssm_scan);
|
||||
GGML_OP_CONVERTER(translate_gated_delta_net);
|
||||
// The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop
|
||||
bool gdn_per_key_gate_supported();
|
||||
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs);
|
||||
#endif
|
||||
GGML_OP_CONVERTER(translate_repeat);
|
||||
GGML_OP_CONVERTER(translate_cumsum);
|
||||
GGML_OP_CONVERTER(translate_fill);
|
||||
GGML_OP_CONVERTER(translate_set);
|
||||
GGML_OP_CONVERTER(translate_diag);
|
||||
GGML_OP_CONVERTER(translate_tri);
|
||||
GGML_OP_CONVERTER(translate_solve_tri);
|
||||
GGML_OP_CONVERTER(translate_pool_1d);
|
||||
GGML_OP_CONVERTER(translate_pool_2d);
|
||||
GGML_OP_CONVERTER(translate_roll);
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
#include "fuse_to_sdpa.h"
|
||||
|
||||
#include <openvino/core/graph_util.hpp>
|
||||
#include <openvino/core/rt_info.hpp>
|
||||
#include <openvino/op/add.hpp>
|
||||
#include <openvino/op/convert.hpp>
|
||||
#include <openvino/op/matmul.hpp>
|
||||
#include <openvino/op/multiply.hpp>
|
||||
#include <openvino/op/scaled_dot_product_attention.hpp>
|
||||
#include <openvino/op/softmax.hpp>
|
||||
#include <openvino/op/transpose.hpp>
|
||||
#include <openvino/pass/pattern/op/label.hpp>
|
||||
#include <openvino/pass/pattern/op/pattern.hpp>
|
||||
#include <openvino/pass/pattern/op/wrap_type.hpp>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
FuseToSDPA::FuseToSDPA() {
|
||||
// Not maintained since FLASH_ATTN_EXT has replaced this pattern
|
||||
const auto m_k = ov::pass::pattern::any_input();
|
||||
const auto m_q = ov::pass::pattern::any_input();
|
||||
const auto m_qk = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_q, m_k});
|
||||
const auto m_qk_f32 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_qk});
|
||||
const auto m_scale = ov::pass::pattern::any_input();
|
||||
const auto m_scaled_qk = ov::pass::pattern::wrap_type<ov::op::v1::Multiply>({m_qk_f32, m_scale});
|
||||
const auto m_mask = ov::pass::pattern::any_input();
|
||||
const auto m_masked_qk = ov::pass::pattern::wrap_type<ov::op::v1::Add>({m_scaled_qk, m_mask});
|
||||
const auto m_softmax_qk = ov::pass::pattern::wrap_type<ov::op::v8::Softmax>({m_masked_qk});
|
||||
const auto m_softmax_qk_f16 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_softmax_qk});
|
||||
const auto m_v = ov::pass::pattern::any_input();
|
||||
const auto m_qkv = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_softmax_qk_f16, m_v});
|
||||
|
||||
const auto callback = [=](ov::pass::pattern::Matcher & m) {
|
||||
auto & pattern_to_output = m.get_pattern_value_map();
|
||||
auto k = pattern_to_output[m_k];
|
||||
auto q = pattern_to_output[m_q];
|
||||
auto v = pattern_to_output[m_v];
|
||||
auto mask = pattern_to_output[m_mask];
|
||||
auto scale = pattern_to_output[m_scale];
|
||||
|
||||
auto mask_f16 = register_new_node<ov::op::v0::Convert>(mask, ov::element::f16);
|
||||
auto scale_f16 = register_new_node<ov::op::v0::Convert>(scale, ov::element::f16);
|
||||
auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask_f16, scale_f16, false);
|
||||
|
||||
ov::replace_node(m.get_match_root(), sdpa);
|
||||
ov::copy_runtime_info(m.get_matched_nodes(), sdpa);
|
||||
|
||||
return true;
|
||||
};
|
||||
register_matcher(std::make_shared<ov::pass::pattern::Matcher>(m_qkv, "ov::frontend::ggml::pass::FuseToSDPA"),
|
||||
callback);
|
||||
}
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -1,17 +0,0 @@
|
||||
#include "openvino/pass/matcher_pass.hpp"
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
class FuseToSDPA : public ov::pass::MatcherPass {
|
||||
public:
|
||||
OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::FuseToSDPA")
|
||||
FuseToSDPA();
|
||||
};
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -225,42 +225,12 @@ void add_position_mask_stateful_swa(TensorMap & tensor_map) {
|
||||
tensor_map["KQ_mask_swa_sliced"] = mask->output(0);
|
||||
}
|
||||
|
||||
void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
|
||||
// When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed
|
||||
// SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos
|
||||
// precompute cannot broadcast across every ROPE use. Skip it here and let
|
||||
// translate_rope() build sin/cos per-op from its own op_params.
|
||||
if (ggml_model_decoder.has_mixed_rope_params()) {
|
||||
return;
|
||||
}
|
||||
int32_t * rope_params = ggml_model_decoder.get_rope_params();
|
||||
if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) {
|
||||
return;
|
||||
}
|
||||
auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
|
||||
std::shared_ptr<ov::Node> rope_freqs_weight;
|
||||
if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) {
|
||||
rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr();
|
||||
}
|
||||
|
||||
auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight);
|
||||
auto sin_theta = sin_cos.first;
|
||||
auto cos_theta = sin_cos.second;
|
||||
|
||||
cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos");
|
||||
sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin");
|
||||
tensor_map.insert({"rope_cos", cos_theta});
|
||||
tensor_map.insert({"rope_sin", sin_theta});
|
||||
}
|
||||
|
||||
// Create common patterns
|
||||
void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
|
||||
if (ggml_model_decoder.is_stateful()) {
|
||||
add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE);
|
||||
add_position_mask_stateful_swa(tensor_map);
|
||||
}
|
||||
// This optimization is error-prone
|
||||
// add_rope_sin_cos(tensor_map, ggml_model_decoder);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
#include <openvino/op/subtract.hpp>
|
||||
#include <openvino/op/transpose.hpp>
|
||||
#include <openvino/op/unsqueeze.hpp>
|
||||
#include <openvino/op/util/precision_sensitive_attribute.hpp>
|
||||
#include <string>
|
||||
|
||||
namespace ov {
|
||||
@@ -43,18 +44,6 @@ void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max
|
||||
FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");
|
||||
}
|
||||
|
||||
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
|
||||
int dim = nb.size() - 1;
|
||||
size_t bytes = nb[dim];
|
||||
for (int i = dim; i > 0; i--) {
|
||||
bytes *= ne[i];
|
||||
if (bytes != nb[i - 1]) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
|
||||
const std::vector<int> & dims) {
|
||||
using namespace ov::op;
|
||||
@@ -311,14 +300,77 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params
|
||||
}
|
||||
}
|
||||
|
||||
Output<Node> cos_theta = std::make_shared<ov::op::v0::Cos>(theta);
|
||||
Output<Node> sin_theta = std::make_shared<ov::op::v0::Sin>(theta);
|
||||
// Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16.
|
||||
//
|
||||
// Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared
|
||||
// element type is not an execution precision: under the f16 hint the GPU plugin compresses these
|
||||
// subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands
|
||||
// where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base
|
||||
// and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency
|
||||
// angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately
|
||||
// right, it is arbitrary, and trig amplifies the error without bound.
|
||||
//
|
||||
// Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the
|
||||
// whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155,
|
||||
// and K right after the rotation carries rel 0.081. The error is depth-dependent because f16
|
||||
// spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525.
|
||||
//
|
||||
// mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is
|
||||
// exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the
|
||||
// Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the
|
||||
// matmuls that dominate. The rotation itself and everything downstream stay f16.
|
||||
//
|
||||
// Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model,
|
||||
// it is validated on one model on the GPU only, and on an f32 path the round trip below makes
|
||||
// cos and sin less accurate.
|
||||
const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0;
|
||||
|
||||
auto cos_op = std::make_shared<ov::op::v0::Cos>(theta);
|
||||
auto sin_op = std::make_shared<ov::op::v0::Sin>(theta);
|
||||
if (pin_angle) {
|
||||
ov::mark_as_precision_sensitive(cos_op->input(0));
|
||||
ov::mark_as_precision_sensitive(sin_op->input(0));
|
||||
}
|
||||
Output<Node> cos_theta = cos_op;
|
||||
Output<Node> sin_theta = sin_op;
|
||||
|
||||
if (mscale != 1.0f) {
|
||||
auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});
|
||||
|
||||
cos_theta = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
|
||||
sin_theta = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
|
||||
auto cos_scaled = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
|
||||
auto sin_scaled = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
|
||||
// Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the
|
||||
// sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair,
|
||||
// so compilation fails with "Arguments do not have the same element type".
|
||||
if (pin_angle) {
|
||||
ov::mark_as_precision_sensitive(cos_scaled->input(1));
|
||||
ov::mark_as_precision_sensitive(sin_scaled->input(1));
|
||||
}
|
||||
cos_theta = cos_scaled;
|
||||
sin_theta = sin_scaled;
|
||||
}
|
||||
|
||||
// Close the f32 island explicitly with an f16 round trip.
|
||||
//
|
||||
// ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32
|
||||
// region propagates forward through the shape-only ops of the cos/sin expansion and then collides
|
||||
// with f16 data in the rotation, so the type mismatch just moves one step down the graph.
|
||||
//
|
||||
// Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4,
|
||||
// the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the
|
||||
// marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the
|
||||
// chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is
|
||||
// a node we control rather than one the pass has to infer.
|
||||
//
|
||||
// Declared types are f32 on both sides at build time, so the frontend sees no type change. On an
|
||||
// f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16.
|
||||
if (pin_angle) {
|
||||
auto pin_boundary = [](Output<Node> x) -> Output<Node> {
|
||||
auto down = std::make_shared<ov::op::v0::Convert>(x, ov::element::f16);
|
||||
return std::make_shared<ov::op::v0::Convert>(down, ov::element::f32);
|
||||
};
|
||||
cos_theta = pin_boundary(cos_theta);
|
||||
sin_theta = pin_boundary(sin_theta);
|
||||
}
|
||||
|
||||
return std::make_pair(sin_theta, cos_theta);
|
||||
@@ -784,20 +836,23 @@ ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int inp
|
||||
return split_node->output(static_cast<size_t>(split_index));
|
||||
}
|
||||
if (split_index >= 0 && split_index < num_splits && !dynamic_split) {
|
||||
// as above: a weak reference, and one Split per output port
|
||||
auto src_node = input.get_node_shared_ptr();
|
||||
std::string rt_key = "split_dim_" + std::to_string(split_dim);
|
||||
std::string rt_key =
|
||||
"split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index());
|
||||
auto & rt_info = src_node->get_rt_info();
|
||||
|
||||
if (rt_info.find(rt_key) == rt_info.end()) {
|
||||
std::shared_ptr<ov::Node> split_node;
|
||||
if (rt_info.count(rt_key) != 0) {
|
||||
split_node = rt_info[rt_key].as<std::weak_ptr<ov::Node>>().lock();
|
||||
}
|
||||
if (split_node == nullptr) {
|
||||
auto axis_const =
|
||||
ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast<int64_t>(split_dim)});
|
||||
auto split_node =
|
||||
split_node =
|
||||
std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
|
||||
split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
|
||||
rt_info[rt_key] = split_node;
|
||||
rt_info[rt_key] = std::weak_ptr<ov::Node>(split_node);
|
||||
}
|
||||
|
||||
auto split_node = rt_info[rt_key].as<std::shared_ptr<ov::op::v1::Split>>();
|
||||
return split_node->output(static_cast<size_t>(split_index));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,42 +13,8 @@ namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
|
||||
std::string getCurrentTime();
|
||||
|
||||
void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs);
|
||||
|
||||
int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb);
|
||||
|
||||
template <typename T> std::vector<int> argsort_descend(const std::vector<T> & v) {
|
||||
std::vector<int> idx(v.size());
|
||||
std::iota(idx.begin(), idx.end(), 0);
|
||||
std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) { return v[i1] > v[i2]; });
|
||||
return idx;
|
||||
}
|
||||
|
||||
template <typename T> std::vector<T> sorted_descend(std::vector<T> v) {
|
||||
std::sort(v.begin(), v.end(), [](T a, T b) { return a > b; });
|
||||
return v;
|
||||
}
|
||||
|
||||
template <typename T> bool is_permuted(const std::vector<T> & strides) {
|
||||
for (size_t i = 0; i < strides.size() - 1; ++i) {
|
||||
if (strides[i] < strides[i + 1]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T> std::vector<T> permute(const std::vector<T> & x, const std::vector<int> & perm) {
|
||||
std::vector<T> result;
|
||||
result.reserve(perm.size());
|
||||
for (int i : perm) {
|
||||
result.push_back(x[i]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
|
||||
const std::vector<int> & dims);
|
||||
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node, const std::vector<int> & dims);
|
||||
|
||||
@@ -151,6 +151,12 @@ std::optional<ov::Tensor> try_make_kv_sliced_tensor(const std::shared_ptr<GgmlOv
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if (ggml_tensor->data == nullptr) {
|
||||
// unallocated input: let the caller build an owning zero tensor rather than slice a null
|
||||
// pointer
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
ov::Shape sliced_shape = full_shape;
|
||||
sliced_shape[2] = static_cast<size_t>(n_kv);
|
||||
|
||||
@@ -192,10 +198,10 @@ std::optional<ov::Tensor> try_make_kv_4d_tensor(const std::shared_ptr<GgmlOvDeco
|
||||
}
|
||||
|
||||
// Column count of a static KQ mask input; must match GgmlOvDecoder::get_graph_input_shape().
|
||||
static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_decoder, const std::string & name) {
|
||||
static size_t get_static_attention_size(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & name) {
|
||||
const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name));
|
||||
if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) {
|
||||
const auto params = ggml_decoder->get_compute_params();
|
||||
const auto & params = ggml_decoder->get_compute_params();
|
||||
const int attention_size = is_swa ? params.attention_size_swa : params.attention_size;
|
||||
if (attention_size > 0) {
|
||||
return static_cast<size_t>(attention_size);
|
||||
@@ -209,10 +215,7 @@ static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_deco
|
||||
}
|
||||
|
||||
static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) {
|
||||
const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
|
||||
const bool manual_gqa_enabled = manual_gqa_env != nullptr ?
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 :
|
||||
ggml_openvino_is_gpu();
|
||||
const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
|
||||
|
||||
uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results.
|
||||
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
@@ -561,6 +564,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_d
|
||||
return context.create_tensor(output_type, output_shape, resolved);
|
||||
}
|
||||
|
||||
// A graph output can also have no backing storage. Give OV an owning tensor so the infer request
|
||||
// has somewhere to write; nothing downstream reads it.
|
||||
if (output_data == nullptr) {
|
||||
return ov::Tensor(output_type, output_shape);
|
||||
}
|
||||
ov::Tensor output_tensor(output_type, output_shape, output_data);
|
||||
return output_tensor;
|
||||
}
|
||||
@@ -713,6 +721,20 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr<GgmlOvDecoder> & ggml_
|
||||
return make_contiguous_split_input_tensor(ggml_tensor, input_shape);
|
||||
}
|
||||
|
||||
// A graph input may legitimately be left unallocated (data == nullptr, no buffer): llama.cpp
|
||||
// skips filling the attention mask when a graph only stores K/V without attending, which is what
|
||||
// a speculative KV-injection pass does. Such an input is never read, but OpenVINO still requires
|
||||
// a backing tensor for the Parameter and constructing an ov::Tensor over a null pointer asserts.
|
||||
// Hand OV an owning zero-filled tensor; its contents cannot affect the result because no op
|
||||
// consumes them.
|
||||
if (input_data == nullptr) {
|
||||
GGML_LOG_WARN("ggml-openvino: unallocated INPUT '%s' (ggml name '%s', type %s, ne=[%ld,%ld,%ld,%ld]) "
|
||||
"-> zero tensor\n",
|
||||
name.c_str(), ggml_tensor->name, ggml_type_name(ggml_tensor->type),
|
||||
(long) ggml_tensor->ne[0], (long) ggml_tensor->ne[1], (long) ggml_tensor->ne[2],
|
||||
(long) ggml_tensor->ne[3]);
|
||||
return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
|
||||
}
|
||||
auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data);
|
||||
return input_tensor;
|
||||
}
|
||||
@@ -790,10 +812,8 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder
|
||||
if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
|
||||
ov::Shape input_shape = {1, 1, 1, 1};
|
||||
ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
|
||||
int32_t inp_out_id = *((int32_t *) ggml_tensor->data);
|
||||
assert(ggml_tensor->ne[0] == 1);
|
||||
assert(inp_out_id == 0);
|
||||
*input_tensor.data<int32_t>() = inp_out_id;
|
||||
// The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read.
|
||||
*input_tensor.data<int32_t>() = 0;
|
||||
return input_tensor;
|
||||
}
|
||||
|
||||
@@ -1256,13 +1276,15 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
|
||||
cache_hit = it != r_ctx->decoder_cache.end();
|
||||
if (cache_hit) {
|
||||
entry = it->second;
|
||||
r_ctx->touch_locked(key);
|
||||
} else {
|
||||
if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) {
|
||||
if (r_ctx->stateful) {
|
||||
r_ctx->clear_caches_locked();
|
||||
}
|
||||
auto mutex = std::make_shared<std::mutex>();
|
||||
entry = std::make_shared<decoder_runtime_ctx>(mutex);
|
||||
r_ctx->decoder_cache[key] = entry;
|
||||
r_ctx->admit_locked(key);
|
||||
}
|
||||
} else {
|
||||
auto mutex = std::make_shared<std::mutex>();
|
||||
@@ -1276,10 +1298,21 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
|
||||
|
||||
if (cache_hit) {
|
||||
ggml_decoder = entry->ptr;
|
||||
// The cache key is only (n_nodes, first/last node name), so it cannot see a change in
|
||||
// WHICH tensors are graph outputs -- and the compiled model's Results are fixed when it is
|
||||
// built. A consumer that starts requesting extra outputs later (speculative decoding marks
|
||||
// the target's per-layer residuals only once the draft is initialised) would otherwise keep
|
||||
// reusing a model that never produces them, and the host would read unwritten buffers as
|
||||
// zeros. Recompile when the output set differs.
|
||||
old_m_params = ggml_decoder->get_model_params();
|
||||
if (!ggml_decoder->is_splited_model()) {
|
||||
cache_hit = old_m_params.can_reuse_dynamically(m_params);
|
||||
}
|
||||
// Must come AFTER can_reuse_dynamically(), which ASSIGNS to cache_hit rather than
|
||||
// and-ing into it and would otherwise silently undo this invalidation.
|
||||
if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) {
|
||||
cache_hit = false;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> ov_input_names;
|
||||
@@ -1654,8 +1687,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
|
||||
|
||||
infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
|
||||
shared_model = compiled_model;
|
||||
entry->ptr = ggml_decoder;
|
||||
|
||||
} // end non-imported (compile) path
|
||||
|
||||
entry->ptr = ggml_decoder;
|
||||
@@ -1725,7 +1756,20 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
|
||||
id = binding.staging_id;
|
||||
}
|
||||
if (needs_bind(binding, input_tensor, id)) {
|
||||
infer_request->set_input_tensor(i, input_tensor);
|
||||
try {
|
||||
infer_request->set_input_tensor(i, input_tensor);
|
||||
} catch (const std::exception & e) {
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
|
||||
auto port = infer_request->get_compiled_model().input(i);
|
||||
GGML_LOG_WARN(
|
||||
"ggml-openvino: DIAG set_input_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
|
||||
" model_shape=%s bound_shape=%s\n",
|
||||
i, param_name.c_str(), key.n_nodes, key.first_node_name.c_str(),
|
||||
key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
|
||||
input_tensor.get_shape().to_string().c_str());
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
|
||||
@@ -1786,12 +1830,40 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
|
||||
id = binding.staging_id;
|
||||
}
|
||||
if (needs_bind(binding, output_tensor, id)) {
|
||||
infer_request->set_output_tensor(i, output_tensor);
|
||||
try {
|
||||
infer_request->set_output_tensor(i, output_tensor);
|
||||
} catch (const std::exception & e) {
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
|
||||
auto port = infer_request->get_compiled_model().output(i);
|
||||
GGML_LOG_WARN(
|
||||
"ggml-openvino: DIAG set_output_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
|
||||
" model_shape=%s bound_shape=%s\n",
|
||||
i, ov_output_names[i].c_str(), key.n_nodes, key.first_node_name.c_str(),
|
||||
key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
|
||||
output_tensor.get_shape().to_string().c_str());
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ov_raw_infer_start = ggml_time_us();
|
||||
infer_request->infer();
|
||||
try {
|
||||
infer_request->infer();
|
||||
} catch (const std::exception & e) {
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
|
||||
auto cm = infer_request->get_compiled_model();
|
||||
GGML_LOG_WARN("ggml-openvino: DIAG infer() threw for n_nodes=%d first=%s last=%s: %s\n", key.n_nodes,
|
||||
key.first_node_name.c_str(), key.last_node_name.c_str(), e.what());
|
||||
for (size_t i = 0; i < ov_input_names.size(); i++) {
|
||||
auto port = cm.input(i);
|
||||
GGML_LOG_WARN(" param[%zu] name=%s model_shape=%s bound_shape=%s\n", i,
|
||||
ov_input_names[i].c_str(), port.get_partial_shape().to_string().c_str(),
|
||||
infer_request->get_input_tensor(i).get_shape().to_string().c_str());
|
||||
}
|
||||
}
|
||||
throw;
|
||||
}
|
||||
infer_end_time = ggml_time_us();
|
||||
for (const auto & out : staged_outputs) {
|
||||
std::memcpy(out.dst, out.src, out.bytes);
|
||||
@@ -2190,11 +2262,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
|
||||
cache_hit = it != r_ctx->decoder_cache.end();
|
||||
if (cache_hit) {
|
||||
entry = it->second;
|
||||
r_ctx->touch_locked(key);
|
||||
} else {
|
||||
r_ctx->clear_caches_locked();
|
||||
auto mutex = std::make_shared<std::mutex>();
|
||||
entry = std::make_shared<decoder_runtime_ctx>(mutex);
|
||||
r_ctx->decoder_cache[key] = entry;
|
||||
r_ctx->admit_locked(key);
|
||||
}
|
||||
} else {
|
||||
auto mutex = std::make_shared<std::mutex>();
|
||||
@@ -2265,10 +2338,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
|
||||
// Same fail-fast as the dynamic path: once the host weight pages have been dropped
|
||||
// they read as zeros, so a recompile here would bake garbage into the new model.
|
||||
if (ggml_openvino_weight_buffers_released()) {
|
||||
GGML_ABORT(
|
||||
"ggml-openvino: a new graph needs to be compiled but host weight buffers were already "
|
||||
"released via GGML_OPENVINO_RELEASE_WEIGHTS. This mode requires "
|
||||
"stable graph shapes; disable host weight release for dynamic workloads.");
|
||||
GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
|
||||
return GGML_STATUS_FAILED;
|
||||
}
|
||||
if (cache_enabled) {
|
||||
std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
|
||||
@@ -2318,6 +2389,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
|
||||
}
|
||||
} else {
|
||||
auto decode_c_params = c_params;
|
||||
// A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the
|
||||
// decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows
|
||||
// than the graph has tokens.
|
||||
decode_c_params.output_len = 1;
|
||||
if (ggml_openvino_kv_slice_enabled()) {
|
||||
decode_c_params.attention_size = m_params.ctx_per_seq;
|
||||
decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa;
|
||||
@@ -3322,7 +3397,7 @@ bool is_model_splitted(ggml_cgraph * cgraph) {
|
||||
// the src is also not the model weights, we think the model is splitted.
|
||||
// the src is also not in model leafs, we think the model is splitted.
|
||||
if (src != nullptr && model_nodes.find(src) == model_nodes.end() &&
|
||||
model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false &&
|
||||
model_weights.find(std::string(src->name)) == model_weights.end() &&
|
||||
model_leafs.find(src) == model_leafs.end()) {
|
||||
if (GgmlOvDecoder::is_inp_tok(src, node)) {
|
||||
return false;
|
||||
@@ -3345,75 +3420,6 @@ bool is_naive(ggml_cgraph * cgraph) {
|
||||
return count < naive_graph_size_threshold;
|
||||
}
|
||||
|
||||
size_t checksum(const void * data, size_t size) {
|
||||
const uint8_t * bytes = static_cast<const uint8_t *>(data);
|
||||
size_t sum = 0;
|
||||
for (size_t i = 0; i < size; ++i) {
|
||||
sum += (uint8_t) i;
|
||||
sum += bytes[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) {
|
||||
if (tensor == nullptr || tensor->data == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::ofstream out(file_path);
|
||||
if (!out.is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t n = ggml_nelements(tensor);
|
||||
out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0]
|
||||
<< ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n
|
||||
<< ", data:" << '\n';
|
||||
|
||||
switch (tensor->type) {
|
||||
case GGML_TYPE_F32: {
|
||||
const auto * data = static_cast<const float *>(tensor->data);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
out << data[i] << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_TYPE_F16: {
|
||||
const auto * data = static_cast<const ggml_fp16_t *>(tensor->data);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
out << ggml_fp16_to_fp32(data[i]) << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_TYPE_BF16: {
|
||||
const auto * data = static_cast<const ggml_bf16_t *>(tensor->data);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
out << ggml_bf16_to_fp32(data[i]) << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_TYPE_I32: {
|
||||
const auto * data = static_cast<const int32_t *>(tensor->data);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
out << data[i] << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case GGML_TYPE_I64: {
|
||||
const auto * data = static_cast<const int64_t *>(tensor->data);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
out << data[i] << '\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
out << "unsupported tensor type for text dump" << '\n';
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void print_input_tensor_info(const std::string & name, const ov::Tensor & input) {
|
||||
// GPU inputs can be device (USM) tensors, whose data() throws; print a host copy of those.
|
||||
const bool is_remote = input.is<ov::RemoteTensor>();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
@@ -158,6 +159,12 @@ struct ov_runtime_context {
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
|
||||
// LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
|
||||
// that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
|
||||
// injection graphs every round -- needs a slot per shape open at once; a single-entry cache
|
||||
// would evict and recompile all of them, every call, forever.
|
||||
std::list<graph_key> lru_keys;
|
||||
static constexpr size_t max_cached_graphs = 8;
|
||||
size_t stateful_kv_size;
|
||||
std::map<std::string, std::string> kv_state_input_name_map;
|
||||
// compute-only copies of graphs that carry unselected ggml_build_forward_select() branches
|
||||
@@ -169,6 +176,39 @@ struct ov_runtime_context {
|
||||
|
||||
ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {}
|
||||
|
||||
// Mark `key` as the most recently used entry. Call on every cache hit and after inserting a
|
||||
// new entry, so eviction always picks the graph shape that has gone longest unused.
|
||||
void touch_locked(const graph_key & key) {
|
||||
lru_keys.remove(key);
|
||||
lru_keys.push_back(key);
|
||||
}
|
||||
|
||||
// Drop the least recently used graph shape's compiled model and its associated per-key
|
||||
// caches. Leaves every other shape's compiled model intact.
|
||||
void evict_lru_locked() {
|
||||
if (lru_keys.empty()) {
|
||||
return;
|
||||
}
|
||||
graph_key victim = lru_keys.front();
|
||||
lru_keys.pop_front();
|
||||
decoder_cache.erase(victim);
|
||||
infer_request_cache.erase(victim);
|
||||
infer_request_cache_prefill.erase(victim);
|
||||
ov_input_names_cache.erase(victim);
|
||||
ov_output_names_cache.erase(victim);
|
||||
ov_input_names_cache_prefill.erase(victim);
|
||||
ov_output_names_cache_prefill.erase(victim);
|
||||
}
|
||||
|
||||
// Make room for one more graph shape if the cache is at capacity, then mark `key` as most
|
||||
// recently used. Call right after inserting `key` into decoder_cache.
|
||||
void admit_locked(const graph_key & key) {
|
||||
while (decoder_cache.size() > max_cached_graphs) {
|
||||
evict_lru_locked();
|
||||
}
|
||||
touch_locked(key);
|
||||
}
|
||||
|
||||
void clear_caches_locked() {
|
||||
decoder_cache.clear();
|
||||
infer_request_cache.clear();
|
||||
@@ -177,6 +217,7 @@ struct ov_runtime_context {
|
||||
ov_output_names_cache.clear();
|
||||
ov_input_names_cache_prefill.clear();
|
||||
ov_output_names_cache_prefill.clear();
|
||||
lru_keys.clear();
|
||||
kv_state_input_name_map.clear();
|
||||
stateful_kv_size = 0;
|
||||
}
|
||||
@@ -192,10 +233,6 @@ enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t ba
|
||||
// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
|
||||
void ov_clear_imported_blobs();
|
||||
|
||||
size_t checksum(const void * data, size_t size);
|
||||
|
||||
bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path);
|
||||
|
||||
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
|
||||
|
||||
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);
|
||||
|
||||
+517
-751
File diff suppressed because it is too large
Load Diff
@@ -7741,8 +7741,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
|
||||
case GGML_OP_SOLVE_TRI:
|
||||
return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K;
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op);
|
||||
// K/V row lists and indexed bias are not supported
|
||||
return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size
|
||||
}
|
||||
|
||||
static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) &&
|
||||
!ggml_rope_get_truncate(op)) {
|
||||
return false;
|
||||
|
||||
@@ -16774,8 +16774,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
}
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
{
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
if (op->src[5] != nullptr) {
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
bool coopmat2 = device->coopmat2;
|
||||
|
||||
@@ -5086,8 +5086,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
|
||||
{
|
||||
// conservative support checks for whether the more resource-intensive shader paths
|
||||
// can be used, to avoid cases where flash_attn is assigned to the CPU later on
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 &&
|
||||
// K/V row lists and indexed bias are not supported
|
||||
supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) &&
|
||||
src0->type == GGML_TYPE_F32 &&
|
||||
(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 ||
|
||||
src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) &&
|
||||
(src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 ||
|
||||
|
||||
@@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context *
|
||||
memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float));
|
||||
|
||||
// sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented
|
||||
if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
|
||||
if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -5545,6 +5545,33 @@ void ggml_flash_attn_ext_add_sinks(
|
||||
a->src[4] = sinks;
|
||||
}
|
||||
|
||||
bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) {
|
||||
return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0;
|
||||
}
|
||||
|
||||
void ggml_flash_attn_ext_add_indexed_bias(
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * table,
|
||||
struct ggml_tensor * indices) {
|
||||
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
|
||||
GGML_ASSERT((table == NULL) == (indices == NULL));
|
||||
a->src[6] = table;
|
||||
a->src[7] = indices;
|
||||
ggml_set_op_params_i32(a, 5, table != NULL);
|
||||
if (!table) {
|
||||
return;
|
||||
}
|
||||
|
||||
const struct ggml_tensor * q = a->src[0];
|
||||
const struct ggml_tensor * mask = a->src[3];
|
||||
GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]);
|
||||
GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]);
|
||||
GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table));
|
||||
GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1);
|
||||
GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices));
|
||||
GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]);
|
||||
}
|
||||
|
||||
// ggml_flash_attn_back
|
||||
|
||||
struct ggml_tensor * ggml_flash_attn_back(
|
||||
|
||||
@@ -466,6 +466,15 @@ extern "C" {
|
||||
const struct llama_model_tensor_override * tt_overrides; // pointer to tensor overrides
|
||||
const int32_t * prune_layers; // pointer to layer indices to prune
|
||||
size_t max_buf_size; // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB)
|
||||
const struct llama_model_imatrix_data * activations; // pointer to activations data
|
||||
const struct llama_model_imatrix_data * statistics; // pointer to statistics data
|
||||
const char * const * stats_schema; // pointer to statistics schema names
|
||||
float target_bpw; // target bits per weight (bpw)
|
||||
int64_t target_size; // target file size in bytes
|
||||
const char * state_file; // pointer to bpw state file
|
||||
const enum ggml_type * target_exclude; // pointer to excluded GGML_TYPEs
|
||||
ggml_abort_callback abort_callback; // callback to abort quantization
|
||||
void * abort_callback_data; // pointer to user data for abort_callback
|
||||
} llama_model_quantize_params;
|
||||
|
||||
typedef struct llama_logit_bias {
|
||||
|
||||
@@ -1592,6 +1592,18 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
|
||||
}
|
||||
}
|
||||
|
||||
bool llm_arch_mmid_down_bf16(const llm_arch & arch) {
|
||||
switch (arch) {
|
||||
case LLM_ARCH_MISTRAL4:
|
||||
case LLM_ARCH_MELLUM:
|
||||
case LLM_ARCH_FLINT:
|
||||
case LLM_ARCH_LAGUNA:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool llama_arch_supports_save(llm_arch arch) {
|
||||
switch (arch) {
|
||||
case LLM_ARCH_SENSENOVA_U1:
|
||||
|
||||
@@ -1037,3 +1037,4 @@ bool llm_arch_is_diffusion (const llm_arch & arch);
|
||||
bool llm_arch_supports_sm_tensor(const llm_arch & arch);
|
||||
bool llm_arch_supports_rs_rollback(const llm_arch & arch);
|
||||
bool llm_arch_supports_mixed_batch(const llm_arch & arch);
|
||||
bool llm_arch_mmid_down_bf16(const llm_arch & arch);
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ LLAMA_API quantize_state_impl * llama_quant_init(
|
||||
const llama_model * model,
|
||||
const llama_model_quantize_params * params);
|
||||
|
||||
LLAMA_API void llama_quant_free(quantize_state_impl * qs);
|
||||
LLAMA_API void llama_quant_free(const quantize_state_impl * qs);
|
||||
|
||||
// Descriptor for constructing a mock model for quantization testing.
|
||||
struct llama_quant_model_desc {
|
||||
|
||||
+5
-5
@@ -1823,7 +1823,7 @@ ggml_tensor * llm_graph_context::build_lora_mm(
|
||||
}
|
||||
|
||||
|
||||
prec_policy.apply(res);
|
||||
prec_policy.apply(res, w);
|
||||
|
||||
if (w_s) {
|
||||
res = ggml_mul(ctx0, res, w_s);
|
||||
@@ -1894,7 +1894,6 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
|
||||
ggml_tensor * slots,
|
||||
bool cached) const {
|
||||
ggml_tensor * w_s = model.get_w_scale(w);
|
||||
|
||||
// as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur`
|
||||
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
|
||||
// the experts in the MoE cache are selected by their slots
|
||||
@@ -1907,7 +1906,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
|
||||
}
|
||||
|
||||
// after the NVFP4 default, so that the policy can request a higher precision
|
||||
prec_policy.apply(res);
|
||||
prec_policy.apply(res, w);
|
||||
|
||||
if (w_s) {
|
||||
const int64_t n_expert = w_s->ne[0];
|
||||
@@ -2656,15 +2655,16 @@ ggml_tensor * llm_graph_context::build_moe_ffn(
|
||||
// ggml_prec_set_src(experts, GGML_PREC_BF16, 1);
|
||||
// the amax op cannot be split across devices, so these architectures are denied -sm tensor [TAG_MOE_AMAX_SCALE]
|
||||
// ref: https://github.com/ggml-org/llama.cpp/pull/30656#issuecomment-6269597922
|
||||
const bool use_amax = llm_arch_mmid_down_bf16(arch) && prec_policy.get_src1(down_exps) != GGML_PREC_BF16;
|
||||
|
||||
llm_graph_amax_src1 amax_src1 = { nullptr, nullptr };
|
||||
|
||||
if (arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MELLUM || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_LAGUNA) {
|
||||
if (use_amax) {
|
||||
amax_src1 = build_amax_src1_f16(cur);
|
||||
cur = amax_src1.res;
|
||||
}
|
||||
|
||||
ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens]
|
||||
//ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above)
|
||||
cb(experts, "ffn_moe_down", il);
|
||||
|
||||
if (amax_src1.scale_s) {
|
||||
|
||||
@@ -173,18 +173,6 @@ void llama_model_saver::add_kv_from_model() {
|
||||
// add_kv(LLM_KV_GENERAL_SAMPLING_MIROSTAT_ETA, ???);
|
||||
add_kv(LLM_KV_GENERAL_NAME, model->name);
|
||||
|
||||
if (!model->prec_policy.prec_src1.empty()) {
|
||||
std::vector<std::string> tensor_names;
|
||||
std::vector<int8_t> values;
|
||||
tensor_names.reserve(model->prec_policy.prec_src1.size());
|
||||
values.reserve(model->prec_policy.prec_src1.size());
|
||||
for (const auto & [w, prec] : model->prec_policy.prec_src1) {
|
||||
tensor_names.push_back(ggml_get_name(w));
|
||||
values.push_back(prec == GGML_PREC_Q8 ? 0 : 1);
|
||||
}
|
||||
add_kv(LLM_KV_GENERAL_TENSOR_EXTRA_NAME, tensor_names);
|
||||
gguf_set_arr_data(gguf_ctx, llm_kv(LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4).c_str(), GGUF_TYPE_BOOL, values.data(), values.size());
|
||||
}
|
||||
// add_kv(LLM_KV_GENERAL_AUTHOR, ???);
|
||||
// add_kv(LLM_KV_GENERAL_VERSION, ???);
|
||||
// add_kv(LLM_KV_GENERAL_URL, ???);
|
||||
|
||||
+35
-13
@@ -29,6 +29,7 @@
|
||||
#include <cassert>
|
||||
#include <cfloat>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
@@ -1405,19 +1406,24 @@ struct llama_model::impl {
|
||||
std::vector<float> tensor_split_owned;
|
||||
};
|
||||
|
||||
bool llama_prec_policy::apply(ggml_tensor * res) const {
|
||||
if (!res || !res->src[0]) {
|
||||
bool llama_prec_policy::apply(ggml_tensor * res, const ggml_tensor * w) const {
|
||||
if (!res) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ggml_tensor * key = w ? w : res->src[0];
|
||||
if (!key) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool applied = false;
|
||||
|
||||
const auto it_acc = prec_acc.find(res->src[0]);
|
||||
const auto it_acc = prec_acc.find(key);
|
||||
if (it_acc != prec_acc.end()) {
|
||||
applied |= ggml_prec_set_acc(res, it_acc->second);
|
||||
}
|
||||
|
||||
const auto it_src1 = prec_src1.find(res->src[0]);
|
||||
const auto it_src1 = prec_src1.find(key);
|
||||
if (it_src1 != prec_src1.end()) {
|
||||
applied |= ggml_prec_set_src(res, it_src1->second, 1);
|
||||
}
|
||||
@@ -1724,6 +1730,30 @@ void llama_model_base::load_vocab(llama_model_loader & ml) {
|
||||
vocab.load(ml, kv);
|
||||
}
|
||||
|
||||
void llama_model_base::load_prec_policy(llama_model_loader & ml) {
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
|
||||
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
|
||||
for (const auto & layer : layers) {
|
||||
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
|
||||
}
|
||||
}
|
||||
|
||||
if (getenv("LLAMA_MOE_AMAX_SKIP") != nullptr) {
|
||||
LLAMA_LOG_WARN("LLAMA_MOE_AMAX_SKIP is set - the MoE amax rescaling is disabled\n");
|
||||
|
||||
if (llm_arch_mmid_down_bf16(arch)) {
|
||||
for (const auto & layer : layers) {
|
||||
if (layer.ffn_down_exps) {
|
||||
prec_policy.set_src1(layer.ffn_down_exps, GGML_PREC_BF16);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// per-tensor activation precision policy
|
||||
prec_policy.load(ml, *this);
|
||||
}
|
||||
|
||||
bool llama_model_base::load_tensors(llama_model_loader & ml) {
|
||||
const auto & split_mode = params.split_mode;
|
||||
const bool use_mlock = params.load_mode == LLAMA_LOAD_MODE_MLOCK || params.load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK;
|
||||
@@ -2080,15 +2110,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
|
||||
}
|
||||
}
|
||||
|
||||
// the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565
|
||||
if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) {
|
||||
for (const auto & layer : layers) {
|
||||
prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32);
|
||||
}
|
||||
}
|
||||
|
||||
// per-tensor activation precision policy
|
||||
prec_policy.load(ml, *this);
|
||||
load_prec_policy(ml);
|
||||
|
||||
ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr);
|
||||
pimpl->mappings.reserve(ml.mappings.size());
|
||||
|
||||
+13
-1
@@ -743,7 +743,7 @@ struct llama_prec_policy {
|
||||
// the key is the weight tensor `res->src[0]`, stores the recommended activation precision type
|
||||
std::unordered_map<const ggml_tensor *, ggml_prec> prec_src1;
|
||||
|
||||
bool apply(ggml_tensor * res) const;
|
||||
bool apply(ggml_tensor * res, const ggml_tensor * w = nullptr) const;
|
||||
|
||||
void set_acc(const ggml_tensor * w, ggml_prec prec) {
|
||||
if (w) {
|
||||
@@ -751,6 +751,17 @@ struct llama_prec_policy {
|
||||
}
|
||||
}
|
||||
|
||||
void set_src1(const ggml_tensor * w, ggml_prec prec) {
|
||||
if (w) {
|
||||
prec_src1[w] = prec;
|
||||
}
|
||||
}
|
||||
|
||||
ggml_prec get_src1(const ggml_tensor * w) const {
|
||||
const auto it = prec_src1.find(w);
|
||||
return it != prec_src1.end() ? it->second : GGML_PREC_UNDEFINED;
|
||||
}
|
||||
|
||||
void load(llama_model_loader & ml, const llama_model & model);
|
||||
};
|
||||
|
||||
@@ -1146,6 +1157,7 @@ struct llama_model_base : public llama_model {
|
||||
void load_hparams(llama_model_loader & ml) override;
|
||||
void load_vocab (llama_model_loader & ml) override;
|
||||
bool load_tensors(llama_model_loader & ml) override;
|
||||
void load_prec_policy(llama_model_loader & ml);
|
||||
|
||||
// model must define these
|
||||
void load_arch_hparams(llama_model_loader & ml) override = 0;
|
||||
|
||||
+2796
-576
File diff suppressed because it is too large
Load Diff
@@ -350,6 +350,7 @@ llama_build_and_test(test-thread-safety.cpp LABEL "main backend" ARGS -m "${MO
|
||||
set_tests_properties(test-thread-safety PROPERTIES FIXTURES_REQUIRED test-download-model)
|
||||
|
||||
llama_build_and_test(test-arg-parser.cpp LABEL behavior)
|
||||
llama_build_and_test(test-quantize-target.cpp LABEL "main behavior backend" LINK llama)
|
||||
llama_build_and_test(test-model-resolution.cpp LABEL behavior)
|
||||
# the test serves its repos from an httplib server, and the library links it privately
|
||||
target_link_libraries(test-model-resolution PRIVATE cpp-httplib)
|
||||
|
||||
+916
-1012
File diff suppressed because it is too large
Load Diff
@@ -6161,6 +6161,79 @@ struct test_mul_mat_id_w4a8 : public test_mul_mat_id {
|
||||
}
|
||||
};
|
||||
|
||||
// src1 GGML_PREC_BF16: the implementation may keep src1 in F32 or BF16, but must not convert it down to F16
|
||||
struct test_mul_mat_id_prec_src1_bf16 : public test_mul_mat_id {
|
||||
test_mul_mat_id_prec_src1_bf16(ggml_type type_a = GGML_TYPE_F32,
|
||||
int n_mats = 8, int n_used = 2, bool b = false,
|
||||
int64_t m = 32, int64_t n = 32, int64_t k = 256)
|
||||
: test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {}
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * out = test_mul_mat_id::build_graph(ctx);
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_MUL_MAT_ID) {
|
||||
ggml_prec_set_src(t, GGML_PREC_BF16, 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->type == GGML_TYPE_I32) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(t->name, "b") == 0) {
|
||||
init_tensor_uniform(t, -1e6f, 1e6f);
|
||||
} else {
|
||||
init_tensor_uniform(t);
|
||||
}
|
||||
}
|
||||
init_mul_mat_id_ids(ctx, n_mats, skip);
|
||||
}
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "MUL_MAT_ID_PREC_SRC1_BF16";
|
||||
}
|
||||
};
|
||||
|
||||
struct test_mul_mat_id_prec_src1_f32 : public test_mul_mat_id {
|
||||
test_mul_mat_id_prec_src1_f32(ggml_type type_a = GGML_TYPE_F32,
|
||||
int n_mats = 8, int n_used = 2, bool b = false,
|
||||
int64_t m = 32, int64_t n = 32, int64_t k = 256)
|
||||
: test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {}
|
||||
double max_nmse_err() override {
|
||||
if (type_a == GGML_TYPE_F32 || type_a == GGML_TYPE_F16) {
|
||||
return 1e-10;
|
||||
}
|
||||
return test_mul_mat_id::max_nmse_err();
|
||||
}
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * out = test_mul_mat_id::build_graph(ctx);
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_MUL_MAT_ID) {
|
||||
ggml_prec_set_src(t, GGML_PREC_F32, 1);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->type == GGML_TYPE_I32) {
|
||||
continue;
|
||||
}
|
||||
if (strcmp(t->name, "b") == 0) {
|
||||
init_tensor_uniform(t, -1e6f, 1e6f);
|
||||
} else {
|
||||
init_tensor_uniform(t);
|
||||
}
|
||||
}
|
||||
init_mul_mat_id_ids(ctx, n_mats, skip);
|
||||
}
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "MUL_MAT_ID_PREC_SRC1_F32";
|
||||
}
|
||||
};
|
||||
|
||||
// FP4 native W4A4 path on the MoE path (default precision)
|
||||
struct test_mul_mat_id_w4a4 : public test_mul_mat_id {
|
||||
test_mul_mat_id_w4a4(ggml_type type_a = GGML_TYPE_NVFP4, ggml_type type_b = GGML_TYPE_F32,
|
||||
@@ -9478,6 +9551,124 @@ struct test_flash_attn_ext_kv_rows : public test_case {
|
||||
}
|
||||
};
|
||||
|
||||
// GGML_OP_FLASH_ATTN_EXT with an indexed bias: mask[key, query] += table[indices[key, query], head, query]
|
||||
struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
const int64_t hs;
|
||||
const int64_t nh; // K/V heads
|
||||
const int64_t gqa;
|
||||
const int64_t kv; // mask columns
|
||||
const int64_t nb; // queries per stream
|
||||
const int64_t n_stream;
|
||||
const int64_t n_bins;
|
||||
const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows
|
||||
const bool sinks;
|
||||
const ggml_type type_KV;
|
||||
|
||||
std::vector<int32_t> rows;
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV);
|
||||
}
|
||||
|
||||
double max_nmse_err() override {
|
||||
return 5e-4;
|
||||
}
|
||||
|
||||
test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2,
|
||||
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16)
|
||||
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream);
|
||||
ggml_set_name(q, "q");
|
||||
|
||||
ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream);
|
||||
ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream);
|
||||
ggml_set_name(k, "k");
|
||||
ggml_set_name(v, "v");
|
||||
|
||||
ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, nb, 1, n_stream);
|
||||
ggml_set_name(m, "m");
|
||||
|
||||
ggml_tensor * r = nullptr;
|
||||
if (kv_rows) {
|
||||
r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, n_stream);
|
||||
ggml_set_name(r, "r");
|
||||
}
|
||||
|
||||
ggml_tensor * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_bins, nh*gqa, nb*n_stream);
|
||||
ggml_set_name(table, "table");
|
||||
|
||||
ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream);
|
||||
ggml_set_name(indices, "indices");
|
||||
|
||||
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f);
|
||||
if (sinks) {
|
||||
ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa);
|
||||
ggml_set_name(s, "s");
|
||||
ggml_flash_attn_ext_add_sinks(out, s);
|
||||
}
|
||||
ggml_flash_attn_ext_add_indexed_bias(out, table, indices);
|
||||
ggml_prec_set_acc(out, GGML_PREC_F32);
|
||||
ggml_set_name(out, "out");
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
std::mt19937 gen(0x1B1A);
|
||||
|
||||
// distinct random cells per stream, some of them padding
|
||||
rows.assign(kv*n_stream, -1);
|
||||
if (kv_rows) {
|
||||
std::vector<int32_t> order(2*kv);
|
||||
for (int64_t s = 0; s < n_stream; ++s) {
|
||||
for (int64_t i = 0; i < 2*kv; ++i) {
|
||||
order[i] = i;
|
||||
}
|
||||
std::shuffle(order.begin(), order.end(), gen);
|
||||
for (int64_t i = 0; i < kv; ++i) {
|
||||
rows[s*kv + i] = i % 19 == 7 ? -1 : order[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (strcmp(t->name, "r") == 0) {
|
||||
ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t));
|
||||
} else if (strcmp(t->name, "m") == 0) {
|
||||
std::vector<float> f(ggml_nelements(t));
|
||||
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
|
||||
for (int64_t s = 0; s < n_stream; ++s) {
|
||||
for (int64_t j = 0; j < nb; ++j) {
|
||||
for (int64_t i = 0; i < kv; ++i) {
|
||||
const bool pad = kv_rows && rows[s*kv + i] < 0;
|
||||
const bool drop = (i + 3*j + 5*s) % 11 == 0;
|
||||
f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<ggml_fp16_t> h(f.size());
|
||||
ggml_fp32_to_fp16_row(f.data(), h.data(), f.size());
|
||||
ggml_backend_tensor_set(t, h.data(), 0, h.size()*sizeof(ggml_fp16_t));
|
||||
} else if (strcmp(t->name, "indices") == 0) {
|
||||
std::vector<int32_t> idx(ggml_nelements(t));
|
||||
std::uniform_int_distribution<int32_t> dis(0, n_bins - 1);
|
||||
for (auto & i : idx) {
|
||||
i = dis(gen);
|
||||
}
|
||||
ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t));
|
||||
} else if (strcmp(t->name, "table") == 0) {
|
||||
init_tensor_uniform(t, -4.0f, 4.0f);
|
||||
} else if (strcmp(t->name, "s") == 0) {
|
||||
init_tensor_uniform(t, -10.0f, 10.0f);
|
||||
} else {
|
||||
init_tensor_uniform(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// GGML_OP_CROSS_ENTROPY_LOSS
|
||||
struct test_cross_entropy_loss : public test_case {
|
||||
const ggml_type type;
|
||||
@@ -12125,6 +12316,23 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 67, 33, 100));
|
||||
test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 64, 32, 256, {2, 3}, {2, 1}));
|
||||
|
||||
// src1 precision on the MoE path: mm_id (n >= 32) and mv_id (n < 32), broadcast and partial K
|
||||
for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) {
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 1, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 32, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 512, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 16, 4, true, 72, 33, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 4, 2, false, 67, 100, 256));
|
||||
}
|
||||
|
||||
for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) {
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 1, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 32, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 512, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 16, 4, true, 72, 33, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 4, 2, false, 67, 100, 256));
|
||||
}
|
||||
|
||||
// FP4 activation precision (default = native W4A4, src1 GGML_PREC_Q8 = W4A8)
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 1, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 32, 256));
|
||||
@@ -13454,6 +13662,21 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
}
|
||||
}
|
||||
|
||||
// flash attention with an indexed bias (Inkling 2 relative-position bias)
|
||||
for (bool kv_rows : {false, true}) {
|
||||
for (int64_t nb : {1, 7, 65}) {
|
||||
for (int64_t n_stream : {1, 2}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, n_stream, 17, kv_rows));
|
||||
}
|
||||
}
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows));
|
||||
for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type));
|
||||
}
|
||||
}
|
||||
|
||||
// sparse mask with large batch size
|
||||
test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512));
|
||||
test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048));
|
||||
|
||||
@@ -0,0 +1,938 @@
|
||||
#include "testing.h"
|
||||
|
||||
#include "ggml-backend.h"
|
||||
#include "ggml-cpp.h"
|
||||
#include "gguf.h"
|
||||
#include "llama-cpp.h"
|
||||
#include "llama.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <signal.h>
|
||||
#endif
|
||||
|
||||
static const uint32_t n_vocab = 256;
|
||||
static const uint32_t n_embd = 256;
|
||||
static const uint32_t n_ff = 512;
|
||||
static const uint32_t n_head = 2;
|
||||
static const uint32_t n_layer = 4;
|
||||
static const float target_bpw = 4.5f;
|
||||
static bool verbose = false;
|
||||
|
||||
static void set_tensor_data(ggml_tensor * tensor, void * /*userdata*/) {
|
||||
std::mt19937 gen(std::hash<std::string>{}(tensor->name));
|
||||
std::normal_distribution<float> dis(0.0f, 0.1f);
|
||||
std::vector<float> data(ggml_nelements(tensor));
|
||||
for (float & v : data) { v = dis(gen); }
|
||||
ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor));
|
||||
}
|
||||
|
||||
// test model
|
||||
static bool save_model(const std::string & fname) {
|
||||
gguf_context_ptr meta(gguf_init_empty());
|
||||
gguf_set_val_str(meta.get(), "general.architecture", "llama");
|
||||
gguf_set_val_u32(meta.get(), "llama.vocab_size", n_vocab);
|
||||
gguf_set_val_u32(meta.get(), "llama.context_length", 256);
|
||||
gguf_set_val_u32(meta.get(), "llama.embedding_length", n_embd);
|
||||
gguf_set_val_u32(meta.get(), "llama.feed_forward_length", n_ff);
|
||||
gguf_set_val_u32(meta.get(), "llama.block_count", n_layer);
|
||||
gguf_set_val_u32(meta.get(), "llama.attention.head_count", n_head);
|
||||
gguf_set_val_u32(meta.get(), "llama.attention.head_count_kv", n_head);
|
||||
gguf_set_val_f32(meta.get(), "llama.attention.layer_norm_rms_epsilon", 1e-5f);
|
||||
gguf_set_val_str(meta.get(), "tokenizer.ggml.model", "none");
|
||||
|
||||
llama_model_params mparams = llama_model_default_params();
|
||||
ggml_backend_dev_t devs[] = { nullptr };
|
||||
mparams.devices = devs;
|
||||
|
||||
llama_model_ptr model(llama_model_init_from_user(meta.get(), set_tensor_data, nullptr, mparams));
|
||||
if (!model) { return false; }
|
||||
llama_model_save_to_file(model.get(), fname.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
// test imatrix
|
||||
struct imatrix_data {
|
||||
std::vector<std::string> names;
|
||||
std::vector<std::vector<float>> values;
|
||||
std::vector<std::vector<float>> activations;
|
||||
std::vector<std::vector<float>> statistics;
|
||||
std::vector<std::string> stats_schema;
|
||||
};
|
||||
|
||||
// stats schema
|
||||
static const std::vector<std::string> default_stats_schema = {
|
||||
"sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance"
|
||||
};
|
||||
|
||||
static std::vector<float> make_stats(std::mt19937 & gen, const int64_t n_per_row) {
|
||||
std::uniform_real_distribution<float> u(0.0f, 1.0f);
|
||||
return {
|
||||
100.0f + 100.0f * u(gen), // sum_sq
|
||||
0.01f * (u(gen) - 0.5f), // mean
|
||||
(float) n_per_row, // elements
|
||||
1.0f + u(gen), // std_deviation
|
||||
u(gen) - 0.5f, // skewness
|
||||
3.0f * u(gen), // kurtosis
|
||||
1.0f + u(gen), // gain
|
||||
80.0f + 20.0f * u(gen), // h_norm
|
||||
10.0f * u(gen), // l2_dist
|
||||
0.5f + 0.5f * u(gen), // cossim
|
||||
0.5f + 0.5f * u(gen), // pearson
|
||||
u(gen), // covariance
|
||||
};
|
||||
}
|
||||
|
||||
static imatrix_data make_imatrix(const std::string & fname_model, const uint32_t seed) {
|
||||
imatrix_data im;
|
||||
|
||||
ggml_context * ctx_meta = nullptr;
|
||||
const gguf_init_params params = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta };
|
||||
gguf_context_ptr ctx(gguf_init_from_file(fname_model.c_str(), params));
|
||||
ggml_context_ptr meta(ctx_meta);
|
||||
if (!ctx) { return im; }
|
||||
|
||||
std::mt19937 gen(seed);
|
||||
std::uniform_real_distribution<float> u(0.0f, 1.0f);
|
||||
for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) {
|
||||
const char * name = gguf_get_tensor_name(ctx.get(), i);
|
||||
const ggml_tensor * tensor = ggml_get_tensor(meta.get(), name);
|
||||
if (ggml_n_dims(tensor) < 2 || strcmp(name, "token_embd.weight") == 0) { continue; }
|
||||
|
||||
const int64_t n_per_row = tensor->ne[0];
|
||||
std::vector<float> values(n_per_row);
|
||||
std::vector<float> activations(n_per_row);
|
||||
for (int64_t j = 0; j < n_per_row; j++) {
|
||||
activations[j] = u(gen) - 0.5f;
|
||||
values[j] = activations[j] * activations[j] + std::exp(2.0f * u(gen) - 1.0f);
|
||||
}
|
||||
|
||||
im.names.push_back(name);
|
||||
im.values.push_back(std::move(values));
|
||||
im.activations.push_back(std::move(activations));
|
||||
im.statistics.push_back(make_stats(gen, n_per_row));
|
||||
}
|
||||
|
||||
im.stats_schema = default_stats_schema;
|
||||
|
||||
return im;
|
||||
}
|
||||
|
||||
static std::vector<llama_model_imatrix_data> imatrix_list(const imatrix_data & im, const std::vector<std::vector<float>> & data) {
|
||||
std::vector<llama_model_imatrix_data> list;
|
||||
for (size_t i = 0; i < im.names.size(); i++) {
|
||||
if (data[i].empty()) { continue; }
|
||||
list.push_back({ im.names[i].c_str(), data[i].data(), data[i].size() });
|
||||
}
|
||||
|
||||
list.push_back({ nullptr, nullptr, 0 });
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
struct quant_run {
|
||||
uint32_t rc = 1; // 0 when quantization succeeds and output is processed
|
||||
std::string log;
|
||||
std::map<std::string, ggml_type> types;
|
||||
size_t n_bytes = 0; // tensor data
|
||||
size_t n_elements = 0;
|
||||
size_t file_size = 0;
|
||||
};
|
||||
|
||||
static void log_callback(ggml_log_level /*level*/, const char * text, void * user_data) {
|
||||
if (user_data) { static_cast<std::string *>(user_data)->append(text); }
|
||||
if (verbose) { fputs(text, stderr); }
|
||||
}
|
||||
|
||||
static quant_run quantize(const std::string & fname_inp, const std::string & fname_out, const imatrix_data & im, llama_model_quantize_params params) {
|
||||
const auto values = imatrix_list(im, im.values);
|
||||
const auto activations = imatrix_list(im, im.activations);
|
||||
const auto statistics = imatrix_list(im, im.statistics);
|
||||
std::vector<const char *> stats_schema;
|
||||
for (const auto & name : im.stats_schema) { stats_schema.push_back(name.c_str()); }
|
||||
stats_schema.push_back(nullptr);
|
||||
params.imatrix = values.data();
|
||||
params.activations = activations.data();
|
||||
params.statistics = statistics.data();
|
||||
params.stats_schema = im.stats_schema.empty() ? nullptr : stats_schema.data();
|
||||
|
||||
quant_run run;
|
||||
// clear previous run's output
|
||||
std::filesystem::remove(fname_out);
|
||||
llama_log_set(log_callback, &run.log);
|
||||
run.rc = llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms);
|
||||
llama_log_set(log_callback, nullptr);
|
||||
if (run.rc != 0) { return run; }
|
||||
|
||||
ggml_context * ctx_meta = nullptr;
|
||||
const gguf_init_params gparams = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta };
|
||||
gguf_context_ptr ctx(gguf_init_from_file(fname_out.c_str(), gparams));
|
||||
ggml_context_ptr meta(ctx_meta);
|
||||
if (!ctx) {
|
||||
run.rc = 1;
|
||||
return run;
|
||||
}
|
||||
|
||||
for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) {
|
||||
const char * name = gguf_get_tensor_name(ctx.get(), i);
|
||||
run.types[name] = gguf_get_tensor_type(ctx.get(), i);
|
||||
run.n_bytes += gguf_get_tensor_size(ctx.get(), i);
|
||||
run.n_elements += ggml_nelements(ggml_get_tensor(meta.get(), name));
|
||||
}
|
||||
|
||||
run.file_size = std::filesystem::file_size(fname_out);
|
||||
|
||||
return run;
|
||||
}
|
||||
|
||||
static size_t count_matches(const std::string & log, const std::string & text) {
|
||||
size_t n = 0;
|
||||
for (size_t pos = log.find(text); pos != std::string::npos; pos = log.find(text, pos + text.size())) { n++; }
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
static size_t logged_number(const std::string & log, const std::string & text) {
|
||||
const size_t pos = log.find(text);
|
||||
return pos == std::string::npos ? SIZE_MAX : (size_t) std::strtoull(log.c_str() + pos + text.size(), nullptr, 10);
|
||||
}
|
||||
|
||||
static size_t count_type(const quant_run & run, const ggml_type type) {
|
||||
size_t n = 0;
|
||||
for (const auto & it : run.types) { n += it.second == type; }
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
static size_t count_type_changes(const quant_run & a, const quant_run & b) {
|
||||
size_t n = 0;
|
||||
for (const auto & it : a.types) {
|
||||
const auto other = b.types.find(it.first);
|
||||
n += other == b.types.end() || other->second != it.second;
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
// the type name of a tensor in a run's output, or "none" if the output has no such tensor
|
||||
static std::string type_name_of(const quant_run & run, const std::string & name) {
|
||||
const auto it = run.types.find(name);
|
||||
return it == run.types.end() ? "none" : ggml_type_name(it->second);
|
||||
}
|
||||
|
||||
// tensor quantization mix rows
|
||||
static std::vector<std::string> mix_rows(const quant_run & run) {
|
||||
std::vector<std::string> rows;
|
||||
for (size_t pos = run.log.find("\terror: "); pos != std::string::npos; pos = run.log.find("\terror: ", pos + 1)) {
|
||||
const size_t start = run.log.rfind('\n', pos) + 1;
|
||||
rows.push_back(run.log.substr(start, run.log.find('\n', pos) - start));
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
static size_t count_row_changes(const quant_run & a, const quant_run & b) {
|
||||
const std::vector<std::string> rows_a = mix_rows(a);
|
||||
const std::vector<std::string> rows_b = mix_rows(b);
|
||||
if (rows_a.empty() || rows_a.size() != rows_b.size()) { return SIZE_MAX; }
|
||||
|
||||
size_t n = 0;
|
||||
for (size_t i = 0; i < rows_a.size(); i++) { n += rows_a[i] != rows_b[i]; }
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
static std::string read_file(const std::string & fname) {
|
||||
std::ifstream file(fname, std::ios::binary);
|
||||
return std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
|
||||
}
|
||||
|
||||
static void write_file(const std::string & fname, const std::string & data) {
|
||||
std::ofstream file(fname, std::ios::binary);
|
||||
file << data;
|
||||
}
|
||||
|
||||
static const size_t state_header_size = 24; // magic, model id, tensor count
|
||||
static const size_t state_entry_size = 28; // candidate count, choice, min and max bpw, elements
|
||||
static const size_t state_candidate_size = 24; // type, bpw, bytes, error
|
||||
|
||||
// offset of the first tensor's candidate count; 0 if the checkpoint holds no candidate
|
||||
static size_t first_count_offset(const std::string & state) {
|
||||
uint32_t len = 0;
|
||||
if (state.size() < state_header_size + sizeof(len)) { return 0; }
|
||||
memcpy(&len, state.data() + state_header_size, sizeof(len));
|
||||
const size_t offset = state_header_size + sizeof(len) + len;
|
||||
|
||||
return state.size() >= offset + state_entry_size + state_candidate_size ? offset : 0;
|
||||
}
|
||||
|
||||
struct fixture {
|
||||
std::string fname_model;
|
||||
std::string fname_out;
|
||||
std::string fname_state;
|
||||
imatrix_data im;
|
||||
quant_run base;
|
||||
};
|
||||
|
||||
// first run parameters
|
||||
static llama_model_quantize_params base_params(const fixture & f) {
|
||||
llama_model_quantize_params params = llama_model_quantize_default_params();
|
||||
params.nthread = 4;
|
||||
params.target_bpw = target_bpw;
|
||||
params.state_file = f.fname_state.c_str();
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
static std::string sibling_path(const fixture & f, const std::string & name) {
|
||||
return (std::filesystem::path(f.fname_state).parent_path() / name).string();
|
||||
}
|
||||
|
||||
static void test_target_bpw(testing & t, const fixture & f) {
|
||||
const double bpw = 8.0 * f.base.n_bytes / f.base.n_elements;
|
||||
t.log("final bpw " + std::to_string(bpw));
|
||||
t.assert_true("bpw does not exceed the target", bpw <= target_bpw);
|
||||
t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05);
|
||||
}
|
||||
|
||||
static void test_state_checkpoint(testing & t, const fixture & f) {
|
||||
const size_t n_scored = count_matches(f.base.log, "processing tensor");
|
||||
const std::string n_tensors = std::to_string(n_scored) + " tensors";
|
||||
t.assert_true("first run scores tensors", n_scored > 0);
|
||||
t.assert_equal("first run saves the checkpoint", (size_t) 1, count_matches(f.base.log, "saved target progress for " + n_tensors + " to " + f.fname_state));
|
||||
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, base_params(f));
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("second run loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)"));
|
||||
t.assert_equal("second run scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor"));
|
||||
t.assert_equal("tensors whose type changed", (size_t) 0, count_type_changes(f.base, run));
|
||||
}
|
||||
|
||||
static void test_target_size(testing & t, const fixture & f) {
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.target_bpw = -1.0f;
|
||||
params.target_size = (int64_t) f.base.file_size * 9 / 10;
|
||||
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
|
||||
const int64_t diff = (int64_t) run.file_size - params.target_size;
|
||||
t.log("file size " + std::to_string(run.file_size) + ", " + std::to_string(diff) + " bytes from the target");
|
||||
t.assert_true("the file is within 8 KiB of the target", std::abs(diff) <= 8 * 1024);
|
||||
}
|
||||
|
||||
static void test_excluded_type(testing & t, const fixture & f) {
|
||||
ggml_type excluded = GGML_TYPE_COUNT;
|
||||
for (const auto & it : f.base.types) {
|
||||
if (it.second != GGML_TYPE_F32 && (excluded == GGML_TYPE_COUNT || count_type(f.base, it.second) > count_type(f.base, excluded))) {
|
||||
excluded = it.second;
|
||||
}
|
||||
}
|
||||
|
||||
t.assert_true("first run selects a type", excluded != GGML_TYPE_COUNT);
|
||||
if (excluded == GGML_TYPE_COUNT) { return; }
|
||||
t.log(std::string("excluding ") + ggml_type_name(excluded) + ", the type of " + std::to_string(count_type(f.base, excluded)) + " tensors");
|
||||
|
||||
const ggml_type exclude[] = { excluded, GGML_TYPE_COUNT };
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.target_exclude = exclude;
|
||||
|
||||
params.state_file = nullptr;
|
||||
const quant_run scored = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, scored.rc);
|
||||
t.assert_equal("scored with excluded types, tensors of the excluded type", (size_t) 0, count_type(scored, excluded));
|
||||
|
||||
params.state_file = f.fname_state.c_str();
|
||||
const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors";
|
||||
const quant_run loaded = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, loaded.rc);
|
||||
t.assert_equal("run loads the checkpoint", (size_t) 1, count_matches(loaded.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)"));
|
||||
t.assert_equal("run scores no tensor", (size_t) 0, count_matches(loaded.log, "processing tensor"));
|
||||
t.assert_equal("loaded from checkpoint, tensors of the excluded type", (size_t) 0, count_type(loaded, excluded));
|
||||
t.assert_equal("run warns that the checkpoint is not saved", (size_t) 1, count_matches(loaded.log, "state checkpoint cannot be saved while --target-exclude is active"));
|
||||
t.assert_equal("checkpoint is not saved while types are excluded", (size_t) 0, count_matches(loaded.log, "saved target progress"));
|
||||
}
|
||||
|
||||
static void test_unknown_type(testing & t, const fixture & f) {
|
||||
std::string state = read_file(f.fname_state);
|
||||
const size_t offset = first_count_offset(state);
|
||||
t.assert_true("first run's checkpoint holds a candidate", offset > 0);
|
||||
if (offset == 0) { return; }
|
||||
|
||||
// type 4 was Q4_2; within ggml_type range but invalid
|
||||
const int32_t type = 4;
|
||||
memcpy(&state[offset + state_entry_size], &type, sizeof(type));
|
||||
const std::string fname = sibling_path(f, "unknown.bpw_state");
|
||||
write_file(fname, state);
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("unknown type is reported", (size_t) 1, count_matches(run.log, "candidate type is not in the selection pool, ignoring state file"));
|
||||
t.assert_equal("unknown checkpoint is not loaded", (size_t) 0, count_matches(run.log, "using " + fname));
|
||||
t.assert_equal("unknown checkpoint is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
|
||||
t.assert_equal("scored again, tensors whose type changed", (size_t) 0, count_type_changes(f.base, run));
|
||||
}
|
||||
|
||||
static void test_zero_candidates(testing & t, const fixture & f) {
|
||||
std::string state = read_file(f.fname_state);
|
||||
const size_t offset = first_count_offset(state);
|
||||
t.assert_true("the first run's checkpoint holds a candidate", offset > 0);
|
||||
if (offset == 0) { return; }
|
||||
|
||||
// drop the first tensor's candidates
|
||||
uint64_t n = 0;
|
||||
memcpy(&n, &state[offset], sizeof(n));
|
||||
state.erase(offset + state_entry_size, n * state_candidate_size);
|
||||
n = 0;
|
||||
memcpy(&state[offset], &n, sizeof(n));
|
||||
const std::string fname = sibling_path(f, "zero.bpw_state");
|
||||
write_file(fname, state);
|
||||
|
||||
// with a type excluded, an empty candidate list that is loaded fails the call instead of crashing the test
|
||||
const ggml_type exclude[] = { GGML_TYPE_IQ1_S, GGML_TYPE_COUNT };
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
params.target_exclude = exclude;
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("empty candidate list is reported", (size_t) 1, count_matches(run.log, "candidate count out of range, ignoring state file"));
|
||||
t.assert_equal("checkpoint with an empty candidate list is not loaded", (size_t) 0, count_matches(run.log, "using " + fname));
|
||||
t.assert_equal("checkpoint with an empty candidate list is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
|
||||
}
|
||||
|
||||
static void test_truncated(testing & t, const fixture & f) {
|
||||
const std::string state = read_file(f.fname_state);
|
||||
const size_t offset = first_count_offset(state);
|
||||
t.assert_true("first run's checkpoint has a candidate", offset > 0);
|
||||
if (offset == 0) { return; }
|
||||
|
||||
// cut before the first candidate count, then before the first candidate type
|
||||
const std::string fname = sibling_path(f, "truncated.bpw_state");
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
write_file(fname, state.substr(0, offset));
|
||||
const quant_run at_count = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
write_file(fname, state.substr(0, offset + state_entry_size));
|
||||
const quant_run at_type = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, at_count.rc);
|
||||
t.assert_equal("checkpoint cut before a candidate count is reported as truncated", (size_t) 1, count_matches(at_count.log, "state file truncated or read error, ignoring"));
|
||||
t.assert_equal("quantize succeeds", 0u, at_type.rc);
|
||||
t.assert_equal("checkpoint cut before a candidate type is reported as truncated", (size_t) 1, count_matches(at_type.log, "state file truncated or read error, ignoring"));
|
||||
}
|
||||
|
||||
static void test_missing_dir(testing & t, const fixture & f) {
|
||||
const std::string dir = sibling_path(f, "no-such-dir");
|
||||
const std::string fname = (std::filesystem::path(dir) / "model.bpw_state").string();
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("path in missing directory fails", 1u, run.rc);
|
||||
t.assert_equal("path in missing directory is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
|
||||
t.assert_equal("path in missing directory stops execution before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
|
||||
t.assert_true("missing directory is not created", !std::filesystem::exists(dir));
|
||||
}
|
||||
|
||||
static void test_unreadable_file(testing & t, const fixture & f) {
|
||||
#ifdef _WIN32
|
||||
GGML_UNUSED(f);
|
||||
t.skip("POSIX permissions only");
|
||||
#else
|
||||
namespace fs = std::filesystem;
|
||||
std::error_code ec;
|
||||
const std::string fname = sibling_path(f, "locked.bpw_state");
|
||||
write_file(fname, "forbidden");
|
||||
// write-only, so that a probe that opens the file for writing could still damage it
|
||||
fs::permissions(fname, fs::perms::owner_write, ec);
|
||||
if (std::ifstream(fname).good()) {
|
||||
fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec);
|
||||
t.skip("the file can still be read, as by root");
|
||||
return;
|
||||
}
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
const bool kept_perms = fs::status(fname, ec).permissions() == fs::perms::owner_write;
|
||||
fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec);
|
||||
t.assert_equal("an unreadable file fails the call", 1u, run.rc);
|
||||
t.assert_equal("an unreadable file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
|
||||
t.assert_equal("an unreadable file stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
|
||||
t.assert_true("an unreadable file keeps its permissions", kept_perms);
|
||||
t.assert_true("an unreadable file keeps its content", read_file(fname) == "forbidden");
|
||||
#endif
|
||||
}
|
||||
|
||||
static void test_directory_path(testing & t, const fixture & f) {
|
||||
const std::string fname = sibling_path(f, "dir.bpw_state");
|
||||
std::filesystem::create_directory(fname);
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("a directory instead of a file fails the call", 1u, run.rc);
|
||||
t.assert_equal("a directory instead of a file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": "));
|
||||
t.assert_equal("a directory stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor"));
|
||||
t.assert_true("the directory is left as it was", std::filesystem::is_directory(fname) && std::filesystem::is_empty(fname));
|
||||
}
|
||||
|
||||
static void test_save_error(testing & t, const fixture & f) {
|
||||
const std::string fname = sibling_path(f, "unsaved.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
std::filesystem::create_directory(fname + ".tmp");
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("a failed save is reported", (size_t) 1, count_matches(run.log, "failed to save progress to " + fname + ".tmp (open error)"));
|
||||
t.assert_equal("a failed save logs no saved checkpoint", (size_t) 0, count_matches(run.log, "saved target progress"));
|
||||
}
|
||||
|
||||
static void test_imatrix_swap(testing & t, const fixture & f) {
|
||||
const imatrix_data im = make_imatrix(f.fname_model, 4321);
|
||||
const std::string fname = sibling_path(f, "swap.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = nullptr;
|
||||
const quant_run fresh = quantize(f.fname_model, f.fname_out, im, params);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run reused = quantize(f.fname_model, f.fname_out, im, params);
|
||||
t.log(std::to_string(count_type_changes(f.base, fresh)) + " tensors change type with the other imatrix");
|
||||
t.assert_equal("quantize succeeds", 0u, fresh.rc);
|
||||
t.assert_equal("quantize succeeds", 0u, reused.rc);
|
||||
t.assert_equal("a checkpoint from another imatrix is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
|
||||
t.assert_equal("a checkpoint from another imatrix is scored again", count_matches(f.base.log, "processing tensor"), count_matches(reused.log, "processing tensor"));
|
||||
t.assert_equal("scored again with another imatrix, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused));
|
||||
}
|
||||
|
||||
static void test_imatrix_parts(testing & t, const fixture & f) {
|
||||
// one float doubled in one list at a time
|
||||
auto check = [&](const std::string & part, const imatrix_data & im) {
|
||||
const std::string fname = sibling_path(f, part + ".bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("a checkpoint from other " + part + " is reported", (size_t) 1, count_matches(run.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
|
||||
t.assert_equal("a checkpoint from other " + part + " is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor"));
|
||||
};
|
||||
|
||||
imatrix_data im = f.im;
|
||||
im.values[0][0] *= 2.0f;
|
||||
check("values", im);
|
||||
|
||||
im = f.im;
|
||||
im.activations[0][0] *= 2.0f;
|
||||
check("activations", im);
|
||||
|
||||
im = f.im;
|
||||
im.statistics[0][0] *= 2.0f;
|
||||
check("statistics", im);
|
||||
}
|
||||
|
||||
static void test_imatrix_order(testing & t, const fixture & f) {
|
||||
// the same imatrix data, passed in reverse order
|
||||
imatrix_data im = f.im;
|
||||
std::reverse(im.names.begin(), im.names.end());
|
||||
std::reverse(im.values.begin(), im.values.end());
|
||||
std::reverse(im.activations.begin(), im.activations.end());
|
||||
std::reverse(im.statistics.begin(), im.statistics.end());
|
||||
const std::string fname = sibling_path(f, "reversed.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors";
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("the same imatrix in another order loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + fname + " (data for " + n_tensors + " loaded)"));
|
||||
t.assert_equal("the same imatrix in another order scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor"));
|
||||
}
|
||||
|
||||
static void test_pruned_layer(testing & t, const fixture & f) {
|
||||
// pruning a block renumbers the ones after it
|
||||
const int32_t prune[] = { 1, -1 };
|
||||
const std::string fname = sibling_path(f, "pruned.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.prune_layers = prune;
|
||||
params.state_file = nullptr;
|
||||
const quant_run fresh = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run reused = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, fresh.rc);
|
||||
t.assert_equal("quantize succeeds", 0u, reused.rc);
|
||||
t.assert_equal("a checkpoint without pruning is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
|
||||
t.assert_equal("a checkpoint without pruning is scored again", count_matches(fresh.log, "processing tensor"), count_matches(reused.log, "processing tensor"));
|
||||
t.assert_equal("scored again with a pruned block, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused));
|
||||
|
||||
// another block pruned, reusing the checkpoint saved for block 1
|
||||
const int32_t prune_other[] = { 2, -1 };
|
||||
params.prune_layers = prune_other;
|
||||
const quant_run other = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
t.assert_equal("the pruned run saves its checkpoint", (size_t) 1, count_matches(reused.log, "saved target progress"));
|
||||
t.assert_equal("quantize succeeds", 0u, other.rc);
|
||||
t.assert_equal("a checkpoint for another pruned block is reported", (size_t) 1, count_matches(other.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
|
||||
t.assert_equal("a checkpoint for another pruned block is scored again", count_matches(fresh.log, "processing tensor"), count_matches(other.log, "processing tensor"));
|
||||
}
|
||||
|
||||
static void test_stats_order(testing & t, const fixture & f) {
|
||||
// stats in reverse order
|
||||
imatrix_data im = f.im;
|
||||
std::reverse(im.stats_schema.begin(), im.stats_schema.end());
|
||||
for (auto & stats : im.statistics) { std::reverse(stats.begin(), stats.end()); }
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = nullptr;
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, im, params);
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_equal("statistics in different order", (size_t) 0, count_matches(run.log, "skipping CNIF"));
|
||||
t.assert_equal("statistics in different order, rows that changed", (size_t) 0, count_row_changes(f.base, run));
|
||||
}
|
||||
|
||||
static void test_stats_missing(testing & t, const fixture & f) {
|
||||
// tensor whose stats vector is cut short or left out
|
||||
const size_t k = std::find(f.im.names.begin(), f.im.names.end(), "blk.1.ffn_down.weight") - f.im.names.begin();
|
||||
t.assert_true("imatrix has blk.1.ffn_down.weight", k < f.im.names.size());
|
||||
if (k == f.im.names.size()) { return; }
|
||||
|
||||
// pearson under another name
|
||||
imatrix_data renamed = f.im;
|
||||
std::replace(renamed.stats_schema.begin(), renamed.stats_schema.end(), std::string("pearson"), std::string("spearman"));
|
||||
const std::string fname = sibling_path(f, "renamed.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
const quant_run missing = quantize(f.fname_model, f.fname_out, renamed, params);
|
||||
|
||||
// no names
|
||||
imatrix_data unnamed = f.im;
|
||||
unnamed.stats_schema.clear();
|
||||
params.state_file = nullptr;
|
||||
const quant_run no_names = quantize(f.fname_model, f.fname_out, unnamed, params);
|
||||
|
||||
// stats vector cut before pearson
|
||||
imatrix_data cut = f.im;
|
||||
cut.statistics[k].resize(10);
|
||||
const quant_run short_stats = quantize(f.fname_model, f.fname_out, cut, params);
|
||||
imatrix_data dropped = f.im;
|
||||
dropped.statistics[k].clear();
|
||||
const quant_run no_stats = quantize(f.fname_model, f.fname_out, dropped, params);
|
||||
|
||||
const size_t n_changed = count_row_changes(f.base, missing);
|
||||
t.log(std::to_string(n_changed) + " mix rows change without CNIF");
|
||||
t.assert_equal("quantize succeeds", 0u, missing.rc);
|
||||
t.assert_true("missing metric changes the mix", n_changed > 0 && n_changed != SIZE_MAX);
|
||||
t.assert_equal("missing metric is reported", (size_t) 1, count_matches(missing.log, "statistics have no pearson metric, skipping CNIF"));
|
||||
t.assert_equal("checkpoint with different statistics names is reported", (size_t) 1, count_matches(missing.log, "state file does not match this model, imatrix or pruned layers, ignoring"));
|
||||
t.assert_equal("checkpoint with different statistics names is scored again", count_matches(f.base.log, "processing tensor"), count_matches(missing.log, "processing tensor"));
|
||||
t.assert_equal("quantize succeeds", 0u, no_names.rc);
|
||||
t.assert_equal("statistics without names are reported", (size_t) 1, count_matches(no_names.log, "statistics have no sum_sq metric, skipping CNIF"));
|
||||
t.assert_equal("statistics without names log one line", (size_t) 1, count_matches(no_names.log, "skipping CNIF"));
|
||||
t.assert_equal("statistics without names, rows that differ from a missing metric", (size_t) 0, count_row_changes(missing, no_names));
|
||||
t.assert_equal("quantize succeeds", 0u, short_stats.rc);
|
||||
t.assert_equal("a short stats vector is not reported as a missing metric", (size_t) 0, count_matches(short_stats.log, "skipping CNIF"));
|
||||
t.assert_equal("quantize succeeds", 0u, no_stats.rc);
|
||||
t.assert_equal("a short stats vector, rows that differ from a left-out one", (size_t) 0, count_row_changes(no_stats, short_stats));
|
||||
}
|
||||
|
||||
// counts its calls, and asks to stop at call number stop_at only
|
||||
struct terminate_probe {
|
||||
size_t n_calls = 0;
|
||||
size_t stop_at = 0;
|
||||
};
|
||||
|
||||
static bool terminate_at(void * data) {
|
||||
auto * probe = static_cast<terminate_probe *>(data);
|
||||
return ++probe->n_calls == probe->stop_at;
|
||||
}
|
||||
|
||||
static void test_abort_callback(testing & t, const fixture & f) {
|
||||
// full scoring no interruptions
|
||||
terminate_probe counter;
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = nullptr;
|
||||
params.abort_callback = terminate_at;
|
||||
params.abort_callback_data = &counter;
|
||||
const quant_run counted = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
// interrupt at half the calls
|
||||
terminate_probe stopper;
|
||||
stopper.stop_at = counter.n_calls / 2;
|
||||
const std::string fname = sibling_path(f, "interrupted.bpw_state");
|
||||
params.state_file = fname.c_str();
|
||||
params.abort_callback_data = &stopper;
|
||||
const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
const bool stopped_wrote = std::filesystem::exists(f.fname_out);
|
||||
params.abort_callback = nullptr;
|
||||
const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
const size_t n_total = count_matches(f.base.log, "processing tensor");
|
||||
const size_t n_saved = logged_number(stopped.log, "interrupted, saving progress for ");
|
||||
t.log(std::to_string(n_saved) + " of " + std::to_string(n_total) + " tensors scored before the stop at call " + std::to_string(stopper.stop_at) + " of " + std::to_string(counter.n_calls));
|
||||
t.assert_equal("quantize succeeds", 0u, counted.rc);
|
||||
t.assert_equal("a callback that never asks to stop, mix rows that changed", (size_t) 0, count_row_changes(f.base, counted));
|
||||
t.assert_equal("the interrupted call fails", 1u, stopped.rc);
|
||||
t.assert_equal("the stop is reported", (size_t) 1, count_matches(stopped.log, "failed to quantize: interrupted"));
|
||||
t.assert_true("the stop comes part way through the scoring", n_saved > 0 && n_saved < n_total);
|
||||
t.assert_equal("the stopped run saves what it scored", (size_t) 1, count_matches(stopped.log, "saved target progress for " + std::to_string(n_saved) + " tensors to " + fname));
|
||||
t.assert_true("the stopped run writes no output", !stopped_wrote);
|
||||
t.assert_equal("quantize succeeds", 0u, resumed.rc);
|
||||
t.assert_equal("the resumed run loads the saved tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_saved) + " tensors loaded)"));
|
||||
t.assert_equal("the resumed run scores the rest", n_total - n_saved, count_matches(resumed.log, "processing tensor"));
|
||||
t.assert_equal("resumed, mix rows that differ from the first run", (size_t) 0, count_row_changes(f.base, resumed));
|
||||
|
||||
// without a target, the main loop calls it once per tensor
|
||||
terminate_probe loop_stopper;
|
||||
loop_stopper.stop_at = 2;
|
||||
llama_model_quantize_params plain = llama_model_quantize_default_params();
|
||||
plain.nthread = 4;
|
||||
plain.abort_callback = terminate_at;
|
||||
plain.abort_callback_data = &loop_stopper;
|
||||
const quant_run main_loop = quantize(f.fname_model, f.fname_out, f.im, plain);
|
||||
t.assert_equal("a stop in the main loop fails the call", 1u, main_loop.rc);
|
||||
t.assert_equal("a stop in the main loop is reported", (size_t) 1, count_matches(main_loop.log, "failed to quantize: interrupted"));
|
||||
t.assert_equal("the main loop stops at the call that asks", (size_t) 2, loop_stopper.n_calls);
|
||||
}
|
||||
|
||||
static void test_interrupt_first_call(testing & t, const fixture & f) {
|
||||
// a copy of the checkpoint, stopped at the first call, before the workers read it back
|
||||
const size_t n_total = count_matches(f.base.log, "processing tensor");
|
||||
const std::string fname = sibling_path(f, "first-call.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
terminate_probe stopper;
|
||||
stopper.stop_at = 1;
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
params.abort_callback = terminate_at;
|
||||
params.abort_callback_data = &stopper;
|
||||
const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
params.abort_callback = nullptr;
|
||||
const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
t.assert_equal("the stopped call fails", 1u, stopped.rc);
|
||||
t.assert_equal("the checkpoint keeps its tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_total) + " tensors loaded)"));
|
||||
t.assert_equal("the next run scores nothing", (size_t) 0, count_matches(resumed.log, "processing tensor"));
|
||||
}
|
||||
|
||||
#ifndef _WIN32
|
||||
static void app_signal_handler(int, siginfo_t *, void *) {}
|
||||
|
||||
// true when both have the same handler, flags and mask
|
||||
static bool same_action(const struct sigaction & a, const struct sigaction & b) {
|
||||
if (a.sa_flags != b.sa_flags) { return false; }
|
||||
if ((a.sa_flags & SA_SIGINFO) ? a.sa_sigaction != b.sa_sigaction : a.sa_handler != b.sa_handler) { return false; }
|
||||
for (int sig = 1; sig < NSIG; sig++) {
|
||||
if (sigismember(&a.sa_mask, sig) != sigismember(&b.sa_mask, sig)) { return false; }
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// read SIGINT and SIGTERM disposition
|
||||
struct disposition_probe {
|
||||
size_t n_calls = 0;
|
||||
struct sigaction during[2];
|
||||
};
|
||||
|
||||
static bool probe_dispositions(void * data) {
|
||||
auto * probe = static_cast<disposition_probe *>(data);
|
||||
if (probe->n_calls++ == 0) {
|
||||
sigaction(SIGINT, nullptr, &probe->during[0]);
|
||||
sigaction(SIGTERM, nullptr, &probe->during[1]);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
static void test_signal_handlers(testing & t, const fixture & f) {
|
||||
#ifdef _WIN32
|
||||
GGML_UNUSED(f);
|
||||
t.skip("POSIX signals only");
|
||||
#else
|
||||
struct sigaction app = {};
|
||||
app.sa_sigaction = app_signal_handler;
|
||||
app.sa_flags = SA_SIGINFO;
|
||||
sigemptyset(&app.sa_mask);
|
||||
sigaddset(&app.sa_mask, SIGTERM);
|
||||
|
||||
const int signals[] = { SIGINT, SIGTERM };
|
||||
struct sigaction prev[2], before[2], after[2];
|
||||
for (int i = 0; i < 2; i++) {
|
||||
sigaction(signals[i], &app, &prev[i]);
|
||||
sigaction(signals[i], nullptr, &before[i]);
|
||||
}
|
||||
|
||||
// checkpoint exists, should not score
|
||||
const std::string fname = sibling_path(f, "signals.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
disposition_probe probe = {};
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
params.abort_callback = probe_dispositions;
|
||||
params.abort_callback_data = &probe;
|
||||
const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
sigaction(signals[i], nullptr, &after[i]);
|
||||
sigaction(signals[i], &prev[i], nullptr);
|
||||
}
|
||||
t.assert_equal("quantize succeeds", 0u, run.rc);
|
||||
t.assert_true("the callback is called", probe.n_calls > 0);
|
||||
t.assert_true("SIGINT keeps its handler, flags and mask during a call", same_action(before[0], probe.during[0]));
|
||||
t.assert_true("SIGTERM keeps its handler, flags and mask during a call", same_action(before[1], probe.during[1]));
|
||||
t.assert_true("SIGINT keeps its handler, flags and mask after a call", same_action(before[0], after[0]));
|
||||
t.assert_true("SIGTERM keeps its handler, flags and mask after a call", same_action(before[1], after[1]));
|
||||
#endif
|
||||
}
|
||||
|
||||
static void test_type_flags(testing & t, const fixture & f) {
|
||||
t.assert_true("without the flags, neither tensor has its flag's type", type_name_of(f.base, "token_embd.weight") != "q8_0" && type_name_of(f.base, "output.weight") != "q6_K");
|
||||
|
||||
// a copy of the checkpoint, so that nothing is scored
|
||||
const std::string fname = sibling_path(f, "flags.bpw_state");
|
||||
write_file(fname, read_file(f.fname_state));
|
||||
llama_model_quantize_params params = base_params(f);
|
||||
params.state_file = fname.c_str();
|
||||
params.token_embedding_type = GGML_TYPE_Q8_0;
|
||||
params.output_tensor_type = GGML_TYPE_Q6_K;
|
||||
const quant_run flags = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
// the same two tensors pinned through --tensor-type
|
||||
const llama_model_tensor_override same[] = {
|
||||
{ "^token_embd\\.weight$", GGML_TYPE_Q8_0 }, { "^output\\.weight$", GGML_TYPE_Q6_K }, { nullptr, GGML_TYPE_COUNT },
|
||||
};
|
||||
llama_model_quantize_params patterns = base_params(f);
|
||||
patterns.state_file = fname.c_str();
|
||||
patterns.tt_overrides = same;
|
||||
const quant_run by_pattern = quantize(f.fname_model, f.fname_out, f.im, patterns);
|
||||
|
||||
// --tensor-type names both tensors too, at another type
|
||||
const llama_model_tensor_override other[] = {
|
||||
{ "^token_embd\\.weight$", GGML_TYPE_Q5_0 }, { "^output\\.weight$", GGML_TYPE_Q5_0 }, { nullptr, GGML_TYPE_COUNT },
|
||||
};
|
||||
params.tt_overrides = other;
|
||||
const quant_run named = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
// the flags' types barred
|
||||
constexpr ggml_type exclude[] = { GGML_TYPE_Q8_0, GGML_TYPE_Q6_K, GGML_TYPE_COUNT };
|
||||
params.tt_overrides = nullptr;
|
||||
params.target_exclude = exclude;
|
||||
const quant_run barred = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
// only --output-tensor-type: the model is not tied, so the token embedding is not pinned
|
||||
params.token_embedding_type = GGML_TYPE_COUNT;
|
||||
params.target_exclude = nullptr;
|
||||
const quant_run output_only = quantize(f.fname_model, f.fname_out, f.im, params);
|
||||
|
||||
const double bpw = 8.0 * flags.n_bytes / flags.n_elements;
|
||||
t.log("realised bpw with the flags " + std::to_string(bpw));
|
||||
t.assert_equal("quantize succeeds", 0u, flags.rc);
|
||||
t.assert_equal("--token-embedding-type sets the token embedding", std::string("q8_0"), type_name_of(flags, "token_embd.weight"));
|
||||
t.assert_equal("--output-tensor-type sets the output", std::string("q6_K"), type_name_of(flags, "output.weight"));
|
||||
t.assert_equal("flags pin two tensors", (size_t) 2, count_matches(flags.log, "(pinned)"));
|
||||
t.assert_true("bpw does not exceed the target", bpw <= target_bpw);
|
||||
t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05);
|
||||
t.assert_equal("quantize succeeds", 0u, by_pattern.rc);
|
||||
t.assert_equal("flags and same --tensor-type pins, mix rows that differ", (size_t) 0, count_row_changes(by_pattern, flags));
|
||||
t.assert_equal("quantize succeeds", 0u, named.rc);
|
||||
t.assert_equal("--token-embedding-type beats --tensor-type", std::string("q8_0"), type_name_of(named, "token_embd.weight"));
|
||||
t.assert_equal("--output-tensor-type beats --tensor-type", std::string("q6_K"), type_name_of(named, "output.weight"));
|
||||
t.assert_equal("quantize succeeds", 0u, barred.rc);
|
||||
t.assert_equal("excluded --token-embedding-type is reported", (size_t) 1, count_matches(barred.log, "--token-embedding-type pins type q8_0 which is ignored by --target-exclude, keeping the pinned type"));
|
||||
t.assert_equal("excluded --output-tensor-type is reported", (size_t) 1, count_matches(barred.log, "--output-tensor-type pins type q6_K which is ignored by --target-exclude, keeping the pinned type"));
|
||||
t.assert_equal("excluded --token-embedding-type keeps its type", std::string("q8_0"), type_name_of(barred, "token_embd.weight"));
|
||||
t.assert_equal("excluded --output-tensor-type keeps its type", std::string("q6_K"), type_name_of(barred, "output.weight"));
|
||||
t.assert_equal("quantize succeeds", 0u, output_only.rc);
|
||||
t.assert_equal("--output-tensor-type alone sets the output", std::string("q6_K"), type_name_of(output_only, "output.weight"));
|
||||
t.assert_equal("--output-tensor-type alone pins one tensor", (size_t) 1, count_matches(output_only.log, "(pinned)"));
|
||||
}
|
||||
|
||||
static int run_tests(testing & t, const std::filesystem::path & dir) {
|
||||
fixture f;
|
||||
f.fname_model = (dir / "model-f32.gguf").string();
|
||||
f.fname_out = (dir / "model-out.gguf").string();
|
||||
f.fname_state = (dir / "model.bpw_state").string();
|
||||
if (!save_model(f.fname_model)) {
|
||||
fprintf(stderr, "failed to create the model\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
f.im = make_imatrix(f.fname_model, 1234);
|
||||
if (f.im.names.empty()) {
|
||||
fprintf(stderr, "failed to read the model\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
f.base = quantize(f.fname_model, f.fname_out, f.im, base_params(f));
|
||||
if (f.base.rc != 0) {
|
||||
fprintf(stderr, "the first quantization failed:\n%s", f.base.log.c_str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
t.test("target_bpw", [&](testing & t) { test_target_bpw(t, f); });
|
||||
t.test("target_size", [&](testing & t) { test_target_size(t, f); });
|
||||
t.test("state_checkpoint", [&](testing & t) { test_state_checkpoint(t, f); });
|
||||
t.test("excluded_type", [&](testing & t) { test_excluded_type(t, f); });
|
||||
t.test("unknown_type", [&](testing & t) { test_unknown_type(t, f); });
|
||||
t.test("zero_candidates", [&](testing & t) { test_zero_candidates(t, f); });
|
||||
t.test("truncated", [&](testing & t) { test_truncated(t, f); });
|
||||
t.test("missing_dir", [&](testing & t) { test_missing_dir(t, f); });
|
||||
t.test("unreadable_file", [&](testing & t) { test_unreadable_file(t, f); });
|
||||
t.test("directory_path", [&](testing & t) { test_directory_path(t, f); });
|
||||
t.test("save_error", [&](testing & t) { test_save_error(t, f); });
|
||||
t.test("imatrix_swap", [&](testing & t) { test_imatrix_swap(t, f); });
|
||||
t.test("imatrix_parts", [&](testing & t) { test_imatrix_parts(t, f); });
|
||||
t.test("imatrix_order", [&](testing & t) { test_imatrix_order(t, f); });
|
||||
t.test("pruned_layer", [&](testing & t) { test_pruned_layer(t, f); });
|
||||
t.test("stats_order", [&](testing & t) { test_stats_order(t, f); });
|
||||
t.test("stats_missing", [&](testing & t) { test_stats_missing(t, f); });
|
||||
t.test("abort_callback", [&](testing & t) { test_abort_callback(t, f); });
|
||||
t.test("interrupt_first_call", [&](testing & t) { test_interrupt_first_call(t, f); });
|
||||
t.test("signal_handlers", [&](testing & t) { test_signal_handlers(t, f); });
|
||||
t.test("type_flags", [&](testing & t) { test_type_flags(t, f); });
|
||||
|
||||
return t.summary();
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv) {
|
||||
testing t;
|
||||
|
||||
const char * env = getenv("LLAMA_TEST_VERBOSE");
|
||||
verbose = env && std::string(env) == "1";
|
||||
t.verbose = verbose;
|
||||
llama_log_set(log_callback, nullptr);
|
||||
|
||||
if (argc > 1) { t.set_filter(argv[1]); }
|
||||
|
||||
llama_backend_init();
|
||||
const std::filesystem::path dir = std::filesystem::temp_directory_path() / ("test-quantize-target-" + std::to_string(std::random_device{}()));
|
||||
std::filesystem::create_directories(dir);
|
||||
const int ret = run_tests(t, dir);
|
||||
std::filesystem::remove_all(dir);
|
||||
llama_backend_free();
|
||||
|
||||
return ret;
|
||||
}
|
||||
+68
-39
@@ -60,11 +60,19 @@ Options:
|
||||
* `--output-tensor-type` use a specific quant type for the output.weight tensor
|
||||
* `--token-embedding-type` use a specific quant type for the token embeddings tensor
|
||||
* `--keep-split` generate the quantized model in the same shards as the input file instead of a single quantized file
|
||||
* `--dry-run` simulate the quantization process
|
||||
* `--max-buffer-size MiB` cap the amount of tensor rows kept in memory while quantizing one tensor (default: 8192). Lower it to quantize models with very large tensors on a machine with little RAM
|
||||
|
||||
Advanced options:
|
||||
* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times.
|
||||
* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times
|
||||
* `--prune-layers` prune (remove) the layers in the list
|
||||
* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times.
|
||||
* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times
|
||||
* `--target-bpw` automatically choose quant types to meet an overall bits per weight (bpw) target
|
||||
* `--target-size` automatically choose quant types to meet a file size target
|
||||
* `--state-file` file name to store or load the bpw/size scores. If left unspecified it defaults to `<model name>-<hash>.bpw_state`; progress is automatically preserved upon interruptions (SIGTERM or Ctrl-C) allowing execution of the same command to resume the process
|
||||
* `--target-exclude` comma-separated list of quant types (names or ordinals) that automatic quant type selection must ignore; for use with `--target-bpw`/`--target-size`. May be specified multiple times. A state checkpoint is not written while this option is active
|
||||
|
||||
When using `--target-bpw` or `--target-size`, any tensors specified by `--tensor-type`, `--token-embedding-type`, or `--output-tensor-type` retain their defined types, with their total size counted toward the overall target. Quantization will fail if the budget allocated to these tensors leaves insufficient capacity for the remainder of the model.
|
||||
|
||||
## (Optional) Convert the multimodal components
|
||||
|
||||
@@ -92,6 +100,16 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf
|
||||
./llama-quantize input-model-f32.gguf q4_k_m 8
|
||||
```
|
||||
|
||||
```bash
|
||||
# simulate naive Q4_K_M quantization process. No model will be generated
|
||||
./llama-quantize --dry-run input-model-f32.gguf q4_k_m 8
|
||||
```
|
||||
|
||||
```bash
|
||||
# naive Q4_K_M quantization overriding general.name and model.rope.freq_base metadata values
|
||||
./llama-quantize --override-kv general.name=str:"New model name" --override-kv model.rope.freq_base=float:1.234e+08 input-model-f32.gguf q4_k_m 8
|
||||
```
|
||||
|
||||
```bash
|
||||
# quantize model enabling re-quantization, leaving the output tensor unquantized and all others quantized at the same level (Q4_K)
|
||||
./llama-quantize --allow-requantize --leave-output-tensor --pure input-model-f32.gguf q4_k_m 8
|
||||
@@ -122,59 +140,69 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf
|
||||
./llama-quantize --imatrix imatrix.gguf --override-kv qwen3moe.expert_used_count=int:16 --prune-layers 20,21,22 input-model-f32.gguf pruned-model-f32.gguf copy 8
|
||||
```
|
||||
|
||||
```bash
|
||||
# quantize model targeting a specific bpw average and save the target computations to the default file. Model type is optional and can be omitted
|
||||
./llama-quantize --target-bpw 4.5678 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
|
||||
```
|
||||
|
||||
```bash
|
||||
# quantize model targeting a specific bpw average using the default state checkpoint (if available) and ignoring IQ2_XXS, IQ2_XS and IQ2_S types (checkpoint is not saved)
|
||||
./llama-quantize --target-bpw 4.5678 --target-exclude IQ2_XXS,IQ2_XS,IQ2_S --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
|
||||
```
|
||||
|
||||
```bash
|
||||
# quantize model targeting a specific bpw average reusing previous target computations in default file (e.g. input-model-8fd7a8bef0803042.bpw_state)
|
||||
./llama-quantize --target-bpw 2.345 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
|
||||
```
|
||||
|
||||
```bash
|
||||
# quantize model targeting a specific file size and save the target computations to a custom file.
|
||||
./llama-quantize --target-size 1.5g --state-file my-state-file.dat --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf
|
||||
```
|
||||
|
||||
## Memory/Disk Requirements
|
||||
|
||||
When running the larger models, make sure you have enough disk space to store all the intermediate files.
|
||||
As the models are currently fully loaded into memory, you will need adequate disk space to save them and sufficient RAM to load them. At the moment, memory and disk requirements are the same. For example (Llama 3.1):
|
||||
|
||||
| Model | Original size | Quantized size (Q4_K_M) |
|
||||
| ----: | ------------: | ----------------------: |
|
||||
|------:|--------------:|------------------------:|
|
||||
| 8B | 32.1 GB | 4.9 GB |
|
||||
| 70B | 280.9 GB | 43.1 GB |
|
||||
| 405B | 1,625.1 GB | 249.1 GB |
|
||||
|
||||
|
||||
## Quantization
|
||||
|
||||
Several quantization methods are supported. They differ in the resulting model disk size and inference speed. For example,
|
||||
|
||||
### [meta-llama/Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B)
|
||||
|
||||
| Measure | IQ1_S | IQ1_M | IQ2_XXS | IQ2_XS | IQ2_S | IQ2_M |
|
||||
| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ |
|
||||
| bits/weight | 2.0042 | 2.1460 | 2.3824 | 2.5882 | 2.7403 | 2.9294 |
|
||||
| size (GiB) | 1.87 | 2.01 | 2.23 | 2.42 | 2.56 | 2.74 |
|
||||
| prompt processing t/s @ 512 | 858.88 ±1.22 | 847.99 ±0.47 | 852.39 ±0.85 | 826.99 ±12.51 | 783.55 ±13.73 | 787.68 ±7.00 |
|
||||
| text generation t/s @ 128 | 79.73 ±0.79 | 72.92 ±0.14 | 79.86 ±0.22 | 78.04 ±0.46 | 77.30 ±2.47 | 74.44 ±0.15 |
|
||||
|
||||
| Measure | IQ3_XXS | IQ3_XS | IQ3_S | IQ3_M | IQ4_XS | IQ4_NL |
|
||||
| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ |
|
||||
| bits/weight | 3.2548 | 3.4977 | 3.6606 | 3.7628 | 4.4597 | 4.6818 |
|
||||
| size (GiB) | 3.04 | 3.27 | 3.42 | 3.52 | 4.17 | 4.38 |
|
||||
| prompt processing t/s @ 512 | 813.88 ±6.53 | 708.71 ±1.26 | 798.78 ±8.81 | 768.70 ±13.73 | 771.80 ±11.38 | 806.03 ±7.07 |
|
||||
| text generation t/s @ 128 | 73.95 ±0.20 | 71.67 ±0.54 | 69.31 ±0.63 | 70.15 ±0.33 | 77.51 ±0.20 | 76.63 ±0.28 |
|
||||
|
||||
|
||||
| Measure | Q2_K_S | Q2_K | Q3_K_S | Q3_K_M | Q3_K_L | Q4_K_S |
|
||||
| --------------------------- | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
|
||||
| bits/weight | 2.9697 | 3.1593 | 3.6429 | 3.9960 | 4.2979 | 4.6672 |
|
||||
| size (GiB) | 2.78 | 2.95 | 3.41 | 3.74 | 4.02 | 4.36 |
|
||||
| prompt processing t/s @ 512 | 798.91 ±6.40 | 784.45 ±7.85 | 752.17 ±7.94 | 783.44 ±9.92 | 761.17 ±7.55 | 818.55 ±9.58 |
|
||||
| text generation t/s @ 128 | 90.01 ±0.12 | 79.85 ±0.20 | 69.84 ±0.18 | 71.68 ±0.22 | 69.38 ±0.49 | 76.71 ±0.20 |
|
||||
|
||||
| Measure | Q4_K_S | Q4_K_M | Q5_K_S | Q5_K_M | Q6_K | Q8_0 |
|
||||
| --------------------------- | ------------ | ------------- | ------------ | ------------ | ------------- | ------------ |
|
||||
| bits/weight | 4.6672 | 4.8944 | 5.5704 | 5.7036 | 6.5633 | 8.5008 |
|
||||
| size (GiB) | 4.36 | 4.58 | 5.21 | 5.33 | 6.14 | 7.95 |
|
||||
| prompt processing t/s @ 512 | 818.55 ±9.58 | 821.81 ±21.44 | 752.52 ±0.99 | 758.69 ±7.43 | 812.01 ±10.82 | 865.09 ±8.30 |
|
||||
| text generation t/s @ 128 | 76.71 ±0.20 | 71.93 ±1.52 | 69.53 ±0.18 | 67.23 ±1.08 | 58.67 ±3.13 | 50.93 ±0.08 |
|
||||
|
||||
| Measure | F16 |
|
||||
| --------------------------- | ------------ |
|
||||
| bits/weight | 16.0005 |
|
||||
| size (GiB) | 14.96 |
|
||||
| prompt processing t/s @ 512 | 923.49 ±0.53 |
|
||||
| text generation t/s @ 128 | 29.17 ±0.04 |
|
||||
| Quant Type | bits/weight | size (GiB) | prompt processing t/s @ 512 | text generation t/s @ 128 |
|
||||
|:----------:|------------:|-----------:|----------------------------:|--------------------------:|
|
||||
| IQ1_S | 2.0042 | 1.87 | 858.88 ±1.22 | 79.73 ±0.79 |
|
||||
| IQ1_M | 2.1460 | 2.01 | 847.99 ±0.47 | 72.92 ±0.14 |
|
||||
| IQ2_XXS | 2.3824 | 2.23 | 852.39 ±0.85 | 79.86 ±0.22 |
|
||||
| IQ2_XS | 2.5882 | 2.42 | 826.99 ±12.51 | 78.04 ±0.46 |
|
||||
| IQ2_S | 2.7403 | 2.56 | 783.55 ±13.73 | 77.30 ±2.47 |
|
||||
| IQ2_M | 2.9294 | 2.74 | 787.68 ±7.00 | 74.44 ±0.15 |
|
||||
| IQ3_XXS | 3.2548 | 3.04 | 813.88 ±6.53 | 73.95 ±0.20 |
|
||||
| IQ3_XS | 3.4977 | 3.27 | 708.71 ±1.26 | 71.67 ±0.54 |
|
||||
| IQ3_S | 3.6606 | 3.42 | 798.78 ±8.81 | 69.31 ±0.63 |
|
||||
| IQ3_M | 3.7628 | 3.52 | 768.70 ±13.73 | 70.15 ±0.33 |
|
||||
| IQ4_XS | 4.4597 | 4.17 | 771.80 ±11.38 | 77.51 ±0.20 |
|
||||
| IQ4_NL | 4.6818 | 4.38 | 806.03 ±7.07 | 76.63 ±0.28 |
|
||||
| Q2_K_S | 2.9697 | 2.78 | 798.91 ±6.40 | 90.01 ±0.12 |
|
||||
| Q2_K | 3.1593 | 2.95 | 784.45 ±7.85 | 79.85 ±0.20 |
|
||||
| Q3_K_S | 3.6429 | 3.41 | 752.17 ±7.94 | 69.84 ±0.18 |
|
||||
| Q3_K_M | 3.9960 | 3.74 | 783.44 ±9.92 | 71.68 ±0.22 |
|
||||
| Q3_K_L | 4.2979 | 4.02 | 761.17 ±7.55 | 69.38 ±0.49 |
|
||||
| Q4_K_S | 4.6672 | 4.36 | 818.55 ±9.58 | 76.71 ±0.20 |
|
||||
| Q4_K_M | 4.8944 | 4.58 | 821.81 ±21.44 | 71.93 ±1.52 |
|
||||
| Q5_K_S | 5.5704 | 5.21 | 752.52 ±0.99 | 69.53 ±0.18 |
|
||||
| Q5_K_M | 5.7036 | 5.33 | 758.69 ±7.43 | 67.23 ±1.08 |
|
||||
| Q6_K | 6.5633 | 6.14 | 812.01 ±10.82 | 58.67 ±3.13 |
|
||||
| Q8_0 | 8.5008 | 7.95 | 865.09 ±8.30 | 50.93 ±0.08 |
|
||||
| F16 | 16.0005 | 14.96 | 923.49 ±0.53 | 29.17 ±0.04 |
|
||||
|
||||
## Background information on llama-quantize
|
||||
|
||||
@@ -194,3 +222,4 @@ Several quantization methods are supported. They differ in the resulting model d
|
||||
- [#5060 - Q3_K_XS](https://github.com/ggml-org/llama.cpp/pull/5060)
|
||||
- [#5196 - 3-bit i-quants](https://github.com/ggml-org/llama.cpp/pull/5196)
|
||||
- [quantization tuning](https://github.com/ggml-org/llama.cpp/pull/5320), [another one](https://github.com/ggml-org/llama.cpp/pull/5334), and [another one](https://github.com/ggml-org/llama.cpp/pull/5361)
|
||||
- [target bpw/size](https://github.com/ggml-org/llama.cpp/pull/15550)
|
||||
|
||||
+393
-84
@@ -1,24 +1,24 @@
|
||||
#include "llama.h"
|
||||
|
||||
#include "build-info.h"
|
||||
#include "common.h"
|
||||
#include "imatrix-loader.h"
|
||||
|
||||
#include "gguf.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <clocale>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <fstream>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <signal.h>
|
||||
#include <unordered_map>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#ifndef NOMINMAX
|
||||
# define NOMINMAX
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
// result of parsing --tensor-type option
|
||||
// changes to this struct must also be reflected in src/llama-quant.cpp
|
||||
struct tensor_type_option {
|
||||
std::string name;
|
||||
@@ -121,8 +121,8 @@ static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftyp
|
||||
[[noreturn]]
|
||||
static void usage(const char * executable) {
|
||||
printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights]\n", executable);
|
||||
printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file]\n");
|
||||
printf(" [--prune-layers] [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size]\n");
|
||||
printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file] [--prune-layers]\n");
|
||||
printf(" [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size] [--target-bpw] [--target-size] [--target-exclude] [--state-file]\n");
|
||||
printf(" model-f32.gguf [model-quant.gguf] type [nthreads]\n\n");
|
||||
printf(" --allow-requantize\n");
|
||||
printf(" allow requantizing tensors that have already been quantized\n");
|
||||
@@ -145,7 +145,7 @@ static void usage(const char * executable) {
|
||||
printf(" use this ggml_type for the token embeddings tensor\n");
|
||||
printf(" --tensor-type tensor_name=ggml_type\n");
|
||||
printf(" quantize this tensor to this ggml_type\n");
|
||||
printf(" this is an advanced option to selectively quantize tensors. may be specified multiple times.\n");
|
||||
printf(" this is an advanced option to selectively quantize tensors; may be specified multiple times.\n");
|
||||
printf(" example: --tensor-type attn_q=q8_0\n");
|
||||
printf(" --tensor-type-file tensor_types.txt\n");
|
||||
printf(" list of tensors to quantize to a specific ggml_type\n");
|
||||
@@ -157,7 +157,7 @@ static void usage(const char * executable) {
|
||||
printf(" --keep-split\n");
|
||||
printf(" generate quantized model in the same shards as input\n");
|
||||
printf(" --override-kv KEY=TYPE:VALUE\n");
|
||||
printf(" override model metadata by key in the quantized model. may be specified multiple times.\n");
|
||||
printf(" override model metadata by key in the quantized model; may be specified multiple times.\n");
|
||||
printf(" WARNING: this is an advanced option, use with care.\n");
|
||||
printf(" --dry-run\n");
|
||||
printf(" calculate and show the final quantization size without performing quantization\n");
|
||||
@@ -165,7 +165,21 @@ static void usage(const char * executable) {
|
||||
printf(" --max-buffer-size MiB\n");
|
||||
printf(" max amount of tensor rows kept in memory while quantizing one tensor (default: 8192)\n");
|
||||
printf(" lower it to quantize models with very large tensors on a machine with little RAM\n\n");
|
||||
printf("note: --include-weights and --exclude-weights cannot be used together\n\n");
|
||||
printf(" --target-bpw n\n");
|
||||
printf(" target a bits per weight (bpw); must be a number between 0.0 and 16.0, 0 means the smallest possible model\n");
|
||||
printf(" advanced option to automatically select quantization types to achieve a total bits per weight (bpw) target\n\n");
|
||||
printf(" --target-size n\n");
|
||||
printf(" target a file size; must be 0 or more, 0 means the smallest possible model\n");
|
||||
printf(" advanced option to automatically select quantization types to achieve a total file size\n");
|
||||
printf(" allowed units: b, k|kib, m|mib, g|gib, t|tib; defaults to b (bytes) if none is provided\n\n");
|
||||
printf(" --state-file [filename]\n");
|
||||
printf(" file name to use/save; if none is provided, the default name will be used\n\n");
|
||||
printf(" --target-exclude type[,type...]\n");
|
||||
printf(" comma-separated ggml_type (names or ordinals) that automatic quant type selection must ignore\n");
|
||||
printf(" advanced option for --target-bpw/--target-size; may be specified multiple times\n\n");
|
||||
printf("note: --include-weights and --exclude-weights cannot be used together\n");
|
||||
printf(" --target-bpw and --target-size cannot be used together\n");
|
||||
printf(" --exclude-weights excludes tensor NAMES, while --target-exclude excludes quant TYPES\n\n");
|
||||
printf("-----------------------------------------------------------------------------\n");
|
||||
printf(" allowed quantization types\n");
|
||||
printf("-----------------------------------------------------------------------------\n\n");
|
||||
@@ -180,7 +194,13 @@ static void usage(const char * executable) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
static int load_imatrix(const std::string & imatrix_file, std::vector<std::string> & imatrix_datasets, std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
|
||||
static int load_imatrix(const std::string & imatrix_file,
|
||||
std::vector<std::string> & imatrix_datasets,
|
||||
std::unordered_map<std::string, std::vector<float>> & values_data,
|
||||
std::unordered_map<std::string, std::vector<float>> & activations_data,
|
||||
std::unordered_map<std::string, std::vector<float>> & statistics_data,
|
||||
std::vector<std::string> & statistics_schema)
|
||||
{
|
||||
common_imatrix loaded;
|
||||
if (!common_imatrix_load(imatrix_file, loaded)) {
|
||||
fprintf(stderr, "%s: failed to load imatrix from '%s'\n", __func__, imatrix_file.c_str());
|
||||
@@ -193,59 +213,84 @@ static int load_imatrix(const std::string & imatrix_file, std::vector<std::strin
|
||||
}
|
||||
|
||||
for (const auto & [name, entry] : loaded.entries) {
|
||||
auto & e = imatrix_data[name];
|
||||
e.resize(entry.sums.size());
|
||||
const int64_t ncounts = (int64_t) entry.counts.size();
|
||||
if (ncounts == 0) {
|
||||
fprintf(stderr, "%s: no counts for entry '%s', skipping\n", __func__, name.c_str());
|
||||
continue;
|
||||
}
|
||||
|
||||
const int64_t nsums = (int64_t) entry.sums.size();
|
||||
if (nsums == 0) {
|
||||
continue;
|
||||
}
|
||||
const int64_t ne0 = nsums / ncounts;
|
||||
|
||||
auto & values = values_data[name];
|
||||
values.resize(nsums);
|
||||
|
||||
if (!loaded.is_legacy) {
|
||||
// GGUF format: normalize by per-expert counts
|
||||
const int64_t ncounts = entry.counts.size();
|
||||
const int64_t ne0 = (int64_t) entry.sums.size() / ncounts;
|
||||
|
||||
for (int64_t j = 0; j < ncounts; ++j) {
|
||||
const float count = (float) entry.counts[j];
|
||||
if (count > 0.0f) {
|
||||
for (int64_t i = 0; i < ne0; ++i) {
|
||||
e[j*ne0 + i] = entry.sums[j*ne0 + i] / count;
|
||||
values[j*ne0 + i] = entry.sums[j*ne0 + i] / count;
|
||||
}
|
||||
} else {
|
||||
for (int64_t i = 0; i < ne0; ++i) {
|
||||
e[j*ne0 + i] = 1;
|
||||
values[j*ne0 + i] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (getenv("LLAMA_TRACE")) {
|
||||
float max_count = 0.0f;
|
||||
for (int64_t j = 0; j < ncounts; ++j) {
|
||||
const float count = (float) entry.counts[j];
|
||||
if (count > max_count) {
|
||||
max_count = count;
|
||||
}
|
||||
}
|
||||
printf("%s: loaded data (size = %6d, n_tokens = %6d, n_chunks = %6d) for '%s'\n",
|
||||
__func__, int(e.size()), int(max_count), int(max_count / loaded.chunk_size), name.c_str());
|
||||
}
|
||||
} else {
|
||||
// Legacy format: sums contain (raw/count)*ncall, divide by ncall
|
||||
const int64_t ncall = entry.counts.empty() ? 0 : entry.counts[0];
|
||||
const int64_t ncall = entry.counts[0];
|
||||
if (ncall > 0) {
|
||||
for (size_t i = 0; i < entry.sums.size(); ++i) {
|
||||
e[i] = entry.sums[i] / ncall;
|
||||
for (int64_t i = 0; i < nsums; ++i) {
|
||||
values[i] = entry.sums[i] / ncall;
|
||||
}
|
||||
} else {
|
||||
for (size_t i = 0; i < entry.sums.size(); ++i) {
|
||||
e[i] = entry.sums[i];
|
||||
for (int64_t i = 0; i < nsums; ++i) {
|
||||
values[i] = entry.sums[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (getenv("LLAMA_TRACE")) {
|
||||
printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n",
|
||||
__func__, int(e.size()), int(ncall), name.c_str());
|
||||
if (!entry.activations.empty()) {
|
||||
auto & activations = activations_data[name];
|
||||
activations.resize(entry.activations.size());
|
||||
if (!loaded.is_legacy) {
|
||||
for (int64_t j = 0; j < ncounts; ++j) {
|
||||
const float count = (float) entry.counts[j];
|
||||
if (count > 0.0f) {
|
||||
for (int64_t i = 0; i < ne0; ++i) {
|
||||
activations[j*ne0 + i] = entry.activations[j*ne0 + i] / count;
|
||||
}
|
||||
} else {
|
||||
for (int64_t i = 0; i < ne0; ++i) {
|
||||
activations[j*ne0 + i] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const int64_t ncall = entry.counts[0];
|
||||
if (ncall > 0) {
|
||||
for (size_t i = 0; i < entry.activations.size(); ++i) {
|
||||
activations[i] = entry.activations[i] / ncall;
|
||||
}
|
||||
} else {
|
||||
for (size_t i = 0; i < entry.activations.size(); ++i) {
|
||||
activations[i] = entry.activations[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!entry.stats.empty()) {
|
||||
statistics_data[name] = entry.stats;
|
||||
}
|
||||
}
|
||||
|
||||
imatrix_datasets = std::move(loaded.datasets);
|
||||
statistics_schema = std::move(loaded.stats_schema);
|
||||
|
||||
if (!imatrix_datasets.empty()) {
|
||||
printf("%s: imatrix datasets=['%s'", __func__, imatrix_datasets[0].c_str());
|
||||
@@ -255,7 +300,7 @@ static int load_imatrix(const std::string & imatrix_file, std::vector<std::strin
|
||||
printf("]\n");
|
||||
}
|
||||
|
||||
printf("%s: loaded %d importance matrix entries from %s computed on %d chunks\n", __func__, int(imatrix_data.size()), imatrix_file.c_str(), loaded.chunk_count);
|
||||
printf("%s: loaded %d importance matrix entries from %s computed on %d chunks\n", __func__, int(values_data.size()), imatrix_file.c_str(), loaded.chunk_count);
|
||||
|
||||
return loaded.chunk_count;
|
||||
}
|
||||
@@ -264,41 +309,74 @@ static int prepare_imatrix(const std::string & imatrix_file,
|
||||
std::vector<std::string> & imatrix_dataset,
|
||||
const std::vector<std::string> & included_weights,
|
||||
const std::vector<std::string> & excluded_weights,
|
||||
std::unordered_map<std::string, std::vector<float>> & imatrix_data) {
|
||||
std::unordered_map<std::string, std::vector<float>> & values_data,
|
||||
std::unordered_map<std::string, std::vector<float>> & activations_data,
|
||||
std::unordered_map<std::string, std::vector<float>> & statistics_data,
|
||||
std::vector<std::string> & stats_schema) {
|
||||
int m_last_call = -1;
|
||||
if (!imatrix_file.empty()) {
|
||||
m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data);
|
||||
m_last_call = load_imatrix(imatrix_file, imatrix_dataset, values_data, activations_data, statistics_data, stats_schema);
|
||||
}
|
||||
if (imatrix_data.empty()) {
|
||||
if (values_data.empty()) {
|
||||
return m_last_call;
|
||||
}
|
||||
if (!excluded_weights.empty()) {
|
||||
for (const auto & name : excluded_weights) {
|
||||
for (auto it = imatrix_data.begin(); it != imatrix_data.end();) {
|
||||
auto pos = it->first.find(name);
|
||||
for (auto vt = values_data.begin(); vt != values_data.end();) {
|
||||
auto pos = vt->first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
it = imatrix_data.erase(it);
|
||||
vt = values_data.erase(vt);
|
||||
} else {
|
||||
++it;
|
||||
++vt;
|
||||
}
|
||||
}
|
||||
for (auto at = activations_data.begin(); at != activations_data.end();) {
|
||||
auto pos = at->first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
at = activations_data.erase(at);
|
||||
} else {
|
||||
++at;
|
||||
}
|
||||
}
|
||||
for (auto st = statistics_data.begin(); st != statistics_data.end();) {
|
||||
auto pos = st->first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
st = statistics_data.erase(st);
|
||||
} else {
|
||||
++st;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!included_weights.empty()) {
|
||||
std::unordered_map<std::string, std::vector<float>> tmp;
|
||||
std::unordered_map<std::string, std::vector<float>> tmp_values;
|
||||
std::unordered_map<std::string, std::vector<float>> tmp_activations;
|
||||
std::unordered_map<std::string, std::vector<float>> tmp_statistics;
|
||||
for (const auto & name : included_weights) {
|
||||
for (auto & e : imatrix_data) {
|
||||
for (auto & e : values_data) {
|
||||
auto pos = e.first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
tmp.emplace(std::move(e));
|
||||
tmp_values.emplace(std::move(e));
|
||||
}
|
||||
}
|
||||
for (auto & a : activations_data) {
|
||||
auto pos = a.first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
tmp_activations.emplace(std::move(a));
|
||||
}
|
||||
}
|
||||
for (auto & s : statistics_data) {
|
||||
auto pos = s.first.find(name);
|
||||
if (pos != std::string::npos) {
|
||||
tmp_statistics.emplace(std::move(s));
|
||||
}
|
||||
}
|
||||
}
|
||||
imatrix_data = std::move(tmp);
|
||||
}
|
||||
if (!imatrix_data.empty()) {
|
||||
printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size()));
|
||||
values_data = std::move(tmp_values);
|
||||
activations_data = std::move(tmp_activations);
|
||||
statistics_data = std::move(tmp_statistics);
|
||||
}
|
||||
|
||||
return m_last_call;
|
||||
}
|
||||
|
||||
@@ -389,6 +467,139 @@ static bool parse_layer_prune(const char * data, std::vector<int> & prune_layers
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool parse_target_bpw(const char * data, float & target_bpw) {
|
||||
if (!data) {
|
||||
printf("\n%s: no target bits per weight (bpw) provided\n\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
target_bpw = std::stof(data);
|
||||
if (!std::isfinite(target_bpw) || target_bpw < 0.0f || target_bpw > 16.0f) {
|
||||
printf("\n%s: target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
catch (const std::exception & e) {
|
||||
printf("\n%s: '%s' is not valid. Target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__, data);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool parse_target_size(const char * data, int64_t & target_size) {
|
||||
if (!data) {
|
||||
printf("\n%s: no target file size provided\n\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
char * end = nullptr;
|
||||
const double val = std::strtod(data, &end);
|
||||
if (end == data || !std::isfinite(val) || val < 0) {
|
||||
printf("\n%s: invalid target file size '%s'\n\n", __func__, data);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string suffix(end);
|
||||
for (auto & c : suffix) { c = std::tolower(c); }
|
||||
|
||||
int64_t mul = 0;
|
||||
if (suffix.empty() || suffix == "b") {
|
||||
mul = 1;
|
||||
} else if (suffix == "k" || suffix == "kib") {
|
||||
mul = 1024;
|
||||
} else if (suffix == "m" || suffix == "mib") {
|
||||
mul = 1024 * 1024;
|
||||
} else if (suffix == "g" || suffix == "gib") {
|
||||
mul = 1024 * 1024 * 1024;
|
||||
} else if (suffix == "t" || suffix == "tib") {
|
||||
mul = 1024LL * 1024 * 1024 * 1024;
|
||||
} else {
|
||||
printf("\n%s: invalid unit '%s' in '%s'. Allowed: b, k or kib, m or mib, g or gib, t or tib\n\n", __func__, suffix.c_str(), data);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (val * mul >= (double)INT64_MAX) {
|
||||
printf("\n%s: invalid target file size '%s'\n\n", __func__, data);
|
||||
return false;
|
||||
}
|
||||
|
||||
target_size = (int64_t)(val * mul);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool parse_target_exclude(const char * data, std::vector<ggml_type> & target_exclude) {
|
||||
if (!data) {
|
||||
printf("\n%s: no quant types provided\n\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto tokens = string_split<std::string>(data, ',');
|
||||
for (const auto & token : tokens) {
|
||||
ggml_type type = GGML_TYPE_COUNT;
|
||||
for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
|
||||
const char * name = ggml_type_name((ggml_type)i);
|
||||
if (name && striequals(name, token.c_str())) {
|
||||
type = (ggml_type)i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (type == GGML_TYPE_COUNT) {
|
||||
const bool numeric = !token.empty() && std::all_of(token.begin(), token.end(), [](unsigned char c) { return std::isdigit(c); });
|
||||
const long ordinal = numeric ? std::strtol(token.c_str(), nullptr, 10) : -1;
|
||||
if (ordinal >= 0 && ordinal < GGML_TYPE_COUNT) {
|
||||
type = (ggml_type)ordinal;
|
||||
}
|
||||
}
|
||||
|
||||
if (type == GGML_TYPE_COUNT) {
|
||||
printf("\n%s: invalid quant type '%s' for --target-exclude\n\n", __func__, token.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (std::find(target_exclude.begin(), target_exclude.end(), type) == target_exclude.end()) {
|
||||
target_exclude.emplace_back(type);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static const char * get_ftype(const float bpw) {
|
||||
const std::map<float, const char *> quant_bpw = {
|
||||
{1.5625, "IQ1_S"},
|
||||
{1.7500, "IQ1_M"},
|
||||
{2.0625, "IQ2_XXS"},
|
||||
{2.3125, "IQ2_XS"},
|
||||
{2.5625, "IQ2_S"},
|
||||
{2.6250, "Q2_K"},
|
||||
{3.0625, "IQ3_XXS"},
|
||||
{3.4375, "Q3_K"},
|
||||
{4.2500, "IQ4_XS"},
|
||||
{4.5000, "Q4_K"},
|
||||
{5.5000, "Q5_K"},
|
||||
{6.5625, "Q6_K"},
|
||||
{8.5000, "Q8_0"},
|
||||
{16.0000, "F16"}
|
||||
};
|
||||
|
||||
return quant_bpw.lower_bound(bpw)->second;
|
||||
}
|
||||
|
||||
static std::atomic<int> interrupt_signal{ 0 };
|
||||
|
||||
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
|
||||
// try to save the state checkpoint if interrupted while scoring
|
||||
static void signal_handler(int signo) {
|
||||
int expected = 0;
|
||||
interrupt_signal.compare_exchange_strong(expected, signo);
|
||||
}
|
||||
#endif
|
||||
|
||||
static bool is_interrupted(void * /*data*/) { return interrupt_signal.load() != 0; }
|
||||
|
||||
// satisfies -Wmissing-declarations
|
||||
int llama_quantize(int argc, char ** argv);
|
||||
|
||||
@@ -402,10 +613,14 @@ int llama_quantize(int argc, char ** argv) {
|
||||
|
||||
int arg_idx = 1;
|
||||
std::string imatrix_file;
|
||||
std::vector<std::string> included_weights, excluded_weights;
|
||||
std::vector<std::string> included_weights;
|
||||
std::vector<std::string> excluded_weights;
|
||||
std::vector<llama_model_kv_override> kv_overrides;
|
||||
std::vector<tensor_type_option> tensor_type_opts;
|
||||
std::vector<int> prune_layers;
|
||||
std::vector<ggml_type> target_exclude;
|
||||
float target_bpw = -1.0f;
|
||||
int64_t target_size = -1;
|
||||
|
||||
for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) {
|
||||
if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) {
|
||||
@@ -436,6 +651,25 @@ int llama_quantize(int argc, char ** argv) {
|
||||
if (arg_idx == argc-1 || !parse_tensor_type_file(argv[++arg_idx], tensor_type_opts)) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
} else if (strcmp(argv[arg_idx], "--target-bpw") == 0) {
|
||||
if (arg_idx == argc-1 || !parse_target_bpw(argv[++arg_idx], target_bpw)) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
} else if (strcmp(argv[arg_idx], "--target-size") == 0) {
|
||||
if (arg_idx == argc-1 || !parse_target_size(argv[++arg_idx], target_size)) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
} else if (strcmp(argv[arg_idx], "--target-exclude") == 0) {
|
||||
if (arg_idx == argc-1 || !parse_target_exclude(argv[++arg_idx], target_exclude)) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
} else if (strcmp(argv[arg_idx], "--state-file") == 0) {
|
||||
if (arg_idx + 1 < argc && argv[arg_idx + 1][0] != '-') {
|
||||
params.state_file = argv[++arg_idx];
|
||||
} else {
|
||||
static char empty[] = "";
|
||||
params.state_file = empty;
|
||||
}
|
||||
} else if (strcmp(argv[arg_idx], "--prune-layers") == 0) {
|
||||
if (arg_idx == argc-1 || !parse_layer_prune(argv[++arg_idx], prune_layers)) {
|
||||
usage(argv[0]);
|
||||
@@ -492,20 +726,28 @@ int llama_quantize(int argc, char ** argv) {
|
||||
if (!included_weights.empty() && !excluded_weights.empty()) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
if (target_bpw != -1.0f && target_size != -1) {
|
||||
usage(argv[0]);
|
||||
}
|
||||
|
||||
std::vector<std::string> imatrix_datasets;
|
||||
std::unordered_map<std::string, std::vector<float>> imatrix_data;
|
||||
int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, imatrix_data);
|
||||
std::unordered_map<std::string, std::vector<float>> values_data;
|
||||
std::unordered_map<std::string, std::vector<float>> activations_data;
|
||||
std::unordered_map<std::string, std::vector<float>> statistics_data;
|
||||
std::vector<std::string> stats_schema;
|
||||
int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, values_data, activations_data, statistics_data, stats_schema);
|
||||
|
||||
std::vector<llama_model_imatrix_data> i_data;
|
||||
std::vector<llama_model_tensor_override> t_override;
|
||||
if (!imatrix_data.empty()) {
|
||||
i_data.reserve(imatrix_data.size() + 1);
|
||||
for (const auto & kv : imatrix_data) {
|
||||
i_data.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()});
|
||||
}
|
||||
i_data.push_back({nullptr, nullptr, 0}); // array terminator
|
||||
params.imatrix = i_data.data();
|
||||
std::vector<llama_model_imatrix_data> vdata;
|
||||
std::vector<llama_model_imatrix_data> adata;
|
||||
std::vector<llama_model_imatrix_data> sdata;
|
||||
std::vector<const char *> sschema;
|
||||
std::vector<llama_model_tensor_override> tto;
|
||||
|
||||
if (!values_data.empty()) {
|
||||
vdata.reserve(values_data.size() + 1);
|
||||
for (const auto & kv : values_data) { vdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
|
||||
vdata.push_back({nullptr, nullptr, 0}); // array terminator
|
||||
params.imatrix = vdata.data();
|
||||
{
|
||||
llama_model_kv_override kvo;
|
||||
std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE);
|
||||
@@ -529,7 +771,7 @@ int llama_quantize(int argc, char ** argv) {
|
||||
llama_model_kv_override kvo;
|
||||
std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES);
|
||||
kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
|
||||
kvo.val_i64 = imatrix_data.size();
|
||||
kvo.val_i64 = values_data.size();
|
||||
kv_overrides.emplace_back(std::move(kvo));
|
||||
}
|
||||
if (m_last_call > 0) {
|
||||
@@ -540,23 +782,47 @@ int llama_quantize(int argc, char ** argv) {
|
||||
kv_overrides.emplace_back(std::move(kvo));
|
||||
}
|
||||
}
|
||||
if (!activations_data.empty()) {
|
||||
adata.reserve(activations_data.size() + 1);
|
||||
for (const auto & kv : activations_data) { adata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
|
||||
adata.push_back({nullptr, nullptr, 0}); // array terminator
|
||||
params.activations = adata.data();
|
||||
}
|
||||
if (!statistics_data.empty()) {
|
||||
sdata.reserve(statistics_data.size() + 1);
|
||||
for (const auto & kv : statistics_data) { sdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); }
|
||||
sdata.push_back({nullptr, nullptr, 0}); // array terminator
|
||||
params.statistics = sdata.data();
|
||||
sschema.reserve(stats_schema.size() + 1);
|
||||
for (const auto & name : stats_schema) { sschema.push_back(name.c_str()); }
|
||||
sschema.push_back(nullptr); // array terminator
|
||||
params.stats_schema = sschema.data();
|
||||
}
|
||||
if (!kv_overrides.empty()) {
|
||||
kv_overrides.emplace_back();
|
||||
kv_overrides.back().key[0] = 0;
|
||||
params.kv_overrides = kv_overrides.data();
|
||||
}
|
||||
if (!tensor_type_opts.empty()) {
|
||||
t_override.reserve(tensor_type_opts.size() + 1);
|
||||
for (const auto & tt : tensor_type_opts) {
|
||||
t_override.push_back({tt.name.c_str(), tt.type});
|
||||
}
|
||||
t_override.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator
|
||||
params.tt_overrides = t_override.data();
|
||||
tto.reserve(tensor_type_opts.size() + 1);
|
||||
for (const auto & tt : tensor_type_opts) { tto.push_back({tt.name.c_str(), tt.type}); }
|
||||
tto.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator
|
||||
params.tt_overrides = tto.data();
|
||||
}
|
||||
if (!target_exclude.empty()) {
|
||||
target_exclude.push_back(GGML_TYPE_COUNT); // array terminator
|
||||
params.target_exclude = target_exclude.data();
|
||||
}
|
||||
if (!prune_layers.empty()) {
|
||||
prune_layers.push_back(-1); // array terminator
|
||||
params.prune_layers = prune_layers.data();
|
||||
}
|
||||
if (target_bpw != -1.0f) {
|
||||
params.target_bpw = target_bpw;
|
||||
}
|
||||
if (target_size != -1) {
|
||||
params.target_size = target_size;
|
||||
}
|
||||
|
||||
llama_backend_init();
|
||||
|
||||
@@ -567,6 +833,7 @@ int llama_quantize(int argc, char ** argv) {
|
||||
|
||||
std::string ftype_str;
|
||||
std::string suffix = ".gguf";
|
||||
std::vector<const char *> tmp_argv(argv, argv + argc);
|
||||
if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) {
|
||||
// argv[arg_idx] is the ftype directly: <input> <ftype>
|
||||
if (!params.dry_run) {
|
||||
@@ -594,7 +861,22 @@ int llama_quantize(int argc, char ** argv) {
|
||||
}
|
||||
arg_idx++;
|
||||
|
||||
if (argc <= arg_idx) {
|
||||
// If --target-bpw or --target-size are set, select a quantization type and ignore any user specified type
|
||||
if (params.target_bpw != -1.0f || params.target_size != -1) {
|
||||
auto * ftype = params.target_bpw != -1.0f ? const_cast<char *>(get_ftype(params.target_bpw)) : const_cast<char *>("F16");
|
||||
bool added_type = false;
|
||||
if (argc == arg_idx) {
|
||||
tmp_argv.push_back(ftype);
|
||||
added_type = true;
|
||||
} else {
|
||||
tmp_argv[arg_idx] = ftype;
|
||||
}
|
||||
tmp_argv.push_back(nullptr);
|
||||
argv = const_cast<char **>(tmp_argv.data());
|
||||
if (added_type) {
|
||||
argc++;
|
||||
}
|
||||
} else if (argc <= arg_idx) {
|
||||
fprintf(stderr, "%s: missing ftype\n", __func__);
|
||||
return 1;
|
||||
}
|
||||
@@ -639,6 +921,24 @@ int llama_quantize(int argc, char ** argv) {
|
||||
}
|
||||
fprintf(stderr, "\n");
|
||||
|
||||
// handle SIGINT and SIGTERM
|
||||
{
|
||||
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
||||
struct sigaction sigint_action;
|
||||
sigint_action.sa_handler = signal_handler;
|
||||
sigemptyset(&sigint_action.sa_mask);
|
||||
sigint_action.sa_flags = SA_RESTART;
|
||||
sigaction(SIGINT, &sigint_action, nullptr);
|
||||
sigaction(SIGTERM, &sigint_action, nullptr);
|
||||
#elif defined (_WIN32)
|
||||
auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
|
||||
return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
|
||||
};
|
||||
SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
|
||||
#endif
|
||||
params.abort_callback = is_interrupted;
|
||||
}
|
||||
|
||||
const int64_t t_main_start_us = llama_time_us();
|
||||
|
||||
int64_t t_quantize_us = 0;
|
||||
@@ -649,7 +949,16 @@ int llama_quantize(int argc, char ** argv) {
|
||||
|
||||
if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms)) {
|
||||
fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str());
|
||||
return 1;
|
||||
const int signo = interrupt_signal.load();
|
||||
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
|
||||
// ensure that a calling shell or script stops too...
|
||||
if (signo) {
|
||||
signal(signo, SIG_DFL);
|
||||
raise(signo);
|
||||
}
|
||||
#endif
|
||||
// ...as a shell reports a process that the signal killed
|
||||
return signo ? 128 + signo : 1;
|
||||
}
|
||||
|
||||
t_quantize_us = llama_time_us() - t_start_us;
|
||||
|
||||
@@ -1274,11 +1274,13 @@ struct server_tool_exec_shell_command : server_tool {
|
||||
{"parameters", {
|
||||
{"type", "object"},
|
||||
{"properties", {
|
||||
// first, so a client can show it while the command still streams; the tool ignores it
|
||||
{"description", {{"type", "string"}, {"description", "Short plain-language description of what this command does, starting with a verb, e.g. 'List files in the project root'. 3 to 10 words. Shown to the user."}}},
|
||||
{"command", {{"type", "string"}, {"description", "Shell command to execute"}}},
|
||||
{"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}},
|
||||
{"max_output_size", {{"type", "integer"}, {"description", string_format("Maximum output size in bytes (default %zu)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE)}}},
|
||||
}},
|
||||
{"required", json::array({"command"})},
|
||||
{"required", json::array({"description", "command"})},
|
||||
}},
|
||||
}},
|
||||
};
|
||||
|
||||
@@ -191,6 +191,23 @@ def test_tools_builtin_edit_file_rejects_non_unique_old_text(tmp_path):
|
||||
os.remove(log_path)
|
||||
|
||||
|
||||
def test_tools_builtin_exec_shell_command_asks_for_a_description():
|
||||
global server
|
||||
server.start()
|
||||
|
||||
res = server.make_request("GET", "/tools")
|
||||
assert res.status_code == 200, res.body
|
||||
tool = next(t for t in res.body if t["tool"] == "exec_shell_command")
|
||||
params = tool["definition"]["function"]["parameters"]
|
||||
# first, so a client can show it while the command still streams
|
||||
assert list(params["properties"])[0] == "description"
|
||||
assert "description" in params["required"]
|
||||
|
||||
# the tool runs without it, as before
|
||||
res = call_tool("exec_shell_command", {"command": "echo hi"})
|
||||
assert "hi" in res["plain_text_response"]
|
||||
|
||||
|
||||
def test_tools_builtin_exec_shell_command_stream():
|
||||
global server
|
||||
server.start()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
VITE_PUBLIC_APP_NAME='llama-ui'
|
||||
VITE_PUBLIC_APP_NAME='Llama Chat'
|
||||
VITE_DEBUG='true'
|
||||
VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033'
|
||||
|
||||
|
||||
@@ -47,6 +47,17 @@ class Trace {
|
||||
this.push({ content: '', role: 'system', type: 'root' });
|
||||
}
|
||||
|
||||
/** An assistant turn whose tool call was stopped mid-stream: cut-off arguments and no result. */
|
||||
stoppedTool(name: string, cutArguments: string, content = ''): this {
|
||||
const id = uuid(this.name, `call-${this.calls++}`).replaceAll('-', '');
|
||||
|
||||
return this.push({
|
||||
content,
|
||||
role: 'assistant',
|
||||
toolCalls: [{ function: { arguments: cutArguments, name }, id, type: 'function' }]
|
||||
});
|
||||
}
|
||||
|
||||
toJsonl(): string {
|
||||
const last = this.messages.at(-1)!;
|
||||
const session = {
|
||||
@@ -330,11 +341,38 @@ function diagrams(): Trace {
|
||||
return trace;
|
||||
}
|
||||
|
||||
/** A chat whose last tool call was stopped while its arguments were still streaming. */
|
||||
function stoppedToolCall(): Trace {
|
||||
const trace = new Trace('Smoke test for the slides page');
|
||||
|
||||
trace.user('Write a quick Playwright smoke test for slides.html and run it.');
|
||||
trace.stoppedTool(
|
||||
'exec_shell_command',
|
||||
JSON.stringify({
|
||||
command: [
|
||||
"cat > /tmp/slides-smoke.mjs <<'EOF'",
|
||||
"import { chromium } from 'playwright';",
|
||||
'',
|
||||
'const browser = await chromium.launch();',
|
||||
'const page = await browser.newPage();',
|
||||
'',
|
||||
"await page.goto('file:///tmp/slides.html');",
|
||||
'EOF',
|
||||
'node /tmp/slides-smoke.mjs'
|
||||
].join('\n')
|
||||
}).slice(0, 160),
|
||||
'I will write the script to a file and run it.'
|
||||
);
|
||||
|
||||
return trace;
|
||||
}
|
||||
|
||||
/** Built-in traces, by name. */
|
||||
export const DEMO_TRACES: Record<string, () => Trace> = {
|
||||
'agentic-debugging': agenticDebugging,
|
||||
diagrams,
|
||||
'long-chat': longChat
|
||||
'long-chat': longChat,
|
||||
'stopped-tool-call': stoppedToolCall
|
||||
};
|
||||
|
||||
export function generateTrace(name: string): null | string {
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { HEADERS } from '../src/lib/constants/headers.constants';
|
||||
import {
|
||||
PWA_FILE_PATHS,
|
||||
PWA_MANIFEST,
|
||||
PWA_MANIFEST_PLUGIN
|
||||
PWA_MANIFEST_PLUGIN,
|
||||
pwaManifest
|
||||
} from '../src/lib/constants/pwa.constants';
|
||||
import type { Plugin } from 'vite';
|
||||
|
||||
const MANIFEST_SOURCE = JSON.stringify(PWA_MANIFEST);
|
||||
// the build writes files relative to its output directory: the path without its leading slash
|
||||
const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1);
|
||||
|
||||
@@ -15,17 +14,24 @@ const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1);
|
||||
* The adapter copies the client output, so the file lands at the root of the build.
|
||||
*/
|
||||
export function pwaManifestPlugin(): Plugin {
|
||||
let manifestSource = '';
|
||||
|
||||
return {
|
||||
// named from the env Vite loaded (.env files too): this module runs in Node, where
|
||||
// import.meta.env is not set and APP_NAME would fall back to its default
|
||||
configResolved(config) {
|
||||
manifestSource = JSON.stringify(pwaManifest(config.env));
|
||||
},
|
||||
configureServer(server) {
|
||||
server.middlewares.use(PWA_FILE_PATHS.MANIFEST, (_req, res) => {
|
||||
res.setHeader(HEADERS.CONTENT_TYPE, PWA_MANIFEST_PLUGIN.CONTENT_TYPE);
|
||||
res.end(MANIFEST_SOURCE);
|
||||
res.end(manifestSource);
|
||||
});
|
||||
},
|
||||
generateBundle() {
|
||||
if (this.environment.name !== PWA_MANIFEST_PLUGIN.ENVIRONMENT) return;
|
||||
|
||||
this.emitFile({ fileName: MANIFEST_FILE, source: MANIFEST_SOURCE, type: 'asset' });
|
||||
this.emitFile({ fileName: MANIFEST_FILE, source: manifestSource, type: 'asset' });
|
||||
},
|
||||
name: PWA_MANIFEST_PLUGIN.NAME
|
||||
};
|
||||
|
||||
@@ -388,3 +388,27 @@
|
||||
.stick-to-bottom-pin {
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
/*
|
||||
* A message's stats and actions stay out of the way until the reader points at
|
||||
* it or tabs into it. Only opacity changes, so their room is kept and nothing
|
||||
* moves when they appear. Touch screens have no hover, so they keep them shown.
|
||||
*/
|
||||
@media (hover: hover) {
|
||||
.message-meta {
|
||||
opacity: 0;
|
||||
transition: opacity 150ms ease-out;
|
||||
}
|
||||
|
||||
.chat-message-user:hover .message-meta,
|
||||
.chat-message-assistant:hover .message-meta,
|
||||
.message-meta:focus-within {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: hover) and (prefers-reduced-motion: reduce) {
|
||||
.message-meta {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
+16
-1
@@ -6,8 +6,14 @@
|
||||
ScrollCarousel
|
||||
} from '#lib/components/app/index.ts';
|
||||
import { ScrollCarouselVariant } from '#lib/enums/index.ts';
|
||||
import { mediaGalleryStore } from '#lib/stores/index.ts';
|
||||
import type { DatabaseMessageExtraMcpResource } from '#lib/types/index.ts';
|
||||
import { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from '#lib/utils/index.ts';
|
||||
import {
|
||||
getAttachmentDisplayItems,
|
||||
isMcpPrompt,
|
||||
isMcpResource,
|
||||
isMediaExtra
|
||||
} from '#lib/utils/index.ts';
|
||||
|
||||
interface Props {
|
||||
class?: string;
|
||||
@@ -26,12 +32,15 @@
|
||||
limitToSingleRow?: boolean;
|
||||
// For vision modality check
|
||||
activeModelId?: string;
|
||||
/** A message's attachments: media opens the conversation's slideshow at it */
|
||||
conversationGallery?: boolean;
|
||||
}
|
||||
|
||||
let {
|
||||
activeModelId,
|
||||
attachments = [],
|
||||
class: className = '',
|
||||
conversationGallery = false,
|
||||
// Default to small size for form previews
|
||||
imageClass = '',
|
||||
imageHeight = 'h-24',
|
||||
@@ -55,6 +64,12 @@
|
||||
event?.stopPropagation();
|
||||
event?.preventDefault();
|
||||
|
||||
if (conversationGallery && item.attachment && isMediaExtra(item.attachment)) {
|
||||
mediaGalleryStore.show(item.attachment);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the index of the clicked item among non-MCP attachments
|
||||
const nonMcpItems = displayItems.filter((i) => !isMcpPrompt(i) && !isMcpResource(i));
|
||||
const index = nonMcpItems.findIndex((i) => i.id === item.id);
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@
|
||||
class={[
|
||||
'md:size-8 size-9 rounded-full p-0',
|
||||
showErrorState &&
|
||||
'bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100'
|
||||
'[--key-edge:var(--button-danger-edge)] bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100'
|
||||
]}
|
||||
disabled={isDisabled}
|
||||
type="submit"
|
||||
|
||||
+61
-38
@@ -1,20 +1,21 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
ChatMessageActionIcons,
|
||||
ChatMessageAgenticContent,
|
||||
ChatMessageAgentTrace,
|
||||
ChatMessageAssistantModel,
|
||||
ChatMessageAssistantProcessingInfo,
|
||||
ChatMessageAssistantRawOutput,
|
||||
ChatMessageAssistantResponse,
|
||||
ChatMessageAssistantStatistics,
|
||||
ChatMessageContextMenu,
|
||||
ChatMessageEditForm
|
||||
} from '#lib/components/app/index.ts';
|
||||
import { SETTINGS_KEYS } from '#lib/constants/index.ts';
|
||||
import { getChatMessageEditContext } from '#lib/contexts/index.ts';
|
||||
import { MessageRole } from '#lib/enums/index.ts';
|
||||
import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts';
|
||||
import { chatStore, modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts';
|
||||
import { modelLoadProgressText } from '#lib/utils/index.ts';
|
||||
import { hasAgenticContent } from '#lib/utils/index.ts';
|
||||
import { hasAgenticContent, modelLoadProgressText } from '#lib/utils/index.ts';
|
||||
|
||||
interface Props {
|
||||
class?: string;
|
||||
@@ -39,7 +40,6 @@
|
||||
// Get edit context
|
||||
const editCtx = getChatMessageEditContext();
|
||||
|
||||
const isAgentic = $derived(hasAgenticContent(message, toolMessages));
|
||||
const processingState = useProcessingState();
|
||||
|
||||
let currentConfig = $derived(settingsStore.config);
|
||||
@@ -47,11 +47,13 @@
|
||||
|
||||
let showRawOutput = $state(false);
|
||||
|
||||
let displayedModel = $derived(message.model ?? null);
|
||||
// A reply that ran the agentic loop ( it called tools ) is an Agent Trace;
|
||||
// a basic chat reply is just its reasoning and its answer. A live reply
|
||||
// becomes a trace the moment its first tool call streams in.
|
||||
const isAgentTrace = $derived(hasAgenticContent(message, toolMessages));
|
||||
|
||||
let isCurrentlyLoading = $derived(chatStore.isLoading);
|
||||
let isStreaming = $derived(chatStore.isStreaming());
|
||||
let hasNoContent = $derived(!message?.content?.trim());
|
||||
let isActivelyProcessing = $derived(isCurrentlyLoading || isStreaming);
|
||||
// A compaction summary reports its own progress on the compaction row, so
|
||||
// this turn stays quiet while it runs instead of duplicating the indicator.
|
||||
@@ -67,21 +69,29 @@
|
||||
);
|
||||
let modelLoadingText = $derived(modelLoadProgressText(modelLoadProgress));
|
||||
|
||||
let showProcessingInfoTop = $derived(
|
||||
message?.role === MessageRole.ASSISTANT &&
|
||||
isActivelyProcessing &&
|
||||
!isCompacting &&
|
||||
hasNoContent &&
|
||||
!isAgentic &&
|
||||
isLastAssistantMessage
|
||||
// The model badge shows from the start of a live reply, before the first
|
||||
// chunk names the model, so the stats row does not pop in under the status
|
||||
let displayedModel = $derived(
|
||||
message.model ?? (isLastAssistantMessage && isActivelyProcessing ? loadTargetModel : null)
|
||||
);
|
||||
|
||||
let showProcessingInfoBottom = $derived(
|
||||
// What the server is doing while nothing is generated yet; null when this
|
||||
// message is not the live one. Empty while tokens are streaming.
|
||||
let statusText = $derived(
|
||||
message?.role === MessageRole.ASSISTANT &&
|
||||
isActivelyProcessing &&
|
||||
!isCompacting &&
|
||||
(!hasNoContent || isAgentic) &&
|
||||
isLastAssistantMessage
|
||||
? modelLoadingText ||
|
||||
processingState.getPromptProgressText() ||
|
||||
processingState.getProcessingMessage()
|
||||
: null
|
||||
);
|
||||
|
||||
// the latest exchange keeps its stats and actions in view; earlier messages
|
||||
// show them on hover, and the setting can keep their stats in view as well
|
||||
let hidesStatsUntilHover = $derived(
|
||||
!isLastAssistantMessage && !currentConfig[SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS]
|
||||
);
|
||||
|
||||
let assistantEl: HTMLDivElement | undefined = $state();
|
||||
@@ -151,7 +161,7 @@
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (showProcessingInfoTop || showProcessingInfoBottom) {
|
||||
if (statusText !== null) {
|
||||
processingState.startMonitoring();
|
||||
}
|
||||
});
|
||||
@@ -167,10 +177,6 @@
|
||||
class="chat-message-assistant text-md group w-full leading-7.5 {className}"
|
||||
role="group"
|
||||
>
|
||||
{#if showProcessingInfoTop}
|
||||
<ChatMessageAssistantProcessingInfo {modelLoadingText} position="top" {processingState} />
|
||||
{/if}
|
||||
|
||||
{#if editCtx.isEditing}
|
||||
<ChatMessageEditForm />
|
||||
{:else}
|
||||
@@ -182,23 +188,31 @@
|
||||
>
|
||||
{#if showRawOutput}
|
||||
<ChatMessageAssistantRawOutput {message} {toolMessages} />
|
||||
{:else}
|
||||
<ChatMessageAgenticContent
|
||||
|
||||
{#if statusText}
|
||||
<ChatMessageAssistantProcessingInfo text={statusText} />
|
||||
{/if}
|
||||
{:else if isAgentTrace}
|
||||
<ChatMessageAgentTrace
|
||||
{isLastAssistantMessage}
|
||||
isStreaming={chatStore.isStreaming()}
|
||||
{message}
|
||||
{statusText}
|
||||
{toolMessages}
|
||||
/>
|
||||
{:else}
|
||||
<ChatMessageAssistantResponse
|
||||
{isLastAssistantMessage}
|
||||
isStreaming={chatStore.isStreaming()}
|
||||
{message}
|
||||
{statusText}
|
||||
/>
|
||||
{/if}
|
||||
</ChatMessageContextMenu>
|
||||
{/if}
|
||||
|
||||
{#if showProcessingInfoBottom}
|
||||
<ChatMessageAssistantProcessingInfo {modelLoadingText} position="bottom" {processingState} />
|
||||
{/if}
|
||||
|
||||
{#if displayedModel}
|
||||
<div class="info my-6 grid gap-4 tabular-nums">
|
||||
<div class={['info my-4 grid gap-4 tabular-nums', hidesStatsUntilHover && 'message-meta']}>
|
||||
<div class="inline-flex flex-wrap items-start gap-2 text-caption text-muted-foreground">
|
||||
<ChatMessageAssistantModel
|
||||
{displayedModel}
|
||||
@@ -218,32 +232,41 @@
|
||||
{/if}
|
||||
|
||||
{#if message.timestamp && !editCtx.isEditing}
|
||||
<ChatMessageActionIcons
|
||||
actionsPosition="left"
|
||||
justify="start"
|
||||
onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
|
||||
onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
|
||||
{onRegenerate}
|
||||
rawOutputEnabled={showRawOutput}
|
||||
showRawOutputSwitch={currentConfig.showRawOutputSwitch}
|
||||
/>
|
||||
<div class={isLastAssistantMessage ? undefined : 'message-meta'}>
|
||||
<ChatMessageActionIcons
|
||||
actionsPosition="left"
|
||||
justify="start"
|
||||
onContinue={currentConfig.enableContinueGeneration ? onContinue : undefined}
|
||||
onRawOutputToggle={(enabled) => (showRawOutput = enabled)}
|
||||
{onRegenerate}
|
||||
rawOutputEnabled={showRawOutput}
|
||||
showRawOutputSwitch={currentConfig.showRawOutputSwitch}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
/* The reply's minimum height decides where a sent message rests once it
|
||||
glides up, and the top offset adds room above it. A phone's floating
|
||||
header covers the top of the page, so there it rests below the header. */
|
||||
:global(.chat-message):last-child .chat-message-assistant {
|
||||
--sent-message-top-offset: var(--page-top);
|
||||
--assistant-min-height-offset: calc(
|
||||
var(--last-user-message-height, 19rem) + var(--chat-form-height, 6rem) +
|
||||
var(--chat-form-bottom-position, 0.5rem) + var(--chat-form-padding-top, 6rem) +
|
||||
var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px)
|
||||
var(--assistant-margin-top, 1rem) + var(--chat-tabs-offset, 0px) +
|
||||
var(--sent-message-top-offset)
|
||||
);
|
||||
min-height: calc(100dvh - var(--assistant-min-height-offset));
|
||||
|
||||
@media (width > 768px) {
|
||||
--sent-message-top-offset: 0.5rem;
|
||||
--assistant-min-height-offset: calc(
|
||||
var(--last-user-message-height, 18rem) + var(--chat-form-height, 6rem) +
|
||||
var(--chat-form-bottom-position, 1rem) + var(--chat-form-padding-top, 6rem) +
|
||||
var(--assistant-margin-top, 3rem) + var(--chat-tabs-offset, 0px)
|
||||
var(--assistant-margin-top, 1rem) + var(--chat-tabs-offset, 0px) +
|
||||
var(--sent-message-top-offset)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-17
@@ -1,25 +1,15 @@
|
||||
<script lang="ts">
|
||||
import type { UseProcessingStateReturn } from '#lib/hooks/use-processing-state.svelte.ts';
|
||||
import { fade } from 'svelte/transition';
|
||||
// One status row for a reply that is waiting on the server: loading the
|
||||
// model, processing the prompt. It has the same box as a trace row, so
|
||||
// the row that comes next takes its place without moving what is below.
|
||||
|
||||
interface Props {
|
||||
modelLoadingText: string | null;
|
||||
processingState: UseProcessingStateReturn;
|
||||
position: 'top' | 'bottom';
|
||||
text: string;
|
||||
}
|
||||
|
||||
let { modelLoadingText, position, processingState }: Props = $props();
|
||||
|
||||
const marginClass = $derived(position === 'top' ? 'mt-6' : 'mt-4');
|
||||
let { text }: Props = $props();
|
||||
</script>
|
||||
|
||||
<div in:fade class="{marginClass} w-full max-w-3xl">
|
||||
<div class="flex flex-col items-start gap-2">
|
||||
<span class="shimmer-text text-body-sm">
|
||||
{modelLoadingText ??
|
||||
processingState.getPromptProgressText() ??
|
||||
processingState.getProcessingMessage() ??
|
||||
'Processing...'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="py-1.5 text-body-sm">
|
||||
<span class="shimmer-text font-medium">{text}</span>
|
||||
</div>
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
<script lang="ts">
|
||||
// A basic chat reply: the model's reasoning, if any, and its answer. A reply
|
||||
// that ran the agentic loop renders as an Agent Trace (ChatMessageAgentTrace)
|
||||
// instead, with its tool calls grouped into rows.
|
||||
|
||||
import ChatMessageReasoningBlock from '../../ChatMessageReasoningBlock.svelte';
|
||||
import ChatMessageAssistantProcessingInfo from './ChatMessageAssistantProcessingInfo.svelte';
|
||||
import { MarkdownContent } from '#lib/components/app/index.ts';
|
||||
import { REPLY_STATUS_FALLBACK } from '#lib/constants/index.ts';
|
||||
import { AgenticSectionType } from '#lib/enums/index.ts';
|
||||
import { agenticStore, settingsStore } from '#lib/stores/index.ts';
|
||||
import type { AgenticSection, DatabaseMessage } from '#lib/types/index.ts';
|
||||
import {
|
||||
deriveAgenticSections,
|
||||
isSectionExpandedByDefault,
|
||||
showsReplyStatus
|
||||
} from '#lib/utils/index.ts';
|
||||
|
||||
interface Props {
|
||||
message: DatabaseMessage;
|
||||
isStreaming?: boolean;
|
||||
isLastAssistantMessage?: boolean;
|
||||
/**
|
||||
* What the server is doing while this reply waits on it ( "Processing
|
||||
* 40%" ), empty while tokens stream, null when the reply is not live.
|
||||
*/
|
||||
statusText?: string | null;
|
||||
}
|
||||
|
||||
let {
|
||||
isLastAssistantMessage = false,
|
||||
isStreaming: isChatStreaming = false,
|
||||
message,
|
||||
statusText = null
|
||||
}: Props = $props();
|
||||
|
||||
// only the last assistant message is live; the chat-level flag is shared
|
||||
const isStreaming = $derived(isChatStreaming && isLastAssistantMessage);
|
||||
|
||||
let expandedStates: Record<number, boolean> = $state({});
|
||||
|
||||
const showThoughtInProgress = $derived(Boolean(settingsStore.config.showThoughtInProgress));
|
||||
|
||||
const hasReasoningError = $derived(
|
||||
isLastAssistantMessage ? !!agenticStore.getLastError(message.convId) : false
|
||||
);
|
||||
|
||||
const sections = $derived(deriveAgenticSections(message, [], [], isStreaming));
|
||||
|
||||
function isExpanded(index: number, section: AgenticSection): boolean {
|
||||
if (expandedStates[index] !== undefined) return expandedStates[index];
|
||||
|
||||
// a basic reply has no tool sections, so the two tool settings never apply
|
||||
return isSectionExpandedByDefault(section, {
|
||||
alwaysShowToolCallContent: false,
|
||||
showThoughtInProgress,
|
||||
showToolCallInProgress: false
|
||||
});
|
||||
}
|
||||
|
||||
function toggleExpanded(index: number, section: AgenticSection) {
|
||||
expandedStates[index] = !isExpanded(index, section);
|
||||
}
|
||||
|
||||
const showStatus = $derived(showsReplyStatus(statusText, sections.at(-1), isStreaming));
|
||||
</script>
|
||||
|
||||
<div class="assistant-response">
|
||||
{#each sections as section, index (index)}
|
||||
{#if section.type === AgenticSectionType.TEXT}
|
||||
<div class="assistant-response-text">
|
||||
<MarkdownContent attachments={message?.extra} content={section.content} />
|
||||
</div>
|
||||
{:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING}
|
||||
<ChatMessageReasoningBlock
|
||||
attachments={message?.extra}
|
||||
{hasReasoningError}
|
||||
{isStreaming}
|
||||
onToggle={() => toggleExpanded(index, section)}
|
||||
open={isExpanded(index, section)}
|
||||
{section}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
{#if showStatus}
|
||||
<ChatMessageAssistantProcessingInfo text={statusText || REPLY_STATUS_FALLBACK} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.assistant-response {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
max-width: 48rem;
|
||||
}
|
||||
|
||||
.assistant-response > :global(*) {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* the answer stands a little apart from the reasoning above it, as in a trace */
|
||||
.assistant-response > :global(:not(.assistant-response-text) + .assistant-response-text) {
|
||||
margin-top: 0.25rem;
|
||||
}
|
||||
</style>
|
||||
+31
-9
@@ -3,7 +3,9 @@
|
||||
// Renders section.toolArgs / section.toolResult directly using the
|
||||
// shared chrome shell.
|
||||
|
||||
import { simpleToolArgFields } from './parsers/tool-call-phrasing';
|
||||
import ToolCallBlock from './ToolCallBlock.svelte';
|
||||
import ToolCallTitle from './ToolCallTitle.svelte';
|
||||
import { Loader2 } from '@lucide/svelte';
|
||||
import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts';
|
||||
import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts';
|
||||
@@ -13,7 +15,6 @@
|
||||
import {
|
||||
classifyToolResult,
|
||||
formatJsonPretty,
|
||||
getToolUi,
|
||||
parseToolResultWithMedia
|
||||
} from '#lib/utils/index.ts';
|
||||
|
||||
@@ -27,14 +28,31 @@
|
||||
|
||||
let { attachments, isStreaming, onToggle, open, section }: Props = $props();
|
||||
|
||||
const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? '');
|
||||
const argFields = $derived(simpleToolArgFields(section.toolArgs));
|
||||
const outputKind = $derived(classifyToolResult(section.toolResult));
|
||||
const parsedLines: ToolResultLine[] = $derived(
|
||||
section.toolResult ? parseToolResultWithMedia(section.toolResult, attachments) : []
|
||||
);
|
||||
</script>
|
||||
|
||||
<ToolCallBlock {isStreaming} meta={null} {onToggle} {open} {section} {title}>
|
||||
{#snippet inputFields(fields: { label: string; value: string }[])}
|
||||
<dl class="grid grid-cols-[minmax(0,max-content)_minmax(0,1fr)] gap-x-6 gap-y-1 text-caption">
|
||||
{#each fields as field, i (i)}
|
||||
<dt class="text-muted-foreground">{field.label}</dt>
|
||||
|
||||
<dd class="min-w-0 font-mono break-words text-foreground/90">{field.value}</dd>
|
||||
{/each}
|
||||
</dl>
|
||||
{/snippet}
|
||||
|
||||
<ToolCallBlock {isStreaming} meta={null} {onToggle} {open} {section}>
|
||||
{#snippet titleSnippet(phrase)}
|
||||
<ToolCallTitle
|
||||
label={phrase.label}
|
||||
target={phrase.target && phrase.quoted ? `'${phrase.target}'` : phrase.target}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
{#snippet children(_meta, ctx)}
|
||||
{#if ctx.isStreamingCall}
|
||||
<div class="mb-2 flex items-center gap-2 text-caption text-muted-foreground/70">
|
||||
@@ -70,12 +88,16 @@
|
||||
<span>Input</span>
|
||||
</div>
|
||||
|
||||
<SyntaxHighlightedCode
|
||||
code={formatJsonPretty(section.toolArgs ?? '')}
|
||||
language={FileTypeText.JSON}
|
||||
maxHeight={MAX_HEIGHT_CODE_BLOCK}
|
||||
streaming={ctx.isCodeStreaming}
|
||||
/>
|
||||
{#if argFields}
|
||||
{@render inputFields(argFields)}
|
||||
{:else}
|
||||
<SyntaxHighlightedCode
|
||||
code={formatJsonPretty(section.toolArgs ?? '')}
|
||||
language={FileTypeText.JSON}
|
||||
maxHeight={MAX_HEIGHT_CODE_BLOCK}
|
||||
streaming={ctx.isCodeStreaming}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
<div
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user