Compare commits

..
2 Commits
Author SHA1 Message Date
George Burton f6d944f6d5 mtmd: fix qwen3omni deepstack allow audio and video (#33041)
* fix: qwen3omni deepstack allow audio and video

* fix: mmproj audio broken/zero-width audio gets its own error line
2026-11-29 19:54:32 +01:00
Zuhal Karadavut 6c83d2ea39 convert : warn when per-channel FP8 weights are dequantized (#33312)
Assisted-by: Claude Code (Claude Opus 5.5)
2026-11-29 19:36:44 +01:00
7 changed files with 109 additions and 17 deletions
+5
View File
@@ -719,6 +719,7 @@ class ModelBase:
channel_scales: dict[str, tuple[Tensor, ...]] = {}
weight_dtypes: dict[str, torch.dtype] = {}
scaled_weights: set[str] = set()
channel_scale_fallback: list[str] = []
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
scale_types = {
gguf.MODEL_TENSOR.ATTN_Q, gguf.MODEL_TENSOR.ATTN_K, gguf.MODEL_TENSOR.ATTN_V,
@@ -778,10 +779,14 @@ class ModelBase:
transformed = self._transform_fp8_scale(weight_name, scale.reshape(-1, 1)) if weight.ndim == 2 else None
if transformed is None or len(transformed) != len(new_names):
self._fp8_e4m3_preserved.discard(weight_name)
channel_scale_fallback.append(weight_name)
continue
channel_scales[weight_name] = transformed
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
if channel_scale_fallback:
logger.warning(f"{len(channel_scale_fallback)} FP8 weights will be dequantized, {type(self).__name__} cannot keep their per-channel scales (first: {channel_scale_fallback[0]})")
expert_groups: dict[str, list[str]] = {}
for name in self.model_tensors:
if (match := expert_pattern.search(name)) and name.endswith(".weight"):
+9 -11
View File
@@ -14,6 +14,13 @@ from .qwen import Qwen3Model, Qwen3MoeModel
from .qwenvl import Qwen25AudioModel
def _vision_config(hparams: dict[str, Any]) -> dict[str, Any]:
# the vision config lives under thinker_config for omni models, at top level for plain VL
if "thinker_config" in hparams:
return hparams["thinker_config"].get("vision_config", {})
return hparams.get("vision_config", {})
@ModelBase.register("Qwen3VLForConditionalGeneration", "Qwen3VLMoeForConditionalGeneration", "Qwen3_5ForConditionalGeneration", "Qwen3_5MoeForConditionalGeneration", "OpenJevModel")
@ModelBase.example("Qwen/Qwen3-VL-4B-Instruct", "Qwen/Qwen3-VL-30B-A3B-Instruct", "Qwen/Qwen3.5-9B", "Qwen/Qwen3.5-35B-A3B")
class Qwen3VLVisionModel(MmprojModel):
@@ -295,11 +302,7 @@ class Qwen3VLTextModel(Qwen3Model):
def set_gguf_parameters(self):
super().set_gguf_parameters()
if "thinker_config" in self.hparams:
vision_config = self.hparams["thinker_config"].get("vision_config", {})
else:
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -318,8 +321,7 @@ class Qwen3VLMoeTextModel(Qwen3MoeModel):
def set_gguf_parameters(self):
super().set_gguf_parameters()
vision_config = self.hparams.get("vision_config", {})
deepstack_layer_num = len(vision_config.get("deepstack_visual_indexes", []))
deepstack_layer_num = len(_vision_config(self.hparams).get("deepstack_visual_indexes", []))
self.gguf_writer.add_num_deepstack_layers(deepstack_layer_num)
@classmethod
@@ -378,10 +380,6 @@ class Qwen3OmniMoeTextModel(Qwen3VLMoeTextModel):
self.gguf_writer.add_eos_token_id(int(token_id))
break
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_num_deepstack_layers(0)
@ModelBase.register("Qwen3ASRForConditionalGeneration")
@ModelBase.example("Qwen/Qwen3-ASR-0.6B-hf")
+47
View File
@@ -653,6 +653,53 @@ MAKE_TEST(test_audio_preprocessor_qwen3a_tail) {
}
}
// audio rows are zero-padded to the (deepstack) vision width, e.g. Qwen3-Omni
MAKE_TEST(test_audio_embd_pad_rows) {
{
// one row, 2 -> 8
std::vector<float> embd = {1.f, 2.f};
mtmd_audio_embd_pad_rows(embd, 1, 2, 8);
t.assert_equal("one row size", (size_t) 8, embd.size());
const std::vector<float> want = {1.f, 2.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
bool content = embd.size() == want.size();
for (size_t i = 0; i < embd.size() && i < want.size(); ++i) {
content = content && embd[i] == want[i];
}
t.assert_true("one row zero-padded", content);
}
{
// three rows, 4 -> 8: rows must keep their order and never leak into each other
const size_t n_tokens = 3, n_embd_row = 4, n_embd_out = 8;
std::vector<float> embd;
for (size_t i = 0; i < n_tokens * n_embd_row; ++i) {
embd.push_back((float) i);
}
mtmd_audio_embd_pad_rows(embd, n_tokens, n_embd_row, n_embd_out);
t.assert_equal("three rows size", n_tokens * n_embd_out, embd.size());
bool content = embd.size() == n_tokens * n_embd_out;
for (size_t i = 0; i < n_tokens && content; ++i) {
for (size_t j = 0; content && j < n_embd_out; ++j) {
const float want = j < n_embd_row ? (float) (i * n_embd_row + j) : 0.0f;
content = content && embd[i * n_embd_out + j] == want;
}
}
t.assert_true("three rows content", content);
}
{
// no-op when the widths match
std::vector<float> embd = {1.f, 2.f, 3.f, 4.f};
mtmd_audio_embd_pad_rows(embd, 2, 2, 2);
t.assert_equal("identity size", (size_t) 4, embd.size());
t.assert_true("identity content", embd == std::vector<float>({1.f, 2.f, 3.f, 4.f}));
}
{
// no rows: nothing to pad, and the row 0 fill must not touch out-of-bounds memory
std::vector<float> embd;
mtmd_audio_embd_pad_rows(embd, 0, 2, 8);
t.assert_equal("zero rows size", (size_t) 0, embd.size());
}
}
MAKE_TEST(test_audio_preprocessor_conformer) {
mtmd_hparams hparams;
hparams.n_mel_bins = 128;
+3 -1
View File
@@ -229,7 +229,9 @@ class TestFP8Conversion(unittest.TestCase):
scales = torch.tensor([0.125, 0.25, 0.5, 1.]).reshape(4, 1)
for eager in (False, True):
with self.subTest(eager=eager):
result = self.convert(ReorderedRowsModel, {name: weight, name + "_scale": scales}, eager=eager, check_lazy=not eager)
with self.assertLogs("hf-to-gguf", level="WARNING") as logs:
result = self.convert(ReorderedRowsModel, {name: weight, name + "_scale": scales}, eager=eager, check_lazy=not eager)
self.assertIn(f"1 FP8 weights will be dequantized, ReorderedRowsModel cannot keep their per-channel scales (first: {name})", "\n".join(logs.output))
dtype, data = result["blk.0.attn_q.weight"]
self.assertEqual(dtype, gguf.GGMLQuantizationType.F16)
np.testing.assert_array_equal(data, (weight.float() * scales).flip(0).numpy())
+22
View File
@@ -14,6 +14,28 @@
constexpr bool DEBUG = false;
void mtmd_audio_embd_pad_rows(std::vector<float> & embd, size_t n_tokens, size_t n_embd_row, size_t n_embd_out) {
GGML_ASSERT(n_embd_row > 0 && n_embd_out >= n_embd_row);
GGML_ASSERT(n_embd_out % n_embd_row == 0);
GGML_ASSERT(embd.size() == n_tokens * n_embd_row);
if (n_tokens == 0 || n_embd_out == n_embd_row) {
return;
}
embd.resize(n_tokens * n_embd_out);
// last to first: a row's source must be read before its slot is overwritten
for (size_t i = n_tokens; i-- > 1;) {
auto row = embd.begin() + (i * n_embd_out);
std::copy_backward(embd.begin() + i * n_embd_row, embd.begin() + (i + 1) * n_embd_row, row + n_embd_row);
std::fill(row + n_embd_row, embd.begin() + (i + 1) * n_embd_out, 0.0f);
}
// row 0 is already in place, only its padding is zeroed
std::fill(embd.begin() + n_embd_row, embd.begin() + n_embd_out, 0.0f);
}
void mtmd_audio_cache::fill_sin_cos_table(uint32_t n) {
sin_vals.resize(n);
cos_vals.resize(n);
+4
View File
@@ -10,6 +10,10 @@
#define MTMD_INTERNAL_HEADER
// zero-pad each row of embd from n_embd_row to n_embd_out values. No-op when equal.
// e.g. the audio rows of Qwen3-Omni are padded to the deepstack vision width.
void mtmd_audio_embd_pad_rows(std::vector<float> & embd, size_t n_tokens, size_t n_embd_row, size_t n_embd_out);
struct mtmd_audio_mel {
int64_t n_len;
int64_t n_len_org;
+19 -5
View File
@@ -1001,18 +1001,23 @@ struct mtmd_context {
}
// if both vision and audio mmproj are present, we need to validate their n_embd
// deepstack vision rows are wider (e.g. Qwen3-Omni); the audio rows are zero-padded to that width
if (ctx_v && ctx_a) {
int n_embd_v = ctx_v->model.n_mmproj_embd();
int n_embd_a = ctx_a->model.n_mmproj_embd();
if (n_embd_v != n_embd_a) {
if (n_embd_a <= 0) {
throw std::runtime_error(mtmd_format(
"mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d)\n",
"invalid audio mmproj, its width is %d\n", n_embd_a));
}
if (n_embd_v != (int64_t) n_embd_a * (1 + ctx_v->model.n_deepstack_layers)) {
throw std::runtime_error(mtmd_format(
"mismatch between vision and audio mmproj (n_embd_v = %d, n_embd_a = %d),"
" the vision width must be the audio width times (1 + deepstack layers of the vision model)\n",
n_embd_v, n_embd_a));
}
}
// since we already validate n_embd of vision and audio mmproj,
// we can safely assume that they are the same
// the vision width is the row width of the context, the audio rows are padded to it
// a gen-only mmproj is validated below
int n_embd_mmproj = ctx_v || ctx_a ? (ctx_v ? ctx_v : ctx_a)->model.n_mmproj_embd() : n_embd_text;
if (n_embd_text > 0 && n_embd_text != n_embd_mmproj) {
@@ -2753,6 +2758,8 @@ static int32_t mtmd_encode_chunk_impl(mtmd_context * ctx, const mtmd_input_chunk
}
if (track) {
if (track->embd.empty()) {
// no padding here: this path requires n_embd_out() to equal the audio width
// (soundtrack tracks are LFM3-only today, models without deepstack vision)
track->embd.resize((size_t) track->n_tokens * ctx->n_embd_out());
if (!mtmd_audio_batch_encode(ctx, track->batch_f32, track->source.get(), 0, track->embd)) {
track->embd.clear();
@@ -2780,8 +2787,15 @@ static int32_t mtmd_encode_chunk_impl(mtmd_context * ctx, const mtmd_input_chunk
if (ctx->ctx_a->model.proj_type == PROJECTOR_TYPE_QWEN3TTS_SPKENC && chunk->tokens_audio->batch_f32.entries.size() == 2) {
return mtmd_qwen3tts_ref_encode(ctx, chunk->tokens_audio.get(), out_embd);
}
out_embd.resize((size_t)chunk->tokens_audio->n_tokens * ctx->n_embd_out());
// the audio graph writes rows of the audio width; pad to the vision width if wider
const size_t n_tokens = chunk->tokens_audio->n_tokens;
const size_t n_embd_a = ctx->ctx_a->model.n_mmproj_embd();
const size_t n_embd_out = ctx->n_embd_out();
out_embd.resize(n_tokens * n_embd_a);
bool ok = mtmd_audio_batch_encode(ctx, chunk->tokens_audio->batch_f32, chunk->tokens_audio->source.get(), chunk->tokens_audio->source_idx, out_embd);
if (ok && n_embd_out != n_embd_a) {
mtmd_audio_embd_pad_rows(out_embd, n_tokens, n_embd_a, n_embd_out);
}
return ok ? 0 : 1;
}