Skip to content

Fix inkling 2 mmproj conversion - #32430

Merged
ngxson merged 1 commit into
ggml-org:masterfrom
bartowski1182:inkling-mmproj
Nov 16, 2026
Merged

ngxson merged 1 commit into
ggml-org:masterfrom
bartowski1182:inkling-mmproj

Conversation

@bartowski1182

Copy link
Copy Markdown
Contributor

Overview

Need to skip dequanting vision tensors, they're stored in bf16

Additional information

Without this, conversion of mmproj fails with NotImplementedError: Quant method is not yet supported: '', with this conversion works as expected:

python3 convert_hf_to_gguf.py --mmproj --outtype bf16 --outfile /mmproj-Inkling-2-Small-bf16.gguf /Inkling-2-Small/
INFO:hf-to-gguf:Loading model: Inkling-2-Small
INFO:hf-to-gguf:Model architecture: Inkling2ForConditionalGeneration
...
INFO:gguf.gguf_writer:/mmproj-Inkling-2-Small-bf16.gguf: n_tensors = 422, total_size = 660.7M
Writing: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 661M/661M [00:02<00:00, 274Mbyte/s]
INFO:hf-to-gguf:Model successfully exported to /mmproj-Inkling-2-Small-bf16.gguf

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES, but mostly cause it was automatic in my pipeline

@bartowski1182
bartowski1182 requested a review from CISC as a code owner November 16, 2026 19:03
@ngxson

ngxson commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

confirmed working on my side

@ngxson
ngxson merged commit d998c67 into ggml-org:master Nov 16, 2026
8 checks passed
bahooo22 added a commit to bahooo22/llama.cpp that referenced this pull request Nov 16, 2026
Витрина форка обязана идти поверх актуального апстрима, но эта дельта не меняет ни одного
байта в наших бинарниках: мастер не является входом сборки. build_kit.ps1 берёт llama-ногу
из llama-kit (-S $src, строка 1147), а ggml для Страты - из пина llama-3cf
(-DSTRATA_GGML_DIR, строка 1108); в CMakeCache прошлого цикла CMAKE_HOME_DIRECTORY равен
.../llama-kit и .../engine. Поэтому мержим и пушим, а пересборку не делаем: она дала бы те
же самые байты и только заняла бы окно у сетки.

Что изменено?
- tools/mtmd (+1326/-13, 15 файлов): поддержка YuE2-3B из ggml-org#32369 (mtmd-helper-gen.cpp
  +690/-5, mtmd.cpp +330, models/yue2-gen.cpp +89) и порядок vision-эмбеддингов Muse Glimmer
  из ggml-org#32433 (models/muse-glimmer.cpp +9/-1). Нога у нас не компилируется: LLAMA_BUILD_MTMD=OFF.
- common/parsers и common/chat.cpp (+175/-54, 5 файлов): парсер inkling из ggml-org#32381 -
  inkling.cpp +165 вместо удалённого inkling2.cpp (-46), реестр в parsers.h и sources.cmake.
- tools/server (+25/-9, 3 файла): схема и контекст под новые mtmd-модели, README.
- conversion и gguf-py (+244/-1, 5 файлов): yue2.py +234, granite.py учитывает
  max_position_embeddings (ggml-org#32436), inkling2.py (ggml-org#32430).
- models/templates (+259, 2 файла): jinja-шаблоны Inkling и Inkling-2-Small.
- tests (+99, 2 файла): test-chat.cpp под новый парсер, печать исключения в test-runner.cpp.
- ggml/src/ggml-opencl (+112/-1): ядро A7 Q4_K non-MoE и фиксы bin flash-attention prefill
  (ggml-org#30948, ggml-org#32110); у нас GGML_OPENCL=OFF.
- src/llama-grammar.cpp (+2), tools/tts (+6/-2, 2 файла), docs/multimodal/tts.md (+48),
  skills/code-review/SKILL.md (+5).
- всего: 38 файлов, +2301/-80, бинарных нет (git diff --cached --numstat).

Зачем?
Держать форк-витрину на актуальной базе апстрима, чтобы следующий синк комплекта (перелиновка
kit-all-sync) решался по замеру, а не по накопившемуся отставанию. Заодно зафиксировано, что
наш CUDA-путь от этого мержа не зависит: из дельты в компилируемых путях только common/ и
src/llama-grammar.cpp, а мастер в сборку не входит вовсе.

Замеры?
- merge-tree refs/heads/master + refs/remotes/origin/master (9581154): rc=0, конфликтных
  путей 0, предсказанное дерево d7b1ac7 - мерж начат только после этого гейта.
- git merge --no-commit --no-ff: rc=0, «Automatic merge went well»; неразрешённых файлов 0.
- git diff --cached --numstat: 38 записей, +2301/-80, бинарных 0 (E:/tmp/sync3_numstat.txt,
  цифровые группы выше взяты из него же, не из памяти).
- база мержа 4303cd9; до мержа master == fork/master == 77802f1, status --porcelain пуст.
- страховка refs/tags/backup/llama-master-pre-sync3-2026-11-17 = 77802f1, только локально.
- стенд на момент мержа: планировщиков 0, python-носителей 0, движков 0, compute-процессов на
  карте 0 (носитель wait_captures_drain_2026-11-17.ps1 -Check в 02:34); компиляции не было.
- leakcheck --prose по этому файлу - последний вызов перед commit -F тем же носителем; при
  находках или rc=2 коммит не делается.

Принятый остаток?
- Пересборка комплекта и перелиновка kit-all-sync (29 файлов в компилируемых путях, 0
  конфликтов в них, 8 конфликтов вне сборки в .github/workflows) - отдельное окно со сборкой;
  живые серверы остаются на sync1636, build-dir.txt не тронут.
- Сетка: закрыто 38 клеток из 50, 7 cliff и 5 дыр на llama-ноге (мера grid16_gap по обоим
  дневным журналам) - их добирают очереди съёмки, а не этот коммит.
- За пользователем: CI-аппрувы и описания PR; пуш master сделан этим прогоном по явному
  разрешению «push слияний - пуш разрешаю».

Итог
Витрина догнала апстрим, не коснувшись бинарников. Точное значение дерева сверяется с
предсказанием merge-tree в том же прогоне носителя, а приёмка пуша - по полному хешу из
ls-remote, так что «мерж чистый» остаётся проверенным фактом, а не обещанием.

---

EN: sync: llama master took 9 upstream commits, no rebuild

The fork showcase has to sit on top of current upstream, yet this delta does not change a
single byte of our binaries: master is not a build input. build_kit.ps1 takes the llama leg
from llama-kit (-S $src, line 1147) and the ggml for Strata from the pinned llama-3cf
(-DSTRATA_GGML_DIR, line 1108); last cycle's CMakeCache reports CMAKE_HOME_DIRECTORY as
.../llama-kit and .../engine. So we merge and push, and skip the rebuild - it would produce
the same bytes while stealing the window from the grid.

What changed?
- tools/mtmd (+1326/-13, 15 files): YuE2-3B support from ggml-org#32369 (mtmd-helper-gen.cpp
  +690/-5, mtmd.cpp +330, models/yue2-gen.cpp +89) and Muse Glimmer vision embedding order
  from ggml-org#32433 (models/muse-glimmer.cpp +9/-1). We do not compile this leg: LLAMA_BUILD_MTMD=OFF.
- common/parsers and common/chat.cpp (+175/-54, 5 files): inkling parser from ggml-org#32381 -
  inkling.cpp +165 replacing the deleted inkling2.cpp (-46), registry in parsers.h and
  sources.cmake.
- tools/server (+25/-9, 3 files): schema and context for the new mtmd models, README.
- conversion and gguf-py (+244/-1, 5 files): yue2.py +234, granite.py honours
  max_position_embeddings (ggml-org#32436), inkling2.py (ggml-org#32430).
- models/templates (+259, 2 files): jinja templates for Inkling and Inkling-2-Small.
- tests (+99, 2 files): test-chat.cpp for the new parser, exception message in test-runner.cpp.
- ggml/src/ggml-opencl (+112/-1): A7 Q4_K non-MoE kernel and the bin flash-attention prefill
  fixes (ggml-org#30948, ggml-org#32110); we build with GGML_OPENCL=OFF.
- src/llama-grammar.cpp (+2), tools/tts (+6/-2, 2 files), docs/multimodal/tts.md (+48),
  skills/code-review/SKILL.md (+5).
- total: 38 files, +2301/-80, no binary files (git diff --cached --numstat).

Why?
Keep the fork showcase on a current upstream base so that the next kit sync (relining
kit-all-sync) is decided by measurement rather than by accumulated lag. This also records
that our CUDA path does not depend on the merge: within the delta only common/ and
src/llama-grammar.cpp live in compiled paths, and master is not a build input at all.

Verified?
- merge-tree refs/heads/master + refs/remotes/origin/master (9581154): rc=0, zero
  conflicting paths, predicted tree d7b1ac7 - the merge started only after this gate.
- git merge --no-commit --no-ff: rc=0, "Automatic merge went well"; zero unresolved files.
- git diff --cached --numstat: 38 entries, +2301/-80, 0 binary
  (E:/tmp/sync3_numstat.txt - every number group above comes from it, not from memory).
- merge base 4303cd9; before the merge master == fork/master == 77802f1, status clean.
- safety ref refs/tags/backup/llama-master-pre-sync3-2026-11-17 = 77802f1, local only.
- stand at merge time: 0 queue schedulers, 0 python carriers, 0 engines, 0 compute processes
  on the GPU (wait_captures_drain_2026-11-17.ps1 -Check at 02:34); nothing was compiled.
- leakcheck --prose on this file is the last call before commit -F in the same carrier; on
  findings or rc=2 the commit does not happen.

Accepted remainder?
- Kit rebuild and relining kit-all-sync (29 files in compiled paths, 0 conflicts there, 8
  conflicts outside the build in .github/workflows) - a separate window with a build; live
  servers stay on sync1636 and build-dir.txt is untouched.
- Grid: 38 of 50 cells closed, 7 cliffs and 5 holes on the llama leg (grid16_gap over both
  daily journals) - capture queues close those, not this commit.
- Up to the user: CI approvals and PR descriptions; the master push was performed by this
  run under the explicit permission "merges may be pushed".

Result
The showcase caught up with upstream without touching the binaries. The resulting tree is
compared byte-exactly against the merge-tree prediction in the same carrier run, and the
push is accepted via a full hash from ls-remote, so "the merge is clean" stays a measured
fact rather than a promise.
danielsimonjr added a commit to danielsimonjr/llama.cpp that referenced this pull request Nov 20, 2026
Fork master now matches upstream master exactly (Inkling 2 fixes
ggml-org#32381, ggml-org#32429, ggml-org#32430, ggml-org#32657 included). The Dory model, converter,
tests and benchmark scripts are removed on user order. Their history stays in
the log (f873ebb..fd9034e).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01UkqVNT6jrkoHwXJjfjXvL2
fencerJP pushed a commit to fencerJP/llama-apu that referenced this pull request Nov 21, 2026
Annieren pushed a commit to Annieren/llama.cpp-upstream that referenced this pull request Nov 23, 2026
Nindaleth pushed a commit to Nindaleth/llama.cpp that referenced this pull request Nov 26, 2026
amangupta-tether added a commit to tetherto/qvac-fabric-llm.cpp that referenced this pull request Nov 26, 2026
…ggml-org#32704 to temp-12032) (#568)

* ggml: bound views by the bytes their strides reach (ggml-org#31584)

* ggml: bound views by the bytes their strides reach

A view was checked against its source with the size of a contiguous
tensor of the same shape, computed before its strides were set. Views
whose rows overlap failed that check although they stay inside their
source, and views with wider strides passed it while reaching past
the end. The view functions now pass their strides to the tensor
constructor, which checks the bytes they actually reach, like
ggml_nbytes. The conv windows of delta_net are created with all their
rows at once instead of being widened after the check.

* ggml: assert that a strided view starts from contiguous elements

The view functions set nb[0] to the type size, so the source must have
contiguous elements along dim 0 for the view to read them.

(cherry picked from commit bbb02c9)

Backport note: prerequisite of the Inkling 2 port. build_conv_state_store
(next commit) writes the conv rollback slots through a view with
overlapping rows, which the old contiguous-size check rejects. The
delta-net-base.cpp hunk is not taken: fabric's delta-net writes its conv
snapshots with one copy per slot and never builds that widened view.

* graph: store the MTP conv snapshots of every recurrent model in one set_rows (ggml-org#31660)

* graph: store the conv state of every rollback arch in one set_rows

The rollback slots of the causal conv history were written with one
copy per slot in qwen4exp, glm5-next, kimi-k3, bailingmoe3, lfm and
mamba2, while delta_net already wrote them with a single set_rows.
build_conv_state_store now does this for all of them: one copy without
rollback, otherwise one set_rows of the overlapping windows into the
min(n, n_rs_seq + 1) slots a rollback can read.

The slot order {n_rs_seq, ..., 0} is computed once per graph and each
conv layer takes a view of its tail. Its size does not depend on the
ubatch, so the reserved graph covers every ubatch shape, and the graph
input that held it is gone.

A model that is not causal never rolls back, so the context clamps
n_rs_seq to 0 for it, like for an arch without rollback support.

* nits: compute the conv slot order in the graph and keep the n_head name of bailingmoe3

* graph: build the conv slot order in each conv layer

The slot order {K-1, ..., 0} of the conv state store was one tensor
shared by every conv layer of the graph, built on the device of the
first one, so each layer on another device copied the view of its
tail. Each conv layer now builds its own order next to its set_rows,
and llm_graph_input_rs no longer holds it.

(cherry picked from commit 040ce19)

Backport note: partial pick, prerequisite of the Inkling 2 port. Only the
new llm_graph_context::build_conv_state_store helper is taken (Inkling 2's
short convolutions call it). The conversion of the existing recurrent
models (delta-net, qwen4exp, glm5-next, kimi-k3, bailingmoe3, lfm, mamba),
the s_slot_rev input removal and the non-causal n_rs_seq clamp are left
out: fabric's recurrent state code (deferred GDN commit, ragged ubatches,
per-slot conv snapshots, no s_slot_rev) has diverged from upstream here, so
those hunks conflict and would change the graphs of the existing models.

* feat: add Inkling 2 support (text + vision) (ggml-org#32217)

* convert : add Inkling2 text GGUF conversion

Assisted-by: Codex

* llama : implement Inkling2 text inference

Assisted-by: Codex

* tests : cover Inkling2 text support

Assisted-by: Codex

* conversion : dequantize packed Inkling2 experts in row chunks

Decode per-layer NVFP4 and MXFP8 schemes, validate companions, and use stored scale shapes with a warning for the declared MXFP8 [32,32] grid. Reorder packed w13 rows and their scale rows together. Keep normal GGUF outtype selection and 3D expert tensors.

Stream 128 rows per expert through LazyChunkedTensor. Real w13 (384x4608x4608) needs a 2.25 MiB F32 chunk instead of a 30.375 GiB expanded layer. Real-shaped sparse probes peak below 5.8 MiB of Python/NumPy chunk allocations, plus 5.2 MiB of callback metadata: budget about 16 MiB per projection including mapped pages, excluding runtime, other tensors and OS cache. Full-model chunk metadata is roughly 370 MiB.

Packed synthetic GGUF weights match the independent pinned vLLM decode bit-for-bit. CPU prefill/decode logits remain within 3.1e-6 absolute error, with 100% argmax agreement. Float fixtures, original-name conversion and CPU architecture checks pass. Real checkpoint conversion remains untested.

Assisted-by: Codex

* convert : add Inkling2 vision mmproj support

Assisted-by: Codex

* mtmd : implement Inkling2 still-image encoder

Assisted-by: Codex

* inkling2 : scope image loading

Assisted-by: Codex

* inkling2 : enable flash attention with folded bias and sinks

Assisted-by: Codex

* cuda : route per-head flash attention masks through vec

Assisted-by: Codex

* mtmd : support Inkling2 temporal frame means

Assisted-by: Codex

* style : restore shared image comment

Assisted-by: Codex

* tests : enlarge Inkling2 context fixture

Assisted-by: Codex

* inkling2 : load per-layer expert feed-forward widths

Assisted-by: Codex

* tests : add Inkling2 Metal fusion baselines

Assisted-by: Codex

* inkling2 : group and align registry entries

Assisted-by: Fable

* convert : regenerate the Inkling2 tokenizer hash with the update script

Assisted-by: Fable

* conversion : revert the print_registered_models change

Assisted-by: Fable

* conversion : sort the Inkling2 model map entries

Assisted-by: Fable

* convert : map Inkling2 vision checkpoint names in the tensor table

Assisted-by: Fable

* convert : map Inkling2 text checkpoint names in the tensor table

Assisted-by: Fable

* tests : document the Inkling2 packed expert conversion test

Assisted-by: Fable

* tests : cover Inkling2 checkpoint and transformers tensor names

Assisted-by: Fable

* llama : place Inkling2 fields and list entries by file convention

Assisted-by: Fable

* gguf-py : align Inkling2 tensor mapping comments

Assisted-by: Fable

* mtmd : place Inkling2 entries by file convention

Assisted-by: Fable

* tests : place Inkling2 cases after the existing ones

Assisted-by: Fable

* cuda : index per-head flash attention masks in the tile and mma kernels

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* inkling2 : project the relative bias before the gather, drop arch branches

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* convert : require Inkling2 hparams, add inkling2 pre-tokenizer

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* mtmd : cap Inkling2 image size, drop video frame averaging

Assisted-by: Claude
Claude-Session: https://claude.ai/code/session_01GbYSza1yxgmTz8wdr6uV8Q

* inkling2 : fix CI build, Meta device assert and Windows conversion test

Assisted-by: Claude

* tests : use the default sliding window for the Inkling2 test model

Assisted-by: Claude

* simplify mtmd part

* give _v arch for vision

* remove alpha channel handling, it should be a follow up

* explicit rule about audio + vision models

* add audio support

* rm audio

* rm gguf mtmd rope base

* address review comment

* nits

* do not normalize embd from mtmd

---------

Co-authored-by: Xuan Son Nguyen <[email protected]>
(cherry picked from commit 5c008e0)

Backport notes (temp-12032 conflict resolution):
- Adjacency conflicts with models upstream added after b12032 (ricursive,
  metis16, kimi-k31, chatterbox, ...): kept fabric's lines, added only the
  Inkling 2 lines.
- llama-graph build_attn: fabric reads the mask from .cnv (aliases .raw except
  for dflash); the new kq_mask parameter falls back to .cnv.
- llama-graph build_moe_ffn: expert_weights_norm_eps branch placed before
  fabric's training_ctx branch, so inference matches upstream.
- test-backend-ops: mask_heads appended after fabric's n_sparse_mask / scale /
  packed_window ctor arguments.
- tools/mtmd: temp-12032 predates the mtmd refactor (upstream 7d7f028), so
  the mtmd-graph.cpp / mtmd-model.cpp / mtmd-subcontext.cpp hunks are placed
  verbatim at the equivalent spots of clip.cpp (mtmd-impl.h -> clip-impl.h,
  mtmd-model.h -> clip-model.h). The README-dev.md line is dropped: it extends
  a "Structure" section that only exists after that refactor. API renames
  follow in a separate commit.

* fabric: adapt Inkling 2 to the temp-12032 graph and mtmd APIs

temp-12032 predates two upstream refactors that the Inkling 2 commit
builds on; pulling them in would touch 170+ and 90+ files, so the new
code is renamed to the pre-refactor API instead. No behaviour change.

- llm_graph_context still takes the model as a constructor argument
  (upstream e0f96a1 made it a member): graph(model, params) and
  make_unique<graph>(*this, params).
- mtmd is still clip-based (upstream 7d7f028 moved it to mtmd_*):
  mtmd_graph -> clip_graph, mtmd_layer -> clip_layer,
  mtmd_image_u8/f32 -> clip_image_u8/f32, MTMD_ALIGN -> CLIP_ALIGN,
  mtmd_format -> string_format, models.v.get() -> ctx_v, also in the new
  test-mtmd-impl case (mtmd_hparams / mtmd_image_size -> clip_*).
- test-backend-ops: fabric's test_flash_attn_ext takes n_sparse_mask,
  scale and packed_window where upstream has q_head_padding, so the new
  per-head-mask cases pass the defaults for those before mask_heads.
- mtmd-image.cpp: drop the trailing blank line left by the relocation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chat: fix inkling 2 begin/end of image tokens placement (ggml-org#32294)

* chat: fix inkling 2 begin/end of image tokens placement

* add test

(cherry picked from commit dd099a6)

Backport notes (temp-12032 conflict resolution): chat.cpp keeps fabric's
thinking_forced_open block before the new split_media call; parsers.h keeps
fabric's workaround namespace; mtmd.cpp keeps the ctx_v argument of the
pre-refactor mtmd API.

* jinja: support json sort_keys=true (ggml-org#32366)

(cherry picked from commit e1925b3)

* chat : implement inkling parser (ggml-org#32381)

(cherry picked from commit 4ddf2b9)

Backport note (temp-12032 conflict resolution): chat.cpp keeps fabric's
thinking_forced_open block; only the split_media call is removed.

* convert: Fix inkling 2 mmproj conversion (ggml-org#32430)

(cherry picked from commit d998c67)

* llama: fixes for Inkling 2 attention mask (ggml-org#32429)

* llama : give Inkling2 its own relative-position attention input

The Inkling2 graph built its flash attention mask from the hybrid iswa
input and passed it to build_attn through a new kq_mask argument. That
argument let a caller pair its own dense mask with the kv_rows of
llm_graph_input_attn_kv_iswa, whose mask follows the per-sequence cell
lists whenever kv_rows is enabled.

Add llm_graph_input_attn_rel_pos instead. It owns dense KQ masks and the
query-to-cell distances, fills both from the same cells, and its
build_attn overload adds the per-head bias to its own mask and never
passes kv_rows. The iswa build_attn is back to its previous signature;
its body moves to build_attn_iswa_impl, which both overloads call.

Inkling2 now folds the per-query sink into the bias with and without
flash attention, so build_attn_mha no longer needs the per-query sink
path.

Assisted-By: Claude Opus 5.5 <[email protected]>

* inkling2 : make the expert weight scale and final logit softcap optional

Load both keys as optional and skip them when they are zero, as other
models do, instead of rejecting zero at load.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : build kv_rows masks for the hybrid iswa memory

llm_graph_input_mem_hybrid_iswa checked its masks with
can_reuse_attn_mask, which expects kv_rows whenever they are enabled,
but built them dense. With a unified cache and flash attention the
check always failed, and hybrid iswa models (LFM2, LFM3, Inkling2)
never reused a graph. Build the masks with build_attn_inp_attn_mask,
like the plain iswa input.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : make the relative-position input a hybrid iswa input

Address review: llm_graph_input_mem_hybrid_iswa_rel derives from
llm_graph_input_mem_hybrid_iswa and owns the attention and recurrent
inputs, so Inkling2 builds one memory input instead of two. Its
attention input is built with dense masks, can_reuse checks them as
dense, and its build_attn asserts that the mask has no kv_rows (TODO:
a kv_rows variant). build_attn_iswa_impl is now a static helper.

Assisted-By: Claude Opus 5.5 <[email protected]>

* llama : compose the hybrid iswa rel input, format inkling2

Address review: llm_graph_input_mem_hybrid_iswa_rel owns its attention
and recurrent inputs like the other composite inputs instead of deriving
from llm_graph_input_mem_hybrid_iswa.

Format src/models/inkling2.cpp like the other model sources: grouped
and aligned key and tensor loading, descriptive per-layer names, blank
lines and section comments between the steps, and cb() names for the
intermediate tensors. The graph is unchanged.

Assisted-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 8af68d4)

Backport notes (temp-12032 conflict resolution):
- build_attn_iswa_impl keeps fabric's slicing of a dense mask that is wider
  than the K view; the iswa build_attn passes fabric's .cnv mask.
- inkling2.cpp keeps the (model, params) graph constructor of temp-12032.

* fabric: fill the Inkling 2 recurrent inputs with the fabric helpers

llm_graph_input_mem_hybrid_iswa_rel (upstream 8af68d4) copies the
upstream recurrent-state input code. On temp-12032 the recurrent inputs
also carry the deferred GDN copy indices, the moved-state range and the
ragged-ubatch offsets, so set_input() and can_reuse() do what fabric's
llm_graph_input_mem_hybrid_iswa does: llm_graph_set_input_rs() and the
moved-range / in-place / ragged checks. Same as the non-rel hybrid iswa
input; no change for upstream-shaped batches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* model : load ffn_gate_up_exps scales (ggml-org#32657)

* model: load `ffn_gate_up_exps` scales

The generic scale pass loads per-expert scales for ffn_gate_exps,
ffn_up_exps and ffn_down_exps but not for the merged ffn_gate_up_exps.
Load ~ffn_gate_up_exps_s there~ and expose it as ffn_up_exps_s ~when the layer
has no separate up tensor,~ since build_moe_ffn applies up_exps_s to the
merged gate_up output. Inkling 2 now passes the expert scales to
build_moe_ffn like the other MoE models.

* Update src/llama-model.cpp

Co-authored-by: Sigbjørn Skjæret <[email protected]>

* Update src/llama-model.h

Co-authored-by: Sigbjørn Skjæret <[email protected]>

---------

Co-authored-by: Sigbjørn Skjæret <[email protected]>
(cherry picked from commit a1f4222)

* model : Inkling 2 Mini (ggml-org#32694)

* Conversion

* Separate model_type

* Add gate_rank to allow building from metadata while testing

* Base model

* Loop graph

* Support the new is_varloop attribute

* Adopt naming scheme from ggml-org#32588

* Rename to varying

(cherry picked from commit 29b52d3)

Backport notes (temp-12032 conflict resolution): adjacency conflicts with
models upstream added after b12032 (domyn-edge, metis16, zaya1, kokoro):
kept fabric's lines, added only the Inkling 2 Mini lines. The graph
constructor is adapted to the temp-12032 API in the next commit.

* fabric: adapt the Inkling 2 Mini graphs to the temp-12032 graph API

Upstream 29b52d3 splits the Inkling 2 graph into build_inputs(),
build_layer() and build_output() members that read `model`, which
upstream llm_graph_context holds since e0f96a1. temp-12032 still
passes the model to the graph constructor, so the Inkling 2 graph keeps
it in a `model` member (as fabric's bailingmoe3 graph does) and the
Inkling 2 / Inkling 2 loop constructors and build_arch_graph() pass it
through. No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* model : inkling2_loop share the loop slots after the scale pass (ggml-org#32704)

The loop slots copied the physical layers at the end of load_arch_tensors,
before the generic pass attaches the optional .scale tensors, so the later
passes through the core ran NVFP4 experts without their per-expert scales.
Add an optional post_arch_tensors hook that runs after the scale pass and
share the slots there.

(cherry picked from commit 690b87d)

* CUDA : fused row L2 clip for Inkling 2

Inkling 2 clips the rows of Q, K and the relative-position queries to an
L2 norm with 8 or 9 ops (the optional per-channel scale MUL, SQR, SUM_ROWS,
SQRT, SCALE, FILL, DIV, CLAMP, MUL), three times per layer visit: on
Inkling 2 Mini that is 144 chains and about 1250 small kernels per token.
ggml_cuda_try_fuse now runs such a chain as one kernel (one warp per row),
and the NVRTC fusion planner leaves the chains to it.

test-backend-ops: L2_CLIP cases with the Q, K and relative-query shapes.

Assisted-by: Claude Opus 5.5

* CUDA : L2 clip fusion skips in-place intermediates, x may alias dst

An in-place node inside the chain changes what the graph computes: with
ggml_fill_inplace the FILL overwrites the norm before the DIV reads it, so
the graph gives x * clamp(1) while the kernel gave the clipped rows. The
matcher now rejects the chain when any intermediate node is in place.

The output may be x itself (the last MUL in place), so x is no longer
__restrict__ in the kernel.

test-backend-ops gets an in-place FILL case, which must not fuse (it failed
with the fusion before), and a case whose output is written over the input.

Assisted-by: Claude Opus 5.5

* Merge pull request #573 from tetherto/gb10-moe-mmq-temp-12032

CUDA : MMQ for MoE batches that pick many experts on DGX Spark

* Merge pull request #579 from tetherto/inkling2-fewrow-moe-temp-12032

CUDA : few-row MMQ for MUL_MAT_ID and Inkling 2 expert rows (port of ggml-org#32065)

* model : Inkling 2 Mini mix() weighted sum with the scores as src0 (port of ggml-org#32855) (#581)

* model : Inkling 2 Mini mix() weighted sum with the scores as src0

The weighted sum over the depth states has K = # of states so the old operand order ran one small mat-vec per token. Putting scores first makes n_embd the long dimension and speeds up prefill by 14-18% on MI300X and 25-37% on B200.

(cherry picked from commit 357a9ee)

* model : keep the old mix() operand order when the model runs on the CPU

The scores as src0 make n_embd the long dimension of the weighted sum, which
is faster on GPUs, but on the CPU the subgraph took 1.5-1.9x as long (review
of this PR, Core Ultra 7 155H). When no layer is offloaded and the output is
on the CPU, mix() builds the former graph again: one mat-vec per token with
the states as src0.

A partly offloaded model keeps the swap everywhere. Choosing per layer was
slower than both orders with 12 of 24 layers on the GPU (DGX Spark: pp512
487 t/s against 507 with the old order and 536 with the swap), as the loop
slots and the physical layers whose weights they share can sit on different
devices.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Eddie Zhou <[email protected]>

* ggml-backend, llama : copy shared MoE weights again for each split that reads them (#588)

With op offload, llama's copy callback uploads only the experts that the ids
of the split's first MUL_MAT_ID select. The scheduler lists a host weight as
an input only of the first split that reads it on a backend, and later
splits reuse that copy. When several MUL_MAT_IDs share an expert weight
(Inkling 2 runs its core layers again in later passes, each with its own
routing), the later ones read experts that were never uploaded: any partial
offload of Inkling 2 Mini gave NaN perplexity, also on upstream master.

The scheduler now lists such a weight again for every later split that reads
it as src0 of a MUL_MAT_ID while a copy callback is set, and the callback
keeps track of the experts it uploaded in the current graph compute, so a
later split uploads only the experts that are still missing.

Assisted-by: Claude Opus 5.5

* ci : HIP VGPR check ignores the flash attention kernels under their new signature

ggml-org#32429 (Inkling 2 attention mask) widened the mask's head stride nb32 of the
flash attention kernels from int32 to int64, which changes their mangled
names from ...iiiiil to ...iiiill. The 88 flash attention kernels the check
already ignores no longer matched, so ubuntu-22-hip-quality-check reported
31 known gfx908 spills on #568, every one an entry of the list under the old
signature. The entries now use the new signature, as upstream's copy of the
script does.

Assisted-by: Claude Opus 5.5

* ggml-webgpu : flash attention does not support a mask per head

ggml-org#32429 lets the flash attention mask carry a plane per head or head group
(mask->ne[2] > 1, broadcast over heads like ne[3] over sequences) for Inkling
2's relative-position bias, and test-backend-ops gained mask_heads cases. The
WebGPU shaders read one mask plane per sequence, so they applied head 0's plane
to every head: all 50 FLASH_ATTN_EXT cases with mask_heads 2, 4 or 8 failed on
gpu-webgpu-apple and gpu-webgpu-nvidia, and inkling2_loop missed the
test-llama-archs tolerance on webgpu-nvidia (1.08e-4). supports_op now declines
such masks, so the op runs on another backend.

Assisted-by: Claude Opus 5.5

* tests : re-record the Metal fusion baseline for the Inkling 2 port

The metal job failed test-fusion with 8 rows on #568:

- ggml-org#32657 creates ffn_gate_up_exps.scale (as ffn_up_exps_s) for layers with
  merged gate/up experts. test-llama-archs builds its models with every
  optional tensor, so the generated cohere2moe, hy_v3, qwen35moe, qwen3next
  and qwen4exp models now carry the scale and build_moe_ffn multiplies the
  merged MUL_MAT_ID output by it. The Metal MUL_MAT_ID+GLU decode fusion
  only matches MUL_MAT_ID -> VIEW -> VIEW -> GLU, and silu(s*g)*(s*u) cannot
  be folded, so those 5 rows no longer occur. GGUFs without the optional
  scale build the old graph and keep the fusion; models with it are NVFP4,
  which the fusion does not take anyway.
- The inkling2 rows were recorded on a tree with a Metal top-k fusion that
  #568 does not have; the same scale pass adds MUL_MAT_ID+MUL for Inkling 2.

Re-recorded on the M3 Ultra with the CI flags: 534 ok, 0 failed on #568's
head and on #568 merged with the current temp-12032.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Pascal <[email protected]>
Co-authored-by: Piotr Wilkin (ilintar) <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Xuan-Son Nguyen <[email protected]>
Co-authored-by: Aldehir Rojas <[email protected]>
Co-authored-by: Bartowski <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: Sigbjørn Skjæret <[email protected]>
Co-authored-by: Pedro Cuenca <[email protected]>
Co-authored-by: Aman Gupta <[email protected]>
Co-authored-by: Eddie Zhou <[email protected]>
KyleAnthonyShepherd pushed a commit to KyleAnthonyShepherd/llama.cpp that referenced this pull request Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants