Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
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
2 changes: 1 addition & 1 deletion common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3047,7 +3047,7 @@ void gpt_params_print_usage(int /*argc*/, char ** argv, const gpt_params & param
options.push_back({ "*", "-fa, --flash-attn (auto|on|off|0|1)", "set Flash Attention (default: %s)", params.flash_attn ? "on" : "off" });
options.push_back({ "*", "-mla, --mla-use", "enable MLA (default: %d)", params.mla_attn });
options.push_back({ "*", "-dsa, --dsa", "enable GLM DSA sparse attention (GLM-DSA arch only; default: %s)", params.dsa ? "enabled" : "disabled" });
options.push_back({ "*", "-fidx, --fused-indexer-topk", "enable the fused indexer topk op (DSA only; default: %s)", params.fused_idx_topk ? "enabled" : "disabled" });
options.push_back({ "*", "-fidx, --fused-indexer-topk", "force the fused indexer topk op (GLM DSA opt-in; OpenPangu selects it automatically on supporting backends)" });
options.push_back({ "*", "-dsatk, --dsa-top-k", "DSA top-k override; <0 uses the model's configured indexer_top_k (default: %d)", params.dsa_top_k });
options.push_back({ "*", "-amb, --attention-max-batch", "max batch size for attention computations (default: %d)", params.attn_max_batch});
options.push_back({ "*", "-no-fmoe, --no-fused-moe", "disable fused MoE (default: %s)", params.fused_moe_up_gate ? "enabled" : "disabled" });
Expand Down
2 changes: 1 addition & 1 deletion common/common.h
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ struct gpt_params {
bool rope_cache = false; // if to use RoPE cache (for supported models)
bool graph_reuse = true; // if to reuse compute graphs
bool dsa = false; // enable GLM DSA sparse attention (off by default; opt-in via --dsa)
bool fused_idx_topk = false; // enable the fused indexer topk op (off by default; opt-in via -fidx pr --fused-indexer-topk)
bool fused_idx_topk = false; // explicitly force fused indexer topk; OpenPangu also has a backend-gated automatic default
int dsa_top_k = -1; // DSA top-k override (<0 => use the model's configured indexer_top_k)
int min_experts = -1;
float thresh_experts = 0;
Expand Down
2 changes: 1 addition & 1 deletion docs/parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Some often used terms.
| `--dsa, -dsa` | | off | Enable GLM DSA sparse attention [PR 2045](https://github.com/ikawrakow/ik_llama.cpp/pull/2045) |
| `--dsa-top-k, -dsatk` | DSA top-k override | -1 | `<0` uses the model's configured `indexer_top_k` [PR 2045](https://github.com/ikawrakow/ik_llama.cpp/pull/2045) |
| `--indexer-cache-type-k type, -ictk` | Indexer K-cache data type | off | Use quantized indexer cache [PR 2075](https://github.com/ikawrakow/ik_llama.cpp/pull/2075) |
| `--fused-indexer-topk, -fidx` | Enable the fused indexer topk op | disabled | Use a dedicated op for computing the DSA indexer top_k KV cache entries [PR 2098](https://github.com/ikawrakow/ik_llama.cpp/pull/2098) |
| `--fused-indexer-topk, -fidx` | Force the fused indexer topk op | GLM DSA: disabled; OpenPangu: automatic on supporting backends | Use a dedicated op for computing the DSA indexer top_k KV cache entries. OpenPangu selects it automatically only when the scheduled backend supports the exact node. GLM DSA remains explicit opt-in. Bring-up switch (compile-time): build with `-DGGML_OPENPANGU_LEGACY_OPS=1` to force the legacy chain for every OpenPangu fused/specialized op (indexer top-k, latent attention, fused RMSNorm+add, offset RoPE, batched mix, pack-cache-rows) at once; the default build (undefined or 0) selects the capability-gated fused paths. The effective policy is reported in the model load log (`openpangu_ops`). [PR 2098](https://github.com/ikawrakow/ik_llama.cpp/pull/2098) |
| `-amb, --attention-max-batch` | Max batch size for attention computations | 0 | Specifies the maximum K*Q size in MB we want to tolerate. [PR 237](https://github.com/ikawrakow/ik_llama.cpp/pull/237) |
| `-fmoe or --fused-moe` | Fused MoE ffn_up and ffn_gate | - | Speedup for MoE models. [PR 229](https://github.com/ikawrakow/ik_llama.cpp/pull/229) |
| `--no-fmoe, --no-fused-moe` | Disable fused MoE | Enabled | See `--fused-moe` |
Expand Down
164 changes: 164 additions & 0 deletions ggml/include/ggml.h
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,11 @@ extern "C" {
GGML_OP_INDEXER_TOPK,
GGML_OP_MASK_TOPK,
GGML_OP_SINKHORN,
GGML_OP_LATENT_ATTN,
GGML_OP_FUSED_RMS_NORM_ADD,
GGML_OP_ROPE_OFFSET,
GGML_OP_BATCHED_MIX,
GGML_OP_PACK_CACHE_ROWS,

GGML_OP_COUNT,
};
Expand Down Expand Up @@ -1556,6 +1561,26 @@ extern "C" {
struct ggml_tensor * b,
float eps);

// Computes rms_norm(a, eps)*weight + residual. a and residual must be
// same-shape F32 tensors with contiguous row elements. Their effective data
// addresses and view offsets, plus the higher-dimensional strides for
// dimensions with more than one element, must be aligned to sizeof(float).
// weight may be NULL (unit weight) or a broadcastable F32/F16 tensor;
// noncanonical weights use a decomposed conversion/copy path instead of
// GGML_OP_FUSED_RMS_NORM_ADD. A canonical fused F32 weight must also have a
// float-aligned effective data address and view offset.
// All dimensions must be positive. All fused-path F32 tensor byte spans and
// the contiguous F32 result size must be representable by ptrdiff_t. CUDA
// also requires the logical row count to fit the device's grid-X limit.
// Automatic differentiation is not supported; gradient-bearing inputs are
// rejected at construction.
GGML_API struct ggml_tensor * ggml_fused_rms_norm_add(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * weight,
struct ggml_tensor * residual,
float eps);

GGML_API struct ggml_tensor * ggml_fused_norm(
struct ggml_context * ctx,
struct ggml_tensor * a,
Expand Down Expand Up @@ -1784,6 +1809,31 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * b);

// Pack two F32 channel regions directly into a row-strided persistent cache.
// Sources must use float-aligned effective addresses, view offsets, and row strides. The
// cache root, row stride, and dst_offset must be aligned for its F32, F16, or Q8_0 access.
// The returned tensor aliases cache at dst_offset and has shape [a.ne0+b.ne0, a.ne1].
GGML_API struct ggml_tensor * ggml_pack_cache_rows(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
struct ggml_tensor * cache,
size_t dst_offset);

// True iff ggml_pack_cache_rows would build without aborting; precheck to fall back to the
// legacy concat+cpy cache write on an unsupported layout instead of crashing.
GGML_API bool ggml_pack_cache_rows_valid(
const struct ggml_tensor * a,
const struct ggml_tensor * b,
const struct ggml_tensor * cache,
size_t dst_offset);

// Retarget an existing pack mutation to another in-bounds cache row. The new offset must
// preserve the destination type alignment required by ggml_pack_cache_rows().
GGML_API void ggml_pack_cache_rows_set_dst_offset(
struct ggml_tensor * pack,
size_t dst_offset);

GGML_API struct ggml_tensor * ggml_cast(
struct ggml_context * ctx,
struct ggml_tensor * a,
Expand Down Expand Up @@ -2047,6 +2097,36 @@ extern "C" {
float beta_fast,
float beta_slow);

// F32 contiguous NeoX RoPE over [rot_off, rot_off + n_dims), copying all
// other channels. a must not carry a gradient and must have ne[3] == 1.
// b must be a packed contiguous I32 vector of length a->ne[2]. Frequency
// factors are not supported (c must be NULL).
GGML_API struct ggml_tensor * ggml_rope_ext_offset(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
struct ggml_tensor * c,
int n_dims,
int rot_off,
int mode,
int n_ctx_orig,
float freq_base,
float freq_scale,
float ext_factor,
float attn_factor,
float beta_fast,
float beta_slow);

// True iff ggml_rope_ext_offset would build without aborting; precheck to fall back to the
// legacy rope chain on an unsupported layout instead of crashing in the constructor.
GGML_API bool ggml_rope_ext_offset_valid(
const struct ggml_tensor * a,
const struct ggml_tensor * b,
const struct ggml_tensor * c,
int n_dims,
int rot_off,
int mode);

GGML_API struct ggml_tensor * ggml_rope_multi(
struct ggml_context * ctx,
struct ggml_tensor * a,
Expand Down Expand Up @@ -2484,6 +2564,67 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * sinks);

// Latent attention over a packed K/V cache with an independently-visible K/V prefix.
// The value vector of cache row n is cache[dv_off .. dv_off+dv, n] (MLA "absorbed"
// layout: openPangu packs [ckv|k_pe] -> dv_off=0; DeepSeek/GLM_DSA packs [k_pe|ckv]
// rope-first -> dv_off=64). The prefix K/V rows are always visible (bias 0); the mask
// applies to the cache segment only.
//
// q: [Dk, T, H] F32, contiguous
// cache: [Dk, N] F32 / F16 / Q8_0; row stride nb[1] arbitrary (windowed views ok)
// prefix_k: [Dk, P] F32 / F16, contiguous; NULL iff P == 0
// prefix_v: [P, Dv] F32 / F16, contiguous (value-transposed: ne0 = P); NULL iff P == 0
// mask: [N, >=T] F32, additive, cache segment only; NULL = unmasked cache
// returns: [Dv, T, H] F32, contiguous
// Precondition: every query column must have at least one visible position (a prefix row,
// or a cache row not masked to -inf). Violating it is undefined: a fully-masked column with
// P == 0 yields NaN on CUDA and on the CPU dense path, and zeros on the CPU indexed path, so
// callers must not depend on the value. Inference-only: a gradient-bearing input is rejected.
GGML_API struct ggml_tensor * ggml_latent_attn_prefix_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * cache,
struct ggml_tensor * prefix_k,
struct ggml_tensor * prefix_v,
struct ggml_tensor * mask,
int dv,
int dv_off,
float scale,
float max_bias);

// Indexed latent attention over absolute cache row ids shared across heads.
// indices: [topk, T] I32, contiguous; mask remains [N, >=T] and is gathered by index.
// Preconditions: each index must lie in [0, N); an out-of-range id aborts on CPU and is
// undefined behavior (an out-of-bounds device read) on CUDA. The visible-position and
// inference-only preconditions above apply here as well.
GGML_API struct ggml_tensor * ggml_latent_attn_indexed_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * cache,
struct ggml_tensor * prefix_k,
struct ggml_tensor * prefix_v,
struct ggml_tensor * mask,
struct ggml_tensor * indices,
int dv,
int dv_off,
float scale,
float max_bias);

// True iff the two constructors above would build the op without aborting (mode 0 = prefix,
// mode 1 = indexed). Precheck this to fall back to the legacy attention chain on a layout the
// fused op cannot represent, instead of crashing in the constructor.
GGML_API bool ggml_latent_attn_ext_valid(
const struct ggml_tensor * q,
const struct ggml_tensor * cache,
const struct ggml_tensor * prefix_k,
const struct ggml_tensor * prefix_v,
const struct ggml_tensor * mask,
const struct ggml_tensor * indices,
int dv,
int dv_off,
float max_bias,
int mode);

// TODO: needs to be adapted to ggml_flash_attn_ext
GGML_API struct ggml_tensor * ggml_flash_attn_back(
struct ggml_context * ctx,
Expand Down Expand Up @@ -2605,6 +2746,29 @@ extern "C" {
float eps,
bool output_transposed);

// Strided token-batched contraction over a small non-leading axis.
//
// r: [D, J, T] F32; nb[0] == sizeof(float), higher strides arbitrary
// mix: [J, O, T] F32; nb[0] == sizeof(float), higher strides arbitrary
// returns: [D, O, T] F32, contiguous
//
// Used higher strides, effective data addresses, and absolute view offsets
// must be float-aligned. Input byte spans must be ptrdiff_t-representable
// and contained by their root view sources.
//
// Computes out[d,o,t] = sum_j r[d,j,t] * mix[j,o,t]. Automatic
// differentiation is not supported; gradient-bearing inputs are rejected.
GGML_API struct ggml_tensor * ggml_batched_mix_ext(
struct ggml_context * ctx,
struct ggml_tensor * r,
struct ggml_tensor * mix);

// True iff ggml_batched_mix_ext would build without aborting; precheck to fall back to the
// legacy per-slot mix loop on an unsupported layout instead of crashing.
GGML_API bool ggml_batched_mix_ext_valid(
const struct ggml_tensor * r,
const struct ggml_tensor * mix);

// custom operators

typedef void (*ggml_unary_op_f32_t) (const int, float *, const float *);
Expand Down
37 changes: 34 additions & 3 deletions ggml/src/ggml-backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
#include "ggml-impl.h"
#include "ggml-rpc.h"
#include "ggml-moe-prefetch.h"
#include "ggml-pack-cache-rows.h"
#ifdef GGML_USE_IQK_MULMAT
#include "iqk/iqk_mul_mat.h"
#endif

#include <cassert>
#include <climits>
Expand Down Expand Up @@ -896,21 +900,40 @@ 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
op->type != GGML_TYPE_IQ2_XXS &&
op->type != GGML_TYPE_IQ2_XS &&
op->type != GGML_TYPE_IQ1_S &&
op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
case GGML_OP_PACK_CACHE_ROWS:
return ggml_pack_cache_rows_op_is_valid(op);
case GGML_OP_LATENT_ATTN:
// The CPU LATENT_ATTN implementation is a scalar per-query-row reference kept for
// correctness/testing, not a throughput path. Report no CPU support so a capability
// gate anchored to a CPU-resident weight (a CPU-only or -ngl 0 run) keeps the
// vectorized legacy attention chain instead of silently adopting the reference op.
// Direct graph compute of a LATENT_ATTN node on the CPU backend still runs the
// reference; only scheduler auto-placement is declined here.
return false;
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,13 +1754,21 @@ 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;
if (node->op == GGML_OP_REDUCE) {
sched->has_reduce = true;
}
// The last op_params slot doubles as a force-new-split sentinel (== 0xff). Ops that
// store data there must keep it != 0xff: GGML_OP_ROPE_OFFSET stores an even rot_off
// (asserted rot_off % 2 == 0), so its value can never be 0xff (255, odd).
if ((node->op == GGML_OP_ADD && node->op_params[0] == 0xff) ||
node->op == GGML_OP_REDUCE ||
node->op == GGML_OP_FAKE_CPY ||
Expand Down
62 changes: 62 additions & 0 deletions ggml/src/ggml-batched-mix.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#pragma once

#include "ggml.h"

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

// Shared CPU/CUDA contract for tensors consumed or produced by
// GGML_OP_BATCHED_MIX. Higher strides are arbitrary, but every effective F32
// address must remain element-aligned and the full byte span must be both
// ptrdiff_t-representable and contained by the root view source.
static inline bool ggml_batched_mix_f32_span_bytes(
const struct ggml_tensor * tensor, size_t * span_out) {
if (tensor == NULL || tensor->type != GGML_TYPE_F32 || tensor->nb[0] != sizeof(float)) {
return false;
}

const size_t max_span = (size_t) PTRDIFF_MAX;
size_t span = sizeof(float);
for (int i = 0; i < GGML_MAX_DIMS; ++i) {
if (tensor->ne[i] <= 0) {
return false;
}
const size_t extent = (size_t) (tensor->ne[i] - 1);
if (extent > 0 && tensor->nb[i] > (max_span - span)/extent) {
return false;
}
span += extent*tensor->nb[i];
}

*span_out = span;
return true;
}

static inline bool ggml_batched_mix_f32_layout_is_valid(const struct ggml_tensor * tensor) {
size_t span = 0;
if (!ggml_batched_mix_f32_span_bytes(tensor, &span)) {
return false;
}
if (tensor->view_offs % sizeof(float) != 0 ||
(tensor->data != NULL && (uintptr_t) tensor->data % sizeof(float) != 0)) {
return false;
}
for (int i = 1; i < GGML_MAX_DIMS; ++i) {
if (tensor->ne[i] > 1 && tensor->nb[i] % sizeof(float) != 0) {
return false;
}
}

if (tensor->view_src == NULL) {
return tensor->view_offs == 0;
}

size_t source_span = 0;
if (!ggml_batched_mix_f32_span_bytes(tensor->view_src, &source_span) ||
tensor->view_src->view_src != NULL || tensor->view_offs > source_span ||
span > source_span - tensor->view_offs) {
return false;
}
return tensor->view_offs <= (size_t) PTRDIFF_MAX - span;
}
Loading