Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions ggml/src/ggml-backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
#include "ggml-impl.h"
#include "ggml-rpc.h"
#include "ggml-moe-prefetch.h"
#ifdef GGML_USE_IQK_MULMAT
#include "iqk/iqk_mul_mat.h"
#endif

#include <cassert>
#include <climits>
Expand Down Expand Up @@ -896,6 +899,11 @@ GGML_CALL static enum ggml_status ggml_backend_cpu_graph_compute(ggml_backend_t
}

GGML_CALL static bool ggml_backend_cpu_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
#ifdef GGML_USE_IQK_MULMAT
struct ggml_backend_cpu_context * cpu_ctx = (struct ggml_backend_cpu_context *) backend->context;
#else
GGML_UNUSED(backend);
#endif
switch (op->op) {
case GGML_OP_CPY:
return
Expand All @@ -906,11 +914,15 @@ GGML_CALL static bool ggml_backend_cpu_supports_op(ggml_backend_t backend, const
case GGML_OP_MUL_MAT:
return true;
//return op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == ggml_internal_get_type_traits(op->src[0]->type).vec_dot_type;
case GGML_OP_INDEXER_TOPK:
#ifdef GGML_USE_IQK_MULMAT
return iqk_indexer_topk_supported(op, cpu_ctx->n_threads);
#else
return false;
#endif
default:
return true;
}

GGML_UNUSED(backend);
}

GGML_CALL static bool ggml_backend_cpu_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
Expand Down Expand Up @@ -1731,7 +1743,12 @@ static void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct gg

const int node_backend_id = tensor_backend_id(node);

assert(node_backend_id != -1); // all nodes should be assigned by now
// GGML_ASSERT (not assert) so an op that no backend supports fails as a defined
// abort even under NDEBUG, rather than falling through to sched->backends[-1] (UB).
// Reachable only in a build where the sole backend's supports_op rejects a node
// (e.g. INDEXER_TOPK on a CPU-only, non-IQK build); such configs already could not
// run the op, so this preserves base's diagnosable failure instead of a silent crash.
GGML_ASSERT(node_backend_id != -1 && "op has no supporting backend");

// check if we should start a new split based on the sources of the current node
bool need_new_split = false;
Expand Down
14 changes: 14 additions & 0 deletions ggml/src/ggml-cuda.cu
Original file line number Diff line number Diff line change
Expand Up @@ -4435,6 +4435,7 @@ static void set_ggml_graph_node_properties(ggml_tensor * node, ggml_graph_node_p
}
for (int i = 0; i < GGML_MAX_SRC; i++) {
graph_node_properties->src_address[i] = node->src[i] ? node->src[i]->data : nullptr;
graph_node_properties->src_type[i] = node->src[i] ? node->src[i]->type : GGML_TYPE_COUNT;
}
memcpy(graph_node_properties->op_params, node->op_params, GGML_MAX_OP_PARAMS);
}
Expand Down Expand Up @@ -4474,6 +4475,19 @@ static bool ggml_graph_node_has_matching_properties(ggml_tensor * node, ggml_gra
return false;
}

// INDEXER_TOPK dispatches a source-type-specialized kernel (dense F16 vs quantized cache,
// and an F32 vs F16 mask variant). Source addresses alone do not identify the captured
// kernel, so a reused graph whose sources were reallocated at the same addresses with a
// different type would replay the wrong kernel. Force re-capture when a source type changes.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You actually ran into this situation? Can you share how?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You actually ran into this situation? Can you share how?

Yes, but this came from a focused INDEXER_TOPK test harness, not from changing cache types inside one openPangu context.

The harness creates one CUDA backend and then runs three same-shape fixtures sequentially: F16 K with an F32 mask, F16 K with an F16 mask, then Q8_0 K with an F32 mask. Each fixture frees its backend buffer before the next one, but the CUDA backend and its graph cache remain alive. The allocator reused the same source addresses.

With CUDA graphs enabled, the matcher accepted the later graph because the output shape/strides, source addresses, and op parameters matched. It did not see that the source types had changed, so INDEXER_TOPK replayed the previously captured type-specialized kernel. The numeric reference/parity check failed. The same sequence passed with CUDA graphs disabled.

Recording the source types forced a recapture and made the graphs-enabled sequence pass. So I did hit the exact same-address/different-type case, but in a deliberate same-process test. I should have made that distinction clear in the description.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, theoretically the graph capture/comparison logic can fail in gazillions of different ways. If we wanted to guard against all possible failure modes, but at the same time still be able to reuse captured graphs, it would become way more complicated and possibly so expensive that it wouldn't bring any benefits to use it. But fortunately for us, we are not writing airplane control software here, so we go by actual usage in the inference engine only.

if (node->op == GGML_OP_INDEXER_TOPK) {
for (int i = 0; i < GGML_MAX_SRC; i++) {
const ggml_type src_type = node->src[i] ? node->src[i]->type : GGML_TYPE_COUNT;
if (src_type != graph_node_properties->src_type[i]) {
return false;
}
}
}

return true;
}

Expand Down
1 change: 1 addition & 0 deletions ggml/src/ggml-cuda/graph.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ struct ggml_graph_node_properties {
int64_t ne[GGML_MAX_DIMS];
size_t nb[GGML_MAX_DIMS];
void * src_address[GGML_MAX_SRC];
ggml_type src_type[GGML_MAX_SRC];
int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)];
};

Expand Down
4 changes: 2 additions & 2 deletions ggml/src/ggml-cuda/indexer_topk.cu
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ void ggml_cuda_op_indexer_topk(ggml_backend_cuda_context & ctx, ggml_tensor * ds
ggml_cuda_pool_alloc<char> q_converted(ctx.pool());
auto q_padded = GGML_PAD(q->ne[0], MATRIX_ROW_PADDING);
if (ggml_is_quantized(k->type)) {
auto nbytes_q = q->ne[1] * max_rows * sizeof(block_q8_1)/QK8_1;
auto nbytes_q = (size_t)(q_padded/QK8_1) * ((size_t) q->ne[1] * max_rows) * sizeof(block_q8_1);
nbytes_q += get_mmq_x_max_host(ggml_cuda_info().devices[ctx.device].cc)*sizeof(block_q8_1_mmq);
q_converted.alloc(nbytes_q);
} else {
Expand All @@ -177,7 +177,7 @@ void ggml_cuda_op_indexer_topk(ggml_backend_cuda_context & ctx, ggml_tensor * ds
auto q_data = (const char *)q->data + istep*max_rows*q->nb[2];
auto m_data = (const char *)m->data + istep*max_rows*m->nb[1];
if (ggml_is_quantized(k->type)) {
quantize_mmq_q8_1_cuda((const float *)q_data, q_converted.get(), q->ne[0], nrows, 1, q_padded, k->type, ctx.stream());
quantize_mmq_q8_1_cuda((const float *)q_data, q_converted.get(), q->ne[0], q->ne[1]*nrows, 1, q_padded, k->type, ctx.stream());
CUDA_CHECK(cudaGetLastError());
mmq_args args{(const char *)k->data, q_converted.get(), kq.get(),
k->ne[0], k->ne[1], int64_t(k->nb[1]),
Expand Down
166 changes: 165 additions & 1 deletion ggml/src/iqk/iqk_mul_mat.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
#include <type_traits>
#include <vector>
#include <algorithm>
#include <climits>
#include <limits>

#include "ggml-impl.h"
#include "ggml-quants.h"
Expand Down Expand Up @@ -1737,6 +1739,157 @@ bool iqk_fused_delta_net(int head_dim, int n_heads, int gqa_ratio, int repeat_ty
}

namespace {
bool iqk_checked_mul_size(size_t a, size_t b, size_t & result) {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sort of thing can only be written by an LLM. Let me see: suppose we handle correctly size_t overflow. Do we expect that a situation where we are dealing with number if operations greater than the maximum value of size_t on a 64-bit platform to ever complete? On a 10 TFlop CPU this will take several days.

if (a != 0 && b > std::numeric_limits<size_t>::max()/a) {
return false;
}
result = a*b;
return true;
}

bool iqk_checked_add_size(size_t a, size_t b, size_t & result) {
if (b > std::numeric_limits<size_t>::max() - a) {
return false;
}
result = a + b;
return true;
}

bool iqk_plain_layout_supported(const ggml_tensor * tensor, ggml_type type, int used_dims) {
if (tensor == nullptr || tensor->type != type || used_dims < 1 || used_dims > GGML_MAX_DIMS) {
return false;
}
const size_t element_size = ggml_type_size(type);
if (tensor->nb[0] != element_size || tensor->view_offs % element_size != 0 ||
(tensor->data != nullptr && (uintptr_t) tensor->data % element_size != 0)) {
return false;
}
size_t extent = element_size;
for (int i = 0; i < used_dims; ++i) {
if (tensor->ne[i] <= 0 || (i > 0 && tensor->nb[i] < extent)) {
return false;
}
size_t offset = 0;
if (!iqk_checked_mul_size((size_t) (tensor->ne[i] - 1), tensor->nb[i], offset) ||
!iqk_checked_add_size(offset, extent, extent)) {
return false;
}
}
size_t end = 0;
return iqk_checked_add_size(tensor->view_offs, extent, end);
}

bool iqk_k_layout_supported(const ggml_tensor * k) {
if (k == nullptr || k->type < 0 || k->type >= GGML_TYPE_COUNT) {
return false;
}
const int64_t block_size = ggml_blck_size(k->type);
if (block_size <= 0 || k->ne[0] <= 0 || k->ne[0] % block_size != 0) {
return false;
}
const size_t type_size = ggml_type_size(k->type);
size_t row_size = 0;
size_t row_offset = 0;
size_t span = 0;
size_t end = 0;
return type_size > 0 && k->nb[0] == type_size &&
k->view_offs % type_size == 0 &&
(k->data == nullptr || (uintptr_t) k->data % alignof(uint16_t) == 0) &&
iqk_checked_mul_size((size_t) (k->ne[0]/block_size), type_size, row_size) &&
k->nb[1] >= row_size &&
iqk_checked_mul_size((size_t) (k->ne[1] - 1), k->nb[1], row_offset) &&
iqk_checked_add_size(row_offset, row_size, span) &&
iqk_checked_add_size(k->view_offs, span, end);
}

bool iqk_indexer_topk_contract_supported(const ggml_tensor * dst, int nthread) {
if (dst == nullptr || dst->op != GGML_OP_INDEXER_TOPK || nthread <= 0 ||
ggml_unary_op(dst->op_params[0]) != GGML_UNARY_OP_RELU) {
return false;
}
const ggml_tensor * k = dst->src[0];
const ggml_tensor * q = dst->src[1];
const ggml_tensor * w = dst->src[2];
const ggml_tensor * m = dst->src[3];
if (k == nullptr || q == nullptr || w == nullptr || m == nullptr) {
return false;
}

const int64_t d = k->ne[0];
const int64_t n_kv = k->ne[1];
const int64_t n_head = q->ne[1];
const int64_t n_tokens = q->ne[2];
const int64_t n_top_k = dst->ne[0];
if (d <= 0 || n_kv <= 0 || n_head <= 0 || n_tokens <= 0 || n_top_k <= 0 ||
d > INT_MAX || n_kv > INT_MAX || n_head > INT_MAX || n_tokens > INT_MAX ||
n_top_k > INT_MAX || n_top_k >= n_kv ||
k->ne[2] != 1 || k->ne[3] != 1 ||
q->ne[0] != d || q->ne[3] != 1 ||
w->ne[0] != n_head || w->ne[1] != n_tokens || w->ne[2] != 1 || w->ne[3] != 1 ||
m->ne[0] != n_kv || m->ne[1] != n_tokens || m->ne[2] != 1 || m->ne[3] != 1 ||
dst->ne[1] != n_tokens || dst->ne[2] != 1 || dst->ne[3] != 1 ||
!iqk_k_layout_supported(k) ||
!iqk_plain_layout_supported(q, GGML_TYPE_F32, 3) ||
!iqk_plain_layout_supported(w, GGML_TYPE_F32, 2) ||
!iqk_plain_layout_supported(dst, GGML_TYPE_I32, 2) ||
(m->type != GGML_TYPE_F32 && m->type != GGML_TYPE_F16) ||
!iqk_plain_layout_supported(m, m->type, 2)) {
return false;
}

const auto tt = ggml_internal_get_type_traits(k->type);
ggml_type q_type = q->type;
size_t quantize_size = 0;
if (tt.is_quantized && tt.vec_dot_type != q->type) {
const auto ttq = ggml_internal_get_type_traits(tt.vec_dot_type);
if (ttq.from_float == nullptr || q->nb[1] != (size_t) d*sizeof(float)) {
return false;
}
q_type = tt.vec_dot_type;
if (d % ggml_blck_size(q_type) != 0) {
return false;
}
const size_t row_size_q = ggml_row_size(q_type, d);
if (!iqk_checked_mul_size(row_size_q, (size_t) n_head, quantize_size)) {
return false;
}
}

MulMat mm;
if (!MulMat::prepare(int(k->type), int(q_type), int(d), mm, int(n_head)) ||
(n_tokens < nthread && n_kv % 32 != 0)) {
return false;
}

size_t kq_size = 0;
size_t score_size = 0;
size_t sorted_size = 0;
size_t work_size = quantize_size;
if (!iqk_checked_mul_size((size_t) n_kv, (size_t) n_head, kq_size) ||
!iqk_checked_mul_size(kq_size, sizeof(float), kq_size) ||
!iqk_checked_mul_size((size_t) n_kv, sizeof(float), score_size) ||
!iqk_checked_mul_size((size_t) n_kv, sizeof(int32_t), sorted_size)) {
return false;
}
if (n_tokens < nthread && quantize_size != 0 &&
!iqk_checked_mul_size(quantize_size, (size_t) n_tokens, work_size)) {
return false;
}
if (!iqk_checked_add_size(work_size, kq_size, work_size) ||
!iqk_checked_add_size(work_size, score_size, work_size) ||
!iqk_checked_add_size(work_size, sorted_size, work_size)) {
return false;
}
if (n_tokens >= nthread) {
if (work_size > std::numeric_limits<size_t>::max() - 127) {
return false;
}
work_size = GGML_PAD(work_size, 128);
return iqk_checked_mul_size(work_size, (size_t) nthread, work_size);
}
return true;
}

size_t iqk_idx_topk_work_wbs_per_thread(const struct ggml_tensor * dst, int nth) {
auto k = dst->src[0];
auto q = dst->src[1];
Expand All @@ -1763,7 +1916,14 @@ inline void iqk_f16_to_f32(int n, const ggml_fp16_t * x, float * y) {
}
}

bool iqk_indexer_topk_supported(const struct ggml_tensor * dst, int nthread) {
return iqk_indexer_topk_contract_supported(dst, nthread);
}

size_t iqk_idx_topk_work_buffer_size(const struct ggml_tensor * dst, int nthread) {
if (!iqk_indexer_topk_supported(dst, nthread)) {
return 0;
}
auto k = dst->src[0];
auto q = dst->src[1];
if (q->ne[2] >= nthread) {
Expand All @@ -1782,7 +1942,7 @@ size_t iqk_idx_topk_work_buffer_size(const struct ggml_tensor * dst, int nthread
}

bool iqk_indexer_topk(struct ggml_tensor * dst, void * work_buffer, barrier_t barrier, void * barrier_data, int ith, int nth) {
if (dst->op != GGML_OP_INDEXER_TOPK) {
if (!iqk_indexer_topk_supported(dst, nth)) {
return false;
}
auto op = ggml_unary_op(dst->op_params[0]);
Expand Down Expand Up @@ -1975,6 +2135,10 @@ bool iqk_indexer_topk(struct ggml_tensor *, void *, barrier_t, void *, int, int)
return false;
}

bool iqk_indexer_topk_supported(const struct ggml_tensor *, int) {
return false;
}

size_t iqk_idx_topk_work_buffer_size(const struct ggml_tensor *, int) {
return 0;
}
Expand Down
1 change: 1 addition & 0 deletions ggml/src/iqk/iqk_mul_mat.h
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ IQK_API bool iqk_fused_delta_net(int head_dim, int n_heads, int gqa_ratio, int r
const float * state_in, float * out_data, float * state_out, float * saved_steps, int state_step_stride, int ith, int nth);

IQK_API bool iqk_indexer_topk(struct ggml_tensor * dst, void * work_buffer, barrier_t barrier, void * barrier_data, int ith, int nth);
IQK_API bool iqk_indexer_topk_supported(const struct ggml_tensor * dst, int nthread);
IQK_API size_t iqk_idx_topk_work_buffer_size(const struct ggml_tensor * dst, int nthread);

#ifdef __cplusplus
Expand Down