Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions ggml/include/ggml.h
Original file line number Diff line number Diff line change
Expand Up @@ -2927,6 +2927,16 @@ extern "C" {
// non-float source it must differentiate), with why, else NULL: the graphs on which
// ggml_build_backward_expand would abort, for a caller that must refuse instead.
GGML_API struct ggml_tensor * ggml_graph_backward_refusal(const struct ggml_cgraph * cgraph, const char ** why);
// Builds the backward into cgraph, or returns the first node it cannot build (with why, which
// must be non-NULL), else NULL: a node ggml_graph_backward_refusal names, or one whose backward
// gave a source no gradient or one of another shape. A refused graph is half built: discard it.
// For a caller that must refuse instead of aborting (training inside a serving process).
GGML_API struct ggml_tensor * ggml_build_backward_expand_or_refuse(
struct ggml_context * ctx, // context for gradient computation
struct ggml_cgraph * cgraph,
struct ggml_tensor ** grad_accs,
const char ** why);
// ggml_build_backward_expand_or_refuse that aborts on a refusal, naming the node and why
GGML_API void ggml_build_backward_expand(
struct ggml_context * ctx, // context for gradient computation
struct ggml_cgraph * cgraph,
Expand Down
16 changes: 15 additions & 1 deletion ggml/src/ggml-opt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -797,7 +797,21 @@ static bool ggml_opt_build(ggml_opt_context_t opt_ctx) {

// gb_grad == graph backward gradients, forward pass, then backward pass to calculate gradients.
opt_ctx->gb_grad = ggml_graph_dup(opt_ctx->ctx_compute, opt_ctx->gf, /*force_grads =*/ true);
ggml_build_backward_expand(opt_ctx->ctx_compute, opt_ctx->gb_grad, opt_ctx->grad_accs.data());
// A backward that breaks its own contract on this graph's shapes (a source given a gradient of
// another shape) is refused like a node without one, before anything is allocated: asserted,
// it aborted the M5's serving engine mid-act (the MoE router's broadcast divisor, 2026-11-07).
{
const char * why = nullptr;
if (const ggml_tensor * node = ggml_build_backward_expand_or_refuse(
opt_ctx->ctx_compute, opt_ctx->gb_grad, opt_ctx->grad_accs.data(), &why)) {
opt_ctx->gb_grad = nullptr; // half built: never reset, duplicated or allocated
opt_ctx->gb_opt = nullptr;
opt_ctx->refusal = std::string("the training graph's backward cannot be built through ") + ggml_op_desc(node)
+ " (node \"" + node->name + "\"): " + why + "; nothing was allocated and serving is unaffected";
GGML_LOG_ERROR("%s: %s\n", __func__, opt_ctx->refusal.c_str());
return false;
}
}
opt_ctx->leaf_grads.clear();
for (int i = 0; i < opt_ctx->gf->n_nodes; ++i) {
ggml_tensor * node = opt_ctx->gf->nodes[i];
Expand Down
79 changes: 65 additions & 14 deletions ggml/src/ggml.c
Original file line number Diff line number Diff line change
Expand Up @@ -6706,6 +6706,11 @@ static void ggml_hash_map_free(struct hash_map * map) {
// else if there is no gradient for tensor, set the corresponding value
// else, just add/subtract/etc. the gradients

// whether the gradient the backward formed for src has src's shape
static bool ggml_backward_grad_fits(const struct ggml_cgraph * cgraph, const struct ggml_tensor * src, size_t isrc) {
return cgraph->grads[isrc] != NULL && ggml_are_same_shape(src, cgraph->grads[isrc]);
}

static void ggml_add_or_set(
struct ggml_context * ctx,
struct ggml_cgraph * cgraph,
Expand Down Expand Up @@ -7145,13 +7150,15 @@ static bool ggml_backward_reaches_src(const struct ggml_tensor * node, int j) {
}
}

static void ggml_compute_backward(
// Returns NULL, or why the gradients it formed break the backward's contract (each source that
// needs a gradient receives one of its own shape): the graph is then refused, never computed.
static const char * ggml_compute_backward(
struct ggml_context * ctx, struct ggml_cgraph * cgraph, int i, const bool * grads_needed) {
struct ggml_tensor * tensor = cgraph->nodes[i];
struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, tensor);

if (!grad) {
return;
return NULL;
}

struct ggml_tensor * src0 = tensor->src[0];
Expand Down Expand Up @@ -7216,7 +7223,13 @@ static void ggml_compute_backward(
ggml_add_or_set(ctx, cgraph, isrc0, grad);
}
if (src1_needs_grads) {
ggml_sub_or_set(ctx, cgraph, isrc1, grad);
// a broadcast src1 (the delta net's g_cs - g_last) is read once per repeat: its
// gradient is the sum over the repeats, as for ADD and MUL
struct ggml_tensor * tmp = grad;
if (!ggml_are_same_shape(src0, src1)) {
tmp = ggml_repeat_back(ctx, tmp, src1);
}
ggml_sub_or_set(ctx, cgraph, isrc1, tmp);
}
} break;
case GGML_OP_MUL: {
Expand All @@ -7236,7 +7249,16 @@ static void ggml_compute_backward(
ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src1));
}
if (src1_needs_grads) {
ggml_sub_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1)));
// a broadcast divisor (the MoE router's weights / clamp(sum_rows(weights)), one sum
// per token over n_expert_used weights) is read once per repeat: its gradient is the
// sum over the repeats. Without it the gradient had the dividend's shape and the
// shape check below aborted the M5's serving engine (2026-11-07, 35B-A3B, 8 experts
// used; the toy MoE that proved #84 uses 1, where the shapes agree).
struct ggml_tensor * tmp = ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1));
if (!ggml_are_same_shape(src0, src1)) {
tmp = ggml_repeat_back(ctx, tmp, src1);
}
ggml_sub_or_set(ctx, cgraph, isrc1, tmp);
}
} break;
case GGML_OP_SQR: {
Expand Down Expand Up @@ -7791,11 +7813,21 @@ static void ggml_compute_backward(
} //break;
}

GGML_ASSERT(!src0_needs_grads || ggml_are_same_shape(src0, cgraph->grads[isrc0]));
// an attention with grad sinks puts its K/V gradient on the sinks, never on K/V themselves
// The contract every case above keeps: a source that needs a gradient receives one of its own
// shape. A break is a defect in that op's backward on this graph's shapes; it is returned, so
// a caller that must not abort (training inside a serving process) refuses the graph by name.
// An attention with grad sinks puts its K/V gradient on the sinks, never on K/V themselves.
const bool kv_sunk = tensor->op == GGML_OP_FLASH_ATTN_EXT && tensor->src[6] != NULL;
GGML_ASSERT(!src1_needs_grads || kv_sunk || ggml_are_same_shape(src1, cgraph->grads[isrc1]));
GGML_ASSERT(!src2_needs_grads || kv_sunk || ggml_are_same_shape(src2, cgraph->grads[isrc2]));
if (src0_needs_grads && !ggml_backward_grad_fits(cgraph, src0, isrc0)) {
return "its backward gave src[0] no gradient or one of another shape";
}
if (src1_needs_grads && !kv_sunk && !ggml_backward_grad_fits(cgraph, src1, isrc1)) {
return "its backward gave src[1] no gradient or one of another shape";
}
if (src2_needs_grads && !kv_sunk && !ggml_backward_grad_fits(cgraph, src2, isrc2)) {
return "its backward gave src[2] no gradient or one of another shape";
}
return NULL;
}

static size_t ggml_visit_parents_graph(struct ggml_cgraph * cgraph, struct ggml_tensor * node, bool compute) {
Expand Down Expand Up @@ -8002,10 +8034,11 @@ struct ggml_tensor * ggml_graph_backward_refusal(const struct ggml_cgraph * cgra
return refused;
}

void ggml_build_backward_expand(
struct ggml_tensor * ggml_build_backward_expand_or_refuse(
struct ggml_context * ctx,
struct ggml_cgraph * cgraph,
struct ggml_tensor ** grad_accs) {
struct ggml_tensor ** grad_accs,
const char ** why) {
GGML_ASSERT(cgraph->n_nodes > 0);
GGML_ASSERT(cgraph->grads);
GGML_ASSERT(cgraph->grad_accs);
Expand All @@ -8028,10 +8061,10 @@ void ggml_build_backward_expand(
GGML_ASSERT(any_loss && "no training loss found, did you forget to call ggml_set_loss?");
}

const char * why = NULL;
const struct ggml_tensor * refused = ggml_backward_mark(cgraph, grads_needed, &why);
struct ggml_tensor * refused = ggml_backward_mark(cgraph, grads_needed, why);
if (refused) {
GGML_ABORT("%s: no backward through %s (%s): %s", __func__, ggml_op_name(refused->op), ggml_op_desc(refused), why);
free(grads_needed);
return refused;
}

for (int i = 0; i < n_nodes_f; ++i) {
Expand All @@ -8053,10 +8086,28 @@ void ggml_build_backward_expand(
for (int i = n_nodes_f - 1; i >= 0; --i) {
// inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
// use allocator to automatically make inplace operations
ggml_compute_backward(ctx, cgraph, i, grads_needed);
const char * broken = ggml_compute_backward(ctx, cgraph, i, grads_needed);
if (broken) {
// the nodes built so far stay in ctx and the graph is half built: the caller discards it
*why = broken;
free(grads_needed);
return cgraph->nodes[i];
}
}

free(grads_needed);
return NULL;
}

void ggml_build_backward_expand(
struct ggml_context * ctx,
struct ggml_cgraph * cgraph,
struct ggml_tensor ** grad_accs) {
const char * why = NULL;
const struct ggml_tensor * refused = ggml_build_backward_expand_or_refuse(ctx, cgraph, grad_accs, &why);
if (refused) {
GGML_ABORT("%s: no backward through %s (%s, node \"%s\"): %s", __func__, ggml_op_name(refused->op), ggml_op_desc(refused), refused->name, why);
}
}

static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
Expand Down
18 changes: 15 additions & 3 deletions tests/test-backend-ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1785,7 +1785,17 @@ struct test_case {
}
}
ggml_graph_cpy(gf, gb);
ggml_build_backward_expand(ctx.get(), gb, nullptr);
// past the walk, a refused build is the op's backward breaking its own contract on these
// shapes (a source given a gradient of another shape): a failure, not "not supported"
{
const char * why = nullptr;
if (const ggml_tensor * node = ggml_build_backward_expand_or_refuse(ctx.get(), gb, nullptr, &why)) {
test_operation_info info(op_desc(out), vars(), ggml_backend_name(backend));
info.set_error("backward", std::string(ggml_op_desc(node)) + ": " + why);
output_printer->print_operation(info);
return false;
}
}
if (expect.size() != 1 || expect[0] != 0.0f) {
GGML_ASSERT(ggml_graph_n_nodes(gb) > ggml_graph_n_nodes(gf));
for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != NULL; t = ggml_get_next_tensor(ctx.get(), t)) {
Expand Down Expand Up @@ -3260,8 +3270,10 @@ struct test_bin_bcast : public test_case {
ggml_set_name(b[i], (std::string("b") + std::to_string(i)).c_str());
}

// The backward pass supports broadcasting only for GGML_ADD:
const bool grad_supported = op == ggml_add && ggml_are_same_shape(a, b[0]) && nf == 1 && !perm1;
// every binary op's backward sums a broadcast src1's gradient over its repeats (the MoE
// router divides n_expert_used weights by one sum per token: ne {1, n, ...} nr {k, 1, ...})
const bool grad_supported = (op == ggml_add || op == ggml_sub || op == ggml_mul || op == ggml_div) &&
nf == 1 && !perm1 && !src_overlap;
if (grad_supported) {
ggml_set_param(a);
ggml_set_param(b[0]);
Expand Down
85 changes: 85 additions & 0 deletions tests/test-opt-dynamic-accum.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -430,12 +430,97 @@ static void run_refuses_graph_without_backward() {
ggml_backend_free(cpu);
}

// what this catches: the MoE router's normalization, weights / clamp(sum_rows(weights), eps, inf)
// (llama-graph.cpp build_moe_ffn), with more than one expert used: the divisor is broadcast over
// the experts, and DIV's backward gave it a gradient of the dividend's shape. The build asserted
// on it and aborted the M5's serving engine during a /train on the 35B-A3B (8 experts used,
// 2026-11-07); the toy MoE in test-llama-archs uses 1, where the two shapes agree. Here w is the
// router's two weights for one token, the loss is w0 / (w0 + w1), and one SGD step must move w by
// -lr * (w1, -w0) / (w0 + w1)^2: the dividend's path and the broadcast divisor's, summed.
static void run_trains_through_broadcast_divisor() {
ggml_backend_t cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
CHECK(cpu != nullptr);
ggml_backend_t backends[] = { cpu };
ggml_backend_sched_t sched = ggml_backend_sched_new(backends, nullptr, 1, GGML_DEFAULT_GRAPH_SIZE, false, true);

ggml_init_params sp = { 8 * ggml_tensor_overhead(), nullptr, true };
ggml_context * ctx_static = ggml_init(sp);
ggml_tensor * w = ggml_new_tensor_2d(ctx_static, GGML_TYPE_F32, 2, 1); // [n_expert_used, n_tokens]
ggml_set_param(w);
ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx_static, cpu);
const float w0[2] = { 1.0f, 3.0f };
ggml_backend_tensor_set(w, w0, 0, sizeof(w0));

ggml_opt_params params = ggml_opt_default_params(sched, GGML_OPT_LOSS_TYPE_SUM);
params.optimizer = GGML_OPT_OPTIMIZER_TYPE_SGD;
params.get_opt_pars = sgd_pars;
ggml_opt_context_t opt_ctx = ggml_opt_init(params);

ggml_init_params cp = { GGML_DEFAULT_GRAPH_SIZE * ggml_tensor_overhead() + 4 * ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, true), nullptr, true };
ggml_context * ctx_compute = ggml_init(cp);
ggml_tensor * pick = ggml_new_tensor_2d(ctx_compute, GGML_TYPE_F32, 2, 1); // which normalized weight is the loss
ggml_tensor * sum = ggml_clamp(ctx_compute, ggml_sum_rows(ctx_compute, w), 6.103515625e-5f, INFINITY); // [1, n_tokens]
ggml_tensor * out = ggml_mul(ctx_compute, ggml_div(ctx_compute, w, sum), pick);
ggml_cgraph * gf = ggml_new_graph_custom(ctx_compute, GGML_DEFAULT_GRAPH_SIZE, true);
ggml_build_forward_expand(gf, out);
ggml_opt_prepare_alloc(opt_ctx, ctx_compute, gf, pick, out);
CHECK(ggml_opt_alloc(opt_ctx, true));
CHECK(ggml_opt_refusal(opt_ctx)[0] == '\0');
const float pick0[2] = { 1.0f, 0.0f };
ggml_backend_tensor_set(pick, pick0, 0, sizeof(pick0));
ggml_opt_eval(opt_ctx, nullptr);
CHECK(ggml_opt_refusal(opt_ctx)[0] == '\0');
float w_after[2];
ggml_backend_tensor_get(w, w_after, 0, sizeof(w_after));
const float s2 = (w0[0] + w0[1]) * (w0[0] + w0[1]);
CHECK(std::fabs(w_after[0] - (w0[0] - LR * ( w0[1] / s2))) < 1e-6f);
CHECK(std::fabs(w_after[1] - (w0[1] - LR * (-w0[0] / s2))) < 1e-6f);

ggml_free(ctx_compute);
ggml_opt_free(opt_ctx);
ggml_backend_buffer_free(buf);
ggml_free(ctx_static);
ggml_backend_sched_free(sched);
ggml_backend_free(cpu);
}

// what this catches: a backward that gives a source a gradient of another shape must be returned
// by ggml_build_backward_expand_or_refuse, naming the node, never asserted: the assert is what took
// the serving process down. The break is made here by a gradient accumulator of the wrong shape
// (w has 1 element, its accumulator 2), so the test needs no op with a broken backward.
static void run_refuses_misshaped_gradient() {
ggml_init_params cp = { 64 * ggml_tensor_overhead() + 2 * ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, true), nullptr, true };
ggml_context * ctx = ggml_init(cp);
ggml_tensor * w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
ggml_set_param(w);
ggml_tensor * x = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
ggml_tensor * out = ggml_mul(ctx, w, x);
ggml_set_name(out, "w_times_x");
ggml_set_loss(out);
ggml_cgraph * gb = ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, true);
ggml_build_forward_expand(gb, out);

ggml_tensor * grad_accs[GGML_DEFAULT_GRAPH_SIZE] = { nullptr };
for (int i = 0; i < ggml_graph_n_nodes(gb); ++i) {
if (ggml_graph_node(gb, i) == w) {
grad_accs[i] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 2);
}
}
const char * why = nullptr;
const ggml_tensor * refused = ggml_build_backward_expand_or_refuse(ctx, gb, grad_accs, &why);
CHECK(refused == out);
CHECK(why != nullptr && std::strstr(why, "src[0]") != nullptr);
ggml_free(ctx);
}

int main() {
ggml_backend_load_all();
run(1);
run(2);
run_manual();
run_refuses_graph_without_backward();
run_trains_through_broadcast_divisor();
run_refuses_misshaped_gradient();
run_label_projection(false);
run_label_projection(true);
for (ggml_type type : { GGML_TYPE_F16, GGML_TYPE_Q8_0 }) {
Expand Down