Compare commits

..
6 Commits
Author SHA1 Message Date
Alexey Kopytko f4f6f2e7db ggml-backend : generic fallback in ggml_backend_tensor_memset (#32574) 2026-11-23 09:48:16 +09:00
Xuan-Son Nguyen 253671d882 chat: fix LFM2.5-VL template detection (#32843) 2026-11-23 01:20:22 +01:00
yochandXuan Son Nguyen 94f3af3d09 mtmd: speed up shared audio FFT (#32815)
* mtmd: speed up shared audio FFT

Replace recursive radix-2 splitting with iterative stages and
batch the existing odd-size DFT across subsequences, preserving
the previous operation order.

Input buffers now hold only N real values for FFT
or 2N interleaved floats for inverse FFT.

Add test_audio_fft for forward and inverse transforms.

Assisted-by: Claude

* nits

---------

Co-authored-by: Xuan Son Nguyen <son@huggingface.co>
2026-11-22 22:04:24 +01:00
George Burtonandgeorge burton f505c30b92 mtmd: fix qwen3a audio tail (#32697)
* add: test to reporduce error reported in https://github.com/ggml-org/llama.cpp/issues/32689

* fix: remove extra tokens from zero-padding of Qwen3-Omni / Qwen3-ASR audio

* add: qwen3a_tokens_for_frames instead of magic numbers

* refactor: only ggml_pad when required

* refactor: move qwen3a_tokens_for_frames as static member of mtmd_graph_qwen3a and add test

* remove: trailing empty line

---------

Co-authored-by: george burton <georgeburton@georges-MacBook-Air.local>
2026-11-22 21:22:46 +01:00
Piotr Wilkin (ilintar) 5bacb7c868 llama : copy all experts of a host weight shared by several nodes (#32807)
* llama : copy all experts of a host weight shared by several nodes

The scheduler copies a host weight to the device once per graph, so a
partial expert copy made for the first MUL_MAT_ID is stale for the
others (e.g. the shared layers of inkling2_loop with --n-cpu-moe).

Assisted-by: Claude Opus 5.5

* llama : copy all experts of a host weight shared by several nodes

Assisted-by: Codex
2026-11-22 20:04:21 +01:00
Max S. d2bceda3de vocab: enable ignore_merges for inkling2 (#32799) 2026-11-22 19:52:33 +01:00
19 changed files with 468 additions and 181 deletions
+1 -1
View File
@@ -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;
+2 -1
View File
@@ -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
+11 -1
View File
@@ -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);
}
-4
View File
@@ -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,
+92
View File
@@ -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 -%}
+6
View File
@@ -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;
-10
View File
@@ -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;
-2
View File
@@ -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 ?
+6 -6
View File
@@ -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);
}
}
}
+3 -3
View File
@@ -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);
}
}
}
+1
View File
@@ -2673,6 +2673,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) {
pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O;
special_bos_id = LLAMA_TOKEN_NULL;
clean_spaces = false;
ignore_merges = true;
} else if (
tokenizer_pre == "granite-embed-multi-97m") {
pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI;
+64 -3
View File
@@ -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() {
+2
View File
@@ -6012,6 +6012,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 +8216,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");
+123
View File
@@ -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
//
+4
View File
@@ -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 {
+13 -4
View File
@@ -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
View File
@@ -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);
+5 -4
View File
@@ -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;
+11 -4
View File
@@ -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:
{