Compare commits

...
2 Commits
Author SHA1 Message Date
Xuan-Son Nguyen 441d045986 server : unblock server_response readers on termination (#33404) 2026-12-01 12:51:32 +01:00
Georgi Gerganov 75bfc7de2e metal : keep the MUL_MAT weight scale off skipped MoE slots (#33430)
* metal : keep skipped MoE slots unscaled with a per-tensor scale

kernel_mul_mat_scale reads the expert ids only when the weight scale is
per-expert or per-channel-per-expert, so a per-tensor scale also scaled
the slots of a skipped expert. The MoE matmul kernels zero those slots,
which turns 0 * +inf into NaN and fails the MUL_MAT_ID scale_gran=3
tests. Always pass the ids for MUL_MAT_ID and separate the skip check
from the per-expert scale offset.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

* metal : keep the matmul weight scale inside the matmul op

The scale pass had to be chained by hand after ggml_metal_op_mul_mat and
ggml_metal_op_mul_mat_id in the encoder switch, and the two cases dropped
its return value on the way. Make it a private tail step of both ops, the
same way kernel_mul_mm_id_map0 and kernel_mul_mm_id_zero belong to
ggml_metal_op_mul_mat_id, and assert the invariant that made ignoring the
fused result safe: a scaled matmul never fuses a following ADD.

No functional change.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)
2026-12-01 12:37:31 +02:00
10 changed files with 159 additions and 69 deletions
+1
View File
@@ -302,6 +302,7 @@ typedef struct {
uint64_t ids_nb0;
uint64_t ids_nb1;
int32_t use_ids;
int32_t has_ids;
} ggml_metal_kargs_mul_mat_scale;
typedef struct {
+78 -56
View File
@@ -388,12 +388,10 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
case GGML_OP_MUL_MAT:
{
n_fuse = ggml_metal_op_mul_mat(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_MUL_MAT_ID:
{
n_fuse = ggml_metal_op_mul_mat_id(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_GET_ROWS:
{
@@ -2771,7 +2769,59 @@ static int ggml_metal_op_mul_mat_mv(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
// apply the weight scale of a MUL_MAT or MUL_MAT_ID built by ggml_mul_mat_ext / ggml_mul_mat_id_ext
// the matmul kernels write the unscaled result, so this pass runs after them with a barrier
static void ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, const ggml_tensor * op) {
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (scale == nullptr) {
return;
}
ggml_metal_library_t lib = ctx->lib;
ggml_metal_encoder_t enc = ctx->enc;
GGML_ASSERT(scale->type == GGML_TYPE_F32);
GGML_ASSERT(op->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous_rows(op));
const ggml_tensor * src0 = op->src[0];
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
const bool has_ids = ids != nullptr;
const bool per_channel_expert = has_ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
const bool per_expert = has_ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
ggml_metal_kargs_mul_mat_scale args = {
/*.ne0 =*/ op->ne[0],
/*.ne2 =*/ op->ne[2],
/*.nb1 =*/ op->nb[1],
/*.nb2 =*/ op->nb[2],
/*.nb3 =*/ op->nb[3],
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
/*.ids_nb0 =*/ has_ids ? ids->nb[0] : 0,
/*.ids_nb1 =*/ has_ids ? ids->nb[1] : 0,
/*.use_ids =*/ per_expert,
/*.has_ids =*/ has_ids,
};
ggml_metal_op_concurrency_reset(ctx);
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
ggml_metal_encoder_set_pipeline(enc, pipeline);
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(has_ids ? ids : scale), 2);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
}
static int ggml_metal_op_mul_mat_impl(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -2957,6 +3007,18 @@ int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const int n_fuse = ggml_metal_op_mul_mat_impl(ctx, idx);
GGML_ASSERT(ggml_get_src_scale(op, 0) == nullptr || n_fuse == 1);
ggml_metal_op_mul_mat_scale(ctx, op);
return n_fuse;
}
// upper bound on the number of entry tiles emitted by kernel_mul_mm_id_map0: the full tiles
// over all entries plus at most one partial tile per expert
static int64_t ggml_metal_op_mul_mat_id_max_tiles(const ggml_tensor * op) {
@@ -2992,7 +3054,7 @@ size_t ggml_metal_op_mul_mat_id_extra_ids(const ggml_tensor * op) {
return ggml_type_size(GGML_TYPE_I32)*(ne20*ne21 + ne02);
}
int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
static int ggml_metal_op_mul_mat_id_impl(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
ggml_metal_library_t lib = ctx->lib;
@@ -3195,6 +3257,18 @@ int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat_id(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const int n_fuse = ggml_metal_op_mul_mat_id_impl(ctx, idx);
GGML_ASSERT(ggml_get_src_scale(op, 0) == nullptr || n_fuse == 1);
ggml_metal_op_mul_mat_scale(ctx, op);
return n_fuse;
}
int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
@@ -3241,58 +3315,6 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (scale == nullptr) {
return 1;
}
ggml_metal_library_t lib = ctx->lib;
ggml_metal_encoder_t enc = ctx->enc;
GGML_ASSERT(scale->type == GGML_TYPE_F32);
GGML_ASSERT(op->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous_rows(op));
const ggml_tensor * src0 = op->src[0];
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
const bool per_channel_expert = ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
const bool per_expert = ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
ggml_metal_kargs_mul_mat_scale args = {
/*.ne0 =*/ op->ne[0],
/*.ne2 =*/ op->ne[2],
/*.nb1 =*/ op->nb[1],
/*.nb2 =*/ op->nb[2],
/*.nb3 =*/ op->nb[3],
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
/*.ids_nb0 =*/ per_expert ? ids->nb[0] : 0,
/*.ids_nb1 =*/ per_expert ? ids->nb[1] : 0,
/*.use_ids =*/ per_expert,
};
ggml_metal_op_concurrency_reset(ctx);
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
ggml_metal_encoder_set_pipeline(enc, pipeline);
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(per_expert ? ids : scale), 2);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
return 1;
}
bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) {
assert(op->op == GGML_OP_FLASH_ATTN_EXT);
-1
View File
@@ -83,7 +83,6 @@ int ggml_metal_op_pool_2d (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_fwht (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_scale (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_add_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_flash_attn_ext (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_bin (ggml_metal_op_t ctx, int idx);
+5 -2
View File
@@ -219,12 +219,15 @@ kernel void kernel_mul_mat_scale(
device const char * s = scale;
if (args.use_ids) {
if (args.has_ids) {
// a skipped expert (id < 0) has zeroed output, do not scale it
const int32_t expert = *((device const int32_t *) (ids + i1*args.ids_nb0 + i2*args.ids_nb1));
if (expert < 0) {
return;
}
s += expert*args.s_nb1;
if (args.use_ids) {
s += expert*args.s_nb1;
}
}
device float * dst_row = (device float *) (dst + i1*args.nb1 + i2*args.nb2 + i3*args.nb3);
+32
View File
@@ -3,6 +3,7 @@
#include "../tools/server/server-chat.h"
#include "../tools/server/server-common.h"
#include "../tools/server/server-decision.h"
#include "../tools/server/server-queue.h"
#include "../tools/server/server-schema.h"
#include "../tools/server/server-slot-sched.h"
@@ -540,6 +541,36 @@ static void test_server_pipe(testing & t) {
});
}
//
// server_response
//
static void test_server_response_terminate(testing & t) {
auto is_unavailable = [](const server_task_result_ptr & res) {
const auto * err = dynamic_cast<const server_task_result_error *>(res.get());
return err != nullptr && err->err_type == ERROR_TYPE_UNAVAILABLE;
};
auto post_completion = [](server_response_reader & rd) {
server_task task(SERVER_TASK_TYPE_COMPLETION);
task.id = rd.get_new_id();
rd.post_task(std::move(task));
};
auto stop_now = []() { return true; };
server_queue queue_tasks;
server_response queue_results;
// task loop is not running, so no result will ever be sent
server_response_reader rd(queue_tasks, queue_results, 1);
post_completion(rd);
queue_results.terminate();
t.assert_true("waiting reader gets an error", is_unavailable(rd.next(stop_now)));
server_response_reader rd_late(queue_tasks, queue_results, 1);
post_completion(rd_late);
t.assert_true("reader added later gets an error", is_unavailable(rd_late.next(stop_now)));
}
//
// server_decision_escape_special_tokens
//
@@ -956,6 +987,7 @@ int main(int argc, char ** argv) {
t.test("lora_helpers", test_lora_helpers);
t.test("server_prompt_reuse", test_server_prompt_reuse);
t.test("server_pipe", test_server_pipe);
t.test("server_response_terminate", test_server_response_terminate);
t.test("decision_escape", test_decision_escape);
t.test("rerank_template", test_rerank_template);
t.test("decision_class_scores", test_decision_class_scores);
+1
View File
@@ -5178,6 +5178,7 @@ void server_context::start_loop() {
void server_context::terminate() {
impl->queue_tasks.terminate();
impl->queue_results.terminate();
}
llama_context * server_context::get_llama_context() const {
+1 -1
View File
@@ -75,7 +75,7 @@ struct server_context {
// this function will block main thread until termination
void start_loop();
// terminate main loop (will unblock start_loop)
// terminate main loop (will unblock start_loop), readers waiting for a result get an error
void terminate();
// get the underlaying llama_context, can return nullptr if sleeping
+20 -8
View File
@@ -429,15 +429,20 @@ void server_response::remove_waiting_task_ids(const std::unordered_set<int> & id
}
}
static server_task_result_ptr make_result_terminated(const std::unordered_set<int> & id_tasks) {
GGML_ASSERT(!id_tasks.empty());
auto res = std::make_unique<server_task_result_error>();
res->id = *id_tasks.begin();
res->err_type = ERROR_TYPE_UNAVAILABLE;
res->err_msg = "server is shutting down";
return res;
}
server_task_result_ptr server_response::recv(const std::unordered_set<int> & id_tasks) {
while (true) {
std::unique_lock<std::mutex> lock(mutex_results);
condition_results.wait(lock, [&]{
if (!running) {
RES_DBG("%s : queue result stop\n", "recv");
std::terminate(); // we cannot return here since the caller is HTTP code
}
return !queue_results.empty();
return !running || !queue_results.empty();
});
for (size_t i = 0; i < queue_results.size(); i++) {
@@ -447,6 +452,11 @@ server_task_result_ptr server_response::recv(const std::unordered_set<int> & id_
return res;
}
}
if (!running) {
RES_DBG("%s", "queue result stop\n");
return make_result_terminated(id_tasks);
}
}
// should never reach here
@@ -465,11 +475,12 @@ server_task_result_ptr server_response::recv_with_timeout(const std::unordered_s
}
}
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
if (!running) {
RES_DBG("%s : queue result stop\n", __func__);
std::terminate(); // we cannot return here since the caller is HTTP code
RES_DBG("%s", "queue result stop\n");
return make_result_terminated(id_tasks);
}
std::cv_status cr_res = condition_results.wait_until(lock, deadline);
if (cr_res == std::cv_status::timeout) {
return nullptr;
}
@@ -510,6 +521,7 @@ void server_response::broadcast(server_task_result_ptr && result) {
}
void server_response::terminate() {
std::unique_lock<std::mutex> lock(mutex_results);
running = false;
condition_results.notify_all();
}
+2 -1
View File
@@ -182,6 +182,7 @@ public:
void remove_waiting_task_ids(const std::unordered_set<int> & id_tasks);
// This function blocks the thread until there is a response for one of the id_tasks
// after terminate(), return the pending results first, then an ERROR_TYPE_UNAVAILABLE error
server_task_result_ptr recv(const std::unordered_set<int> & id_tasks);
// same as recv(), but have timeout in seconds
@@ -198,7 +199,7 @@ public:
// (used by router mode)
void broadcast(server_task_result_ptr && result);
// terminate the waiting loop
// wake up all readers, used when no more results will be sent
void terminate();
};
+19
View File
@@ -171,3 +171,22 @@ def test_server_ctrl_break():
server.process.send_signal(signal.CTRL_BREAK_EVENT)
# exit code 0 means a clean shutdown, the default handler would end it with STATUS_CONTROL_C_EXIT
assert server.process.wait(timeout=60) == 0
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal")
def test_server_sigterm_during_request():
global server
server.n_slots = 1
server.n_ctx = 131072
server.n_predict = -1
server.start()
stream = server.make_stream_request("POST", "/completion", data={
"prompt": "Once upon a time",
"ignore_eos": True,
"stream": True,
})
next(stream)
server.process.send_signal(signal.SIGTERM)
# the client keeps the connection open, so the HTTP thread must not wait for a result forever
assert server.process.wait(timeout=10) == 0
stream.close()