mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-23 03:07:37 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
212c547fe9 | ||
|
|
f5e6915c28 | ||
|
|
dd53f70d08 | ||
|
|
1f8baae28d | ||
|
|
44d50873b5 | ||
|
|
7778de0c3f | ||
|
|
f4f6f2e7db | ||
|
|
253671d882 | ||
|
|
94f3af3d09 | ||
|
|
f505c30b92 | ||
|
|
5bacb7c868 |
+1
-1
@@ -1406,7 +1406,7 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const
|
||||
}
|
||||
|
||||
// LFM2.5 format detection: template uses plain "List of tools: [...]" with no special tokens
|
||||
if (src.find("List of tools: [") != std::string::npos &&
|
||||
if (src.find("List of tools: ") != std::string::npos &&
|
||||
src.find("<|tool_list_start|>") == std::string::npos) {
|
||||
LOG_DBG("Using specialized template: LFM2.5\n");
|
||||
return common_chat_params_init_lfm2_5;
|
||||
|
||||
+36
-38
@@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
|
||||
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto header = p.literal(HEADER);
|
||||
auto end = p.literal(END);
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto header = p.token(HEADER);
|
||||
auto end = p.token(END);
|
||||
|
||||
auto think = p.literal(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(END) + end));
|
||||
auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end);
|
||||
auto think = p.token(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(end) + end));
|
||||
auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end);
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
|
||||
return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end;
|
||||
return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end;
|
||||
}
|
||||
|
||||
auto blocks = p.zero_or_more(header + (thinking | text));
|
||||
@@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
return blocks;
|
||||
}
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
const auto & function = tool.at("function");
|
||||
std::string name = function.at("name");
|
||||
|
||||
auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":");
|
||||
auto args = p.tool_args(p.json());
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end));
|
||||
});
|
||||
|
||||
// tool calls are the last blocks of the turn
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
auto tool_calls = header + p.trigger_rule("tool-calls", calls);
|
||||
// the call takes the name in the JSON
|
||||
auto tool_json = p.token(TOOL_JSON);
|
||||
auto tool_body = [&](const common_peg_parser & json_name) {
|
||||
return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",")
|
||||
<< p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end;
|
||||
};
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return blocks + tool_calls;
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
const auto & function = tool.at("function");
|
||||
std::string name = function.at("name");
|
||||
std::string quoted = json(name).dump();
|
||||
|
||||
// The research model does not generate a tool name before the tool call token
|
||||
auto json_name = p.literal(quoted.substr(1, quoted.size() - 2));
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name)));
|
||||
});
|
||||
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
return blocks + header + calls;
|
||||
}
|
||||
|
||||
return blocks + p.optional(tool_calls);
|
||||
auto name = p.until(tool_json);
|
||||
auto body = tool_body(p.string_content('"'));
|
||||
auto next = p.rule("tool-call", header + p.tool(name + tool_json + body));
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps();
|
||||
auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more);
|
||||
|
||||
return blocks + p.optional(calls);
|
||||
});
|
||||
|
||||
if (has_response_format || use_tools) {
|
||||
data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
});
|
||||
|
||||
if (data.grammar_lazy) {
|
||||
// a header followed by text and not by a content token is a tool call, the grammar starts at the name
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
|
||||
};
|
||||
// Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
|
||||
// an output that starts with no content token is a tool call. not for a continuation, it starts with text
|
||||
if (!inputs.has_continuation()) {
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
+2
-2
@@ -97,7 +97,7 @@ Legend:
|
||||
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
@@ -133,4 +133,4 @@ Legend:
|
||||
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
|
||||
+4
-4
@@ -16812,11 +16812,11 @@
|
||||
"OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL"
|
||||
|
||||
|
Can't render this file because it is too large.
|
+7
-1
@@ -12345,7 +12345,13 @@
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU"
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -57,8 +57,9 @@ extern "C" {
|
||||
void * (*get_base) (ggml_backend_buffer_t buffer);
|
||||
// (optional) initialize a tensor in the buffer (eg. add tensor extras)
|
||||
enum ggml_status (*init_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor);
|
||||
// tensor data access
|
||||
// (optional) fill tensor data with a value, ggml_backend_tensor_memset falls back to set_tensor
|
||||
void (*memset_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size);
|
||||
// tensor data access
|
||||
void (*set_tensor) (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size);
|
||||
void (*get_tensor) (ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size);
|
||||
// (optional) 2d data copies
|
||||
|
||||
@@ -761,7 +761,17 @@ void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size
|
||||
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
||||
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
||||
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
||||
GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
if (buf->iface.memset_tensor == NULL) {
|
||||
GGML_ASSERT(buf->iface.set_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
// fallback: write the value in chunks with set_tensor
|
||||
const std::vector<uint8_t> chunk(std::min(size, (size_t) 1024*1024), value);
|
||||
for (size_t chunk_offset = 0; chunk_offset < size; chunk_offset += chunk.size()) {
|
||||
ggml_backend_tensor_set(tensor, chunk.data(), offset + chunk_offset, std::min(size - chunk_offset, chunk.size()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
buf->iface.memset_tensor(buf, tensor, value, offset, size);
|
||||
}
|
||||
|
||||
@@ -226,6 +226,7 @@ set(GGML_OPENCL_KERNELS
|
||||
gemm_noshuffle_q4_0_q8_1_dp4a
|
||||
gemm_coopk_q4_0_q8_1_dp4a
|
||||
gemm_coopk_q4_k_q8_1_dp4a
|
||||
gemm_coopk_q4_k_q8_1_dp4a_bin_c8
|
||||
gemm_coopk_q6_k_q8_1_dp4a
|
||||
pack_b_f16_coopmat
|
||||
gemm_noshuffle_q4_0_f32_coopmat
|
||||
|
||||
@@ -1163,6 +1163,8 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_sgn_f32, kernel_sgn_f32_4, kernel_sgn_f32_nc, kernel_sgn_f16, kernel_sgn_f16_4, kernel_sgn_f16_nc;
|
||||
cl_kernel kernel_step_f32, kernel_step_f32_4, kernel_step_f32_nc, kernel_step_f16, kernel_step_f16_4, kernel_step_f16_nc;
|
||||
cl_kernel kernel_elu_f32, kernel_elu_f32_4, kernel_elu_f32_nc, kernel_elu_f16, kernel_elu_f16_4, kernel_elu_f16_nc;
|
||||
cl_kernel kernel_xielu_f32 = nullptr;
|
||||
cl_kernel kernel_xielu_f16 = nullptr;
|
||||
cl_kernel kernel_hardswish_f32, kernel_hardswish_f32_4, kernel_hardswish_f32_nc, kernel_hardswish_f16, kernel_hardswish_f16_4, kernel_hardswish_f16_nc;
|
||||
cl_kernel kernel_hardsigmoid_f32, kernel_hardsigmoid_f32_4, kernel_hardsigmoid_f32_nc, kernel_hardsigmoid_f16, kernel_hardsigmoid_f16_4, kernel_hardsigmoid_f16_nc;
|
||||
cl_kernel kernel_floor_f32, kernel_floor_f32_4, kernel_floor_f32_nc, kernel_floor_f16, kernel_floor_f16_4, kernel_floor_f16_nc;
|
||||
@@ -1514,6 +1516,15 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = nullptr;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c4 = 8;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c2 = 8;
|
||||
cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr;
|
||||
cl_kernel kernel_quant_a_q8_1_k4 = nullptr;
|
||||
int nsg_coopk_dp4a_q4_k_bin_c8 = 4;
|
||||
cl_mem coopk_c8_qa_image = nullptr;
|
||||
cl_mem coopk_c8_qa_buffer = nullptr;
|
||||
size_t coopk_c8_qa_image_bytes = 0;
|
||||
cl_mem coopk_c8_ds_image = nullptr;
|
||||
cl_mem coopk_c8_ds_buffer = nullptr;
|
||||
size_t coopk_c8_ds_image_bytes = 0;
|
||||
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 = nullptr;
|
||||
cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr;
|
||||
int nsg_coopk_dp4a_q6_k = 8;
|
||||
@@ -1521,7 +1532,25 @@ struct ggml_backend_opencl_context {
|
||||
#endif // GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
|
||||
~ggml_backend_opencl_context() {
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
for (cl_kernel kernel : {
|
||||
kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8,
|
||||
kernel_quant_a_q8_1_k4
|
||||
}
|
||||
) {
|
||||
if (kernel != nullptr) {
|
||||
CL_CHECK(clReleaseKernel(kernel));
|
||||
}
|
||||
}
|
||||
for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) {
|
||||
if (image != nullptr) {
|
||||
CL_CHECK(clReleaseMemObject(image));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
for (cl_kernel kernel : {
|
||||
kernel_xielu_f32,
|
||||
kernel_xielu_f16,
|
||||
kernel_mul_mm_f16_f32_kq_p8,
|
||||
kernel_mul_mm_q8_f32_kqv,
|
||||
kernel_fa_p8_fixup,
|
||||
@@ -1851,13 +1880,22 @@ static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * bac
|
||||
// COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild.
|
||||
static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx,
|
||||
const char * kernel_src, const char * kernel_name,
|
||||
const std::string & opts_base, int & nsg) {
|
||||
const std::string & opts_base, int & nsg, bool fatal = true) {
|
||||
while (nsg >= 2) {
|
||||
const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg);
|
||||
cl_program program = build_program_from_source(backend_ctx, kernel_src, opts);
|
||||
cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal);
|
||||
if (program == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
cl_int err;
|
||||
cl_kernel kernel = clCreateKernel(program, kernel_name, &err);
|
||||
CL_CHECK(err);
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
if (fatal) {
|
||||
CL_CHECK(err);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
size_t max_workgroup_size = 0;
|
||||
CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE,
|
||||
sizeof(max_workgroup_size), &max_workgroup_size, NULL));
|
||||
@@ -1871,6 +1909,46 @@ static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * back
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) {
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
const std::string kernel_src {
|
||||
#include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h"
|
||||
};
|
||||
#else
|
||||
const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl");
|
||||
#endif
|
||||
cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(),
|
||||
"kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts,
|
||||
backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8, false);
|
||||
if (program == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
cl_int err;
|
||||
|
||||
cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err);
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
return;
|
||||
}
|
||||
|
||||
cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err);
|
||||
CL_CHECK(clReleaseProgram(program));
|
||||
if (err != CL_SUCCESS) {
|
||||
CL_CHECK(clReleaseKernel(gemm));
|
||||
return;
|
||||
}
|
||||
|
||||
if (backend_ctx->get_kernel_workgroup_size(quant) < 64) {
|
||||
CL_CHECK(clReleaseKernel(gemm));
|
||||
CL_CHECK(clReleaseKernel(quant));
|
||||
return;
|
||||
}
|
||||
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm;
|
||||
backend_ctx->kernel_quant_a_q8_1_k4 = quant;
|
||||
}
|
||||
|
||||
static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx,
|
||||
const std::string & kernel_src, const char * kernel_name,
|
||||
int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) {
|
||||
@@ -1940,8 +2018,12 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4,
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2);
|
||||
|
||||
const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
if (use_adreno_bin_kernels(backend_ctx) && (!env || !*env || atoi(env) != 0)) {
|
||||
static const bool use_coopk_bin = [] {
|
||||
const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
return !env || !*env || atoi(env) != 0;
|
||||
}();
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) {
|
||||
const std::string base_opts = backend_ctx->kernel_compile_opts
|
||||
+ " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->rows_coopk_dp4a_q4_k);
|
||||
for (int cols = 4; cols >= 2; cols -= 2) {
|
||||
@@ -1965,6 +2047,7 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx
|
||||
}
|
||||
nsg = nsg_eff;
|
||||
}
|
||||
load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx);
|
||||
}
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
@@ -4839,6 +4922,8 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
CL_UNARY_EXT_K(round)
|
||||
CL_UNARY_EXT_K(trunc)
|
||||
#undef CL_UNARY_EXT_K
|
||||
CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
@@ -12207,6 +12292,14 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
|
||||
case GGML_UNARY_OP_SILU:
|
||||
return op->src[0]->type == op->type &&
|
||||
(op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
|
||||
case GGML_UNARY_OP_XIELU:
|
||||
for (int64_t ne : op->src[0]->ne) {
|
||||
if (ne > INT_MAX) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return op->src[0]->type == op->type &&
|
||||
(op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16);
|
||||
case GGML_UNARY_OP_GELU:
|
||||
case GGML_UNARY_OP_RELU:
|
||||
case GGML_UNARY_OP_GELU_ERF:
|
||||
@@ -21239,6 +21332,51 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc)
|
||||
|
||||
#undef GGML_CL_UNARY_EXT_WRAP
|
||||
|
||||
static void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
UNUSED(src1);
|
||||
|
||||
auto * backend_ctx = (ggml_backend_opencl_context *) backend->context;
|
||||
cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->kernel_xielu_f16 : backend_ctx->kernel_xielu_f32;
|
||||
|
||||
const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra;
|
||||
const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra;
|
||||
|
||||
const cl_ulong offset0 = extra0->offset + src0->view_offs;
|
||||
const cl_ulong offsetd = extrad->offset + dst->view_offs;
|
||||
|
||||
GGML_TENSOR_LOCALS(int, ne0, src0, ne);
|
||||
GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb);
|
||||
GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb);
|
||||
|
||||
const float alpha_n = ggml_get_op_params_f32(dst, 1);
|
||||
const float alpha_p = ggml_get_op_params_f32(dst, 2);
|
||||
const float beta = ggml_get_op_params_f32(dst, 3);
|
||||
const float eps = ggml_get_op_params_f32(dst, 4);
|
||||
|
||||
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00));
|
||||
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00));
|
||||
CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01));
|
||||
CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02));
|
||||
CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03));
|
||||
CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1));
|
||||
CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2));
|
||||
CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3));
|
||||
CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n));
|
||||
CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p));
|
||||
CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta));
|
||||
CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps));
|
||||
|
||||
const size_t nth = 64;
|
||||
size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03};
|
||||
size_t local[] = {nth, 1, 1};
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst);
|
||||
}
|
||||
|
||||
static void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
GGML_ASSERT(src0->extra);
|
||||
@@ -28117,6 +28255,69 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t
|
||||
}
|
||||
|
||||
#ifdef GGML_OPENCL_USE_ADRENO_KERNELS
|
||||
// make sure the image1d_buffer `image` is a proper view of `buffer` by either
|
||||
// creating a new image1d_buffer or reuse existing one.
|
||||
// upon success, `image_buffer` is set to the cl_mem in `buffer` and
|
||||
// `image_bytes` the size in `buffer` and `image` is the image1d_buffer.
|
||||
static bool ggml_cl_coopk_c8_image(
|
||||
ggml_backend_opencl_context * backend_ctx,
|
||||
ggml_cl_buffer & buffer,
|
||||
size_t bytes,
|
||||
cl_mem & image,
|
||||
cl_mem & image_buffer,
|
||||
size_t & image_bytes
|
||||
) {
|
||||
// required bytes exceed image1d_buffer limit
|
||||
if (bytes / 16 > backend_ctx->image_max_buffer_size) {
|
||||
return false;
|
||||
}
|
||||
// existing image1d_buffer can be reused
|
||||
if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) {
|
||||
return true;
|
||||
}
|
||||
// a new one is needed, so release the existing one
|
||||
if (image != nullptr) {
|
||||
CL_CHECK(clReleaseMemObject(image));
|
||||
image = nullptr;
|
||||
}
|
||||
|
||||
image_buffer = nullptr;
|
||||
image_bytes = 0;
|
||||
|
||||
cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32};
|
||||
cl_image_desc desc = {};
|
||||
desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER;
|
||||
desc.image_width = bytes / 16;
|
||||
desc.buffer = buffer.buffer;
|
||||
|
||||
cl_int err;
|
||||
image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err);
|
||||
if (err != CL_SUCCESS) {
|
||||
image = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
image_buffer = buffer.buffer;
|
||||
image_bytes = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) {
|
||||
const int cu = MAX(1, (int) backend_ctx->fa.compute_units);
|
||||
int ksplit = 1;
|
||||
float best_eff = 0.0f;
|
||||
for (int k = 1; k <= MIN(8, n_blocks); ++k) {
|
||||
const int wg = base_wg * k;
|
||||
const int waves = CEIL_DIV(wg, cu);
|
||||
const float eff = (float) wg / (waves * cu);
|
||||
if (eff > best_eff + 0.06f) {
|
||||
best_eff = eff;
|
||||
ksplit = k;
|
||||
}
|
||||
}
|
||||
return ksplit;
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
@@ -28154,11 +28355,100 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const gg
|
||||
int N = ne1;
|
||||
int K = ne00;
|
||||
|
||||
const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5;
|
||||
if (backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr &&
|
||||
N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 &&
|
||||
src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N &&
|
||||
K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX &&
|
||||
src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr &&
|
||||
src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 &&
|
||||
ggml_is_contiguous(src1) && ggml_is_contiguous(dst)
|
||||
) {
|
||||
const int kb = K / 32;
|
||||
const size_t qa_bytes = (size_t)8 * K;
|
||||
const size_t ds_bytes = (size_t)16 * kb * sizeof(cl_half);
|
||||
|
||||
backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes);
|
||||
backend_ctx->prealloc_moe_da.allocate(context, ds_bytes);
|
||||
|
||||
if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes,
|
||||
backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) &&
|
||||
ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes,
|
||||
backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes)
|
||||
) {
|
||||
const int n_blocks = N * kb;
|
||||
|
||||
cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4;
|
||||
CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device));
|
||||
CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
|
||||
CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
|
||||
CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1));
|
||||
CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks));
|
||||
CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb));
|
||||
|
||||
size_t quant_local[] = {64};
|
||||
size_t quant_global[] = {(size_t)8 * kb};
|
||||
backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst);
|
||||
|
||||
int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb);
|
||||
if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) {
|
||||
ksplit = 1;
|
||||
}
|
||||
|
||||
cl_mem out = extrad->data_device;
|
||||
cl_ulong out_offset = offsetd;
|
||||
|
||||
if (ksplit > 1) {
|
||||
backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float));
|
||||
out = backend_ctx->prealloc_splitk_partial.buffer;
|
||||
out_offset = 0;
|
||||
}
|
||||
|
||||
const cl_uchar mask_d6 = 0x3F;
|
||||
const cl_uchar mask_d4 = 0x0F;
|
||||
const cl_uchar mask_hi2 = 0xC0;
|
||||
|
||||
const size_t nsg = backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8;
|
||||
cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8;
|
||||
|
||||
CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q));
|
||||
CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s));
|
||||
CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d));
|
||||
CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm));
|
||||
CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image));
|
||||
CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image));
|
||||
CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out));
|
||||
CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset));
|
||||
CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M));
|
||||
CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N));
|
||||
CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6));
|
||||
CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4));
|
||||
CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2));
|
||||
CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit));
|
||||
|
||||
size_t local[] = {64, nsg, 1};
|
||||
size_t global[] = {(size_t)M / 4, nsg * ksplit, 1};
|
||||
backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst);
|
||||
|
||||
if (ksplit > 1) {
|
||||
const int rows = M * N;
|
||||
cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32;
|
||||
CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out));
|
||||
CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows));
|
||||
CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit));
|
||||
size_t reduce_local[] = {64};
|
||||
size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64};
|
||||
backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous).
|
||||
// This switch disables only this bin-layout path; weight conversion is unchanged.
|
||||
static const char * env_coopk_bin = getenv("GGML_OPENCL_COOPK_Q4_K_BIN");
|
||||
const bool use_coopk_bin = !env_coopk_bin || !*env_coopk_bin || atoi(env_coopk_bin) != 0;
|
||||
if (use_coopk_bin && ne1 >= 2 && ne1 <= 4 &&
|
||||
if (ne1 >= 2 && ne1 <= 4 &&
|
||||
ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) &&
|
||||
backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr &&
|
||||
((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2
|
||||
@@ -40516,6 +40806,10 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_elu;
|
||||
break;
|
||||
case GGML_UNARY_OP_XIELU:
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_xielu;
|
||||
break;
|
||||
case GGML_UNARY_OP_HARDSWISH:
|
||||
if (!any_on_device) { return false; }
|
||||
func = ggml_cl_hardswish;
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
#pragma OPENCL EXTENSION cl_khr_fp16 : enable
|
||||
#ifdef cl_khr_integer_dot_product
|
||||
#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable
|
||||
#endif
|
||||
|
||||
#ifndef COOPK_NSG
|
||||
#define COOPK_NSG 4
|
||||
#endif
|
||||
#define COK_SG 64
|
||||
#define COK_ROWS 4
|
||||
|
||||
#define COK_PACK4(a, b, c, e) \
|
||||
(((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24))
|
||||
|
||||
// Pack each four K values as (0, 2, 1, 3); scales and sums are interleaved at width eight.
|
||||
kernel void kernel_quant_a_q8_1_k4(
|
||||
global const float * src,
|
||||
global uint * qa,
|
||||
global half * ds,
|
||||
ulong offset_src,
|
||||
int total_blocks,
|
||||
int k_b
|
||||
) {
|
||||
const int blk = get_global_id(0);
|
||||
if (blk >= 8 * k_b) {
|
||||
return;
|
||||
}
|
||||
const int col = blk / k_b;
|
||||
const int b = blk % k_b;
|
||||
if (blk >= total_blocks) {
|
||||
vstore8((uint8)(0), 0, qa + blk * 8);
|
||||
ds[(2 * b) * 8 + col] = (half)0;
|
||||
ds[(2 * b + 1) * 8 + col] = (half)0;
|
||||
return;
|
||||
}
|
||||
src = (global const float *)((global const char *)src + offset_src);
|
||||
const int base = blk * 32;
|
||||
float v[32];
|
||||
float amax = 0.0f;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
v[i] = src[base + i];
|
||||
amax = fmax(amax, fabs(v[i]));
|
||||
}
|
||||
const float d = amax / 127.0f;
|
||||
const float id = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
int q[32];
|
||||
int sum = 0;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
q[i] = (int)rint(v[i] * id);
|
||||
sum += q[i];
|
||||
}
|
||||
uint8 out;
|
||||
out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]);
|
||||
out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]);
|
||||
out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]);
|
||||
out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]);
|
||||
out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]);
|
||||
out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]);
|
||||
out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]);
|
||||
out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]);
|
||||
vstore8(out, 0, qa + blk * 8);
|
||||
ds[(2 * b) * 8 + col] = (half)d;
|
||||
ds[(2 * b + 1) * 8 + col] = (half)(d * (float)sum);
|
||||
}
|
||||
|
||||
#define COK_SPREAD(t) (((t) | ((t) << 12)) & 0x0F0F0F0Fu)
|
||||
#define COK_DOT_RC4(r, c) \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W0.s##r, A.s0, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W1.s##r, A.s1, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W2.s##r, A.s2, d##r.s##c); \
|
||||
d##r.s##c = dot_acc_sat_4x8packed_ss_int(W3.s##r, A.s3, d##r.s##c);
|
||||
#define COK_DOT_COL4(c, t) \
|
||||
{ const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \
|
||||
COK_DOT_RC4(0, c) COK_DOT_RC4(1, c) COK_DOT_RC4(2, c) COK_DOT_RC4(3, c) }
|
||||
|
||||
kernel void kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8(
|
||||
global const uint * src0_q,
|
||||
global const uchar * src0_s,
|
||||
global const half * src0_d,
|
||||
global const half * src0_dm,
|
||||
read_only image1d_buffer_t src1_qa,
|
||||
read_only image1d_buffer_t src1_ds,
|
||||
global float * dst,
|
||||
ulong offsetd,
|
||||
int m,
|
||||
int k,
|
||||
int n_no_padding,
|
||||
uchar mask_d6,
|
||||
uchar mask_d4,
|
||||
uchar mask_hi2,
|
||||
int ksplit
|
||||
) {
|
||||
dst = (global float *)((global char *)dst + offsetd);
|
||||
const int gx = get_global_id(0);
|
||||
const int sg = get_local_id(1);
|
||||
const int lane = get_local_id(0);
|
||||
const int ks = get_group_id(1);
|
||||
const int row0 = gx * COK_ROWS;
|
||||
const int num_32blk = k / 32;
|
||||
const int k_t = k >> 4;
|
||||
const int fence = (int)(mask_d6 >> 6);
|
||||
const int nslice = ksplit * COOPK_NSG;
|
||||
const int chunk = (num_32blk + nslice - 1) / nslice;
|
||||
const int b_beg = (ks * COOPK_NSG + sg) * chunk;
|
||||
const int b_end = min(b_beg + chunk, num_32blk);
|
||||
float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f);
|
||||
float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f);
|
||||
|
||||
for (int sb = b_beg >> 3; sb * 8 < b_end; ++sb) {
|
||||
const half4 dd = vload4(0, src0_d + row0 + sb * m);
|
||||
const half4 dmm = vload4(0, src0_dm + row0 + sb * m);
|
||||
global const uchar * sc = src0_s + sb * 12 * m + row0;
|
||||
const int j_beg = max(b_beg - sb * 8, 0);
|
||||
const int j_end = min(b_end - sb * 8, 8);
|
||||
for (int j = j_beg; j < j_end; ++j) {
|
||||
const int blk = sb * 8 + j;
|
||||
int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0);
|
||||
for (int h = 0; h < 2; ++h) {
|
||||
const int u0 = (blk << 2) + (h << 1);
|
||||
const int at = (blk << 1) + h;
|
||||
const uint4 wa = vload4(0, src0_q + row0 + u0 * m);
|
||||
const uint4 wb = vload4(0, src0_q + row0 + (u0 + 1) * m);
|
||||
const uint4 W0 = COK_SPREAD(wa & 0xFFFFu);
|
||||
const uint4 W1 = COK_SPREAD(wa >> 16);
|
||||
const uint4 W2 = COK_SPREAD(wb & 0xFFFFu);
|
||||
const uint4 W3 = COK_SPREAD(wb >> 16);
|
||||
COK_DOT_COL4(0, at) COK_DOT_COL4(1, at) COK_DOT_COL4(2, at) COK_DOT_COL4(3, at)
|
||||
// Keep the second activation group dependent on the first dot products.
|
||||
const int at4 = at + (d0.s0 & fence);
|
||||
COK_DOT_COL4(4, at4) COK_DOT_COL4(5, at4) COK_DOT_COL4(6, at4) COK_DOT_COL4(7, at4)
|
||||
}
|
||||
uchar4 scv, mnv;
|
||||
if (j < 4) {
|
||||
scv = vload4(0, sc + j * m) & (uchar4)(mask_d6);
|
||||
mnv = vload4(0, sc + (j + 4) * m) & (uchar4)(mask_d6);
|
||||
} else {
|
||||
const uchar4 bh = vload4(0, sc + (j + 4) * m);
|
||||
const uchar4 bl = vload4(0, sc + (j - 4) * m);
|
||||
const uchar4 bj = vload4(0, sc + j * m);
|
||||
scv = (bh & (uchar4)(mask_d4)) | ((bl >> (uchar4)(6)) << (uchar4)(4));
|
||||
mnv = (bh >> (uchar4)(4)) | ((bj >> (uchar4)(6)) << (uchar4)(4));
|
||||
}
|
||||
const float4 scf = convert_float4(dd) * convert_float4(scv);
|
||||
const float4 mnf = convert_float4(dmm) * convert_float4(mnv);
|
||||
const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk)));
|
||||
acc0 = mad(convert_float8(d0), da * scf.s0, acc0);
|
||||
acc1 = mad(convert_float8(d1), da * scf.s1, acc1);
|
||||
acc2 = mad(convert_float8(d2), da * scf.s2, acc2);
|
||||
acc3 = mad(convert_float8(d3), da * scf.s3, acc3);
|
||||
const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk + 1)));
|
||||
acc0 = mad(sa, -mnf.s0, acc0);
|
||||
acc1 = mad(sa, -mnf.s1, acc1);
|
||||
acc2 = mad(sa, -mnf.s2, acc2);
|
||||
acc3 = mad(sa, -mnf.s3, acc3);
|
||||
}
|
||||
}
|
||||
|
||||
local float8 reduceLM[COK_SG * (COOPK_NSG - 1)];
|
||||
float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f);
|
||||
float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f);
|
||||
#define COK_REDUCE(accv, outv) \
|
||||
barrier(CLK_LOCAL_MEM_FENCE); \
|
||||
if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \
|
||||
barrier(CLK_LOCAL_MEM_FENCE); \
|
||||
if (sg == 0) { \
|
||||
float8 sum = (accv); \
|
||||
for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \
|
||||
(outv) = sum; \
|
||||
}
|
||||
COK_REDUCE(acc0, out0)
|
||||
COK_REDUCE(acc1, out1)
|
||||
COK_REDUCE(acc2, out2)
|
||||
COK_REDUCE(acc3, out3)
|
||||
#undef COK_REDUCE
|
||||
#define COK_STORE_COL(c) \
|
||||
if ((c) < n_no_padding) { \
|
||||
vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \
|
||||
}
|
||||
if (sg == 0) {
|
||||
dst += (size_t)ks * (size_t)m * (size_t)n_no_padding;
|
||||
COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3)
|
||||
COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7)
|
||||
}
|
||||
#undef COK_STORE_COL
|
||||
}
|
||||
@@ -83,3 +83,29 @@ UNARY_EXT(floor, floor(x), floor
|
||||
UNARY_EXT(ceil, ceil(x), ceil(x))
|
||||
UNARY_EXT(round, round(x), round(x))
|
||||
UNARY_EXT(trunc, trunc(x), trunc(x))
|
||||
|
||||
// xielu has more args, cannot fit in UNARY_EXT
|
||||
inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) {
|
||||
return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x;
|
||||
}
|
||||
|
||||
#define XIELU_KERNEL(NAME, TYPE) \
|
||||
kernel void kernel_xielu_##NAME( \
|
||||
global const char * src0, ulong offset0, \
|
||||
global char * dst, ulong offsetd, \
|
||||
int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \
|
||||
ulong nb0, ulong nb1, ulong nb2, ulong nb3, \
|
||||
float alpha_n, float alpha_p, float beta, float eps) { \
|
||||
const size_t i3 = get_group_id(2); \
|
||||
const size_t i2 = get_group_id(1); \
|
||||
const size_t i1 = get_group_id(0); \
|
||||
src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \
|
||||
dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \
|
||||
for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \
|
||||
const float x = *(global const TYPE *)(src0 + i0*nb00); \
|
||||
*(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \
|
||||
} \
|
||||
}
|
||||
|
||||
XIELU_KERNEL(f32, float)
|
||||
XIELU_KERNEL(f16, half)
|
||||
|
||||
@@ -1683,10 +1683,6 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) {
|
||||
LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__);
|
||||
return false;
|
||||
}
|
||||
if (tensor->buffer->iface.memset_tensor == nullptr) {
|
||||
LOG_ERROR("[%s] memset not implemented by backend buffer\n", __func__);
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, value: %u\n",
|
||||
__func__, rpc_log_format_tensor(tensor).c_str(), (void *) tensor->buffer, tensor->data, request.offset,
|
||||
|
||||
@@ -2117,7 +2117,7 @@ class ggml_webgpu_shader_lib {
|
||||
webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) {
|
||||
ggml_webgpu_pad_pipeline_key key = {};
|
||||
key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D;
|
||||
key.circular = !key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0;
|
||||
key.circular = context.dst->op == GGML_OP_ROLL || (!key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0);
|
||||
|
||||
auto it = pad_pipelines.find(key);
|
||||
if (it != pad_pipelines.end()) {
|
||||
|
||||
@@ -964,16 +964,18 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src
|
||||
(uint32_t) dst->ne[1],
|
||||
(uint32_t) dst->ne[2],
|
||||
(uint32_t) dst->ne[3],
|
||||
// Pad sizes
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 0),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 1),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 2),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 3),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 4),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 5),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 6),
|
||||
(uint32_t) ggml_get_op_params_i32(dst, 7),
|
||||
};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
if (dst->op == GGML_OP_ROLL) {
|
||||
// Circular padding with unchanged dimensions implements a roll.
|
||||
const int64_t shift = ggml_get_op_params_i32(dst, i);
|
||||
params.push_back((uint32_t) (shift < 0 ? shift + src->ne[i] : shift));
|
||||
params.push_back(0);
|
||||
} else {
|
||||
params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i));
|
||||
params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<wgpu::BindGroupEntry> entries = {
|
||||
ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src),
|
||||
@@ -3740,6 +3742,7 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
|
||||
return ggml_webgpu_pool2d(ctx, src0, node);
|
||||
case GGML_OP_COL2IM_1D:
|
||||
return ggml_webgpu_col2im_1d(ctx, src0, node);
|
||||
case GGML_OP_ROLL:
|
||||
case GGML_OP_PAD_REFLECT_1D:
|
||||
case GGML_OP_PAD:
|
||||
return ggml_webgpu_pad(ctx, src0, node);
|
||||
@@ -5299,6 +5302,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
|
||||
case GGML_OP_PAD_REFLECT_1D:
|
||||
supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
|
||||
break;
|
||||
case GGML_OP_ROLL:
|
||||
case GGML_OP_PAD:
|
||||
supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32;
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
{{- bos_token -}}
|
||||
{%- set keep_past_thinking = keep_past_thinking | default(false) -%}
|
||||
|
||||
{%- macro format_arg_value(arg_value) -%}
|
||||
{%- if arg_value is string -%}
|
||||
{{- '"' + arg_value + '"' -}}
|
||||
{%- elif arg_value is mapping -%}
|
||||
{{- arg_value | tojson -}}
|
||||
{%- else -%}
|
||||
{{- arg_value | string -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro parse_content(content) -%}
|
||||
{%- if content is string -%}
|
||||
{{- content -}}
|
||||
{%- else -%}
|
||||
{%- set _ns = namespace(result="") -%}
|
||||
{%- for item in content -%}
|
||||
{%- if item.type == "image" -%}
|
||||
{%- set _ns.result = _ns.result + "<image>" -%}
|
||||
{%- elif item.type == "text" -%}
|
||||
{%- set _ns.result = _ns.result + item.text -%}
|
||||
{%- else -%}
|
||||
{%- set _ns.result = _ns.result + item | tojson -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{{- _ns.result -}}
|
||||
{%- endif -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- macro render_tool_calls(tool_calls) -%}
|
||||
{%- set tool_calls_ns = namespace(tool_calls=[]) -%}
|
||||
{%- for tool_call in tool_calls -%}
|
||||
{%- set func_name = tool_call.function.name -%}
|
||||
{%- set func_args = tool_call.function.arguments -%}
|
||||
{%- set args_ns = namespace(arg_strings=[]) -%}
|
||||
{%- for arg_name, arg_value in func_args.items() -%}
|
||||
{%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%}
|
||||
{%- endfor -%}
|
||||
{%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%}
|
||||
{%- endfor -%}
|
||||
{{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}}
|
||||
{%- endmacro -%}
|
||||
|
||||
{%- set ns = namespace(system_prompt="", last_assistant_index=-1) -%}
|
||||
{%- if messages[0].role == "system" -%}
|
||||
{%- if messages[0].content is defined -%}
|
||||
{%- set ns.system_prompt = parse_content(messages[0].content) -%}
|
||||
{%- endif -%}
|
||||
{%- set messages = messages[1:] -%}
|
||||
{%- endif -%}
|
||||
{%- if tools -%}
|
||||
{%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "Today's date: " + strftime_now("%Y-%m-%d") + "\n\nList of tools: " + (tools | tojson) -%}
|
||||
{%- endif -%}
|
||||
{%- if ns.system_prompt -%}
|
||||
{{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}}
|
||||
{%- endif -%}
|
||||
{%- for message in messages -%}
|
||||
{%- if message.role == "assistant" -%}
|
||||
{%- set ns.last_assistant_index = loop.index0 -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- for message in messages -%}
|
||||
{{- "<|im_start|>" + message.role + "\n" -}}
|
||||
{%- if message.role == "assistant" -%}
|
||||
{%- generation -%}
|
||||
{%- if message.thinking is defined and (keep_past_thinking or loop.index0 == ns.last_assistant_index) -%}
|
||||
{{- "<think>" + message.thinking + "</think>" -}}
|
||||
{%- endif -%}
|
||||
{%- if message.tool_calls is defined -%}
|
||||
{{- render_tool_calls(message.tool_calls) -}}
|
||||
{%- endif -%}
|
||||
{%- if message.content is defined -%}
|
||||
{%- set content = parse_content(message.content) -%}
|
||||
{%- if not keep_past_thinking and loop.index0 != ns.last_assistant_index -%}
|
||||
{%- if "</think>" in content -%}
|
||||
{%- set content = content.split("</think>")[-1] | trim -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{{- content + ("" if (continue_final_message and loop.last) else "<|im_end|>\n") -}}
|
||||
{%- endif -%}
|
||||
{%- endgeneration -%}
|
||||
{%- else %}
|
||||
{%- if message.content is defined -%}
|
||||
{{- parse_content(message.content) + "<|im_end|>\n" -}}
|
||||
{%- endif -%}
|
||||
{%- endif %}
|
||||
{%- endfor -%}
|
||||
{%- if add_generation_prompt -%}
|
||||
{{- "<|im_start|>assistant\n" -}}
|
||||
{%- endif -%}
|
||||
@@ -3143,6 +3143,12 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor
|
||||
return false;
|
||||
}
|
||||
|
||||
// Later loop passes can select different experts from the same device copy.
|
||||
// TODO: copy only the experts needed by each pass (see #32807 and #32809).
|
||||
if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ggml_tensor * ids = node->src[2];
|
||||
if (ggml_nelements(ids) == 0) {
|
||||
return true;
|
||||
|
||||
@@ -88,16 +88,6 @@ void llama_log_callback_default(ggml_log_level level, const char * text, void *
|
||||
fflush(stderr);
|
||||
}
|
||||
|
||||
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size) {
|
||||
static const std::vector<uint8_t> zeros(1024*1024, 0);
|
||||
|
||||
// not all backend buffers implement ggml_backend_tensor_memset(), so write zeros instead
|
||||
// TODO: make this a generic fallback in `ggml_backend_tensor_memset` when `set_tensor` is available
|
||||
for (size_t ofs = 0; ofs < size; ofs += zeros.size()) {
|
||||
ggml_backend_tensor_set(t, zeros.data(), offset + ofs, std::min(size - ofs, zeros.size()));
|
||||
}
|
||||
}
|
||||
|
||||
void replace_all(std::string & s, const std::string & search, const std::string & replace) {
|
||||
if (search.empty()) {
|
||||
return;
|
||||
|
||||
@@ -96,8 +96,6 @@ struct buffer_view {
|
||||
}
|
||||
};
|
||||
|
||||
void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size);
|
||||
|
||||
void replace_all(std::string & s, const std::string & search, const std::string & replace);
|
||||
|
||||
// TODO: rename to llama_format ?
|
||||
|
||||
@@ -2919,10 +2919,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
|
||||
|
||||
if (is_contiguous) {
|
||||
llama_clear_tensor_data(k, sinfo.head() * k_size_row, cell_count * k_size_row);
|
||||
ggml_backend_tensor_memset(k, 0, sinfo.head() * k_size_row, cell_count * k_size_row);
|
||||
} else {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(k, sinfo.idxs[0][i] * k_size_row, k_size_row);
|
||||
ggml_backend_tensor_memset(k, 0, sinfo.idxs[0][i] * k_size_row, k_size_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2941,10 +2941,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
|
||||
|
||||
if (is_contiguous) {
|
||||
llama_clear_tensor_data(v, sinfo.head() * v_size_row, cell_count * v_size_row);
|
||||
ggml_backend_tensor_memset(v, 0, sinfo.head() * v_size_row, cell_count * v_size_row);
|
||||
} else {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(v, sinfo.idxs[0][i] * v_size_row, v_size_row);
|
||||
ggml_backend_tensor_memset(v, 0, sinfo.idxs[0][i] * v_size_row, v_size_row);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -2954,12 +2954,12 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_
|
||||
const uint32_t h = sinfo.head();
|
||||
|
||||
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
|
||||
llama_clear_tensor_data(v, (h + j * cells.size()) * v_size_el, cell_count * v_size_el);
|
||||
ggml_backend_tensor_memset(v, 0, (h + j * cells.size()) * v_size_el, cell_count * v_size_el);
|
||||
}
|
||||
} else {
|
||||
for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
|
||||
for (uint32_t i = 0; i < cell_count; ++i) {
|
||||
llama_clear_tensor_data(v, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el);
|
||||
ggml_backend_tensor_memset(v, 0, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1265,17 +1265,17 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head
|
||||
for (uint32_t il = 0; il < n_layer; ++il) {
|
||||
if (r_l[il] != nullptr) {
|
||||
const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
|
||||
llama_clear_tensor_data(r_l[il], cell_head * r_size_row, cell_count * r_size_row);
|
||||
ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row);
|
||||
}
|
||||
|
||||
if (s_l[il] != nullptr) {
|
||||
const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
|
||||
llama_clear_tensor_data(s_l[il], cell_head * s_size_row, cell_count * s_size_row);
|
||||
ggml_backend_tensor_memset(s_l[il], 0, cell_head * s_size_row, cell_count * s_size_row);
|
||||
}
|
||||
|
||||
if (p_l[il] != nullptr) {
|
||||
const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state());
|
||||
llama_clear_tensor_data(p_l[il], cell_head * p_size_row, cell_count * p_size_row);
|
||||
ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5366,6 +5366,14 @@ struct test_gated_delta_net : public test_case {
|
||||
// lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence
|
||||
const float g_min;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "GATED_DELTA_NET";
|
||||
}
|
||||
|
||||
// compare only the view returned by build_graph, not the full op output
|
||||
bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; }
|
||||
|
||||
std::string vars() override {
|
||||
std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k);
|
||||
if (g_min != -20.0f) {
|
||||
@@ -5423,6 +5431,10 @@ struct test_gated_delta_net : public test_case {
|
||||
k = ggml_cpy(ctx, k, k_permuted);
|
||||
}
|
||||
ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K);
|
||||
if (K > 1 && n_seq_tokens > K) {
|
||||
// n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0
|
||||
out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -9075,17 +9087,18 @@ struct test_roll : public test_case {
|
||||
const int shift3;
|
||||
const int shift4;
|
||||
const bool permute;
|
||||
const std::array<int64_t, 4> ne_a;
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR5(shift0, shift1, shift3, shift4, permute);
|
||||
return VARS_TO_STR6(shift0, shift1, shift3, shift4, permute, ne_a);
|
||||
}
|
||||
|
||||
test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false)
|
||||
: shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute) {}
|
||||
test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false,
|
||||
std::array<int64_t, 4> ne_a = {10, 5, 4, 3})
|
||||
: shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute), ne_a(ne_a) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
int64_t ne[4] = {10, 5, 4, 3};
|
||||
ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
|
||||
ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_a.data());
|
||||
ggml_set_name(a, "a");
|
||||
|
||||
if (permute) {
|
||||
@@ -13171,6 +13184,11 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_pad_reflect_1d(GGML_TYPE_F32, {3000, 384, 4, 1}));
|
||||
test_cases.emplace_back(new test_roll());
|
||||
test_cases.emplace_back(new test_roll(3, -2, 1, -1, true));
|
||||
test_cases.emplace_back(new test_roll(0, 0, 0, 0, false, {1, 1, 1, 1}));
|
||||
test_cases.emplace_back(new test_roll(256, 0, 0, 0, false, {257, 1, 1, 1}));
|
||||
test_cases.emplace_back(new test_roll(-16, 6, -2, 1, false, {17, 7, 3, 2}));
|
||||
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1}));
|
||||
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1}));
|
||||
test_cases.emplace_back(new test_arange());
|
||||
test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 3.0f, 3.5f, 1.0f));
|
||||
test_cases.emplace_back(new test_arange(GGML_TYPE_F32, -10.0f, 10.0f, 0.3f));
|
||||
@@ -13904,6 +13922,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
|
||||
test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 0.0f, n, 1.0f));
|
||||
}
|
||||
|
||||
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1}));
|
||||
test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1}));
|
||||
|
||||
// embedding lookups: one token (decode) and one batch of 2048 tokens (prefill)
|
||||
for (int r : {16, 32768}) {
|
||||
test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 2000000, r, 1, 1, false)); // Qwen4-Exp n-gram table, 16 rows per token
|
||||
|
||||
@@ -357,14 +357,17 @@ static bool test_buft(ggml_backend_buffer_type_t buft) {
|
||||
// Mock buffer type
|
||||
//
|
||||
// Ad-hoc host-backed buffer type used to exercise the dispatch logic in
|
||||
// ggml_backend_tensor_{set,get,copy}_n without relying on real backend hooks.
|
||||
// ggml_backend_tensor_{set,get,copy}_n and ggml_backend_tensor_memset
|
||||
// without relying on real backend hooks.
|
||||
//
|
||||
|
||||
struct mock_config {
|
||||
bool memset;
|
||||
bool set_n;
|
||||
bool get_n;
|
||||
bool cpy_n;
|
||||
bool cpy_n_result;
|
||||
int set_calls;
|
||||
int set_n_calls;
|
||||
int get_n_calls;
|
||||
int cpy_n_calls;
|
||||
@@ -373,10 +376,12 @@ struct mock_config {
|
||||
static mock_config g_mock = {};
|
||||
|
||||
static void mock_config_reset(bool set_n, bool get_n, bool cpy_n, bool cpy_n_result) {
|
||||
g_mock.memset = true;
|
||||
g_mock.set_n = set_n;
|
||||
g_mock.get_n = get_n;
|
||||
g_mock.cpy_n = cpy_n;
|
||||
g_mock.cpy_n_result = cpy_n_result;
|
||||
g_mock.set_calls = 0;
|
||||
g_mock.set_n_calls = 0;
|
||||
g_mock.get_n_calls = 0;
|
||||
g_mock.cpy_n_calls = 0;
|
||||
@@ -397,6 +402,7 @@ static void mock_buffer_memset_tensor(ggml_backend_buffer_t buffer, struct ggml_
|
||||
}
|
||||
|
||||
static void mock_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
|
||||
g_mock.set_calls++;
|
||||
memcpy((char *) tensor->data + offset, data, size);
|
||||
|
||||
GGML_UNUSED(buffer);
|
||||
@@ -466,7 +472,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b
|
||||
/* .free_buffer = */ mock_buffer_free_buffer,
|
||||
/* .get_base = */ mock_buffer_get_base,
|
||||
/* .init_tensor = */ NULL,
|
||||
/* .memset_tensor = */ mock_buffer_memset_tensor,
|
||||
/* .memset_tensor = */ NULL,
|
||||
/* .set_tensor = */ mock_buffer_set_tensor,
|
||||
/* .get_tensor = */ mock_buffer_get_tensor,
|
||||
/* .set_tensor_2d = */ NULL,
|
||||
@@ -478,6 +484,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b
|
||||
/* .get_tensor_n = */ NULL,
|
||||
/* .cpy_tensor_n = */ NULL,
|
||||
};
|
||||
if (g_mock.memset) iface.memset_tensor = mock_buffer_memset_tensor;
|
||||
if (g_mock.set_n) iface.set_tensor_n = mock_buffer_set_tensor_n;
|
||||
if (g_mock.get_n) iface.get_tensor_n = mock_buffer_get_tensor_n;
|
||||
if (g_mock.cpy_n) iface.cpy_tensor_n = mock_buffer_cpy_tensor_n;
|
||||
@@ -665,13 +672,67 @@ static bool test_mock_grouping() {
|
||||
return true;
|
||||
}
|
||||
|
||||
// verify that memset routes to memset_tensor when the buffer has it and to set_tensor otherwise
|
||||
static bool test_mock_memset(bool with_hook) {
|
||||
mock_config_reset(false, false, false, true);
|
||||
g_mock.memset = with_hook;
|
||||
|
||||
ggml_init_params params = {};
|
||||
params.mem_size = ggml_tensor_overhead();
|
||||
params.no_alloc = true;
|
||||
|
||||
ggml_context_ptr ctx(ggml_init(params));
|
||||
if (!ctx) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// the fallback writes in chunks of this size, see ggml_backend_tensor_memset
|
||||
const size_t chunk_size = 1024*1024;
|
||||
const int n_chunks = 2;
|
||||
|
||||
std::vector<ggml_tensor *> tensors;
|
||||
ggml_backend_buffer_ptr buf = alloc_tensors(ctx.get(), mock_buft(), { n_chunks*chunk_size/sizeof(float) }, tensors);
|
||||
if (!buf) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t n_bytes = ggml_nbytes(tensors[0]);
|
||||
|
||||
// leaves untouched bytes at both ends
|
||||
const size_t offset = 3;
|
||||
const size_t size = n_bytes - 2*offset;
|
||||
|
||||
std::vector<uint8_t> expected(n_bytes, 0), out(n_bytes, 0);
|
||||
memset(expected.data() + offset, 0xA5, size);
|
||||
|
||||
ggml_backend_tensor_set(tensors[0], out.data(), 0, n_bytes);
|
||||
|
||||
g_mock.set_calls = 0;
|
||||
ggml_backend_tensor_memset(tensors[0], 0xA5, offset, size);
|
||||
ggml_backend_tensor_get(tensors[0], out.data(), 0, n_bytes);
|
||||
|
||||
if (out != expected) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// the hook writes without set_tensor, the fallback with one set_tensor call per chunk
|
||||
const int expected_calls = with_hook ? 0 : n_chunks;
|
||||
if (g_mock.set_calls != expected_calls) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool test_mock() {
|
||||
return
|
||||
test_mock_set_get_n(true) &&
|
||||
test_mock_set_get_n(false) &&
|
||||
test_mock_copy_n(true) &&
|
||||
test_mock_copy_n(false) &&
|
||||
test_mock_grouping();
|
||||
test_mock_grouping() &&
|
||||
test_mock_memset(true) &&
|
||||
test_mock_memset(false);
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
+34
-9
@@ -5653,6 +5653,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
|
||||
for (const int version : { 1, 2 }) {
|
||||
auto tst = peg_tester(version == 1 ? "models/templates/thinkingmachines-Inkling.jinja" :
|
||||
"models/templates/thinkingmachines-Inkling-2-Small.jinja", detailed_debug);
|
||||
tst.specials({ "<|message_model|>", "<|content_thinking|>", "<|content_text|>", "<|content_invoke_tool_json|>", "<|end_message|>" });
|
||||
|
||||
// Inkling 1 has the first header in the generation prompt, Inkling 2 writes it
|
||||
const std::string H = "<|message_model|>";
|
||||
@@ -5693,7 +5694,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
|
||||
.expect_tool_calls({
|
||||
{ "special_function", R"({"arg1":1})", "" },
|
||||
})
|
||||
.expect_rules({ "tool-0" })
|
||||
.expect_rules({ "tool-calls" })
|
||||
.expect_grammar()
|
||||
.run();
|
||||
|
||||
// Thinking, content, then a tool call
|
||||
@@ -5721,20 +5723,41 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
|
||||
})
|
||||
.run();
|
||||
|
||||
// The block closer inside a string argument does not end the block
|
||||
tst.test(P + "python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('<|end_message|>')\"}}" + E)
|
||||
.tools({ python_tool })
|
||||
.expect_tool_calls({
|
||||
{ "python", R"JSON({"code":"print('<|end_message|>')"})JSON", "" },
|
||||
})
|
||||
.run();
|
||||
|
||||
// Forced tool call
|
||||
tst.test(P + "<|content_thinking|>I should call it" + E + H + CALL)
|
||||
.reasoning_format(COMMON_REASONING_FORMAT_AUTO)
|
||||
.tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED)
|
||||
.tools({ special_function_tool })
|
||||
.expect(simple_assist_msg("", "I should call it", "special_function", R"({"arg1":1})", ""))
|
||||
.expect_rules({ "tool-0" })
|
||||
.expect_grammar()
|
||||
.run();
|
||||
|
||||
// The research model does not write the name before the tool token
|
||||
for (const auto tool_choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) {
|
||||
tst.test(P + "<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E)
|
||||
.tool_choice(tool_choice)
|
||||
.tools({ special_function_tool })
|
||||
.expect_tool_calls({
|
||||
{ "special_function", R"({"arg1":1})", "" },
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
// A tool that is not in the list, with spaces in the JSON
|
||||
tst.test(P + "unknown_tool<|content_invoke_tool_json|>{\"name\": \"unknown_tool\", \"args\": {\"arg1\": 1}}" + E)
|
||||
.tools({ special_function_tool })
|
||||
.expect_tool_calls({
|
||||
{ "unknown_tool", R"({"arg1": 1})", "" },
|
||||
})
|
||||
.run();
|
||||
|
||||
// The call takes the name in the JSON, not the one before the tool token
|
||||
tst.test(P + "special<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E)
|
||||
.tools({ special_function_tool })
|
||||
.expect_tool_calls({
|
||||
{ "special_function", R"({"arg1":1})", "" },
|
||||
})
|
||||
.run();
|
||||
|
||||
// Response format
|
||||
@@ -6012,6 +6035,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
|
||||
"models/templates/LFM2-8B-A1B.jinja",
|
||||
"models/templates/LFM2.5-Instruct.jinja",
|
||||
"models/templates/LFM2.5-8B-A1B.jinja",
|
||||
"models/templates/LFM2.5-VL.jinja",
|
||||
}) {
|
||||
test_lfm2_parser(tmpl, detailed_debug);
|
||||
}
|
||||
@@ -8215,6 +8239,7 @@ static void test_template_generation_prompt() {
|
||||
"models/templates/LFM2-8B-A1B.jinja",
|
||||
"models/templates/LFM2.5-Instruct.jinja",
|
||||
"models/templates/LFM2.5-8B-A1B.jinja",
|
||||
"models/templates/LFM2.5-VL.jinja",
|
||||
}) {
|
||||
auto tmpls = read_templates(tmpl);
|
||||
check(tmpls, basic(), "<|im_start|>assistant\n");
|
||||
|
||||
@@ -609,6 +609,50 @@ MAKE_TEST(test_audio_preprocessor_whisper_chunks) {
|
||||
}
|
||||
}
|
||||
|
||||
MAKE_TEST(test_audio_preprocessor_qwen3a_tail) {
|
||||
mtmd_hparams hparams;
|
||||
hparams.n_mel_bins = 128;
|
||||
hparams.audio_sample_rate = 16000;
|
||||
hparams.audio_n_fft = 400;
|
||||
hparams.audio_window_len = 400;
|
||||
hparams.audio_hop_len = 160;
|
||||
|
||||
ggml_backend_ptr backend(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr));
|
||||
ggml_backend_t backends[] = { backend.get() };
|
||||
ggml_backend_sched_ptr sched(ggml_backend_sched_new(backends, nullptr, 1, 256, false, true));
|
||||
|
||||
mtmd_audio_preprocessor_qwen3a preproc(hparams, sched.get());
|
||||
preproc.initialize();
|
||||
|
||||
// one 800-frame window covers 128000 samples (hop 160), so longer audio is split;
|
||||
// the last window is emitted with its exact frame count, the graph pads the final 100-frame chunk
|
||||
// { sample count, expected n_len of each output window }
|
||||
const std::vector<std::pair<size_t, std::vector<int64_t>>> cases = {
|
||||
{ 0, {} },
|
||||
{ 1, {1} },
|
||||
{ 32000, {200} },
|
||||
{ 128000, {800} },
|
||||
{ 128160, {800, 1} },
|
||||
{ 168000, {800, 250} },
|
||||
{ 170080, {800, 263} },
|
||||
{ 176000, {800, 300} },
|
||||
};
|
||||
|
||||
for (const auto & [n_samples, expected] : cases) {
|
||||
const std::string name = std::to_string(n_samples) + " samples";
|
||||
std::vector<float> samples(n_samples, 0.0f);
|
||||
if (n_samples > 0) {
|
||||
samples.back() = 0.5f;
|
||||
}
|
||||
mtmd_audio_preproc_out out = preproc.preprocess(samples.data(), samples.size());
|
||||
t.assert_equal("windows for " + name, expected.size(), out.entries.size());
|
||||
for (size_t i = 0; i < out.entries.size(); i++) {
|
||||
t.assert_equal("frames for " + name, expected[i], out.entries[i].nx());
|
||||
t.assert_equal("mel bins for " + name, 128, out.entries[i].ny());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MAKE_TEST(test_audio_preprocessor_conformer) {
|
||||
mtmd_hparams hparams;
|
||||
hparams.n_mel_bins = 128;
|
||||
@@ -837,6 +881,64 @@ static double tone_amplitude(const std::vector<float> & x, double freq, int rate
|
||||
return 2.0 * std::sqrt(re * re + im * im) / (x.size() - 2 * skip);
|
||||
}
|
||||
|
||||
MAKE_TEST(test_audio_fft) {
|
||||
// the sizes in use: powers of two, and an odd part (400 = 16 * 25, 736 = 32 * 23, 1920 = 128 * 15)
|
||||
// plus small edge cases: 4 = gather + one stage, 6 = n_odd 3 with n_sub 2, 15 = odd composite with n_sub 1
|
||||
const int sizes[] = { 1, 2, 3, 4, 6, 12, 15, 256, 400, 512, 736, 1920 };
|
||||
const double pi = 3.14159265358979323846;
|
||||
for (int n : sizes) {
|
||||
mtmd_audio_cache cache;
|
||||
cache.fill_sin_cos_table(n);
|
||||
// phase offset so that x[0] != 0 (n = 1 would otherwise compare all zeros)
|
||||
std::vector<float> x(2 * n);
|
||||
for (int i = 0; i < 2 * n; i++) {
|
||||
x[i] = (float) std::sin(0.37 * i + 0.001 * i * i + 0.5);
|
||||
}
|
||||
std::vector<float> out(8 * n);
|
||||
for (bool inv : { false, true }) {
|
||||
// input sized exactly as documented so that sanitizers catch any overread
|
||||
const std::vector<float> in(x.begin(), x.begin() + (inv ? 2 * n : n));
|
||||
if (inv) {
|
||||
mtmd_audio_ifft(cache, in.data(), n, out.data());
|
||||
} else {
|
||||
mtmd_audio_fft(cache, in.data(), n, out.data());
|
||||
}
|
||||
double max_err = 0.0, max_ref = 0.0;
|
||||
for (int k = 0; k < n; k++) {
|
||||
double re = 0.0, im = 0.0;
|
||||
for (int j = 0; j < n; j++) {
|
||||
const double theta = (inv ? 2 : -2) * pi * (double) ((int64_t) j * k % n) / n;
|
||||
const double a = inv ? x[2 * j] : x[j];
|
||||
const double b = inv ? x[2 * j + 1] : 0.0;
|
||||
re += a * std::cos(theta) - b * std::sin(theta);
|
||||
im += a * std::sin(theta) + b * std::cos(theta);
|
||||
}
|
||||
if (inv) {
|
||||
re /= n;
|
||||
im /= n;
|
||||
}
|
||||
max_err = std::max({ max_err, std::fabs(re - out[2 * k]), std::fabs(im - out[2 * k + 1]) });
|
||||
max_ref = std::max({ max_ref, std::fabs(re), std::fabs(im) });
|
||||
}
|
||||
t.assert_true(std::string(inv ? "ifft" : "fft") + " n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref),
|
||||
max_ref > 0.0 && max_err <= 1e-5 * max_ref);
|
||||
}
|
||||
|
||||
// round trip: ifft(fft(x)) == x for real x
|
||||
std::vector<float> spec(8 * n);
|
||||
mtmd_audio_fft(cache, x.data(), n, spec.data());
|
||||
const std::vector<float> spec_in(spec.begin(), spec.begin() + 2 * n);
|
||||
mtmd_audio_ifft(cache, spec_in.data(), n, out.data());
|
||||
double max_err = 0.0, max_ref = 0.0;
|
||||
for (int k = 0; k < n; k++) {
|
||||
max_err = std::max({ max_err, (double) std::fabs(out[2 * k] - x[k]), (double) std::fabs(out[2 * k + 1]) });
|
||||
max_ref = std::max(max_ref, (double) std::fabs(x[k]));
|
||||
}
|
||||
t.assert_true("fft round trip n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref),
|
||||
max_ref > 0.0 && max_err <= 1e-5 * max_ref);
|
||||
}
|
||||
}
|
||||
|
||||
static std::vector<float> resample_chunked(mtmd_helper_resampler * rs, const std::vector<float> & in, size_t chunk) {
|
||||
std::vector<float> res;
|
||||
for (size_t off = 0; off < in.size(); off += chunk) {
|
||||
@@ -1062,6 +1164,27 @@ MAKE_TEST(test_kokoro_istft) {
|
||||
t.assert_true("constant signal, max error " + std::to_string(max_err), max_err < 1e-4f);
|
||||
}
|
||||
|
||||
// 13 tokens per 100-frame chunk; the tail is ceil^3 (one halving per stride-2 conv layer)
|
||||
MAKE_TEST(test_qwen3a_tokens_for_frames) {
|
||||
const std::vector<std::pair<int64_t, int64_t>> cases = {
|
||||
{ 0, 0 },
|
||||
{ 1, 1 },
|
||||
{ 99, 13 },
|
||||
{ 100, 13 },
|
||||
{ 101, 14 },
|
||||
{ 110, 15 },
|
||||
{ 200, 26 },
|
||||
{ 210, 28 },
|
||||
{ 1000, 130 },
|
||||
{ 1024, 133 },
|
||||
};
|
||||
|
||||
for (const auto & [frames, expected] : cases) {
|
||||
const std::string name = std::to_string(frames) + " frames";
|
||||
t.assert_equal(name, expected, mtmd_graph_qwen3a::qwen3a_tokens_for_frames(frames));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// main
|
||||
//
|
||||
|
||||
@@ -387,6 +387,10 @@ struct mtmd_graph_mobilenetv5 : mtmd_graph {
|
||||
struct mtmd_graph_qwen3a : mtmd_graph {
|
||||
mtmd_graph_qwen3a(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {}
|
||||
ggml_cgraph * build() override;
|
||||
|
||||
// audio tokens from n_frames mel frames: 13 per 100-frame chunk, ceil^3(tail) otherwise.
|
||||
// shared with mtmd_model::n_output_tokens so they cannot drift
|
||||
static int64_t qwen3a_tokens_for_frames(int64_t n_frames);
|
||||
};
|
||||
|
||||
struct mtmd_graph_mimo_audio : mtmd_graph {
|
||||
|
||||
@@ -6,14 +6,19 @@ ggml_cgraph * mtmd_graph_qwen3a::build() {
|
||||
// inp_raw: [n_frames, n_mel, 1] (nx=n_frames, ny=n_mel)
|
||||
ggml_tensor * inp = build_inp_raw(1);
|
||||
|
||||
const int64_t n_frames = inp->ne[0]; // total frames, padded to multiple of chunk_size
|
||||
const int64_t n_mel = inp->ne[1]; // 128
|
||||
const int64_t chunk_size = 100; // n_window * 2 (n_window=50 from model config)
|
||||
const int64_t n_chunks = n_frames / chunk_size;
|
||||
const int64_t n_chunks = (inp->ne[0] + chunk_size - 1) / chunk_size;
|
||||
const int64_t n_pre_pad = inp->ne[0];
|
||||
|
||||
GGML_ASSERT(n_frames % chunk_size == 0); // preprocessor should already pad the input
|
||||
GGML_ASSERT(inp->type == GGML_TYPE_F32);
|
||||
|
||||
// zero-pad the last chunk to chunk_size, as the reference pads all chunks to the longest one
|
||||
if (n_pre_pad % chunk_size > 0) {
|
||||
inp = ggml_pad(ctx0, inp, n_chunks * chunk_size - n_pre_pad, 0, 0, 0);
|
||||
}
|
||||
const int64_t n_frames = inp->ne[0];
|
||||
|
||||
// View mel spectrogram as batched 100-frame chunks: [chunk_size, n_mel, 1, n_chunks]
|
||||
inp = ggml_view_4d(ctx0, inp,
|
||||
chunk_size, n_mel, 1, n_chunks,
|
||||
@@ -69,7 +74,11 @@ ggml_cgraph * mtmd_graph_qwen3a::build() {
|
||||
inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, pos_tmp, tgt));
|
||||
}
|
||||
|
||||
ggml_tensor * cur = build_vit(inp, n_pos,
|
||||
// drop the outputs of the padding in the last chunk
|
||||
const int64_t n_out = qwen3a_tokens_for_frames(n_pre_pad);
|
||||
inp = ggml_view_2d(ctx0, inp, inp->ne[0], n_out, inp->nb[1], 0);
|
||||
|
||||
ggml_tensor * cur = build_vit(inp, n_out,
|
||||
NORM_TYPE_NORMAL, hparams.ffn_op,
|
||||
nullptr, // pos embd already added above
|
||||
nullptr);
|
||||
|
||||
+124
-138
@@ -129,152 +129,140 @@ void mtmd_audio_cache::fill_mel_filterbank_matrix(int64_t n_mel,
|
||||
}
|
||||
}
|
||||
|
||||
// Unified DFT implementation for both forward and inverse transforms
|
||||
// FFT/IFFT of N = n_sub * n_odd points (n_sub a power of two, n_odd odd): batched odd-size DFT of the n_sub subsequences into bit-reversed blocks, then iterative radix-2 stages
|
||||
// matches the previous recursive implementation for finite inputs (the twiddle-1 multiply of the first stage is skipped when n_odd == 1)
|
||||
// Template parameters:
|
||||
// Inverse: false = DFT with exp(-2πi·k·n/N), no scaling
|
||||
// true = IDFT with exp(+2πi·k·n/N), scales by 1/N
|
||||
// RealInput: true = input is real-valued (stride 1), avoids imaginary computations
|
||||
// false = input is complex-valued (interleaved real/imag, stride 2)
|
||||
template <bool Inverse, bool RealInput>
|
||||
static void dft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
const int n_sin_cos_vals = cache.sin_vals.size();
|
||||
const int sin_cos_step = n_sin_cos_vals / N;
|
||||
|
||||
constexpr float sign = Inverse ? 1.0f : -1.0f;
|
||||
const float scale = Inverse ? (1.0f / N) : 1.0f;
|
||||
|
||||
for (int k = 0; k < N; k++) {
|
||||
float re = 0;
|
||||
float im = 0;
|
||||
|
||||
for (int n = 0; n < N; n++) {
|
||||
int idx = (k * n * sin_cos_step) % n_sin_cos_vals;
|
||||
float cos_val = cache.cos_vals[idx];
|
||||
float sin_val = cache.sin_vals[idx];
|
||||
|
||||
if constexpr (RealInput) {
|
||||
// Real input: in_im = 0, simplifies to:
|
||||
// re += in_re * cos_val
|
||||
// im += sign * in_re * sin_val
|
||||
float in_re = in[n];
|
||||
re += in_re * cos_val;
|
||||
im += sign * in_re * sin_val;
|
||||
} else {
|
||||
float in_re = in[n * 2 + 0];
|
||||
float in_im = in[n * 2 + 1];
|
||||
// (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i
|
||||
re += in_re * cos_val - sign * in_im * sin_val;
|
||||
im += sign * in_re * sin_val + in_im * cos_val;
|
||||
}
|
||||
}
|
||||
|
||||
out[k * 2 + 0] = re * scale;
|
||||
out[k * 2 + 1] = im * scale;
|
||||
}
|
||||
}
|
||||
|
||||
// Cooley-Tukey FFT/IFFT unified implementation
|
||||
// Template parameters:
|
||||
// Inverse: false = FFT with exp(-2πi·k/N), no scaling
|
||||
// true = IFFT with exp(+2πi·k/N), scales by 0.5 at each level
|
||||
// Inverse: false = FFT with exp(-2 pi i k / N), no scaling
|
||||
// true = IFFT with exp(+2 pi i k / N), scales by 1/N (1/n_odd in the DFT, 0.5 per stage)
|
||||
// RealInput: true = input is real-valued (stride 1)
|
||||
// false = input is complex-valued (interleaved real/imag, stride 2)
|
||||
// in is not modified, out needs 2 * N floats + 2 * max(N / 2, n_sub) floats of scratch
|
||||
template <bool Inverse, bool RealInput>
|
||||
static void fft_impl(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
static void fft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
GGML_ASSERT(N > 0);
|
||||
const int n_sin_cos_vals = cache.sin_vals.size();
|
||||
|
||||
if (N == 1) {
|
||||
out[0] = in[0];
|
||||
if constexpr (RealInput) {
|
||||
out[1] = 0.0f;
|
||||
} else {
|
||||
out[1] = in[1];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const int half_N = N / 2;
|
||||
if (N - half_N * 2 == 1) {
|
||||
// Odd N: fall back to DFT
|
||||
dft_impl<Inverse, RealInput>(cache, in, N, out);
|
||||
return;
|
||||
}
|
||||
|
||||
// Split into even and odd
|
||||
if constexpr (RealInput) {
|
||||
// Real input: stride is 1, copy only real values
|
||||
float * even = in + N;
|
||||
for (int i = 0; i < half_N; ++i) {
|
||||
even[i] = in[2 * i];
|
||||
}
|
||||
float * even_fft = out + 2 * N;
|
||||
fft_impl<Inverse, true>(cache, even, half_N, even_fft);
|
||||
|
||||
float * odd = even;
|
||||
for (int i = 0; i < half_N; ++i) {
|
||||
odd[i] = in[2 * i + 1];
|
||||
}
|
||||
float * odd_fft = even_fft + N;
|
||||
fft_impl<Inverse, true>(cache, odd, half_N, odd_fft);
|
||||
} else {
|
||||
// Complex input: stride is 2, copy complex pairs
|
||||
float * even = in + N * 2;
|
||||
for (int i = 0; i < half_N; ++i) {
|
||||
even[i * 2 + 0] = in[2 * i * 2 + 0];
|
||||
even[i * 2 + 1] = in[2 * i * 2 + 1];
|
||||
}
|
||||
float * even_fft = out + 2 * N;
|
||||
fft_impl<Inverse, false>(cache, even, half_N, even_fft);
|
||||
|
||||
float * odd = even;
|
||||
for (int i = 0; i < half_N; ++i) {
|
||||
odd[i * 2 + 0] = in[(2 * i + 1) * 2 + 0];
|
||||
odd[i * 2 + 1] = in[(2 * i + 1) * 2 + 1];
|
||||
}
|
||||
float * odd_fft = even_fft + N;
|
||||
fft_impl<Inverse, false>(cache, odd, half_N, odd_fft);
|
||||
}
|
||||
|
||||
float * even_fft = out + 2 * N;
|
||||
float * odd_fft = even_fft + N;
|
||||
|
||||
const int sin_cos_step = n_sin_cos_vals / N;
|
||||
|
||||
constexpr float sign = Inverse ? 1.0f : -1.0f;
|
||||
constexpr float scale = Inverse ? 0.5f : 1.0f;
|
||||
constexpr int n_in = RealInput ? 1 : 2; // floats per input value
|
||||
|
||||
for (int k = 0; k < half_N; k++) {
|
||||
int idx = k * sin_cos_step; // t = 2*M_PI*k/N
|
||||
float re = cache.cos_vals[idx];
|
||||
float im = sign * cache.sin_vals[idx];
|
||||
int n_odd = N;
|
||||
while (n_odd % 2 == 0) {
|
||||
n_odd /= 2;
|
||||
}
|
||||
const int n_sub = N / n_odd;
|
||||
|
||||
float re_odd = odd_fft[2 * k + 0];
|
||||
float im_odd = odd_fft[2 * k + 1];
|
||||
// j = bitrev(r) for r = 0, 1, ...: add 1 to j starting from its highest bit h
|
||||
auto bitrev_next = [](int & j, int h) {
|
||||
for (; j & h; h >>= 1) {
|
||||
j ^= h;
|
||||
}
|
||||
j |= h;
|
||||
};
|
||||
|
||||
out[2 * k + 0] = scale * (even_fft[2 * k + 0] + re * re_odd - im * im_odd);
|
||||
out[2 * k + 1] = scale * (even_fft[2 * k + 1] + re * im_odd + im * re_odd);
|
||||
float * scratch = out + 2 * N;
|
||||
int len = 2 * n_odd; // size of the blocks after the next stage
|
||||
if (n_odd > 1) {
|
||||
const int sin_cos_step = n_sin_cos_vals / n_odd;
|
||||
const float dft_scale = Inverse ? (1.0f / n_odd) : 1.0f;
|
||||
float * acc = scratch;
|
||||
for (int k = 0; k < n_odd; k++) {
|
||||
std::fill(acc, acc + 2 * n_sub, 0.0f);
|
||||
int idx = 0; // (k * n * sin_cos_step) % n_sin_cos_vals
|
||||
for (int n = 0; n < n_odd; n++) {
|
||||
const float cos_val = cache.cos_vals[idx];
|
||||
const float sin_val = cache.sin_vals[idx];
|
||||
const float * x = in + n * n_sub * n_in;
|
||||
for (int r = 0; r < n_sub; r++) {
|
||||
if constexpr (RealInput) {
|
||||
acc[2 * r + 0] += x[r] * cos_val;
|
||||
acc[2 * r + 1] += sign * x[r] * sin_val;
|
||||
} else {
|
||||
// (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i
|
||||
acc[2 * r + 0] += x[2 * r + 0] * cos_val - sign * x[2 * r + 1] * sin_val;
|
||||
acc[2 * r + 1] += sign * x[2 * r + 0] * sin_val + x[2 * r + 1] * cos_val;
|
||||
}
|
||||
}
|
||||
idx += k * sin_cos_step;
|
||||
if (idx >= n_sin_cos_vals) {
|
||||
idx -= n_sin_cos_vals;
|
||||
}
|
||||
}
|
||||
for (int r = 0, j = 0; r < n_sub; r++, bitrev_next(j, n_sub / 2)) {
|
||||
out[2 * (j * n_odd + k) + 0] = acc[2 * r + 0] * dft_scale;
|
||||
out[2 * (j * n_odd + k) + 1] = acc[2 * r + 1] * dft_scale;
|
||||
}
|
||||
}
|
||||
} else if (N == 1) {
|
||||
out[0] = in[0];
|
||||
out[1] = RealInput ? 0.0f : in[1];
|
||||
return;
|
||||
} else {
|
||||
// size 1 subsequences: the values r and r + N / 2 form block bitrev(r) of the first stage
|
||||
const int half_N = N / 2;
|
||||
for (int j = 0, r = 0; j < half_N; j++, bitrev_next(r, half_N / 2)) {
|
||||
const float * a = in + r * n_in;
|
||||
const float * b = in + (r + half_N) * n_in;
|
||||
if constexpr (RealInput) {
|
||||
out[4 * j + 0] = scale * (a[0] + b[0]);
|
||||
out[4 * j + 1] = 0.0f;
|
||||
out[4 * j + 2] = scale * (a[0] - b[0]);
|
||||
out[4 * j + 3] = 0.0f;
|
||||
} else {
|
||||
out[4 * j + 0] = scale * (a[0] + b[0]);
|
||||
out[4 * j + 1] = scale * (a[1] + b[1]);
|
||||
out[4 * j + 2] = scale * (a[0] - b[0]);
|
||||
out[4 * j + 3] = scale * (a[1] - b[1]);
|
||||
}
|
||||
}
|
||||
len = 4;
|
||||
}
|
||||
|
||||
out[2 * (k + half_N) + 0] = scale * (even_fft[2 * k + 0] - re * re_odd + im * im_odd);
|
||||
out[2 * (k + half_N) + 1] = scale * (even_fft[2 * k + 1] - re * im_odd - im * re_odd);
|
||||
for (; len <= N; len *= 2) {
|
||||
const int half_N = len / 2;
|
||||
const int sin_cos_step = n_sin_cos_vals / len;
|
||||
// twiddles of this stage, contiguous
|
||||
float * twiddle = scratch;
|
||||
for (int k = 0; k < half_N; k++) {
|
||||
twiddle[2 * k + 0] = cache.cos_vals[k * sin_cos_step]; // t = 2*M_PI*k/len
|
||||
twiddle[2 * k + 1] = sign * cache.sin_vals[k * sin_cos_step];
|
||||
}
|
||||
for (int i = 0; i < N; i += len) {
|
||||
float * even_fft = out + 2 * i;
|
||||
float * odd_fft = even_fft + 2 * half_N;
|
||||
for (int k = 0; k < half_N; k++) {
|
||||
const float re = twiddle[2 * k + 0];
|
||||
const float im = twiddle[2 * k + 1];
|
||||
const float re_even = even_fft[2 * k + 0];
|
||||
const float im_even = even_fft[2 * k + 1];
|
||||
const float re_odd = odd_fft[2 * k + 0];
|
||||
const float im_odd = odd_fft[2 * k + 1];
|
||||
|
||||
even_fft[2 * k + 0] = scale * (re_even + re * re_odd - im * im_odd);
|
||||
even_fft[2 * k + 1] = scale * (im_even + re * im_odd + im * re_odd);
|
||||
|
||||
odd_fft[2 * k + 0] = scale * (re_even - re * re_odd + im * im_odd);
|
||||
odd_fft[2 * k + 1] = scale * (im_even - re * im_odd - im * re_odd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Forward FFT for real input (used by mel spectrogram)
|
||||
static void fft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
static void fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
fft_impl<false, true>(cache, in, N, out);
|
||||
}
|
||||
|
||||
// Inverse FFT for complex input
|
||||
static void ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
static void ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
fft_impl<true, false>(cache, in, N, out);
|
||||
}
|
||||
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
fft(cache, in, N, out);
|
||||
}
|
||||
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) {
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) {
|
||||
ifft(cache, in, N, out);
|
||||
}
|
||||
|
||||
@@ -594,9 +582,10 @@ bool mtmd_audio_preprocessor_whisper::process(const float * samp
|
||||
//
|
||||
// Matches the Python WhisperFeatureExtractor called with truncation=False:
|
||||
// - reflection padding of n_fft/2 samples at each end (center=True)
|
||||
// - Whisper-style log10 + (max-8)/4 normalization applied to full audio
|
||||
// - output split into ≤30s (3000 mel frames) windows, each padded to a
|
||||
// multiple of 200 frames (n_window * 2) for the cgraph batch view
|
||||
// - the last STFT frame is dropped, giving n_samples / hop_length frames
|
||||
// - Whisper-style log10 + (max-8)/4 normalization over the kept frames
|
||||
// - output split into 800-frame (n_window_infer) windows; the graph
|
||||
// zero-pads the last 100-frame chunk
|
||||
//
|
||||
|
||||
void mtmd_audio_preprocessor_qwen3a::initialize() {
|
||||
@@ -648,11 +637,17 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl
|
||||
return false;
|
||||
}
|
||||
|
||||
// Whisper-style normalization: clamp to (max - 8), scale to [-1, 1]
|
||||
{
|
||||
// WhisperFeatureExtractor drops the last STFT frame, keeping n_samples / hop_length frames;
|
||||
// sub-hop clips would give 0 frames, clamp to 1 so the cgraph stays non-empty
|
||||
const int64_t n_eff = std::max<int64_t>(1, std::min(mel_full.n_len - 1, (int64_t)(n_samples / hparams.audio_hop_len)));
|
||||
|
||||
// Whisper-style normalization over the kept frames: clamp to (max - 8), scale to [-1, 1]
|
||||
if (!shape_only) {
|
||||
double mmax = -1e20;
|
||||
for (float v : mel_full.data) {
|
||||
if (v > mmax) mmax = v;
|
||||
for (int64_t m = 0; m < mel_full.n_mel; m++) {
|
||||
for (int64_t t = 0; t < n_eff; t++) {
|
||||
mmax = std::max(mmax, (double)mel_full.data[m * mel_full.n_len + t]);
|
||||
}
|
||||
}
|
||||
mmax -= 8.0;
|
||||
for (float & v : mel_full.data) {
|
||||
@@ -660,25 +655,16 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl
|
||||
}
|
||||
}
|
||||
|
||||
// The effective frame count: center-padded STFT gives ~n_samples/hop_length frames.
|
||||
// We take min(mel_full.n_len, n_samples/hop + 1) to avoid including excess frames.
|
||||
const int64_t n_eff = std::min(mel_full.n_len,
|
||||
(int64_t)(n_samples / hparams.audio_hop_len) + 1);
|
||||
|
||||
// Split into inference windows matching n_window_infer=800 from model config.
|
||||
// Each window is padded to the next multiple of chunk_size for the cgraph.
|
||||
// The mtmd caller loops over output entries, so long audio is handled automatically.
|
||||
const int chunk_size = 100; // conv sub-chunk size (n_window * 2, n_window=50)
|
||||
const int window_size = 800; // mel frames per forward pass (n_window_infer=800)
|
||||
|
||||
for (int64_t off = 0; off < n_eff; off += window_size) {
|
||||
const int64_t win_eff = std::min((int64_t)window_size, n_eff - off);
|
||||
const int64_t n_chunks = (win_eff + chunk_size - 1) / chunk_size;
|
||||
const int64_t n_padded = n_chunks * chunk_size;
|
||||
|
||||
mtmd_audio_mel out;
|
||||
out.n_mel = mel_full.n_mel;
|
||||
out.n_len = n_padded;
|
||||
out.n_len = win_eff;
|
||||
out.n_len_org = win_eff;
|
||||
out.data.assign((size_t)out.n_mel * (size_t)out.n_len, 0.0f);
|
||||
for (int64_t m = 0; m < out.n_mel; m++) {
|
||||
@@ -1957,7 +1943,7 @@ mtmd_audio_zonos3_synth::mtmd_audio_zonos3_synth(const std::vector<float> & mixe
|
||||
b.n_fft = n_fft[i];
|
||||
b.cache.fill_sin_cos_table(b.n_fft);
|
||||
b.cache.fill_hann_window(b.n_fft, true);
|
||||
b.ifft_in.assign((size_t) b.n_fft * 2 * 4, 0.0f);
|
||||
b.ifft_in.assign((size_t) b.n_fft * 2, 0.0f);
|
||||
b.ifft_out.assign((size_t) b.n_fft * 2 * 4, 0.0f);
|
||||
b.mix_in.assign((size_t) h, 0.0f);
|
||||
b.mix_avail = h;
|
||||
@@ -2118,7 +2104,7 @@ mtmd_audio_streaming_istft::mtmd_audio_streaming_istft(int n_fft, int hop_length
|
||||
overlap_buffer(n_fft, 0.0f),
|
||||
window_sum_buffer(n_fft, 0.0f),
|
||||
padding_to_remove((n_fft - hop_length) / 2),
|
||||
ifft_in(n_fft * 2 * 4, 0.0f), // extra space for recursive IFFT
|
||||
ifft_in(n_fft * 2, 0.0f),
|
||||
ifft_out(n_fft * 2 * 4, 0.0f) {
|
||||
GGML_ASSERT(n_fft > 0 && hop_length > 0 && hop_length <= n_fft);
|
||||
cache.fill_sin_cos_table(n_fft);
|
||||
|
||||
@@ -52,10 +52,10 @@ struct mtmd_audio_cache {
|
||||
);
|
||||
};
|
||||
|
||||
// FFT of N real samples -> N complex values (interleaved), in needs 2 * N floats and out 8 * N floats (scratch)
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out);
|
||||
// inverse FFT of N complex values (interleaved), scaled by 1 / N; in and out need 8 * N floats (scratch)
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out);
|
||||
// FFT of N real samples -> N complex values (interleaved), in holds N floats, out needs 8 * N floats (scratch)
|
||||
void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out);
|
||||
// inverse FFT of N complex values (interleaved), scaled by 1 / N; in holds 2 * N floats, out needs 8 * N floats (scratch)
|
||||
void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out);
|
||||
|
||||
// compute one log10-mel frame from n_fft windowed samples, cache must be initialized for n_fft
|
||||
void mtmd_audio_log_mel_frame(const mtmd_audio_cache & cache, const float * samples, int n_fft, int n_mel, float * out);
|
||||
@@ -208,6 +208,7 @@ struct mtmd_audio_preprocessor_gemma4ua : mtmd_audio_preprocessor {
|
||||
|
||||
struct mtmd_audio_preprocessor_qwen3a : mtmd_audio_preprocessor {
|
||||
mtmd_audio_preprocessor_qwen3a(const mtmd_model * model) : mtmd_audio_preprocessor(model) {}
|
||||
mtmd_audio_preprocessor_qwen3a(const mtmd_hparams & hparams, ggml_backend_sched_t sched) : mtmd_audio_preprocessor(hparams, sched) {}
|
||||
void initialize() override;
|
||||
bool process(const float * samples, size_t n_samples, std::vector<mtmd_audio_mel> & output, bool shape_only) const override;
|
||||
|
||||
|
||||
@@ -4737,6 +4737,16 @@ int mtmd_model::n_output_tokens_y(const mtmd_image_f32 * img) const {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int64_t mtmd_graph_qwen3a::qwen3a_tokens_for_frames(int64_t n_frames) {
|
||||
const int64_t chunk_size = 100; // n_window * 2
|
||||
const int64_t tokens_per_chunk = 13; // 100 -> 50 -> 25 -> 13 after 3x stride-2 conv2d
|
||||
const int64_t n_full = n_frames / chunk_size;
|
||||
const int64_t n_tail = n_frames % chunk_size;
|
||||
// ceil(ceil(ceil(n_tail / 2) / 2) / 2), one halving per conv layer
|
||||
const int64_t n_tail_tokens = n_tail == 0 ? 0 : (((n_tail + 1) / 2 + 1) / 2 + 1) / 2;
|
||||
return n_full * tokens_per_chunk + n_tail_tokens;
|
||||
}
|
||||
|
||||
int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const {
|
||||
const auto & params = hparams;
|
||||
|
||||
@@ -4946,10 +4956,7 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const {
|
||||
} break;
|
||||
case PROJECTOR_TYPE_QWEN3A:
|
||||
{
|
||||
// chunk_size=100 frames --> 3x stride-2 conv2d --> 13 tokens per chunk
|
||||
const int chunk_size = 100;
|
||||
const int tokens_per_chunk = 13;
|
||||
n_patches = (img->nx() / chunk_size) * tokens_per_chunk;
|
||||
n_patches = (int) mtmd_graph_qwen3a::qwen3a_tokens_for_frames(img->nx());
|
||||
} break;
|
||||
case PROJECTOR_TYPE_GLMA:
|
||||
{
|
||||
|
||||
@@ -31,7 +31,29 @@
|
||||
|
||||
<div class={['flex w-5 shrink-0 items-center justify-center', className]}>
|
||||
{#if isLoading}
|
||||
<MODEL_LOAD_ICONS.loading class="{ICON_CLASS_DEFAULT} animate-spin text-muted-foreground" />
|
||||
<MODEL_LOAD_ICONS.loading
|
||||
class="{ICON_CLASS_DEFAULT} animate-spin text-muted-foreground {showAction && revealOnHover
|
||||
? 'group-hover:hidden [@media(pointer:coarse)]:hidden'
|
||||
: ''}"
|
||||
/>
|
||||
|
||||
<div
|
||||
class={!showAction
|
||||
? 'hidden'
|
||||
: revealOnHover
|
||||
? 'hidden group-hover:flex [@media(pointer:coarse)]:flex'
|
||||
: 'flex'}
|
||||
>
|
||||
<ActionIcon
|
||||
class="h-5 w-5 hover:text-foreground"
|
||||
icon={MODEL_LOAD_ICONS.cancel}
|
||||
iconSize="h-4 w-4"
|
||||
onclick={() => modelsStore.status.cancelLoad(option.model)}
|
||||
stopPropagationOnClick
|
||||
tooltip="Cancel loading model"
|
||||
tooltipAsTitle
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- the state dot is what the row shows at rest; the action takes its place on hover -->
|
||||
{#if showAction && revealOnHover}
|
||||
|
||||
@@ -22,6 +22,7 @@ import LoadIcon from '@lucide/svelte/icons/power';
|
||||
import RetryIcon from '@lucide/svelte/icons/rotate-cw';
|
||||
import PromptCommandIcon from '@lucide/svelte/icons/sparkles';
|
||||
import VideoIcon from '@lucide/svelte/icons/video';
|
||||
import CancelLoadIcon from '@lucide/svelte/icons/x';
|
||||
import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
|
||||
import type { ModelCapabilities } from '#lib/types/models.js';
|
||||
import type { Component } from 'svelte';
|
||||
@@ -80,6 +81,7 @@ export const MODEL_DOWNLOAD_ICONS = {
|
||||
|
||||
/** Icons the model load control shows for its states and actions. */
|
||||
export const MODEL_LOAD_ICONS = {
|
||||
cancel: CancelLoadIcon,
|
||||
failed: LoadFailedIcon,
|
||||
load: LoadIcon,
|
||||
loading: LoadingIcon,
|
||||
|
||||
@@ -152,6 +152,8 @@ export class ModelStatusManager {
|
||||
private listedSidecarsByRepo = $derived.by(() =>
|
||||
ModelsService.draftSidecarsByRepo(this.host.routerModels)
|
||||
);
|
||||
/** Models whose load the user cancelled; the failure the force-kill triggers is intentional, not a load failure. */
|
||||
private loadCancelRequests = new SvelteSet<string>();
|
||||
private loadingStates = new SvelteMap<string, boolean>();
|
||||
private loadProgress = new SvelteMap<string, ModelLoadProgress>();
|
||||
/** Paused downloads with their last reported progress, or null when none arrived before the pause. */
|
||||
@@ -198,8 +200,8 @@ export class ModelStatusManager {
|
||||
});
|
||||
// /models/sse feed state, the single source of truth for status and load progress
|
||||
private statusAbort: AbortController | null = null;
|
||||
private statusReaderActive = false;
|
||||
|
||||
private statusReaderActive = false;
|
||||
private statusWaiters = new SvelteMap<
|
||||
string,
|
||||
{ target: ServerModelStatus; resolve: () => void; reject: (e: Error) => void }[]
|
||||
@@ -269,10 +271,15 @@ export class ModelStatusManager {
|
||||
|
||||
this.subscribe();
|
||||
|
||||
// mark before the kill: the feed can report the child's death before
|
||||
// this request returns, and load() must not toast it as a failure
|
||||
this.loadCancelRequests.add(modelId);
|
||||
|
||||
try {
|
||||
await ModelsService.unload(modelId);
|
||||
toast.info(`Load cancelled: ${this.host.toDisplayName(modelId)}`);
|
||||
} catch (error) {
|
||||
this.loadCancelRequests.delete(modelId);
|
||||
toast.error(`Failed to cancel load: ${this.host.toDisplayName(modelId)}`);
|
||||
|
||||
throw error;
|
||||
@@ -516,11 +523,17 @@ export class ModelStatusManager {
|
||||
toast.success(`Model loaded: ${this.host.toDisplayName(modelId)}`);
|
||||
} catch (error) {
|
||||
this.rejectStatus(modelId, error instanceof Error ? error : new Error('load failed'));
|
||||
this.host.error = error instanceof Error ? error.message : 'Failed to load model';
|
||||
toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`);
|
||||
|
||||
// a user cancel force-kills the child, which settles this waiter as a
|
||||
// failure; cancelLoad already reported the cancel, so stay silent
|
||||
if (!this.loadCancelRequests.delete(modelId)) {
|
||||
this.host.error = error instanceof Error ? error.message : 'Failed to load model';
|
||||
toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`);
|
||||
}
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
this.loadCancelRequests.delete(modelId);
|
||||
this.loadingStates.set(modelId, false);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user