Skip to content

Add 397B compatibility - #4

Closed
paragon-of-brah wants to merge 13 commits into
am17an:mtp-cleanfrom
paragon-of-brah:mtp-clean-397B
Closed

paragon-of-brah wants to merge 13 commits into
am17an:mtp-cleanfrom
paragon-of-brah:mtp-clean-397B

Conversation

@paragon-of-brah

Copy link
Copy Markdown

Overview

Add Qwen 3.5 397B Compatibility

Additional information

As per comment, in Qwen 3.5 397B MTP experts are stored in separate tensors:

mtp.layers.0.mlp.experts.0.down_proj.weight
mtp.layers.0.mlp.experts.0.gate_proj.weight
mtp.layers.0.mlp.experts.0.up_proj.weight

mtp.layers.1.mlp.experts.0.down_proj.weight
mtp.layers.1.mlp.experts.0.gate_proj.weight
mtp.layers.1.mlp.experts.0.up_proj.weight

etc.

So you get this error

INFO:hf-to-gguf:blk.60.attn_norm.weight,              torch.bfloat16 --> F32, shape = {4096}
Traceback (most recent call last):
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 13673, in <module>
    main()
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 13667, in main
    model_instance.write()
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 933, in write
    self.prepare_tensors()
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 4662, in prepare_tensors
    super().prepare_tensors()
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 793, in prepare_tensors
    for new_name, data_torch in (self.modify_tensors(data_torch, name, bid)):
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 5490, in modify_tensors
    yield from super().modify_tensors(data_torch, name, bid)
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 5446, in modify_tensors
    yield from super().modify_tensors(data_torch, name, bid)
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 4849, in modify_tensors
    yield from super().modify_tensors(data_torch, name, bid)
  File "/home/user/AI/llama.cpp/convert_hf_to_gguf.py", line 4647, in modify_tensors
    datas.append(self._experts[bid][ename])
                 ~~~~~~~~~~~~~~~~~~^^^^^^^
KeyError: 'model.layers.0.mlp.experts.0.down_proj.weight'

convert_hf_to_gguf.py needs to be changed to deal with the differences. The way i dealt with it was to imitate the way Qwen 3.5 35B packs its MTP tensors.

I have made a quant based on the shipped Qwen 3.5 397B from the qwen team using the modified convert_hf_to_gguf.py, then I used ik_llama.cpp to make a ~q5 quant and ran it with MTP enabled.

Performance is meh, but acceptance rates are ok. I have not tuned this at all, parameters are a bit random, and I'm offloading MTP exps to CPU because I have no VRAM.

      -ot "blk\.60\.ffn.*_exps.*=CPU"
      -mtp
      --recurrent-ckpt-mode per-step
      --draft-p-min 0.8
      --draft-max 6

No MTP

prompt eval time =   35886.98 ms / 14860 tokens (    2.42 ms per token,   414.08 tokens per second)
       eval time =   44691.15 ms /   404 tokens (  110.62 ms per token,     9.04 tokens per second)
      total time =   80578.14 ms / 15264 tokens

MTP

prompt eval time =   36777.28 ms / 14860 tokens (    2.47 ms per token,   404.05 tokens per second)
       eval time =   52738.47 ms /   506 tokens (  104.23 ms per token,     9.59 tokens per second)
      total time =   89515.75 ms / 15366 tokens
draft acceptance rate = 0.90966 (  292 accepted /   321 generated)
statistics mtp: #calls(b,g,a) = 1 213 146, #gen drafts = 146, #acc drafts = 140, #gen tokens = 321, #acc tokens = 292, dur(b,g,a) = 0.001, 6511.409, 0.051 ms


I HAVE NOT TESTED any other Qwen version with this convert_hf_to_gguf.py, and I don't know if those work, albeit they should.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: I used - ironically - Qwen 3.5 397B to identify the issue

@github-actions github-actions Bot added the python label May 8, 2026
@am17an
am17an force-pushed the mtp-clean branch 7 times, most recently from a957b77 to 8e9a07d Compare May 16, 2026 10:21
@am17an am17an mentioned this pull request May 17, 2026
8 of 11 tasks
@am17an am17an closed this May 19, 2026
am17an pushed a commit that referenced this pull request Aug 11, 2026
* Get started with Onyx

* Add architecture

* Skip keys handled in super()

* Loading tensors

* Shorten

* Graph

* Apply suggestion from @pcuenca

* Remove norm now embedding in transformers weights

* Add eot

* Explicit output_multiplier

* Handle post_norm_eps

* No super call; unhardcode eot.

The pattern `self._set_vocab_gpt2()` seems preferred throughout the
codebase, and it allows `set_vocab()` to be called from a different part
of the Python class hierarchy: the drafter model converter that we may
need eventually.

* Register for drafting

* DFlash: inherit rope type from the linked target.

Another option would be to store it in the gguf file itself.

* mmproj conversion

Note: some fields to be renamed after the implementation works. We are
keeping compatibility with the reference Meta gguf for testing purposes.

* "clip" header declarations

* Load mmproj

* Pre-processing

* Graph

* Go back to using delimiters.

Otherwise our generations are worse.

Transformers does not use them. We need to trace inputs to verify
whether they are equivalent.

* downsample_factor -> merge_size

* Add vision graph

lol, forgot from a previous commit

* Additional renames, align with llama.cpp / transformers

* Prefer _size instead of independent _h and _w

* Fix token layout

Co-authored-by: Young Han <[email protected]>

* onyx: bring the chat parser onto the onyx branch

common/chat.cpp on this branch has no Onyx handling, so a converted model
serves malformed chat: the assistant preamble leaks into content
("to=self<|message|>...") and tool calls fail with

    HTTP 500 "The model produced output that does not match the expected
              peg-native format"

common_chat_params_init_onyx exists on onyx-fair-patch, added there by
8bb73dd3d. It was never on this branch, so this is not a regression --
the two lines developed independently.

The code here is taken verbatim from that commit. It is the clean side of
`git merge origin/onyx-fair-patch`: chat.cpp is one of the files that
merges without conflict. The full merge is not viable -- it produces 13
conflicts, including add/add on conversion/onyx.py and src/models/onyx.cpp
where the q_norm-folding and metadata-scale approaches contradict each
other, and #4/#7 are stacked on this branch's side of that.

Verified on this branch: builds with 0 errors, converts an Onyx checkpoint,
and serving it gives "4" for "What is 2+2?" plus a correct
get_weather {"city":"Paris"} tool call, where the unported branch gives the
two failures above.

No converter or runtime changes are included, so this should not interact
with the q_norm work.

Co-authored-by: Beto de Paola <[email protected]>

* Less params, bilinear pos-emb interpolation as a graph op instead of CPU

* Map to symbolic V_MMPROJ instead of strings

* Make a couple params explicit

* Patchify via build_inp()

* No param for rope_theta

* Small cleanup

* Restore blank line

* Unpermute, to adapt to the latest transformers checkpoint

* Apply norm after token embeddings

This follows the latest transformers approach.

* Remove duplicated function

* build_vit

* onyx: use the model rope theta on sliding-window layers

* DFlash: conversion from transformers drafter

* Revert rope_type derivation from target

NOTE: this breaks compatibility with Meta's distributed DFlash GGUFs, as
the Q/K are stored in "NEOX" (rotated half) format, like in
transformers.

* Apply suggestion from @pcuenca

* Set model type

* Remove comment that will become obsolete

* Hardcode post_norm_rms_eps instead of new param

* Derive SWA+RoPE pattern from gguf array or scalar

* Fix model type <-> number of layers

* Reorder

* Rename

* Fix typo

* DFlash: seed the draft KV cache from multimodal embedding batches

`common_speculative_impl_draft_dflash::process()` returned early on any batch carrying embeddings, so an image prefill never had its target-layer features fused through the DFlash encoder and injected into the draft's KV cache. That left a hole spanning the image's positions, and the next injection at a post-image position failed to initialize its batch:

```
decoding image batch 1/1, n_tokens_batch = 256
decode: failed to initialize batch
llama_decode: failed to decode, ret = -1
process: llama_decode(ctx_dft) failed rc=-1 (n_tokens=17, offset=0)
srv decode: failed to process speculative batch
```

Every image request with `--spec-type draft-dflash` failed with HTTP 500. Text-only was unaffected, since those batches carry token ids and were let through.

Restore the earlier condition, which admits a batch that is either tokens or embeddings and skips only the degenerate neither/both cases. The rest of `process()` is already layout-agnostic -- it gathers features via `llama_get_embeddings_layer_inp()` and indexes `batch_in.pos[]` / `batch_in.seq_id[]`, none of which assume token ids -- so this is the whole fix.

Validated against `muse-glimmer-30B-bf16.gguf` + `mmproj-muse-glimmer-30B-bf16.gguf` + a DFlash draft head, on an image describe-the-shapes request:

- before: HTTP 500, `failed to process speculative batch`
- after: HTTP 200, draft acceptance 0.34012 (167 accepted / 491 generated), mean len 3.04

Output equivalence holds, which is the property that matters: at temperature 0 the drafted response is byte-identical to the same request served with no draft attached (1213/1213 chars), so the draft is drafting correctly through the image context rather than merely not crashing.

* Conversion: prefer rewrite to mapping

* Revert "Conversion: prefer rewrite to mapping"

This reverts commit a92d0ac.

* fix lint

* sliding_window metadata is not optional

* disable state save/load

* Apply suggestion from @pcuenca

---------

Co-authored-by: Young Han <[email protected]>
Co-authored-by: Beto de Paola <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: ruanrms <[email protected]>
Co-authored-by: Xuan Son Nguyen <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants