Compare commits

...
Author SHA1 Message Date
Pascal 40f77d45d3 tests : use the fused mul_mat tolerance for LOOP_CTRL 2026-11-28 08:59:41 +01:00
Aleksander Grygier 8e23278c7c ui: show only the mention label in generated conversation titles (#33205)
An `@`-mention is sent to the model as a `[name](file:///abs/path)` link, so
a title derived from the first user message inherited the whole link and the
path crowded out the words. Collapse every mention to the text inside its
square brackets when the title comes from the message itself, which covers
both the non-LLM setting and the fallback used when LLM output is unusable.

The LLM prompt still sees the full link, so the model keeps the path.
2026-11-27 20:28:53 +01:00
Aleksander Grygier 6d8a8886fa ui: draw markdown tables with row rules instead of a cell grid (#33195)
A table in a chat column drew a rule around every cell, a band behind the
header and a frame around its scroll wrapper. The lines did the separating
twice over, so the table read heavier than the prose around it.

A hairline under each row carries the structure on its own now: no cell grid,
no header band, no frame, and the outer columns line up with the text above
and below. GFM column alignment arrives as an align attribute, which an
authored text-align beats, so the three values are restated and a
right-aligned column keeps its figures under its header. Numbers take tabular
figures, code in a cell stays one token, and a table of six or more columns
keeps a width a word sits on and scrolls in its wrapper.

The Tables story covers it: alignment, code and links in cells, a list and a
line break in a cell, escaped pipes and an empty cell, and a table wider than
the column.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-27 17:20:19 +01:00
Pedro Cuenca 4c7344447c [Inkling 2] Support nvfp4 pass-through (#33062) 2026-11-27 15:44:37 +01:00
fox5611 3ab385146c CUDA: fix ADD_ID launch for more than 65535 tokens (#33162)
The grid's y dimension came directly from the token count, so ADD_ID
launches with more than 65535 tokens failed with "invalid configuration
argument". NVIDIA and HIP are equally affected, since gridDim.y is
capped at 65535 on both.

Clamp the grid and stride over ne2 in the kernel, matching convert.cu
and pad.cu. Add a test case at 70000 tokens; the existing cases top out
at 129.

Assisted-by: Claude Opus 5
2026-11-27 15:32:42 +01:00
Ruben Ortlam d67b7a99d8 vulkan: handle empty conv3d kernel, fixes validation error (#33106) 2026-11-27 15:31:18 +01:00
Jeff Bolz 3b103f75e9 vulkan: further optimize coopmat2 GDN (#32860)
* vulkan: further optimize coopmat2 GDN

Refactor split+store callbacks so hi and lo portions are all stored together.
This should help allow the stores to be vectorized.

Interleave the state store callbacks with the gram_pmat work. The compiler
doesn't seem to let these things overlap without manual effort like this. I
suspect this is because the compiler doesn't have smart enough alias analyssis
to know what can/can't conflict.

Similarly, split the invert function into separate calculation/store calls,
so the inverse work can interleave better with the MMAs.

Move "solved" from sh_dh to sh_sh - reusing sh_dh needed a barrier but sh_sh
doesn't.

* interact properly with new replay code
2026-11-27 15:26:19 +01:00
Aaron Teo 4346838ad8 ggml-zdnn: make zTensor memory usage visible for fitting (#31849)
* ggml-zdnn: make memory usage visible for fitting

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: switch to a flag check for ztensor buffer storage

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: fix rebase conflicts

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

---------

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
2026-11-27 15:22:50 +01:00
NoahandJohannes Gäßler 0020197457 CUDA: cache the device type at init (#33142)
* CUDA: cache the device type at init

ggml_backend_cuda_device_get_type called cudaGetDeviceProperties on every
call, which takes ~0.7-1 ms with the CUDA 12 runtime. With tensor
overrides on multiple GPUs the scheduler queries the device type for every
split input, so this ran dozens of times per token.

Store the device type in ggml_cuda_device_info at init. It is derived from
prop.integrated, not from the integrated flag, which is forced off (#15034).

Ref #33132

* Apply suggestion from @JohannesGaessler

---------

Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
2026-11-27 15:18:23 +01:00
a386950136 ggml: support quant scales for fp8 and nvfp4 (#28898)
* ggml: add tensor scaling (per-tensor, per-channel, per-expert, per-expert-per-channel) support

* add meta backend scale split

* add optional activation scales to mul_mat and mul_mat_id tensors

* handle bitnet scales too, disable in backends

* Don't treat single expert as per-channel-per-expert

* Temp workaround for moe-cache with scaled data-types

* Also apply scales in CPU backend 's tiled mul_mat

* Handle strided views on scales

* Make *scale tensors use existing GGML_OP_MUL buffer probe

* Make scale tensors required for ggml_type with needs_scale=true

* Make needs_scale=true for FP8

* Use ggml_need_scale in code-base

* Transform companion FP8 scales

* Add comment explaining intended use of activation scales

* Fix pre-existing view-handling failure in meta backend

eae135bd4 exposed an issue with single-ton dimension ambiguitiy + views
in meta backend, see https://github.com/ggml-org/llama.cpp/actions/runs/39765669007/job/119780422102

* Enforce scale side-cars for scaled data-types during conversion

* tq quants also need scales

* llama: use map for scale tensors instead of manual handling

Assisted-by: Codex

* Fix conversion edge-case for FP8 block-scales

* Revert "tq quants also need scales"

This reverts commit 5920e55b01.

* Disable dedicated kernels also for kleidiai in requant test

We want to test requant errors so we should be using the same kernels
to avoid a cofounder

* Add separate tests for scaled and unscaled DSV2

* Also remove IQ from needs_scale related tests/behvaior

* Wire activation scales and disallow broadcasting over K

* Adjust build_* in lfm3.cpp

* Avoid internal includes in test-llama-arch for moe scales

see https://github.com/ggml-org/llama.cpp/pull/27512#discussion_r4410518158

* djust build_* in limite.c
pp as well

* Adjust build_* for mistral 4

* More build_*_ffn changes

* fp8 : fix integration after rebase

* Another round of model scale map fixes

* Only read scales for valid experts

* handle input scales through cache similar to weight scales

* check supports_op in cache slots

* use is_scalar/is_vector functions

* fix Windows CI cleanup failure

* exclude BLOOM, JAIS and REFACT from sm_tensor due to Alibi not handled in TP correctly yet

* increase error threshold for hunyuan and maincoder context shifting

* adapt CUDA fusion code to scale change

* fix MoE cache too small error

* increase error threshold for hrm_text

* replace missing model matmul cases

* clean up unused CUDA code

* more missed matmuls

* handle per-tensor (scalar) scales in moe cache

* place scales with their weights

* increase error threshold for moe scales check

* restore CUDA cublaslt scale path

* convert model matmuls, handle weight views, add tests

* fix comments and error style

* cuda: use global scale functions

* fix kleidiai

* cuda: honour f32 prec in cublaslt call

* update Metal fusion count

* fix gemma4 scale issue

* don't remove trivial scale if required

* adapt new models changes

* adapt conversion qwen4exp changes and tests

* improve error message when scale unsupported

* address feedback

* adapt new models

* metal : apply the weight scale of MUL_MAT and MUL_MAT_ID

* ggml : avoid `ggml_type_traits` ABI change + TODOs

* metal : drop the comments of the weight scale epilogue

* undo moe-cache-specific changes

* tests : update the Metal fusion baseline

* handle scale in repack and kleidiai, fix scale buffer placement in loader

* llama : fix weight scale lookup, validate MUL_MAT_ID scales

- only look up a weight scale for .weight tensors (k_scale/v_scale
  tensors were checked against the weight scale and failed to load)
- check MUL_MAT_ID weight scale shapes at load time instead of asserting
- llama-quantize: error out on nvfp4/f8_e4m3 targets (no scale computed)
- llama-quant: NULL -> nullptr

* clean up unnecessary tests

---------

Co-authored-by: Oliver Simons <osimons@nvidia.com>
Co-authored-by: Pascal <admin@serveurperso.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-27 14:51:55 +01:00
AWA 15fcfc7357 convert : preserve pooler for BertForSequenceClassification (#33122)
* convert : preserve pooler for BertForSequenceClassification

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>

* convert : address review feedback for BertForSequenceClassification

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>

* convert : use setdefault for classifier_activation

---------

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>
2026-11-27 12:37:10 +01:00
Lucius 7b74cb92d6 graph : read recurrent states in place instead of copying (#28841) (#30139)
* graph : read recurrent states in place instead of copying (#28841)

This is a graph only change that speeds up token output in the majority of cases and backends by removing state copy steps.
Where possible, kernels now read recurrent states directly from the cache instead of a copy from ggml_get_rows.
A change to RWKV6/7 makes it read its old state before overwriting.
A graph-reuse check condition is added to keep track of whether states are read in place.

Assisted-by: Claude Opus 5.5 + Sol 6.1

* graph : keep recurrent-state graph the same shape, both when read in place or for movement

Vulkan and Metal failed under GGML_SCHED_NO_REALLOC. The readers now always read the states from cache.
Graph shape is mainmtained throughout.

Assisted by: Opus 5.5

* Prevent any throughput regressions from caching clashing with speculative decoding rollback snapshots. Fix WebGPU CI error by skipping the fusion step when input states overlap with the cache it writes to.

* Refactor comment on rollback snapshots in llama-graph

Simplified comment.

* tests : add regression test for after memory clear

* graph : check rs_in_place when reusing the hybrid iswa rel input

* graph : document build_rs rules, read src0 directly in get_rs_in_place

* graph : expose the rs snapshot rule once via get_rs_snapshots

* graph : drop the repeated snapshot rule from the build_rs comment

* graph : clarify the build_rs snapshot comment
2026-11-27 12:15:29 +01:00
anujj 2a8bf0f593 cuda : fix NVFP4 MMQ y_scale over-read in the stream-k fixup (#33136) 2026-11-27 15:18:10 +05:30
Aman Gupta e7ec6361dc moe-cache : support experts selected on another backend (#33133)
When the experts are selected on another backend than the cache, e.g. the loop passes of inkling2_loop with a layer split, the lookup reads a copy of the ids made by the scheduler, which has no source to read the shape from. Take the experts per token from build_lookup instead.

Fixes #33101
2026-11-27 11:32:07 +02:00
Sigbjørn Skjæret 69812f63c2 llama : remove unused llm_tensor enums (#33179) 2026-11-27 10:18:09 +01:00
Georgi Gerganov f351f415d6 metal : check all fused nodes for concurrency (#33175)
* metal : check all fused nodes for concurrency

The concurrency check for a fused group only examined the last node, so
intermediate outputs (e.g. the TOPK_MOE ids/weights) and the group's
sources (e.g. the router logits) were ignored. This allowed the fused
top-k kernel to run concurrently with the router matmul that writes its
input, producing nondeterministic expert routing.

Check every node of the fused group instead.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : update the Metal fusion baseline for bailingmoe3

PR #33081 enables the SSM_CONV + SILU fusion in bailingmoe3. Record the
new SSM_CONV+UNARY count in the Metal baseline.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
2026-11-27 11:10:50 +02:00
Aleksander Grygier 00d5c142c8 ui: share conversations to Hugging Face datasets as agent traces (#32608)
* ui: add @ggml-org/llama-huggingface, a Hugging Face account as a package

A package in ui/lib that gives an app running in the browser, with no
server of its own, a Hugging Face account. Its plain entry holds "Sign in
with Hugging Face" (OAuth with PKCE and dynamic client registration) and
the Hub calls: who the account is, its datasets, and committing a trace
file to one. Its Svelte entry holds the account as state (HfAccount) and
the components that show it, built on Llama UI: the account panel and the
dialog that shares a trace.

It knows no app: the app says who it is and hands over what to share.
Llama Chat compiles it from source, like the other packages, so the
llama-server image builds (.devops) and the asset staging
(scripts/ui-assets.cmake) copy its sources next to the other packages'.
CI checks and tests it.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: share conversations to Hugging Face datasets as agent traces

A conversation's menu and each message get a Share action. It uploads the
conversation, or the branch up to that message, to a Hugging Face dataset
as a JSONL trace, which the Hub shows in its trace viewer.

The sign-in is part of the share: the dialog (@ggml-org/llama-huggingface)
asks for it with "Sign in with Hugging Face" (contribute-repos: the app
creates datasets and writes only to the ones it created) or with a pasted
access token. It then shows the datasets the account can add to as tiles,
with a tile to create a new one (public unless the private option is
ticked); with none to add to, it asks for the name of a new dataset. A
pasted token reaches every dataset of the account; a sign-in reaches the
ones this browser shared to.

Once shared, the dialog shows the trace as a file with the first messages
of the conversation fading out below it, and every action in one place at
the bottom right.

Once signed in, Settings > General shows the account with its Sign out;
before that it shows nothing.

The builds we release have the sharing: the prebuilt UI llama-server
downloads, the llama-server images and the npm package. A build of your
own has it only when asked for. VITE_PUBLIC_HUGGING_FACE=true bundles the
package's sign-in, upload and dialogs; without it the package's Svelte
entry resolves to an inert stand-in, which CI checks against the bundle
built with it. The dev server, the tests and Storybook have it.
-DLLAMA_UI_HUGGING_FACE=ON adds it to llama-server's UI built from source
(it builds again when the option changes), and the Docker images take the
variable as a build argument.

The conversation menu is now one component, ConversationActions, used by
the sidebar row, the search results and the chat tabs, so each offers the
same actions.

Llama Chat and its llama-chat alias go to 0.4.0.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-27 10:09:42 +01:00
Jhen-Jie HongandMax Krasnyansky ca123ba763 hex-hmx: fix accuracy issues in act and weight scaling, drop w8a8+f16 hybrid mode (no longer needed) (#33166)
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
2026-11-26 23:38:31 -08:00
Ruben Ortlam f89a243d53 vulkan: add FA compact bias support for Inkling 2 Mini (#32898)
* vulkan: add FA compact bias support for Inkling 2 Mini

* fix xe condition and function signature

* fix RDNA regression

* batch loads to allow overlap and coalescing
2026-11-27 07:45:08 +01:00
cwriter ed2153e708 sycl: dequantize reordered q6_K in f32 like the canonical kernel (#32726) 2026-11-26 22:01:40 -05:00
e0b9fd7d76 ggml-openvino: CI op-test fixes and NPU improvements (#33088)
* ggml-openvino: KV-only prefill on the static path, with one decode step for the outputs

On the static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC=1) the prefill model of a graph with
KV-shared attention layers is compiled with only the cache writes as outputs. The new conversion pass
KeepCacheResults (openvino/pass/keep_cache_results.cpp, registered in pass_registry/common.cpp from
GraphTraits::kv_only_outputs) removes the other Results and the Parameters nothing reads any more, so OpenVINO
drops everything that only feeds the logits: for models whose tail layers read an earlier layer's KV (Gemma 3n/4
E-series) every KV-shared layer and the LM head. When the batch needs logits, the decode model is run once on the
output token: it rewrites that token's KV rows with the same values and runs the dropped layers against the
complete cache. The decoder keeps its full output list and only reports which outputs are caches; an imported
cached model takes the cache outputs as its output names.

It is on by default and applies only where it pays off and is valid: graphs with KV-shared attention, at most one
output token per batch, and no HFA prefill or decode KV windows. GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off; the
earlier name GGML_OPENVINO_NPU_KV_ONLY_PREFILL is still accepted.

Gemma 4 E2B Q4_0 on NPU (KV_SLICE=0, NPU_TURBO=YES): llama-bench pp512 1320-1375 -> 2349-2454 t/s,
pp2048 1146-1202 -> 2268-2513 t/s; E4B pp512 587 -> 773, pp2048 591 -> 847 t/s. llama-server, E2B, 3016-token
prompt, prefill chunk 512, context checkpoints off: 1097-1108 -> 2136-2448 t/s. Greedy outputs match the full
prefill on 3 of 4 needle prompts; the fourth differs by one near-tie token that also flips between baseline runs.

* ggml-openvino: NPU host gather for large embedding tables

GGML_OPENVINO_NPU_HOST_GATHER=1 gathers the rows of large host-resident embedding tables (at least
64 MiB, raw GGUF data, ids from a graph input) on the host. The static graph gets the rows through a
ggml_host_rows_<node> input instead of an OpenVINO Gather over the table. With NPUW function calls the
table becomes a function input, and gathering from an input that large costs about as much as
streaming the whole table every call: 21.6 ms of the ~62 ms Gemma 4 E2B decode step, against 0.45 ms
for the same partition with the table baked in. A table used only for such lookups (the Gemma 3n/4
per-layer embedding table) is no longer converted, requantized or bound to the NPU.

Gemma 4 on NPU (NPU_TURBO=YES, KV_SLICE=0, 868-token prompt), together with KV-only prefill: E2B decode
65.3 -> 40.3 ms/token, prefill 925 -> 392 ms, system commit 8.5 -> 4.4 GB, load 109 -> 61 s; E4B decode
150 -> 72 ms/token, prefill 1931 -> 1022 ms, commit 14.6 -> 9.1 GB. Greedy outputs match the default on
3 of 4 needle prompts; the fourth differs by one near-tie token that also flips between baseline runs.

* ggml-openvino: NPU host gather and KV-only prefill with the weightless blob cache

Make the two NPU options work with GGML_OPENVINO_NPU_WEIGHTLESS_BANK / SELF_CONTAINED_MMAP:
- host gather also accepts tables in OpenVINO buffers when a raw-weight cache mode keeps (or, with
  SELF_CONTAINED_MMAP, wraps) the raw GGUF bytes there;
- a warm import binds only the decoder inputs present in the compiled blob, since KV-only prefill
  (out_ids) and host gather (token ids) can leave inputs unused, as HFA prefill already did;
- a weights file that cannot be written (e.g. a full disk) no longer fails the graph: the pair is
  compiled and run without being cached.

Gemma 4 on NPU (NPU_TURBO=YES, KV_SLICE=0, 868-token prompt), weightless cache + MMAP warm start with
host gather and KV-only prefill: E2B load 1.8 s, system commit 2.5 GB, prefill 385-414 ms, decode
39.5-41 ms/token, cache 1.5 GB; E4B load 3.3-3.6 s, commit 4.7-4.8 GB, prefill ~1.0 s, decode 68.5-69.8
ms/token, cache 3.3 GB. Greedy outputs are byte-identical to the default path on export and import.

* ggml-openvino: let GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT apply to Q4_K/Q5_K tables when set

Q4_K and Q5_K token_embd tables default to the channel-wise int8 of ggml_openvino_get_requant_type() on NPU and
ignored GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT. They now follow it when it is set explicitly; the Q6_K behaviour and
all defaults are unchanged. Gemma 4 E2B ties a Q4_K table to the output layer: int8 stores it in 384 MiB,
q4_0_128 in 198 MiB (llama-server working set -0.18 GB; accuracy not yet measured).

* ggml-openvino: export prefill model of every KV window for weightless bank cache

With a weightless-bank model cache and sliced (non head-major) KV, round the static prefill attention size up to the decode KV window, so prefill sizes are the window sizes (1024/2048/4096/8192). The export run (SELF_CONTAINED_MMAP=0) then builds the prefill model of every window at startup, so an import-only run (SELF_CONTAINED_MMAP=1) has a pair for any prompt length.

* ggml-openvino: integer KV_SLICE, KV-only with decode windows, gemma-4 pruned masks

- GGML_OPENVINO_KV_SLICE takes 0, 1 or a multiple of 256 as the base of the
  attended KV windows; decode windows (BLOB_PREBUILD) use the same base.
- KV-only prefill works together with decode KV windows: the output step runs
  the decode model of the window the next decode step uses.
- gemma-4 prune_shared (upstream #32342) adds host-filled out_mask/out_mask_swa
  and inp_prune_ids/inp_prune_keep inputs. The pruned masks are not graph
  inputs: their rows are gathered in the OV model from the (sliced, padded)
  input masks with inp_prune_ids. The KV-only output step ignores
  inp_prune_keep, and HFA prefill is not used for the pruned masks.

* ggml-openvino: keep the compiled model alive while reading its inputs (-Wdangling-reference)

* ggml-openvino: make the NPU weightless-bank cache automatic with the model cache dir

Remove GGML_OPENVINO_SELF_CONTAINED_BLOB, GGML_OPENVINO_NPU_WEIGHTLESS_BANK and
GGML_OPENVINO_NPU_SHARED_BANK. On NPU, setting GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR
alone now selects the weightless-bank cache layout.

Why
---
The self-contained (SC) mode embedded the full weights into every exported blob
and kept separate ggml-sc-prefill / ggml-sc-decode NPUW banks. Compared to the
weightless bank (WB) it:
- wrote the weights once per blob (prefill, decode and every KV window), so the
  cache was several times larger;
- disabled the decode KV windows (decode_bucket returned 0), so decode always
  ran at the full context;
- needed an in-process keep-alive workaround;
- was much slower and heavier to import. Earlier phi-4-mini data: SC import
  38 s / 8.8 GB InUse / 636 prefill t/s vs WB 3.7 s / 3.3 GB / 1245 t/s.
WB was strictly better, so it becomes the only NPU cache layout and the
three opt-in switches are dropped.

New behaviour
-------------
- If the directory holds valid blobs, manifests and the shared weights file
  for the prefill/decode pair, they are imported directly
  ("model cache HIT (weightless bank)").
- Otherwise the models are compiled and exported as weightless blobs plus one
  <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair and
  KV window, and a warning is logged ("no usable cached blob(s) in <dir> ...;
  compiling and exporting ... as weightless-bank blobs"). The same warning is
  logged for each decode KV window and each prefill KV window that has to be
  compiled.
- NPU graphs without a KV cache no longer use the model cache and always
  compile.
- GGML_OPENVINO_SELF_CONTAINED_MMAP is kept (GGUF mmap as weight buffer, lazy
  large compute buffers). It now needs only NPU + cache dir, stays import-only
  and its error messages name the cache directory.
- The fingerprint tag of weightless blobs is unchanged, so existing weightless
  caches (exported with NPU_WEIGHTLESS_BANK=1) remain valid.

Code changes
------------
- ggml-openvino-extra.{h,cpp}: drop the SELF_CONTAINED_BLOB, NPU_WEIGHTLESS_BANK
  and NPU_SHARED_BANK entries from the env table; replace
  ggml_openvino_npu_raw_weight_cache_enabled() and
  ggml_openvino_npu_weightless_bank_enabled() with
  ggml_openvino_npu_weightless_cache_enabled() (NPU && cache dir set); drop the
  SELF_CONTAINED_BLOB early return in ggml_openvino_npu_decode_bucket().
- ggml-openvino.cpp: raw weight upload, keeping the raw weights on Windows and
  the self-contained mmap buffer now key off the new helper.
- ggml-decoder.cpp: the raw-cache checks, including is_host_gather_rows(), use
  the new helper.
- utils.{h,cpp}: drop the embedded-weight (self-contained) blob path, the
  in-process keep-alive and the shared-bank sc-prefill/sc-decode branch;
  remove the self_contained field from static_build_args and
  ov_compiled_graph. model_cache_dir is left empty for NPU graphs without a KV
  cache; weightless_bank = NPU && cache dir set. Import with skipped weights
  always uses ov::weights_path + enable_weightless; compile enables weightless
  export whenever the weightless bank is in use.
- model-cache.h: comments updated for the single cache layout.
- Docs: OPENVINO.md and OpenVINO-ENV-VARS.md drop the removed variables and
  describe the automatic weightless bank.

Port notes
----------
Cherry-picked from d97d7fb52 (refact-cache-v0) onto xuejun/gemma4-e2b-v1.
Conflicts in ggml-openvino-extra.cpp, utils.h and utils.cpp were resolved by
keeping this branch's newer features and only removing SC/WB/SHARED:
- GGML_OPENVINO_KV_ONLY_PREFILL and GGML_OPENVINO_NPU_HOST_GATHER (env entries
  and helpers) are kept;
- ggml_openvino_npu_decode_bucket() keeps this branch's
  "BLOB_PREBUILD ? ggml_openvino_kv_slice_base() : 0";
- ov_compiled_graph keeps prefill_fp / decode_fp;
- a leftover ggml_openvino_npu_raw_weight_cache_enabled() call in
  ggml-decoder.cpp (from a branch-only commit) was switched to the new helper.

Verification
------------
phi-4-mini Q4_0 llama-server on NPU (c=8192, chunk 1024, KV_SLICE=1,
BLOB_PREBUILD=1, LAZY_HOST_THRESHOLD_MB=128, no bank env var set):
- cold export: weightless bank selected automatically, 8 blobs (prefill +
  decode for KV windows 1024/2048/4096/8192, 3.6-10.8 MB each) + one
  2125 MB weights.bin; load 67.3 s, prefill 1119 t/s, decode 22.09 t/s;
- 3 imports with SELF_CONTAINED_MMAP=1, all blobs cache HIT, no recompile:

    avg of 3 imports   baseline(lazy128)   this commit   delta
    LoadMs             3822                3686          -3.6%
    InUseDeltaMB       3398                3470          +2.1%
    Prefill t/s        1260                1253          -0.6%
    Decode t/s         22.45               22.67         +1.0%

  compare_baseline.ps1 -Variant lazy128: within tolerance.
- llama-simple smoke test on NPU passes.

* ggml-openvino: remove GGML_OPENVINO_NPU_PARALLEL_COMPILE

Drop the opt-in switch that compiled the NPU prefill and decode models
concurrently. Prefill and decode are now always compiled one after the
other, which was already the default behaviour.

Why
---
- It was off by default and not used by any preset, launch config or
  bench script.
- It only applied when the weightless bank was off. Since the weightless
  bank is now automatic whenever GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR is
  set on NPU, it could only take effect for uncached runs.
- Compiling both models at the same time raises the host memory peak
  during load, which works against the memory-reduction work on NPU.
- It added a second, rarely tested code path around build_static_model().

Code changes
------------
- ggml-openvino-extra.{h,cpp}: remove the GGML_OPENVINO_NPU_PARALLEL_COMPILE
  env table entry and ggml_openvino_npu_parallel_compile_enabled().
- utils.cpp: remove the parallel_compile flag and the std::async branch in
  the static (NPU) compile path; keep the sequential prefill -> decode
  compile, including the no-KV-cache and shared decode_source cases,
  unchanged. Update the comments that mentioned parallel compilation and
  drop the now unused <future> include.
- dev_doc/OpenVINO-ENV-VARS.md: remove the variable from the table.

A leftover GGML_OPENVINO_NPU_PARALLEL_COMPILE in the environment is now
reported as an unknown variable and ignored.

Verification
------------
- llama-server and llama-simple build with GGML_OPENVINO (MSVC Release).
- llama-simple granite-4.0-1b Q4_0 on NPU decodes 20 tokens correctly.

* ggml-openvino: apply clang-format

* docs : add a gemma-4 E2B NPU example with the model cache

* docs : update docs

* ggml-openvino: remove dead code and simplify env handling

* ggml-openvino: add GGML_OPENVINO_DEBUG_DYNAMIC_DIMS

* ggml-openvino: one compiled-model cache per static (NPU) graph

Replace the static-path cache bookkeeping with a single cache per cgraph
entry. The key is the cgraph; the value is a map of compiled models, one
per static variant (prefill/decode, KV window, SWA window, output length),
each holding its own infer request.

Why
---
The static (NPU) path kept compiled models in several places that had to
be kept in sync:
- a prefill/decode "compiled pair" in ov_compiled_graph shared across
  backends through compiled_cache->graphs;
- per-KV-window decode and prefill models plus their requests and I/O name
  caches in ov_runtime_context;
- a process-wide table of imported blobs (g_imported_blobs /
  import_cached_blob / ov_clear_imported_blobs).
Export, import, KV-window switching and fallback each walked a different
subset of these, which made the logic hard to follow and to change.

New structure
-------------
- utils.h:
  - ov_static_variant_key {prefill, attention_size, attention_size_swa,
    output_len}, ordered and comparable.
  - ov_static_variant {compiled model, lazily created infer request,
    input/output names}.
  - decoder_runtime_ctx owns std::map<key, variant> variants plus the
    per-graph state shared by all variants (kv_only_prefill,
    decode_unfold, cache_base_extra, prefill/decode prepared flags and the
    weights path/bank/layout).
  - ov_compiled_graph is reduced to the fields used by the dynamic path;
    the prefill request/name caches are removed from ov_runtime_context.
- utils.cpp (static path):
  - Small helpers before ov_graph_compute_static: variant key list,
    fingerprint, weights selection, blob usability check, decoder build,
    compile config, conversion, weights layout and
    static_load_variants().
  - static_load_variants() imports every usable blob and compiles the rest
    in one place. The first prefill and decode models are still converted
    before any compile (Bonsai-8B ordering). Each model logs
    "<prefill|decode> model of KV window N imported/compiled in X ms".
  - ov_graph_compute_static() now: looks up the entry, resets it when the
    graph cannot be reused, picks the needed prefill key and the decode
    key, loads what is missing, then takes the request from the variant
    (created on first use). The KV-only output step and KV growth use the
    same variant map; the separate decode-window request switching is gone.
  - Removed g_imported_blobs, import_cached_blob() and
    ov_clear_imported_blobs().
- ggml-openvino.cpp: drop the ov_clear_imported_blobs() call in backend
  free.
- model-cache.cpp is unchanged.

Cache behaviour (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR set on NPU)
-------------------------------------------------------------------
- GGML_OPENVINO_SELF_CONTAINED_MMAP=0: models with a usable blob are
  imported, all missing ones (every prefill/decode KV window) are compiled
  and exported as weightless-bank blobs plus the shared weights file.
- GGML_OPENVINO_SELF_CONTAINED_MMAP=1: every model is imported from the
  cache. A missing blob now fails immediately with
  "GGML_OPENVINO_SELF_CONTAINED_MMAP: no usable cached <prefill|decode>
  model of KV window N in <dir>; run once with
  GGML_OPENVINO_SELF_CONTAINED_MMAP=0 to build the cache".
- Compiling after the host weights were released still fails fast.
- The fingerprint formula (cache_base_extra and per-variant salt) is
  unchanged, so existing caches stay valid: a fresh phi-4-mini export
  produces the same 8 blob names as a cache from the previous commit.

Behaviour changes
-----------------
- Compiled models belong to their backend entry and are no longer shared
  across backends through compiled_cache->graphs.
- Without head-major KV, an export compiles all prefill KV windows but
  keeps only the needed one resident; the others are imported from the
  cache on first use. With SELF_CONTAINED_MMAP=1 or head-major KV all
  variants are kept.

Verification
------------
- llama-server and llama-simple build with GGML_OPENVINO (MSVC Release);
  llama-simple granite-4.0-1b Q4_0 on NPU decodes 20 tokens correctly.
- phi-4-mini Q4_0 llama-server on NPU (c=8192, chunk 1024, KV_SLICE=1,
  BLOB_PREBUILD=1, KV_ON_DEMAND=1, HFA_PREFILL=1, DECODE_UNFOLD=1,
  LAZY_HOST_THRESHOLD_MB=128):
  - export: 8 models compiled and exported (blob names identical to the
    previous cache), load 64.7 s, prefill 1152 t/s, decode 21.8 t/s;
  - 3 imports with SELF_CONTAINED_MMAP=1, no recompile:

      avg of 3 imports   baseline(lazy128)   this commit   delta
      LoadMs             3822                3725          -2.5%
      InUseDeltaMB       3398                3386          -0.4%
      Prefill t/s        1260                1266          +0.4%
      Decode t/s         22.45               22.48         +0.1%

    compare_baseline.ps1 -Variant lazy128: within tolerance.
- gemma-4-E2B Q4_0 llama-server on NPU (c=8192, ub 1024, chunk 512,
  KV-only prefill path): export compiles 8 models (load 404 s); 2 imports
  with SELF_CONTAINED_MMAP=1, no recompile, no errors: avg load 4452 ms,
  InUse 2534 MB, prefill 2315 t/s, decode 21.55 t/s.
- SELF_CONTAINED_MMAP=1 with an empty cache dir (granite llama-simple)
  exits with the error message above.

* docs : update docs

* ggml-openvino: check the conv state cache feature size in CPY

* ggml-openvino: apply clang-format

* ggml-openvino: fix SSM_CONV_CONCAT_FUSION test on GPU

- ssm_conv: use a 2D GroupConvolution (unit H dim) instead of 1D. The OV 2026.4 GPU plugin fails to compile the 1D form in ACCURACY mode (Weights/ifm mismatch) when the input comes from RMSNorm -> Transpose -> Concat.

- cpy: handle CPY into a contiguous view of a plain (non-KV, non-recurrent) tensor at a static offset via op_case 4, and splice on the flattened base so offsets spanning rows are written correctly.

* ggml-openvino: fix GATED_DELTA_NET_CACHE_FUSION test

* ggml-openvino: fix SHORT_CONV test

---------

Co-authored-by: Anisha Kulkarni <anisha.dattatraya.kulkarni@intel.com>
Co-authored-by: ravi9 <ravi.panchumarthy@intel.com>
2026-11-26 18:26:55 -08:00
Anant Shrivastava a07831a008 sycl: route BMG D=256 single-query decode to the FA vector kernel (#30606) 2026-11-26 18:47:37 -05:00
lhezandHongqiang Wang 9fa7a33cbb opencl: add multi token f32 GEMV for spec verify (#33098)
* opencl: add multi token F32 GEMV

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
Assisted-by: Codex

* opencl: let ne01 > 512 still use tiled GEMM

---------

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-26 13:26:17 -08:00
Sv. Lockal e087c6c4e7 hip : fix bf16 MFMA operand vector type for CDNA (#33086)
Follow-up to ggml-org/llama.cpp#30885: the CDNA MFMA bf16 builtins
also take short vectors, so LLVM 23 rejects __bf16 for gfx908, gfx90a,
gfx942 and gfx950.
2026-11-26 21:36:34 +01:00
stornic56 492d23cc9e bailingmoe3 : fuse ssm_conv + silu and remove redundant copies (#33081)
* bailingmoe3 : apply silu before reshape to enable fused conv kernel

* bailingmoe3 : avoid redundant copies before attention output projection
2026-11-26 21:36:16 +01:00
Aleksander Grygier e8d7128fea ui: type /cwd and other slash commands anywhere in the chat input (#33070)
* ui: type the working directory on a /cwd line in the chat input

On a desktop, choosing the working directory from the + menu or the chip
puts `/cwd <path>` above the message being written, with the caret after
the path, instead of opening a separate search field. The suggestions
follow what is typed there, Enter picks only from them, and closing the
picker gives the message back as it was.

The chat form's pickers float above the line being written, also in the
collapsed form, and fit their suggestions between a min and a max width.
A directory under home always shows from `~/`.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: find working directories by a partial name, allowing for a typo

A plain name on the /cwd line is now looked up anywhere under home, not
only among its direct children, with the nearest folders listed first.
A search that finds nothing is retried allowing for one wrong, missing,
extra or swapped character.

Assisted-by: Claude (Fable 5.2)

* ui: keep the path pickers at one width and list hidden folders last

The @ mention and /cwd pickers no longer resize with their results, and
folders that are hidden or sit inside a hidden folder rank below regular
ones unless the query itself starts with a dot.

Assisted-by: Claude (Fable 5.2)

* ui: list a relative path's own folder before its deeper namesakes

A query with a path in it (ui/lib/voi) was matched only below some other
folder, never at the top of the scope, so hidden copies were the only
results. The path is now also followed from the scope itself and listed
first.

Assisted-by: Claude (Fable 5.2)

* ui: fix the folder pickers' review findings

- Read a backslash as a path separator under a Windows home or working
  directory, in the /cwd and @ pickers.
- Leave Enter to an IME composition, and to the message when the caret is
  below the /cwd line.
- Close the /cwd line before sending, so it is not sent as text.
- Keep the highlighted folder when the deeper results arrive, and do not
  leave the deep search's failure unhandled.
- Walk the typo search nearest depth first and stop once it finds something.
- Surface the deep search's error when a relative path finds nothing.

Assisted-by: Claude (Fable 5.2)

* ui: highlight the first suggestion of every new round in the pickers

A list that renders under a resting pointer no longer counts as a hover, and the
folder picker starts each round of results on its first folder.

Assisted-by: Claude (Fable 5.2)

* ui: keep the new chat's form in place as chips appear under it

Assisted-by: Claude (Fable 5.2)

* ui: drop the command picker's icons and shorten /compact's description

Assisted-by: Claude (Fable 5.2)

* ui: always edit the system message in the chat form, without a model selector

The + menu turns the form into the system message editor whether or not the
conversation shows its system message, and the editor offers no model selector.

Assisted-by: Claude (Fable 5.2)

* ui: add /system-message and keep the form's size in system message mode

The command turns the chat form into the system message editor. The editor's
dashed edge is an inset outline in place of the card's own edge, so the card
keeps its size.

Assisted-by: Claude (Fable 5.2)

* ui: find a rooted path's name further down, and retry a failed home lookup

`@~/llama.cpp` and `/cwd ~/llama.cpp` list `~/git/llama.cpp` when home itself
holds no such name. A failed lookup of the server's home directory is no longer
kept for the session, so the working directory can show from `~/` once it works.

Assisted-by: Claude (Fable 5.2)

* ui: type slash commands anywhere in the message

A command is found at the caret, after other words or on another line, not only
at the start of the input. Picking one takes just the command out and leaves the
words around it, and /cwd stays where it was typed (the + menu writes it at the
caret), so the path no longer jumps to a line of its own above the message.

Assisted-by: Claude (Opus 5.5)

* ui: keep the words after an argless command, and track /cwd by its edits

- only /prompt and /cwd read the words after them: Enter after
  `use /m the small one` no longer picks /model and deletes the sentence
- the open /cwd picker follows its own command after an edit, never
  another /cwd the message names, and closes when its command is deleted
- a blocked send leaves the /cwd command and its picker alone
- callers of the server home share one request
- a typo-tolerant folder search whose every glob fails shows the error
- hidden folders sort last behind backslash separators too

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 21:25:36 +01:00
Piotr Wilkin (ilintar) 2a335259ca ggml/CUDA+HIP: Flash Attention with indexed bias (#33063)
* cuda : port indexed bias FA onto the refactored loaders

Replays the #32740 bias support on the shared typed tile loader, adds bias
in F32 to match the CPU reference and routes rows via KV_indirection.

* cuda : return zeros for a fully masked FA query row

An all -inf mask row has a zero softmax sum, which divided gave NaN. Guard
the tile, vec and results-combine divisions so it gives zeros, as ggml-cpu.

* Code review from Fable
* fixup! cuda : port indexed bias FA onto the refactored loaders
2026-11-26 21:13:03 +01:00
Shawn Gu 47d6192fce opencl: add MoE int8 bin kernel host side changes for Adreno A850 (#33069) 2026-11-26 11:51:32 -08:00
Nikita Belokopytovandruixiang63 6d54465e9d ci: relax spec dec acceptance length floor (#33127)
* tests: relax Qwen3 DSpark acceptance length floor

* relax threshold for all spec decs

---------

Co-authored-by: ruixiang63 <wangruixiang07@outlook.com>
2026-11-26 21:36:23 +02:00
Pascal 98cc730cc8 tests : relax the DEPTH_MIX tolerance to the mul_mat one (#33141) 2026-11-26 20:10:25 +01:00
Aleksander Grygier e630f78729 ui: install the demo harness before the app's type check in CI (#33145)
The app's demo helpers import @ggml-org/llama-demo, a link to ui/lib/demo,
and svelte-check resolves the harness sources' imports (@playwright/test
among them) from ui/lib/demo/node_modules. The Checks job installed only
the app, so its type check failed on the harness since it moved there.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 20:09:59 +01:00
Aleksander Grygier 5d7bb89f47 ui: fix the phone model sheet's search field and reasoning row (#33144)
* ui: fix the phone model sheet's search width and reasoning row

Give the sheet's foot the lists' gutter, so the search field lines up
with the inset groups above it. Draw the reasoning effort as an inset
group like the All models row, with its levels sliding open inside it.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: give the sheet search and header values the plain text field look

The phone model sheet's search borrowed the chat form's glass surface,
gradient edge and all; it is now a plain SearchInput in the chat form's
pill shape. The header value fields drew their own transparent textarea
next to Input keys; they use the shared Textarea, so every text field has
the same background and border.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: hide the reasoning row while the phone model sheet searches

A typed search gives the sheet to its results; the reasoning row comes
back once the search is cleared.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: use a model for dictation from the phone model sheet

Holding a model that hears offers Use for dictation, as the desktop row's
microphone does, and the model chosen for it can hand the choice back to
Automatic.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: tidy the phone model sheet after review

- Keep for dictation on the model Automatic picked, instead of Use for
  dictation on a model that already transcribes it.
- Keep the reasoning row mounted while a search hides it, so its levels
  are as they were left.
- Name the Reasoning row label once for both pickers.
- Restore the stores the dictation test changes, and cover the keep case.
- Mention the dictation options on the Mobile Flows page.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 19:58:57 +01:00
Aleksander Grygier 0ac39e4705 ui: NVFP4 as 4-bit in Discover, model details inside Search (#33120)
* ui: show NVFP4 quants in the 4-bit row of Discover Models details

The quant regexes only knew MXFP, so NVFP4 files had no quant token,
landed in "Other" and showed their whole filename on the chip.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show a model's details inside the search dialog

Picking a Hugging Face model in Search now keeps the dialog open and
shows the Discover details pane under the search input, below the picked
row, instead of opening the full Discover dialog. Esc, typing or picking
the row again goes back to the results.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep the search dialog one size, match the model details skeleton

The search dialog no longer grows when a model's details open in it. The
details skeleton follows the loaded layout: row heights, chip widths that
wrap where the real ones do, a readme title, and no leftover block under
the quant rows.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: leaner model details in the search dialog

The details shown in Search drop the "View on Hugging Face" button and
the description, through a `compact` prop on the details pane, and the
search dialog is a step wider so the metadata chips fit on one line.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 19:54:31 +01:00
Aleksander Grygier fa9f928f25 ui: move the demo harness to ui/lib/demo and render videos on the Llama brand (#33125)
* ui: render demo videos in a window on a brand ground

A demo video is now rendered from the recorded frames: the app in a rounded window on a Llama brand ground, camera zooms with motion blur, captions under the window, and an optional logo card. DEMO_POLISH=0 gives the plain screencast as before.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: let demos mock llama-server and record Storybook stories

Assisted-by: Claude (Opus 5.5 Medium)

* ui: check chat search end to end against a mocked llama-server

Assisted-by: Claude (Opus 5.5 Medium)

* ui: add a skill to demo, test and document Llama Chat and Llama UI changes

Assisted-by: Claude (Opus 5.5 Medium)

* ui: describe the demo render in the README and the ui-demo skill

Assisted-by: Claude (Opus 5.5 Medium)

* ui: zoom the whole stage in demo videos, show taps on touch demos

The camera now moves over the stage, so the window comes closer with its corners and the ground round it. The render runs in a Chromium of its own at 1x. A touch device shows a fingertip tap in place of the cursor.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: make the demo camera moves shorter and snappier

Assisted-by: Claude (Opus 5.5 Medium)

* ui: fix tiled shadows when the demo camera zooms in

Each copy of the window is now laid out where the camera puts it instead of scaled with a transform: Chromium cut the scaled shadow into tiles, which left light rectangles round a zoomed window. The motion blur now spans half a frame, like a 180 degree shutter.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: draw the zoomed demo window on one canvas

The motion blur copies are drawn on one stage canvas, with the squircle corners and the shadow in 2D, instead of as one layer each: twelve large layers overran Chromium's tile memory while the camera moved, and the dropped tiles showed as light blocks round the window.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: leave phone demos unzoomed in the ui-demo skill and README

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show each demo video beside its description in the PR

A test's description annotation is written to the video manifest; when the tests have one, the Demo section puts one video to a row with its title and description.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: move the demo harness to ui/lib/demo

The recorder, the render, the Demo driver, storage and the pr and docs commands are now @ggml-org/llama-demo in ui/lib/demo, for any app in the suite. It imports only Playwright's types: the app passes in its page, so it runs from source with nothing installed. Llama Chat keeps its fixtures, servers and traces command in its demo folder.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: harden the demo render and the pr command

The render cleans up after a failure and removes the part-written mp4. A page the render cannot frame records plainly instead of losing its captions, demos fail early outside Chromium, and the render's extra time is added after the demo, so a test.setTimeout() in it cannot take it away. demo:pr finds the app in the worktree from git's own prefix, a description's line breaks stay inside its table cell, zoomIn scrolls its target into view, and a quick second tap keeps its fingertip.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: teach the ui-demo skill to shape, check and publish a demo

Assisted-by: Claude (Opus 5.5 Medium)

* ui: import the demo harness as @ggml-org/llama-demo

Llama Chat adds ui/lib/demo as a local file: dependency, which npm links, and imports it by name instead of by relative path. Nothing is published; npm ci leaves a link that only the demo commands follow.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 17:15:39 +01:00
Aman Gupta 0e4e925e8f CUDA: fuse the Inkling 2 short conv, depth mix, loop controller, L2 clip and situ chains (#33060)
* model : inkling2 order the conv ops so backends can fuse them

* CUDA: fuse the Inkling 2 short conv, depth mix, loop controller, L2 clip and situ chains
2026-11-26 23:15:36 +08:00
Gabor Nagy 6aad4c7efd nix : remove x86_64-darwin support (#33114)
26.05 is the last release to support x86_64-darwin and support for this
platform was dropped in 26.11.
2026-11-26 15:58:09 +01:00
Ruben Ortlam 46ba8b7008 vulkan: fix Windows driver RDNA1 architecture misclassification (#33123) 2026-11-26 15:56:30 +01:00
Jesse 436d7e81ca DPI setting for PDF as Images - Inkling-2-Mini-BF16's work (#33061) 2026-11-26 14:57:50 +01:00
Nick Towle a866b4ade6 ui: pass theme to toasts (#33082) 2026-11-26 14:12:27 +01:00
Radoslav Gerganov 4ba835c637 tests : add RPC support to test-llama-archs (#33112)
Running test-llama-archs with an RPC device is quite useful as an
integration test for the RPC backend. Here is a sample run with the
Vulkan backend:

ggml-rpc-server -d Vulkan1
test-llama-archs --rpc 127.0.0.1:50052 -b RPC0
2026-11-26 14:57:25 +02:00
Karlis 689194808a quantize : include clocale for std::setlocale (#33105)
[no ci]
2026-11-26 13:56:00 +01:00
thelittlefiremanandSigbjørn Skjæret fd4b137e38 CI: add Hip occupancy check and small static analysis report (#32365)
* ci: check for occupancy regressions vs master in HIP quality check

Add scripts/hip/gcn-cdna-occupancy-check.py, which compares per-kernel
occupancy between two GGML_HIP_EXPORT_METRICS build logs and fails when
a kernel drops occupancy. Wire it into the HIP quality check workflow:
the baseline (master) is built with the same target and flags, then
compared against the PR build.

Assisted-by: Hermes Agent

* ci: reuse spill-check build and cache master baseline for occupancy check

The PR-side metrics.log is shared with the VGPR spill check, so the
occupancy comparison adds no extra PR build. The master baseline metrics
log is cached by master-push runs and restored on PRs; it is only
rebuilt as a fallback when the master tip has no cached baseline.

* ci: report occupancy and spill changes as a markdown artifact

Extend gcn-cdna-occupancy-check.py to also compare per-kernel VGPR and
SGPR spills, and add a --report option that writes a markdown report
with all regressions and improvements. The workflow uploads the report
as an artifact on PRs, even when the check fails.

* ci: split metrics check and markdown report into separate scripts

gcn-cdna-metrics-check.py compares per-kernel occupancy and spills and
can dump all deltas as TSV; gcn-cdna-metrics-report.py generates the
markdown report from that dump. The workflow runs both on PRs and
uploads the report as an artifact.

* ci: consolidate HIP kernel metrics checks using Clang YAML remarks

Merge VGPR threshold, occupancy/spill comparison, and Markdown reporting
into one script with unchanged checking rules and output formats. Parse
per-kernel optimization records instead of interleaved text diagnostics.
Add unit tests and update the CI baseline cache to contain YAML records.

* ci: preserve comparison kernel selection and fix Python indentation

Count only kernels with occupancy or spill remarks, as before the YAML
migration. Add a regression test for VGPR-only records and fix flake8.

* ci: fix Python type checking for HIP metrics scripts

Cast metric entries to lists before appending and check the dynamic
module spec and loader are available before executing the tests.
Preserve existing checks and reports.

* ci: add blocking and warning HIP kernel regression rules

Preserve the VGPR limit and its exemptions, block spill increases and
occupancy drops with increasing VGPRs, and warn on occupancy-only drops.
Collect all findings and generate the report before failing CI.

Request device optimization records explicitly and bypass ccache during
metrics builds; print YAML diagnostics to investigate missing kernel
resource remarks in ROCm 7.2.1.

* ci: preserve device-only HIP optimization records

Do not enable host remarks: Clang writes host and device optimization
records to the same output path. Filter the device records to kernel
resource usage and validate the compiler output before expensive builds.
Invalidate old baseline caches and avoid reporting a missing TSV.

* ci: include HIP runtime in metrics probe

Assisted-by: ChatGPT

* ci: build only ggml-hip for kernel metrics and propagate build errors

Assisted-by: ChatGPT

* ci: match HIP baseline to merge commit and publish job summary

Assisted-by: ChatGPT

* ci: trust the HIP CI checkout directory before resolving baseline

Assisted-by: ChatGPT

* ci: cache HIP baseline metrics in HF buckets

Assisted-by: ChatGPT

* ci: publish HIP metrics report to logs and job summary

Assisted-by: ChatGPT

* Ci: hip auto clean every 30 days

Assisted-by: ChatGPT

* Update .github/workflows/hip-quality-check.yml

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>

* ci: fix conflits and rebase

Assisted-by: ChatGPT

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
2026-11-26 14:50:32 +02:00
Ruixiang WangandNikita Belokopytov 55d482814b DFlash2: support Inkling-2-Mini DFlash2 (#33073)
* support inkling2 DFlash2

* address review comments

Assisted-by: Claude Opus 5.5
Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com>

---------

Co-authored-by: Nikita Belokopytov <belokopytov.n@gmail.com>
2026-11-26 14:47:55 +02:00
PascalandGeorgi Gerganov 7365e4793c tests : take the test-fusion moe flag from the fixture name (#33104)
* tests : take the test-fusion moe flag from the fixture name

The moe flag came from the arch name, so the dense and MoE fixtures
of an arch shared a baseline key, and MoE-only archs were keyed as
dense. Read it from the -dense/-moe suffix written by
test-llama-archs and regenerate the Metal baseline. Only the moe
column changes, no count moves.

* Apply suggestion from ggerganov

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>

---------

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-26 14:44:02 +02:00
Sigbjørn Skjæret b16f15350a ci : move vulkan-nvidia runners to dgx spark (#33113)
* move vulkan-nvidia runners to dgx spark

* --sudo
2026-11-26 13:42:59 +01:00
Aman Gupta b671865c7b CUDA: move the fusion code out of ggml-cuda.cu (#33087)
Move the fusion matchers, ggml_cuda_can_fuse, ggml_cuda_try_fuse and the
fusion alloc deps of graph_optimize into fusion.cu, unchanged.
fusion.cuh exports ggml_cuda_try_fuse and ggml_cuda_fusion_add_alloc_deps.
The GGML_CUDA_DISABLE_FUSION check is done by the two callers, and
ggml_cuda_is_view_or_noop moves to common.cuh since the compute loop
also uses it.
2026-11-26 18:58:44 +08:00
Aleksander Grygier 8c6418001d ui: read the Enable MCP setting through one getter (#33067)
uiStore.isMcpEnabled and mcpStore.isFeatureEnabled read the same setting. The MCP store's getter stays, and the two callers of the UI store's use it.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 11:53:21 +01:00
anujj 09c1410642 ggml : support a BF16 src1 in MUL_MAT and MUL_MAT_ID (CPU, CUDA) (#32533)
* ggml : support a BF16 src1 in MUL_MAT and MUL_MAT_ID (CPU, CUDA)

* ggml : fix MMVF expert offset overflow and tighten BF16 src1 gates

* ggml : strided BF16 src1 tests, explicit MUSA Q2_K rule, MMVF offset fix moved to its own PR

* cuda : move the MUL_MAT_ID MMVF rule into ggml_cuda_should_use_mmvf

* cuda : read a BF16 src1 in MMVF through a template parameter, for BF16 and FP8 weights only

* cuda : MMVF src1 pairs via ggml_cuda_cast, rename type to type_src0
2026-11-26 15:59:27 +05:30
Aman Gupta 28148b5f06 llama : refuse SPLIT_MODE_TENSOR for Hadamard-folded models (#33080)
Prism Bonsai models (prism.hadamard) aborted in the meta backend with
GGML_ASSERT(split_state.ne[j] % div == 0) when loaded with -sm tensor:
the ssm_out input permutation from tiled to grouped GDN head order
reshapes the head-split activation to [hd, n_k, n_rep] and the split
lands on n_rep (3 for 2 devices). Past that, the explicit sign vectors
are mirrored while their inputs are split, and the 1024-wide rotation
blocks would straddle the device slices of ffn_down (17408 = 17 blocks).

Fail at load with a clear message instead.

Assisted-by: Claude Opus 5.5
2026-11-26 11:44:26 +02:00
Aman Gupta 51ab45e3c5 CUDA: fuse the top-k MoE weight norm with an additive sum bias (#32943)
Assisted-by: Claude Opus 5.5
2026-11-26 11:30:42 +02:00
Aman Gupta caea914e9d CUDA: loop over ne2/ne3 in non-contiguous concat (#33006)
The non-contiguous concat kernel mapped dst ne[2] and ne[3] directly to
gridDim.y and gridDim.z, which are limited to 65535. Larger tensors made
the launch fail with "invalid configuration argument". Cap the grid and
loop over the remaining rows in the kernel.

Fixes #32956

Assisted-by: Claude Opus 5.5
2026-11-26 11:29:58 +02:00
Pascal e38ea719bd CUDA: fix ROCm CI, do not pick the tile FA kernel for DKQ 576 with a GQA ratio not divisible by 4 (#33045)
* CUDA: flash attention tile kernel for DKQ 576 with a GQA ratio of 2

The tile kernel for 576/512 only had variants for GQA ratios that are
multiples of 4, while the kernel selection accepts any ratio from 2,
so an MLA attention with a ratio of 2 aborted on GPUs that use the
tile kernel, such as RDNA. Add the 2 column configuration, copied from
the 512/512 one of each table, and dispatch even ratios to it. Odd
ratios have no tile variant: the selection now reports them as
unsupported instead of picking the tile kernel. Cover the ratios 2
and 3 in test-backend-ops.

* CUDA: pass the K/V types to the tile kernel for 576 with a GQA ratio of 2

#32901 added the K and V types as template parameters of the tile kernel,
the ratio 2 dispatch for DKQ 576 still used the old parameter list.

* CUDA: report DKQ 576 with a GQA ratio not divisible by 4 as unsupported by the tile kernel

Use the selection instead of a new tile specialization, as suggested in
review: drop the 2 column variant and only pick the tile kernel for
576/512 when the GQA ratio is a multiple of 4, the ncols2 = 4 and 16
variants it has. The ncols2 = 4 variant cannot serve a ratio of 2, a
block reads a single K/V head.
2026-11-26 11:25:33 +02:00
Aleksander Grygier 074f1f3f73 ui: npx llama-chat talks to llama-server on :9931 by default (#33095)
Without --server, the CLI's config.json now points the app at
llama-server's default port on the host the page was opened from,
instead of the CLI's own address, which has no API and answered 404.
Bump @ggml-org/llama-chat and llama-chat to 0.3.1.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-26 08:52:24 +01:00
Georgi Gerganov 1715275226 sync : ggml 2026-11-26 09:38:27 +02:00
Georgi Gerganov 2a59da5bf2 ggml : bump version to 1.1.1 (ggml/1703)
* ggml : bump version to 1.1.1

* authors : update
2026-11-26 09:38:27 +02:00
Alan Zhai 07ba74babd sycl: update linux refer doc (#32583) 2026-11-26 00:41:32 -05:00
Todd Malsbary 267dda8180 sycl: Remove check for host waits in fattn-mkl from graph checks (#31208)
Signed-off-by: Todd Malsbary <todd.malsbary@intel.com>
2026-11-26 00:40:10 -05:00
Max Krasnyansky e0f884d405 ggml-hexagon 2.0 : support for int-hmx, automatic f32 -> f16 lowering, and generic dma pipelines (#32582)
* hexagon : add DMA pipeline, htp_tensor_read, and cache/mdev cleanup

- Add dma-proxy thread/ring for main-thread DMA offload (clamp n_hvx <= hw_nth - 2)
- Add syncht in hmx-queue after HMX VTCM stores

* hexagon : add F16/collapse graph lowering and fusion updates

* hexagon : update host kparams solver for W8A8 HMX, F16, and DMA

* hexagon : add INT-HMX W8A8 matmul, F16 support, and DMA writeback

- Use 64-col dual-acc (weight.b:deep + mxswapacc) across all arches and :cm activation layout
- Pre-issue chunk-0 weight DMA via dma_proxy, balance 4-row quad output threads, and defer output DMA pop

* hexagon : add HMX W8A8 Q8_0 KV flash attention and DMA writeback

hex-fa: cleanup dma_queue usage and mask buffers
hex-fa: fix new op tests and corner cases
hex-fa: cleanup kernel selection and solver
hex-fa: improve decode performance (split-kv)

* hexagon : add F16, DMA, and micro-kernel optimizations for unary/norm ops

* hexagon : add mixed F16/F32 and HVX optimizations for binary ops

* hexagon : add F16, DMA, and state fusion for gated-delta-net

Alsp pipeline GDN HMX/HVX with batched dispatch and spill-free inversion

* hexagon : add F16, token-major fusion, and DMA updates for SSM ops

* hexagon : add F16 and HVX optimizations for rope, softmax, and glu

rope: optimize init and add common fast-path

* hexagon : add F16, DMA, and spill fixes for argsort and top-k

* hexagon : add F16 lowering and optimizations for lightning-indexer and dsv4

* hexagon : add F16 and DMA updates for row and concat ops

* hexagon : convert simple ops to dma-pipeline, F16, and warning/mdev cleanup

* hexagon: add support for fusing MUL_MAT_NX with GLU ops (GEGLU,SWIGLU,...)

- Double-buffer vtcm_up/vtcm_wt_scales_up, add 0-spill direct loop0 FP16 GLU strip kernels, trim sub-ULP FP16 sigmoid terms
- Balance 4-row quad GLU threads, defer output DMA pop, and pre-issue chunk-0 weight DMA via dma_proxy

* tests : add F16/mixed-type and Hexagon op test cases

For now do not include ssm_conv tests that break ggml-metal

* hexagon : update trace and run scripts

* hexagon : update Snapdragon backend README and developer docs

Includes updated tensor tiling description (it is 32x4 now)

--
Co-authored-by: Ehsan Bateni <ebateni@qti.qualcomm.com>
Co-authored-by: Todor Boinovski <todorb@qti.qualcomm.com>
Co-authored-by: Trivikram Reddy <tamarnat@qti.qualcomm.com>
Co-authored-by: Yanzhao Wang <yanzhaow@qti.qualcomm.com>

Assisted-by: Antigravity
2026-11-25 20:59:59 -08:00
anujj f8b7ed5250 cuda : fix int overflow of the MMF matrix offsets (#33044) 2026-11-26 10:19:40 +05:30
gianni-cor 55b2238be8 ggml : add TANH backward pass (#32136)
Build the gradient dy * (1 - y^2) from the forward output with existing
ops, no new op is needed. Add TANH to the gradient-checked unary ops.

Signed-off-by: gianni-cor <gianfranco.cordella@tether.io>
2026-11-26 12:38:00 +08:00
Clemens Wasser a8ad690ca9 sycl: add gated delta net ESIMD kernel (#31762) 2026-11-25 21:38:28 -05:00
cwriter aee03fbe80 sycl: fuse recurrent convolution windows (#31355) 2026-11-25 21:12:07 -05:00
Aleksander Grygier 9c003a97ab ui: open settings, the + menu and the model picker as sheets on phones, and manage MCP from settings (#33036)
* ui: add inset lists, rounder bottom sheets and a native select to the design system

Inset lists (grouped rows with inset dividers, titles and captions) are surface utilities in llama-ui, documented in DESIGN.md and the Surfaces story. Bottom drawers get the sheet radius and rounder inset groups, switches a finger-sized variant, and SearchInput an inputClass prop.

NativeSelect is a trigger styled like the app's select that opens the OS's own picker, and useSheetPages a page stack with slide transitions for sheets.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open settings and the add menu on phones as sheets of inset pages, and manage MCP from settings

On a phone, Settings is a full-height sheet over the sidebar: theme tiles, then a row per section that pushes the section's page, with Tools, tool groups and MCP servers as further pages. Changes apply as they are made. Selects open the OS picker, number fields are 16px so iOS does not zoom, and switches are finger-sized.

The + menu is a sheet of the same inset pages, which stays open while the file picker is up. Settings and a primary New chat button sit at the bottom of the phone sidebar, and Show less sticks to the bottom of the chat list.

Show MCP becomes Enable MCP: while it is off, no MCP server is connected and chats get no MCP tools. The servers are managed from Settings, in a dialog on the desktop and a page in the phone sheet; the sidebar entry and /mcp-servers are removed. Someone who already added a server gets Enable MCP on.

A setting can name the devices it applies to, and is listed only there. Switching sections scrolls back to the top, the system message has a placeholder, inputs offer no browser autofill, the desktop settings sidebar sits on the dialog's background, and the sidebar footer groups its rows only when it shows more than one.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: pick models on a phone from a short sheet, and list the desktop selector's models without a Local models section

On a phone, the model picker opens on a short view: the chat's model, the dictation model, loaded models, favorites and recent ones, marked In chat and Dictation. A tap switches the model; holding a row opens its menu, with More details and Unload for a loaded model. All models is a page of its own, in the same grouped rows. The reasoning effort keeps its list of levels, above the search, which is a SearchInput at the foot of the sheet in the chat form's surface.

On the desktop, the server's models are listed in their family groups without a Local models section around them. They sit in an Other models section only when favorites or loaded models are listed above them, and the section headings have no icons.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: let demos touch, hold and seed chats, and import traces through either settings section

demo.tap and demo.hold drive touch input on a phone viewport, a chats option seeds the sidebar with conversations, and trace imports find Data or Import/Export in the settings.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: release llama-ui 0.7.0 and llama-chat 0.3.0

Llama UI gains the sheet components (SheetHeader, SheetPages, InsetList and its rows) and NativeSelect; Llama Chat gains the phone sheets and Enable MCP.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 22:39:55 +01:00
PascalandGeorgi Gerganov 7135e2fd69 metal : spread the short mat-vec lanes over src1 rows (#33034)
* metal : spread the short mat-vec lanes over src1 rows

The short mat-vec kernel (K < 32) mapped its 32 lanes to 32 src0 rows
and handled one src1 row per threadgroup, so with few src0 rows most
lanes were idle. It now covers min(ne01, 32) src0 rows of 32/that src1
rows.

This is the weighted sum over the depth states of Inkling 2 since
#32855 (1-3 src0 rows, K = number of states, 2304 src1 rows).
Inkling-2-Mini UD-Q4_K_XL, M5 Max, master -> this PR:
  pp512 888 -> 1052 t/s, pp2048 771 -> 894 t/s, tg128 unchanged.
PPL and greedy output bit-identical, the graph is unchanged.

Tested: test-backend-ops -b MTL0 -o MUL_MAT (new small-K cases).

* cont : clean-up comment

---------

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-25 22:39:14 +01:00
Sergio Sánchez VallésandSergio Sanchez 5917b39ff7 convert : map the Inkling-2 LoRA tensor names (#33055)
PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention output gate (self_attn.o_proj.gate_proj.weight); neither is in the Inkling-2 tensor map, so convert_lora_to_gguf.py stops with 'Can not map tensor'. Strip the .linear. segment and map the gate to ATTN_GATE.

Co-authored-by: Sergio Sanchez <sergiosv96@users.noreply.github.com>
2026-11-25 20:49:09 +01:00
bri-prism 8d35ba4f7b metal : revert "metal: increase default command buffers on iPhone (#31815)" (#33050)
This reverts commit 1f3ea67fbf.
2026-11-25 20:28:59 +01:00
Gabor Nagy acb269e511 nix : fix build on darwin (#32955)
`darwin.apple_sdk` is deprecated and has been removed. It's not needed
anymore to build on darwin.
2026-11-25 20:27:14 +01:00
lhez d9dae03443 opencl: Adreno E17 compiler quirks off by default (#33013) 2026-11-25 11:20:30 -08:00
Aleksander Grygier eb56575095 ui: stop the streaming reply with Escape (#33051)
Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 20:02:31 +01:00
5a09582d80 model : add RAON-1-mini-preview support (#32176)
* vocab : add RAON pre-tokenizer and NFC normalization
* model : add RAON hybrid attention and mHC graph
* convert : add MXFP8 weight dequantization
* convert : add RAON HF to GGUF conversion and schema
* chat : add the RAON chat template
* tests : add RAON vocab regression files for test-tokenizer-0
* llama-quant : add RAON quantization rules for attention projections
* vocab : move RAON to the standard tokenizer list and remove its dedicated tokenizer test
* convert : move MTP layer check to filter_tensors and correct comment on _KEEP_UNQUANTIZED
* convert : add orphan-scale gurad for MXFP8 scales
* model : remove redundant graph expansion, use require() for RDA head size validation, and add comment for MLA latent normalization
* llama : share KDA conv1d between Raon and Kimi K3
* convert : remove redundant MXFP8 dequantization
* model : align RAON MoE call formatting with other models
* tests : remove RAON quantization test
* model : match RAON MoE weight normalization to the HF reference
* set expert_weights_norm_eps to 1e-20, which introduced in commit 5c008e0
* tests : add Metal fusion test for Raon

Assisted-by: Codex
Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Dong Won Kim <63934649+ddwkim@users.noreply.github.com>
Co-authored-by: Hyeonghwan Kim (김형환) <kim2h7903@krafton.com>
Co-authored-by: Seohyun Choi <seohyun.choi@krafton.com>
Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com>
2026-11-25 19:38:12 +01:00
Piotr Wilkin (ilintar) 2d5b3ddde3 model: use the indexed bias in the Inkling 2 graph (#33053)
* use the indexed bias in the Inkling 2 graph
* Remove RPC check
2026-11-25 19:01:27 +01:00
Johannes Gäßler 94a1e4b722 CUDA: refactor & deduplicate FA data loading (#32901)
* CUDA: refactor & deduplicate FA data loading

* fix float2 indexing

* fix hip quality check
2026-11-25 18:47:26 +01:00
PascalandXuan Son Nguyen c943331339 model : add hy_v4_flash on the DSA iSWA cache (#32960)
* model : add hy_v4_flash on the DSA iSWA cache

Tencent Hy4 flash is a hy_v4 trunk (iHC, gated MLA, sinks) with
sparse and sliding-window MLA layers, sandwich norms, latent routed
experts and deepseek41 Engram tables.

The sparse layers select their context with a pooled indexer: the
keys of 4 consecutive tokens are pooled by a per-channel softmax of a
gate plus a position bias, normed, and rotated at the position of the
first token. A token attends to the best scored pools of its sequence
plus its own pool.

The model runs on llama_kv_cache_dsa_iswa as dots3note does. The
indexer cache holds the projected value and gate of each token, and
the pools are rebuilt from the cells for every ubatch by
llama_kv_cache::set_input_kpool(), so there is no pooled state to
keep in sync with sequence edits, checkpoints or state save/restore.
The selection goes through ggml_top_k_mask with the pool members as
blocks and the token's own pool as extra cells.

Not covered yet: the MTP block (its tensors are skipped), the vision
tower, multiple KV streams, and backends without GGML_OP_TOP_K_MASK.

* convert : add hy_v4_flash

The converter of the hy_v4_flash model, without the vision parts.

The four Engram tables are written as one per_layer_token_embd
tensor of about 127 GB in BF16. Concatenating them with torch.cat
materializes the whole tensor at write time, so they are streamed one
table at a time in row chunks through the _StreamedBytes path of
deepseek41, which keeps the conversion within 100 GB of RAM.

* tests : add hy_v4_flash to test-llama-archs

A 4 layer fixture that alternates sparse and sliding-window layers,
with hyper-connections, one Engram module, an indexer on the sparse
layers and a latent width distinct from the expert width, so that a
transposed routed_down or routed_up is caught.

* kv-cache : do not shift the pooled indexer cache

The pooled indexer of hy_v4_flash caches the value and the gate of
each token, without a position: the pooled key is rotated in the
graph. A K-shift rotated these rows as if they were roped keys, which
broke the pooled keys after a context shift.

* tests : add the hy_v4_flash Metal fusion baseline

* model, mtmd : add hy_v4_flash vision

The vision tower of hy_v4_flash, with its projector in mtmd and its
converter.

The published files carry M-RoPE sections, so the text model runs the
interleaved M-RoPE path: the rope rows keep their reference order and
are reordered to NeoX halves in the graph. The tokens of an image share
their position, so the indexer pools now group consecutive tokens in
sequence order instead of consecutive positions, and a pooled key is
rotated at the four positions of its first member.

Without a backend that runs GGML_OP_TOP_K_MASK, the picked pools are
expanded to their cells and go through build_top_k_mask.

* CUDA: lightning indexer for 16 heads

hy_v4_flash scores its pools with 16 indexer heads, which the CUDA
backend did not support, so the scheduler ran the 12 sparse layers'
indexers on the CPU at every step. Both kernels already handle 16
heads: the mma kernel needs a multiple of 16 and the vector kernel
splits the heads in 4 passes.

* model : move the Hy4 flash Engram gathers before the token embeddings

With the gathers after build_inp_embd, the mixed embedding DUP and SET_ROWS
sat between two host nodes and stayed on the CPU. Those ops use every thread,
so all the CPU workers woke up on each decoded token for a 12K copy.
Gathering first lets the scheduler put them on the GPU, as in qwen4exp, and
leaves only small single threaded lookups on the host.

* llama : speed up the Hy4 flash pool inputs on long contexts

set_input_kpool deduplicated the pools through a map keyed by vectors even
with a single sequence, sorted cells that are already in order and scanned
every pool owner for each token. Dedup only when the ubatch has several
sequences, skip the sort when the cells are ordered and mark the earlier
pools of the token's sequence directly. At 129k cells the host cost of a
decode step drops from 4.0 ms to 0.5 ms, the logits are unchanged.

* llama : use a unified KV cache for Hy4 flash

The pools gather their members from a single KV stream, so a split cache
with several sequences hit an assert in the graph. Switch to the unified
cache with a warning, the sequences then share n_ctx.

* rm redundant code in mtmd

* clean up comments

---------

Co-authored-by: Xuan Son Nguyen <son@huggingface.co>
2026-11-25 18:39:50 +01:00
Ravi PanchumarthyandMustafa Cavus 244640b7f2 ggml-openvino: fix CI op tests and improve KV cache decode (#33002)
* ggml-openvino: write back consumed in-place nodes of op-test graphs

On the naive path every node of an op-test graph is a model output,
except an in-place node that another node reads: it got no output, so
its destination buffer was never written. GATED_DELTA_NET_CACHE_FUSION
copies the final state into the cache and then reads the copy, so the
cache kept its old contents.

Write such a node back through its view_src, as is already done when
nothing reads it. Model graphs are unchanged.

* ggml-openvino: keep the rest of the buffer in a partial in-place FILL

An in-place FILL on a view into part of a larger buffer produced only
the filled values. Its output stands for the whole in-place source, so
the write-back put those values at the start of the buffer and not at
the view's offset.

For a contiguous view with a static shape, build the whole buffer: the
elements before the view, the filled values, then the elements after
it. Add NodeContext::get_inplace_op_src() to detect the in-place case.

* ggml-openvino: fix softplus precision for large negative inputs

softplus was computed as relu(x) + log(1 + exp(-|x|)). When exp(-|x|)
is below the precision of 1 + exp(-|x|), the log returns 0 or one ulp,
so for x below about -16 in f32 the result was 0 or far off. The
SOFTPLUS test case with inputs in [-16.6, -16] fails on CPU and GPU.

Compute log1p(y) for y = exp(-|x|) with the series
y - y^2/2 + y^3/3 - y^4/4 when y < 0.01, where its relative error is
below 2e-9, and keep log(1 + y) above that.

* ggml-openvino: finer GPU KV rounding for decode batches

Rounding the GPU KV length up to a power of two makes a batch attend up
to twice the rows that hold data right after each power of two. Decode
reads every attended row, so long contexts lose decode speed.

The GPU plugin keeps memory for each attended length: several large
buffers for a prompt batch, about one copy of K and V for a decode
batch. Keep the power of two for prompt batches (more than 16 tokens
per sequence), and round decode batches up to a multiple of 2^k / 4 and
of 256. That is four lengths per power of two, with at most 25% masked
rows.

* ggml-openvino : keep the head axis of the 4-D KV cache static

* ggml-openvino: split two one-line lambdas per clang-format

The backend's .clang-format keeps a lambda on one line only when it is a
function argument (AllowShortLambdasOnASingleLine: Inline). The constant
helpers in the softplus and FILL translators are assigned to variables,
so clang-format splits them. Formatting only.

---------

Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
2026-11-25 07:53:56 -08:00
Chipmunk 679d8677b2 llama : fix seq state restore with ON_DEVICE (#30318) 2026-11-25 16:48:55 +01:00
Georgi Gerganov beb9d49339 llama.cpp : bump version to 1.1.0 (#33043)
* llama.cpp : bump version to 1.1.0

* authors : update
2026-11-25 17:11:22 +02:00
AWA 532d67426b vocab : implement Metaspace prepend_scheme always for BPE (#33038)
* vocab : implement Metaspace prepend_scheme always for BPE

* Drop test-tokenizer-mmbert
2026-11-25 16:02:25 +01:00
maxipesfix 5e4fda8ed0 ui: fix for a chat form update loop with large fonts and long model names (otherwise web interface gets Error 500) (#33037)
* ready for PR

* addressing review comments
2026-11-25 15:43:01 +01:00
Georgi Gerganov a28feb4589 sync : ggml
[no ci]
2026-11-25 16:06:38 +02:00
Georgi Gerganov 3125043613 ggml : bump version to 1.1.0 (ggml/1699)
* ggml : bump version to 1.1.0

* authors : update
2026-11-25 16:06:38 +02:00
Adrien Gallouët 98f870c220 llama : honor metaspace_prepend_scheme for SPM (#31986)
* llama : honor metaspace_prepend_scheme for SPM

This fixes chat prompts for Nanbeige4.3-33B

Signed-off-by: Adrien Gallouët <angt@huggingface.co>

* Add global escaped_space

Signed-off-by: Adrien Gallouët <angt@huggingface.co>

---------

Signed-off-by: Adrien Gallouët <angt@huggingface.co>
2026-11-25 14:59:00 +01:00
AWA 2e2f5a0373 model : load YaRN hparams in llama_model_base::load_hparams (#33032)
* model : read YaRN beta_fast and beta_slow hparams in deepseek2

* model : load YaRN hparams in llama_model_base::load_hparams

* tests : remove test per review
2026-11-25 14:20:55 +01:00
Aleksander Grygier 41c7a1b49d ui: fix tool result media shown twice, uncapped and dropped after its run (#33010)
* ui: drop images of old turns from the context, read_media loads them again

When read_media is offered and the model has vision, the images of user
turns far behind leave the request. A note stays in their place with an
"attachment:" path, and read_media resolves that path from the
attachments the browser holds, with no call to the server. Without the
tool, attachments are sent as before.

The cut moves once per 4 turns, so the server keeps its cache between
moves. The chat request, the pre-encode and the compaction summary read
the same list.

Images of a tool result now get the max resolution cap that attached
images get.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: store the media of a tool result once

The tool result message was created with its extracted media, then
onAttachments appended the same extras to it again, so the trace showed
every read_media image twice. The callback had no other use and goes.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: images of tool results follow the cut of old turns

A stored tool result now sends its media to the model as the run that
called the tool did, only what the model can read, through one helper,
so the image stays in later turns and the server's cache stays valid.
Before, it left the request once the run ended, with no note to load it
again.

The cut of old turns now covers tool results too, read_media's own
included: their images leave with a note and an "attachment:" path.

Media stored twice by the earlier bug is sent, noted and shown once.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep attached images in the context

Takes back the cut of old turns: images of turns far behind stay in the
request, and read_media has no "attachment:" path. Each move of the cut
made the server process everything after the removed image again, which
costs far more than the tokens of the image it frees.

The fixes stay: the media of a tool result is stored once, its images
get the max resolution cap, and it goes along in later turns.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: send the media of a stored tool result in agent requests

The agent request turned a tool message with content parts into an
empty string, so a stored tool result with media reached the model
with no text and no image on later turns.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 14:13:26 +01:00
Aleksander Grygier 77026f6e61 ui: open the warm microphone only once the pointer rests on its button (#33033)
The record button opened the microphone as soon as the pointer entered it,
so a mouse only passing over turned the browser's recording indicator on.
It now waits until the pointer (or the focus) has rested on the button for
VOICE_WARMUP_REST_MS; moving on the button restarts the wait.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 13:47:52 +01:00
Aleksander Grygier c8eda101c1 ui: add file extensions to the Vite config's local imports (#33023)
Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 13:43:04 +01:00
Sigbjørn Skjæret 996de35a9c ci : revert disable musa.Dockerfile from docker.yml (#33025) 2026-11-25 13:42:19 +01:00
Masashi Yoshimura ab16df399f webgpu : add log1p for softplus op (#33017) 2026-11-25 13:25:28 +01:00
Aleksander Grygier 0cac1220e3 ui: time each tool group by its own loop and show the task time in the reply stats (#33030)
The tool call group's timer now times its own loop of calls, from its first
call's start to its last call's end, ticking while it runs and kept once the
reply is done. The harness records each call's id and wall-clock start and
end with its timing for this.

The reply's statistics show the whole task time next to the generation
stats, ticking while an agentic reply runs.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 13:16:19 +01:00
Aleksander Grygier 1ed4e77f4d ui: search home by default in the working-directory picker and pin tool call chevrons (#33028)
* ui: search home by default in the working-directory picker

A plain query now navigates home as if typed after `~/`, and Enter on a
plain query commits that folder under home. Queries starting from a root
(`/`, `C:\`, `\\host\share`) or `~` still navigate the absolute tree.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: pin the tool call chevron and timer to the end of the row

Tool call, group, reasoning and search result headers span the full
width: the title takes the rest of the row and truncates, while the
timer and the chevron stay at the right end, so a title that changes
while it streams no longer moves them.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 13:14:03 +01:00
Baran Bati 48ac736960 server : handle CTRL_BREAK_EVENT on Windows for clean shutdown (#32080)
Windows can't send SIGINT to a child process, so scripts that launch
llama-server could only kill it, which skips the clean shutdown. The
console control handler only handled CTRL_C_EVENT, so a CTRL_BREAK_EVENT
sent to the server's own process group ended it with
STATUS_CONTROL_C_EXIT.

- server: handle CTRL_BREAK_EVENT the same as CTRL_C_EVENT in the
  console control handler
- scripts/moe-cache-tune.py: on Windows, start the server in a new
  process group and stop it with CTRL_BREAK_EVENT. On other platforms,
  stop it with SIGINT. In both cases, kill it afterwards as a fallback.
- tests: add test_server_ctrl_break (Windows only) and a
  ServerProcess.share_console option. Console control events only
  reach a server that shares the test's console, hence the option.
2026-11-25 16:59:01 +05:30
LostRuins Concedo 5220a2d404 quant : avoid macro collision on windows (#33014)
[no release]
2026-11-25 11:17:26 +01:00
xjf888800 0fc7e1716f docs : fix stale CPU support in ops.md (#32796)
* fix repeat

* whole test-backend-ops CSV update.
2026-11-25 11:00:05 +01:00
Alexey Kopytko 6d5f648721 ggml-cpu : accept the flash_attn_ext indexed bias (#33016)
The reference implementation is in place, but the device rejected the op, so
test-backend-ops skipped all the indexed-bias cases. The spacemit FA path
leaves the op to the generic CPU path.
2026-11-25 11:48:31 +02:00
Aman Gupta 52f6e0247a metal : commit the graph in chunks with one command buffer thread (#32947)
Assisted-by: Claude Opus 5.5
2026-11-25 11:42:34 +02:00
Aleksander Grygier de30697285 ui: import conversations or settings by dropping them anywhere in the app (#32958)
* ui : add global drag-and-drop import for conversations and settings

Dropping an exported conversation (.zip, .jsonl) or settings (.json)
anywhere in the app now routes to a global importer instead of attaching
the file to a message. A state machine in use-drop-import classifies the
file, shows a review dialog (settings diff, single-conversation preview,
or bulk picker), and applies it on confirmation. The chat screen defers
import files so they are not treated as attachments.

* ui : preview settings diff before importing from Import/Export tab

The Import/Export settings tab now opens the same settings diff dialog
used by drag-and-drop (showing which values would change) before applying
an imported settings file. It reuses computeSettingsDiff from the global
drop-import hook instead of importing immediately.

* ui : fix formatting in drag-and-drop import

* ui : use SvelteMap/SvelteSet and fix eslint in drag-and-drop import

* ui : adapt drag-and-drop import to current lint rules

Assisted-by: Claude (Opus 5.5 Medium)

* ui : fix importing dropped conversations

Store a plain snapshot of the previewed conversation, since IndexedDB
cannot clone the reactive proxy, and collapse drops that carry the same
conversation more than once to its newest copy, so the selection list
no longer crashes on duplicate keys.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : simplify the dropped conversation preview dialog

Drop the icon and the description from the header, and give the
preview padding and a subtler border.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : set the dropped conversation preview on a recessed surface

Assisted-by: Claude (Opus 5.5 Medium)

* ui : ask to open a dropped conversation after importing it

Assisted-by: Claude (Opus 5.5 Medium)

* ui : diff dropped settings against what importing applies

Importing applies the file over the defaults, so a key the file leaves
out goes back to its default instead of showing as unset.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : match the settings import preview to the conversation preview

Assisted-by: Claude (Opus 5.5 Medium)

* ui : set the drop import text through type roles

Assisted-by: Claude (Opus 5.5 Medium)

* ui : attach dropped files on the chat unless they are exports

The chat now reads each dropped .json, .jsonl or .zip and hands only real
Llama Chat exports to the importer, through a drop-import context set by the
layout; everything else is attached as on master, mixed drops included. Its
drag events no longer bubble to the document, so the import overlay no
longer shows over the chat or stays up after an attachment drop.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : one drop area to import and a choice of what to export

The Import/Export tab now has a single drop area (or file picker) that takes
conversations, settings or a full backup and goes through the same previews
as dropping anywhere in the app. Export asks for conversations, settings or
everything; everything is one ZIP with the conversations and settings.json,
which importing reads back, showing the settings first and the conversations
after. Sensitive data is an inline checkbox instead of its own dialog.

Bulk import now reports conversations already in the library instead of
counting them as imported, and reloads groups like the tab used to.

Assisted-by: Claude (Opus 5.5 Medium)

* ui : import demo traces through the Import/Export drop area

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 09:56:31 +01:00
Aman Gupta 62d6c8cb3a ggml: allow input async copies (#30685)
* ggml: allow input async copies

Copy the host inputs of a split with set_tensor_async followed by a
single synchronize, instead of one blocking copy per input. This is
opt-in per device through the new async_host_input cap, which only
CUDA sets. Other backends keep the current path.

The async path is used without pipeline parallelism only. With
pipeline parallelism, the input backend also waits on the slot event
before an async copy, since CUDA peer copies run on the source stream.
This replaces the synchronize on graph reuse in process_ubatch.

* remove sched change

* tests : add get_props to test-alloc dummy device

* tests : check that sched inputs can be overwritten after compute_async

* ggml : rename async_host_input to fast_async_host_input, address review comments
2026-11-25 16:56:15 +08:00
Kartik Gulia 5bd90fa0e4 common : implement named tool choice (#31564)
* common : implement named tool choice for automatic parsers

* common : add qwen3-coder support

* common : remove redundant condition

* common : set parallel_tool_calls to false for named tool

* common : implement tool choice allowed subset

* cleanup

* fix formatting + move validation to common

* more formatting >_<
2026-11-25 10:39:09 +02:00
Javier Argomedoanddiabluz 522d6fdd44 deepseek41 : read quantized indexer K in place when fused_idx is set (#32795)
Indexer K is a strided view of the kv pool; with fused_idx the fused
indexer reads it through strides and supports quantized types, so the
F32 cast was a pure extra copy per ubatch: PP/TG +2..+15% by depth,
VRAM unchanged. Quantized K now scores through the MMA kernel (like
f16 caches); deep greedy A/B shows only 0.02-0.13-nat near-tie swaps,
paired PPL < 0.1% with no direction.

Co-authored-by: diabluz <diabluz@users.noreply.github.com>
2026-11-25 10:36:02 +02:00
Martin Emrich 61d456a232 common : accept boolean "value": true JSON schema (#32908)
* accept boolean "true" JSON schema

... as sent e.g. by "RAGFlow".

* revert over-eager tests
2026-11-25 10:35:44 +02:00
Aman Gupta ea72294814 ggml: allow reserving scratch memory in graph_optimize (#31898)
* ggml: allow reserving scratch memory in graph_optimize

Add add_scratch to ggml_backend_graph_optimize_params. A backend can
reserve compute buffer memory that is allocated before a node `first`
and kept until a node `last` has been computed, e.g. for data that
several nodes share. The scheduler adds the scratch tensor to the graph
copy right before `first` and frees it with an alloc dep at `last`.

* ggml: clarify the lifetime of add_scratch memory

* ggml: build the pending scratch set from the scratch map
2026-11-25 10:34:49 +02:00
Aleksander Grygier 36d818e161 ui: edit the system message in the chat form when it is hidden in conversations (#32967)
* ui: edit the system message in the chat form when it is hidden in conversations

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open the hidden system message from a chip under the chat form

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep a new chat's system message as a form attachment until the first message

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open the chat form in two rows while it holds the system message attachment

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show a conversation's hidden system message in a chip under the chat form

The attachment stays for a new chat, until the first message sends it.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show the system message chip whenever a conversation has one

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 08:42:41 +01:00
Michael Taylor 81ff0cab06 sycl: F8 e4m3 initial support SET_ROWS, CPY, ADD, MUL_MAT, MUL_MAT_ID (#31871) 2026-11-25 02:35:18 -05:00
Michael Taylor cddaa915a4 SYCL : ROLL op handles permuted source (#31799) 2026-11-25 02:29:04 -05:00
Aleksander Grygier e8906e6b0c ui: add --ui-agent for agent mode without server tools or the MCP proxy (#33004)
* ui: add --ui-agent to run Llama Chat with browser tools only

Assisted-by: Claude (Opus 5.5 Medium)

* ui: say that --ui-agent leaves direct MCP servers available

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-25 07:08:29 +01:00
Aman Gupta abca692003 model : inkling2 graph with fewer ops in mix() and control() (#32948)
Assisted-by: Claude Opus 5.5
2026-11-25 11:54:30 +08:00
Shawn Gu e6443bd7eb opencl: add clc coopmat moe kernel for q4_0/q4_1/q4_k/q5_0/q5_1/q5_k/q6_k/mxfp4 (#32971) 2026-11-24 16:42:30 -08:00
Rajarshi Datta 79c69f4b06 tests : fix MSVC static build of test-batch-alloc and test-server-component (#32870)
Fixes #32868
2026-11-25 00:20:46 +01:00
33aeb17f85 feat: Inkling 2 DSpark support (#32218)
* conversion
* init cpp side
* handle temp > 0
* dspark : fix Inkling2 draft state width, reseeding and draw order
* spec: align Inkling2 DSpark with n_max draft tokens same as the other DSparks
* unify rnn condition with markov_head_type
* formatting issues and restructure some DSpark functions

---------

Co-authored-by: Xuan Son Nguyen <son@huggingface.co>
Co-authored-by: ruixiang63 <wangruixiang07@outlook.com>
2026-11-24 21:11:46 +01:00
anujj 22b99122e1 cuda : fix int overflow of the MMVF matrix offsets (#32965) 2026-11-24 20:26:08 +01:00
Kong Jiale dfdfca22bc docs : describe SpacemiT runtime environment variables (#32452)
Signed-off-by: gitGurugu <jialekong2004@mails.ccnu.edu.cn>
Signed-off-by: Wang Yang <yangwang@iscas.ac.cn>
2026-11-24 21:02:39 +02:00
velonica0 a1cee51c9d ggml : fix SpacemiT flash attention null mask, ALiBi and softcap (#32182) 2026-11-24 20:47:34 +02:00
Georgi Gerganov bb692efaa4 cmake : include the llguidance header from the source tree (#32928)
Cargo 1.100 changed the build directory layout for intermediate artifacts, so
the header destination llguidance derives from $OUT_DIR no longer resolves to
target/release, and the build fails on a missing llguidance.h. The header is a
source file that cargo only copies around, so include it from the llguidance
source tree instead of from the build output.

ref: https://github.com/rust-lang/cargo/pull/17354

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)
2026-11-24 20:31:24 +02:00
Sigbjørn Skjæret dbaf582af4 ci : move some jobs to gb10 runners (#32968) 2026-11-24 19:02:31 +01:00
Aleksander Grygier 0ce7f213b0 ui: run Llama Chat apart from llama-server, named in config.json or npx --server (#32945)
* ui: run Llama Chat apart from llama-server, named in config.json

The app reads config.json, a file next to index.html, once before it
starts. A "server" URL in it sends every API request there instead of
to the app's own origin: /props, /v1, /models, /tools, the CORS proxy
and the realtime socket. Without one nothing changes.

npx llama-chat --server <url> answers that file itself, and
npx llama-chat build --server <url> writes it. The service worker
leaves it out of its cache, so a host can change it without a new
build.

Assisted-by: Claude (Fable 5.2)

* ui: release Llama Chat 0.2.0 with --server

Bumps @ggml-org/llama-chat and llama-chat to 0.2.0 so the publish
workflow ships the --server flag to npx once this reaches master.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: expect the Llama Chat name in the PWA manifest e2e test

#32890 named the PWA Llama Chat by default, but the E2E test still
expected llama-ui, so the UI workflow failed on master and on every UI PR.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 17:38:56 +01:00
Aleksander Grygier 96eb41bc48 ui: fix prebuilt UI download in shallow clones (#32952)
In a shallow clone the git commit count is not the build number, so the build asked for a UI version that does not exist (b1 with --depth 1) and fell back to 'latest'. Use the release tag on HEAD when it was fetched, else 'latest'.

Also check a downloaded archive right after extraction. If it does not have the files this checkout needs, drop it and build without an embedded UI instead of failing the build.

Refs #32780

Assisted-by: Claude (Fable 5.2)
2026-11-24 17:34:34 +01:00
Sigbjørn Skjæret 23f0c0182f convert : fix qwen3-omni conversion (#32941) 2026-11-24 17:33:45 +01:00
Marco Colombo f20c5907c0 ggml-cpu: repack kernels for targets without dotprod (ARMv8.0 64-bit) for Q4_0/Q8_0 (#32142)
* ggml-cpu: optimized kernels for ARM v8.0 (without dotprod)

* ggml-cpu: fix comment and align to implementation

* ggml-cpu: exclude new kernels for apple arch
2026-11-24 16:18:37 +00:00
Aleksander Grygier 8bf2eae708 ui: expect the Llama Chat name in the PWA manifest e2e test (#32959)
#32890 named the PWA Llama Chat by default, but the E2E test still
expected llama-ui, so the UI workflow failed on master and on every UI PR.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 17:10:20 +01:00
5fddd0b998 ggml-cpu: add SVE-optimized q5_0 and q5_1 dot-product kernels (#30867)
* Merged PR 5925: SVE suooprt for ggml_vec_dot_q5_0_q8_0, ggml_vec_dot_q5_1_q8_1

SVE suooprt for ggml_vec_dot_q5_0_q8_0, ggml_vec_dot_q5_1_q8_1

* perf(arm): optimize q5_0 q8_0 dot products with SVE

- Load high-bit masks directly from quantized blocks
- Replace lookup-table expansion with predicated SVE duplication
- Reduce scalar high-bit unpacking overhead

* fix(arm): load SVE masks through inline assembly

- Add a helper to load mask data as svbool_t with ldr
- Replace direct svbool_t pointer casts in the q5 dot-product path

* fix(arm): correct q5/q8 SVE bitmask handling

- Fix qh bit inversion in the SVE q5_0/q8_0 dot-product path
- Use the proper predicate-aware svnot_b_z mask logic for bit extraction
- Restore correct quantized compute behavior on ARM SVE targets

* fix(arm): simplify q5_1/q8_1 bitpack handling

- replace manual qh extraction with vector bitmask loads in the ARM SVE path
- remove temporary unpack buffers used during q5_1 dot-product assembly
- preserve the qh bit pattern while keeping the quantized dot-product logic intact

* fix(ggml-cpu): support SVE load on non-GNU compilers

- Add the existing GNU/Clang inline assembly path for SVE bool loading
- Provide a portable fallback for other compilers using SVE intrinsics
- Preserve current behavior on supported toolchains while improving compatibility

* fix(cpu): cast SVE input pointer before byte load

- fix SVE byte load by casting the uint32_t pointer to uint8_t*
- preserve correct mask generation in load_as_svbool on Arm SVE
- prevent undefined pointer aliasing in the SIMD vector path

* fix(arm): restrict q5 SVE kernels to supported vector lengths

- Limit q5 dot-product paths to 256-bit and 512-bit SVE vectors
- Assert when encountering unsupported vector lengths
- Localize the SVE predicate loader to the ARM quantization kernels

* perf(arm): optimize SVE q5 dot products for VL128

- Add an intrinsic predicate loader for SVE VL128 qh halves
- Replace table-based qh expansion in q5_0 and q5_1 paths
- Remove temporary qh expansion buffers
- Preserve direct predicate loads for wider SVE vector lengths

* fix(arm): correct SVE q5 predicate loading

- Unify predicate loading for q5 quantization paths
- Prevent out-of-bounds reads from 8-bit high-bit storage
- Remove unsupported VL512 q5 dot-product cases

* fix(arm): support SVE VL512 q5 dot products

- Bound qh predicate loads for SVE vectors at or above 512 bits
- Use the shared SVE vector-length helper
- Extend q5_0 and q5_1 dot products to VL512

* docs(arm): clarify SVE predicate loader limit

- Document that values beyond the first 32 bits of qh are undefined
- Warn that the loader may cause a SEGV for vector lengths above 1024

* perf(arm): reuse SVE vector length in quantized dot products

- Pass the cached vector length to SVE predicate loading
- Remove repeated SVE vector length queries
- Allow unsupported vector lengths to exit without assertions

* docs(arm): remove outdated SVE loader warning

- Remove obsolete VL > 1024 SEGV warning from load_as_svbool

* fix compilation errors

---------

Co-authored-by: Kato, Masaya 加藤 雅也 <kato.masaya@fujitsu.com>
Co-authored-by: Masaru Ito <masaru.ito.mi@jp.fujitsu.com>
2026-11-24 23:34:54 +08:00
Hamish M. Blair 66a3b01b0a server : include MCP image and audio data in tool results (#32064) 2026-11-24 16:23:30 +01:00
Alexey Kopytko d3c257a493 context : prevent excessive CPU polling without OpenMP (#32378)
* common : prevent polling while GPU computes (on Metal or without OpenMP)

* use AudioWorkIntervalCreate to keep the thread on P-cores

* Revert "use AudioWorkIntervalCreate to keep the thread on P-cores"

This reverts commit a7270d23c0.
2026-11-24 17:12:26 +02:00
Georgi Gerganov 3090e45a86 metal : reserve the top-k scratch only for short rows (#32942)
The bitonic top-k path is only faster for short rows. On M5 and M2 Ultra it
wins up to 128 columns; above that the radix path is faster. Use the radix
path for ncols > 128.

The radix path selects in place and needs no scratch, but the buffer type
always reserved 2*4 bytes per source element, which is 8 GiB for a
524288 x 2048 score. Reserve the bitonic worst case at the 128-column
threshold instead: 2*4*128*nrows, clamped to at least the output tensor size.
This keeps the allocation bounded and consistent with the bitonic path.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
2026-11-24 16:34:08 +02:00
Aleksander Grygier ba8521a44e ui: smooth chat form height and working directory chip across routes (#32950)
* ui: ease the chat form height and fade the working directory chip across routes

Assisted-by: Claude (Opus 5.5 Medium)

* ui: open the room for the working directory chip first, then fade it in

Assisted-by: Claude (Opus 5.5 Medium)

* ui: skip the working directory chip transition when the route changes

Assisted-by: Claude (Opus 5.5 Medium)

* ui: resize the working directory chip's box in full before fading the chip in

Assisted-by: Claude (Opus 5.5 Medium)

* ui: halve the working directory chip transition

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 15:29:51 +01:00
Ruben Ortlam 72cda4a222 vulkan: add chunked GDN replay support (#32721)
* vulkan: add replay support to chunked GDN shaders

* use atomicStore instead of atomicExchange for readability
2026-11-24 16:21:34 +02:00
losewayy 922cff91e9 cuda : fuse RMS_NORM + MUL + MROPE/IMROPE and tune block size (#32500)
* cuda : support MROPE/IMROPE and tune block size in rms_norm_mul_rope

* cuda : use 64 threads for multi-token ncols <= 256 in rms_norm_mul_rope

Assisted-by: Antigravity
2026-11-24 16:20:58 +02:00
ZhaolunYinandAleksander Grygier 2e779d5e70 Webui nix fix (#32645)
* applied fix for write into nix store

* added cuda_nvml_dev to package.nix because it is required for compilation

* chore: lint brand-favicons.ts

---------

Co-authored-by: Aleksander Grygier <aleksander.grygier@gmail.com>
2026-11-24 15:04:39 +01:00
Eddie Zhou 396ed2ccea model : Inkling 2 Mini mix() weighted sum with the scores as src0 (#32855)
* 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.

* model : return the mix() output in its matmul layout
2026-11-24 15:03:20 +01:00
Aleksander Grygier 97bbf98fdf ui: make Llama Chat a plain chat unless llama-server offers agent features (#32949)
Llama Chat showed its tools, MCP and agentic settings and ran the agentic
loop for every server. Now it does so only for a llama-server that offers
its built-in tools or its proxy, which --agent turns on together; the app
reads this from /props and /tools. Without them it is a plain chat: a
message and its reply, with reasoning when the model gives it. The chat
store sends the classic request, the tools store has no tools and the MCP
store connects to no server, so the tools menu, the working folder, the MCP
entry and page, and the Tools and Agentic settings are gone. Tool calls in
earlier conversations still display.

The Show MCP setting moves from General to the Agentic settings, with the
rest of what agent mode adds.

VITE_PUBLIC_AGENTIC=false builds an app that is a plain chat for every
server, and leaves Llama Harness's loop out of the bundle: the harness gets
a ./trace entry with the phrasing alone, and Vite resolves the package to a
small stub that re-exports it. A CI job builds the variant and checks the
loop is not in it.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 15:00:46 +01:00
Noah 40fe9164f4 server : retry prompt cache restore after clearing idle slots (#30997)
With a unified KV cache, a RAM-cached prompt can fail to restore because another idle slot still holds the cells it needs. Save and clear the other idle slots and retry the restore once in update_prompt_cache(). Builds on #32828, which keeps the cache entry intact when a restore fails.

Fixes #30961.
2026-11-24 14:13:59 +01:00
Sebastian KuzminskyandAleksander Grygier 26f5048d5c fix building in symlinked directories (#32903)
* fix building in symlinked directories

My checkout is in a symlinked directory, so that the cmake CWD differs
from its realpath:
```
$ echo $PWD
/home/[READACTED]/llama.cpp
$ realpath $PWD
/data/home/[READACTED]/llama.cpp
```

The build here fails with this error:
```
CMake Error: Unable to read from file:
  ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css
because:
  Can't lstat ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css
CMake Error at /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:229 (file):
  file failed to compress:
  /home/[REDACTED]/llama.cpp/build/ui/apps/chat/ui-gzip/_gzip/_app/immutable/assets/0.Cc4cGcci.css
Call Stack (most recent call first):
  /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:629 (emit_files)
```

This is because the cmake `emit_files` function uses relative paths and
is inconsistent about its use of realpath.

This commit fixes the build in my environment by switching from relative
to absolute paths for the archive member files, so that the distinction
between realpath and non-realpath doesn't mess things up.

* refactor: Apply suggestion

---------

Co-authored-by: Aleksander Grygier <aleksander.grygier@gmail.com>
2026-11-24 14:07:00 +01:00
Aman Gupta 9578bd3fe4 CUDA: ignore strides of size-1 dims in bin_bcast (#32854)
After collapsing contiguous dims, the stride of a trailing dim of size 1
becomes the size of the whole tensor. Its index is always 0, but the
uint32 stride asserts still fire once the tensor has more than 2^32
elements, e.g. the per-head relative-position mask add of inkling2 at
n_kv > ~87k with -ub 2048.

Fixes #32804

Assisted-by: Claude Opus 5.5
2026-11-24 14:48:02 +02:00
Aman Gupta e683365a74 model : inkling2 clip with ggml_l2_norm (#32940)
Assisted-by: Claude Opus 5.5
2026-11-24 14:47:28 +02:00
Eddie Zhou 4c92c5bfb7 CUDA: reduce all cooperative softmax partials when nsm > 256 (#32897)
* CUDA: reduce all cooperative softmax partials when nsm > 256

Fixes #32852

* CUDA: drop the remaining cooperative softmax grid size assert
2026-11-24 20:04:00 +08:00
IsNotandSigbjørn Skjæret 2a487782f2 vocab : speed up BPE tokenization (#32859)
* vocab : avoid string allocations in BPE tokenization

* whitespace--

---------

Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
2026-11-24 13:41:21 +02:00
Plasmatix Ultraandplasmatixultra 6fb428332e CUDA: NVFP4 dequant, pack 8 blocks per CTA (#32875)
Launch dequantize_block_nvfp4 with dim3(32, 8) so each CTA covers 8 NVFP4 blocks (256 values), as the K-quants do.

Assisted-by: Claude Code

Co-authored-by: plasmatixultra <plasmatixultra@users.noreply.github.com>
2026-11-24 13:38:47 +02:00
Nikhil Jain 6ac648d7a9 webgpu : Fix indexing bug in softmax kernel (#32691)
* Only run webgpu CI on my fork

* Add webgpu only workflow

* resolve merge conflicts

* add row check for softmax

* add test

* Add test to test case eval
2026-11-24 13:37:56 +02:00
Takamichi Ohara 94165b288d webgpu : add POOL_1D support (#32254) 2026-11-24 13:37:10 +02:00
thelittlefireman a8ed778914 hip: use MMQ over MMVQ for Q4_K,N8 and NVFP4,N7-8 on VEGA20 (#32805) 2026-11-24 13:36:32 +02:00
uvos 6970118ef1 HIP: CDNA1 MMQ config without stream-k (#32837) 2026-11-24 13:35:00 +02:00
Aleksander Grygier ae6a7ad2c5 ui: move the agentic loop and trace phrasing into @ggml-org/llama-harness (#32927)
* ui: add @ggml-org/llama-harness, the agentic loop as a package, in ui/lib/harness

Llama Harness is the agentic loop as headless TypeScript with no UI, no DOM and no dependencies. It streams a turn, runs
the tools the model called, gives it the results, and repeats until the model answers without a tool call. An app gives
it an inference client and tools, and reads the run as a stream of events: run(messages, tools, signal). It ships a
client for any OpenAI-compatible endpoint, so it also runs on its own in Node. The UI workflow type-checks, tests and
packs it.

Assisted-by: Claude (Fable 5.2)

* ui: run Llama Chat's agentic loop through @ggml-org/llama-harness

The loop leaves the agentic store, which now gives the harness what the app owns: ChatService as its inference client,
the enabled tools behind the permission gate, and the callbacks that store each turn. Its API and the flow's callbacks
are unchanged. A unit test runs the flow end to end with the server and the tools mocked.

Chat compiles the harness from source through an alias, so the builds that copy or isolate ui/apps/chat now bring
ui/lib/harness along: CMake and Nix through LLAMA_HARNESS_DIR, the Dockerfiles with a COPY.

Assisted-by: Claude (Fable 5.2)

* ui: bring the architecture docs in line with the ui/ folder

The layout card no longer calls the move planned, the harness is in the
pages, and they say that Llama Chat does not import @ggml-org/llama-ui yet.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: phrase agent traces in @ggml-org/llama-harness

The plain-language lines of an agent trace move out of Llama Chat into the
harness, as a headless trace module any app on it can use: what one tool call
did ("Read app.ts"), what it is doing now ("Running npm test", "Thinking"),
what a run of calls did ("Ran 3 commands, read 2 files"), and how calls fold
into one row with the reasoning around them.

createTracePhraser knows llama-server's built-in tools. An app adds its own
with resolvers and a phrasing table; any other tool reads as "Used <tool>"
with its main argument, and a call with a description shows the model's own
words. The lenient parse of streamed arguments and the targeted read of a
path in a whole-file argument move with it.

Llama Chat keeps its Svelte components and phrases only its own tools: the
browser tools, web search and tool_search. Its functions keep their names and
signatures, so nothing that renders a trace changes.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 11:12:47 +01:00
Georgi Gerganov 5fe4906859 ci : disable test-llama-context on ubuntu-llvmpipe (#32932)
The dummy-model context sweep no longer fits within the job timeout on
the llvmpipe runner. Exclude it from the ctest run there, keeping the
coverage in the other jobs.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
2026-11-24 12:11:19 +02:00
AircgandPascal 82dd970474 server : fix skipped prompt cache lookups (#28992)
* server : fix skipped prompt cache lookups

Assisted-by: Claude Opus 5

* server : let the slot scheduler ask the prompt cache

Move the prompt cache lookup into server_slot_sched::select() so the
plan alone decides whether the cache is updated, and the caller only
applies it.

find_better() and has_better() are now const, and find_better() also
returns the common prefix, so load() no longer recomputes it.

---------

Co-authored-by: Pascal <admin@serveurperso.com>
2026-11-24 11:54:31 +02:00
Aleksander Grygier a6ac41c757 ui: match tool call timer font size to its title (#32922)
Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 09:25:18 +01:00
Aleksander Grygier 3fccd98e9d ui: let the chat form's model selection decide the submit state (#32920)
When the last assistant message came from a model that is no longer
available, the submit button stayed red and disabled even after an
available model was picked in the form, since availability checked the
conversation's model first. The form's selection now decides it; the
conversation's model only counts when nothing is selected.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-24 09:25:04 +01:00
Aman Gupta 4af4bb6d8a rpc : reuse one context for request tensors on the server (#32896) 2026-11-24 09:43:50 +02:00
Georgi GerganovandIsNot-10 b12f22d2f2 ggml : use a range-reduced log1p for softplus (#32655)
* metal : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and precise::log(1 + x) otherwise.
This avoids the cancellation in log(1 + exp(x)) for negative inputs and does
not rely on fast-math folding of (1 + e) - 1.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : add a softplus test for negative inputs

Use inputs in [-16.6, -16.0], where log(1 + exp(x)) has up to ~2x
relative error. This catches both the old form and the fast-math-folded
compensated form.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* ggml : use log1pf in ggml_compute_softplus_f32

Use log1pf(expf(input)) so the host helper keeps the true value for
x < -16.64.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* vulkan : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* opencl : use a range-reduced log1p for softplus

Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
Co-authored-by: IsNot-10 <209144869@qq.com>

* vulkan : move log1p to utils.glsl

Move the range-reduced log1p out of unary.comp into utils.glsl so that
other ops such as topk_moe and ssm_scan can include it.  The body is
unchanged; only the call site in op_softplus is renamed.

Co-authored-by: IsNot-10 <209144869@qq.com>
Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB)

---------

Co-authored-by: IsNot-10 <209144869@qq.com>
2026-11-24 09:30:43 +02:00
losewayy d141011c25 vulkan: support state size 96 in ssm_scan (#32162)
* vulkan: support state size 96 in ssm_scan

Assisted-by: Claude Code

* vulkan: specialize ssm_scan state size

Assisted-by: Codex

* vulkan: clarify ssm_scan constant names

Assisted-by: Codex
2026-11-24 08:25:31 +01:00
lhez 12d47ba2f4 opencl: fix GDN QK offsets (#32747)
Assisted-by: Codex
2026-11-23 21:14:37 -08:00
lhezandHongqiang Wang af5c58347f opencl: add c8 q6_k coopk GEMM for up to n=8 spec verify (#32909)
Assisted-by: Codex

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-23 17:12:33 -08:00
Max Krasnyansky c74c71a6f7 fix editor config in master (#32914) 2026-11-23 15:47:20 -08:00
Aldehir Rojas 38b9cad71d quantize : make local const static for MSVC (#32902) 2026-11-23 17:41:33 -06:00
d35dc4d9e6 GDN: use replay instead of rollback (#31669)
* GDN: use replay instead of rollback [WIP]

* memory : move rs_max with the sequence when find_slot swaps cells

find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the
way, but not rs_max, so that sequence inherited the rollback depth of the
cell's previous owner. A smaller value made seq_rm refuse the rollback
(#31656), a larger one made snapshot mode restore the previous owner's
snapshots.

With rs_replay the pending columns are copied along with the state, so
rs_max follows the sequence. Without it only the final state is copied and
the snapshots stay behind, so the moved sequence gets rs_max 0.

* delta_net: drop the graph replay fallback

The graph fallback ran the replay as two gdn ops and copied the
committed state from the replay gdn when keep, from the main gdn
otherwise. Backends whose graph_optimize reorders nodes (Metal,
Vulkan) then give keep and non keep ubatches a different node order
for the same node count, and the scheduler reallocates on every
switch (abort under GGML_SCHED_DEBUG_REALLOC).

The replay now always runs in the gdn op. A device without the replay
in its gdn op leaves the op to the CPU through the scheduler, as for
any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe,
rs_replay_fused and the rep_mask input.

* metal: replay the pending gated delta net tokens in the kernel

The gated delta net kernel replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a function constant of the pipeline, keep is a kernel
argument as on CUDA. The pending buffers fall back to src0 when the
op has no replay.

* vulkan: replay the pending gated delta net tokens in the shader

The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a specialization constant of the pipeline, keep is a
push constant as on CUDA. The pending buffers bind q when the op has
no replay. The result checker clones the op with its replay sources.

* webgpu: replay the pending gated delta net tokens in the shader

The gated delta net shader replays the pending tokens of each seq
before the new ones, with the same state update as the main loop and
no attention output. With keep, it writes the state after the replay
and skips the final state.

The replay is a define of the pipeline, keep is a param as on CUDA.
The replay count goes through workgroupUniformLoad, so that the loop
around the workgroup barriers stays uniform.

* delta_net: share the replay conv window views across layers

Each replay layer took its own view of the rs_rep_cols input. The
scheduler copies every view of a host input as a separate split input,
so a verify graph uploaded one copy per layer. The views of the delta
net and the PLE conv windows are now built once per graph, like the
s_copy views.

* vulkan: clamp the gated delta net replay count to n_pend

The replay count comes from a buffer, so the shader bounds it to the
pending rows before looping over them. The pipeline array comment now
names the replay index next to the other ones.

Address review from 0cc4m.

* hex-gdn: add support for replay

Enable replay in HVX path
Enable replay in HMX path

* gdn: fix rebase conflicts (missing cparams, etc)

* llama : drop the fused GDN probes brought back by the rebase

il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn
was always false), so restore master's version of that code.

* delta_net : replay for the KDA models and Clover-MoE

Clover-MoE has the Qwen 3.5 layout and only needs the arch gate.

Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv
windows one after the other in a row. With replay the row holds three
channels-first histories [d_inner, window + pending]:
build_conv_state_replay takes the gathered rows of the layer and the
block index. The pending gate rows hold S_v gates per head (KDA).

GLM5-Next gets the -sm tensor split rules for the replay rows.

Tested with test-llama-archs models: logits match snapshots bit for bit
with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and
test-llama-context passes in both modes.

* cuda : same KDA update in the gated delta net main and replay loops

The KDA main loop called expf(g) twice inline, the replay loop reads
g from registers. On sm_89 nvcc fused the two loops differently, so a
replayed state was a few ulp off the state of the first pass. Compute
g into registers in the main loop too: replay matches snapshots bit for
bit on sm_89, and the sm_120 output does not change.

* opencl: support replay in GDN

* llama : replay inputs for the hybrid iswa rel memory input

build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and
cparams to build_rs_inp_impl and fill the replay inputs in set_input,
like the other hybrid inputs.

* webgpu: keep the gated delta net replay within the storage buffer limit

* delta_net : add ggml_gated_delta_net_ext, replay is the only rollback

ggml_gated_delta_net_ext takes the optional replay inputs and always
outputs one state. ggml_gated_delta_net(..., K) is back to its master
signature and is deprecated; both build the same op, so the backends
are unchanged.

The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the
KDA models) now always replay the kept tokens when n_rs_seq > 0. The
LLAMA_RS_REPLAY env flag and the snapshot branch of
build_recurrent_attn are removed.

test-backend-ops drops the K > 1 snapshot cases and the K parameter of
the gated delta net tests. The cache fusion test copies the single
state.

* ggml-cpu : spacemit: leave the gdn replay to the generic kernel

The RVV gated delta net kernel does not read the replay inputs. Return
false when op param 1 (n_pend) is set, so that the generic kernel runs
the op.

* vulkan : fill views at any offset

ggml_vk_fill bound dst without allowing a misaligned offset, so a fill
of a view whose offset is not a multiple of
minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in
build_rs hits this with the wider replay conv rows on devices with a
64-byte alignment.

Bind dst from the aligned offset below it and pass the element offset
in KY. test_fill gets an offset to fill a view in place.

---------

Co-authored-by: Pascal <admin@serveurperso.com>
Co-authored-by: Max Krasnyansky <maxk@qti.qualcomm.com>
Co-authored-by: Li He <lih@qti.qualcomm.com>
2026-11-23 15:06:02 -08:00
Evan Huus c212d25ad3 server : preserve a prompt-cache entry until restores succeed (#32828)
Assisted-by: Codex
2026-11-23 21:50:29 +01:00
Hongqiang WangandLi He fd24ee26ad opencl: fetch the Adreno binary kernel library at configure time for Windows on Snapdragon (#31759)
* opencl: fetch the Adreno binary kernel library at configure time

Make GGML_OPENCL_USE_ADRENO_BIN_KERNELS an option, default ON, and add
GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH, default ON. On Windows, CMake
downloads the pinned adreno-opencl-kernels release from the Qualcomm
Software Center, verifies its SHA256, and copies the DLL and its license
next to the executables. A failed download is only a warning; the
backend then uses its builtin kernels.

The opencl-adreno release job turns the fetch off, since it ships only
ggml-opencl.dll.

* opencl: fetch the Adreno binary kernel library only on ARM64

The library is built for Windows on ARM64 only.

* opencl: add download timeout and better handle output dir

Assisted-by: Codex

* opencl: add .txt to license file

Assisted-by: Codex

---------

Co-authored-by: Li He <lih@qti.qualcomm.com>
2026-11-23 12:39:04 -08:00
Aleksander Grygier 8355b88625 ui: remove the Matte theme and the Light surfaces setting (#32906)
Paper is now the only light theme: its surface tokens stay the base
values, and the theme-matte overrides, the setting, its enum and the
Storybook surface switch are gone.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 21:38:18 +01:00
Georgi Gerganov 51831d47d0 metal : add NVFP4 support (#32825)
* metal : add NVFP4 support

Follow the MXFP4 path: add the UE4M3 scale decode, the NVFP4 dequantizers,
a dedicated mat-vec kernel with its MUL_MAT_ID, small-batch and MMA variants,
the mul_mm / mul_mm_id and tensor-op variants, and the get_rows and cpy
kernels. Enable the type in supports_op.

Tested on an M5 Max with ggml-org/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF:NVFP4
and test-backend-ops (MUL_MAT, MUL_MAT_ID, W4A8/W4A4, CPY, GET_ROWS).

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2))

* metal : skip the small-batch path for NVFP4

With the few-row MMA kernels covering ne11 3..16, the small-batch mat-vec
kernels are only reachable at ne11 = 2, where they are 17-59% slower than the
generic mat-vec kernel on an M2 Ultra and an M5 Max.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2))
2026-11-23 21:02:30 +02:00
Georgi Gerganov ab789a246c metal : batch concat rows and copy them in vector chunks (#32824)
* metal : batch concat rows and copy them in vector chunks

The concat kernel copied one element per thread, so wide rows with many rows ran at a
fraction of the memory bandwidth. Batch several rows per threadgroup and copy the
contiguous dim-0 elements in 4-element chunks when the row is contiguous.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* test : cover concat vector and misaligned row paths

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : hoist the concat src1 row offset into scalars

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : peel to align the concat vector copy

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : vectorize concat rows along any dimension

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : specialize concat with function constants

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : drop the concat row-batch dispatch

Batching several rows per threadgroup reduces the number of threads by
the batch factor. On machines with a large GPU this leaves too few
requests in flight and the copy becomes latency bound:

  M5 Ultra (36 CPU)   f16 [1024,8,256,1] d=0   8.1 us -> 17.2 us
                      f32 [4096,8,256,1] d=0  35.4 us -> 118.5 us
                      f16 [4096,8,256,1] d=2  50.9 us -> 102.0 us

An interleaved sweep of the (nth, nrptg) dispatch over the concat perf
cases on an M2 Ultra and an M5 Ultra shows that the base dispatch is
best or tied for every shape once the rows are vectorized, and that the
gains of the previous commit come from the vector copy alone:

  M2 Ultra  f16 [1024,8,256,1] d=0  32.4 us -> 17.0 us
  M5 Ultra  f16 [1024,8,256,1] d=0  13.3 us ->  8.1 us

Keep the vector copy and the function-constant specialization, and
return to the original dispatch.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)

* metal : revert the concat function constants

Specializing the concat kernel on the concat dimension and on whether a
row is split across threadgroups with function constants makes the
strided scalar path slower. Interleaved over the concat perf cases on an
M5 Ultra, the specialized kernel is not faster than the plain one, and
it costs up to 18% on shapes that are already at the memory bandwidth
limit:

  f32 [2050,8,256,1] b=255 d=0  21.0 us -> 25.1 us
  f32 [2050,8,256,1] b=256 d=2  31.1 us -> 36.7 us
  f16 [4096,8,256,1] b=256 d=2  31.2 us -> 36.7 us

Revert the specialization and keep copying rows with the runtime
arguments. The concat change is now limited to the kernel itself.

Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB)
2026-11-23 21:01:41 +02:00
Piotr Wilkin (ilintar) 239242322d ggml: compact bias on the existing FLASH_ATTN_EXT (#32740)
* compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan
* remove the Vulkan support from this PR
* move the CUDA/HIP and Inkling 2 graph changes out of this PR
* CPU reference implementation of the indexed bias
* move the indexed bias test to test-backend-ops, add the bias in F32 on CPU
* incorporate review remarks
2026-11-23 18:17:11 +01:00
Ed Addario 30ec35ae2e quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error (#15550)
* Refactor pareto optimise and convexify
* Refactor lagrange_penalty()
* Refactor quantisation checks into its own function
* Exit loop if no better solution found
* Replace slope with cross product
* Adjust for small vector size
* Simplify candidates sorting
* Add comments to explain magic numbers
* Increase scale multiplier
* Move is_iq() into a lambda and remove unused variables
* Combine quant types
* Reduce bpw range
* Refactor outlier trimming
* Tighten worker allocator
* Check for direction reversal
* Simplify dequantisation
* Calculate bpw over all tensors
* Compute rows based on tensor shape and slice count
* Prioritise important tensors
* Select quantization type if target_bpw is set unless user specifies type and threads
* Relax lambda clamping
* Add signal handler
* Add save_bpw_state()
* Add load_bpw_state()
* Add delete_bpw_state()
* Persist progress
* Uninstall signal handler and cleanup
* Fix trimming logic
* Generate model ID hash
* Remove bias mode computation
* Remove --no-bias option
* Automatically determine if bias error is significant
* Reduce compute time by parallelising tensor processing - courtesy of https://github.com/ddh0
* Add quant types
* Add --keep-bpw-state option
* Refactor signal handlers
* Update quant types
* Minor refactoring
* Add tensor type and depth heuristics
* Add option to override bpw state file name
* Minor refactoring
* Finetune heuristics
* Update usage
* Fix lambda capture
* Update epsilon specifier
* Finetune heuristics
* Simplify tensor selection
* Read statistics from imatrix
* Add Euclidean-Cosine score to identify important tensors
* Improved is_important() logic
* Fix lambda capture bug in Windows and initialise candidate_types struct
* Remove processing statistics_data
* Add --disable-tensor-importance option
* Use more descriptive option naming
* Relax target bpw range
* Increase importance boost for final pass
* Add B/F16 to get_ftype()
* Process bpw targets up to B/F16
* Improve state checkpoint filename
* Add code comments
* Update usage()
* Update README.md
* Change checkpoint file magic
* Prepare for future optimization algorithms
* Add parse_target_size()
* Add --target-size option
* Implement target_size logic
* Update usage()
* Refactor parameter names
* Refactor option names
* Update parameter names
* Improve file handling
* Remove file deletion
* Refactor variable names
* Update usage()
* Add use_wce option
* Read statistics_data from imatrix
* Add experimental entropy-modulated weighted cosine error (WCE)
* Performance optimisations (AI assisted)
* Memory optimisations (AI assisted)
* Update output log
* Fix state file name generation and simplify_pareto() lambda capture
* Change tensor importance score logic
* Refactor is_quantizable()
* Improve WCE to be magnitude-aware
* Expected Output Error MSE
* Fix scale factor overwrite bug
* Test removing unused headers
* Remove wce flag
* Angle-aware/Magnitude-aware (MSE/WCE) hybrid error estimation
* Revert to weighted cosine error estimation
* Enhanced scaling factor
* Use centered‑normalized importance scaling factor (CNIF)
* Remove redundant logs
* Improve state file handling
* Update usage instructions
* Update ftype parsing logic
* Flag experimental features subject to future removal
* Fix --target-size description
* Fix "casts away qualifiers" compiler warning
* Exclude user defined tensors (--tensor-type) from the Lagrangian optimization
(courtesy of https://github.com/AesSedai)
* TurboQuant bias factor for inner-product sensitive tensors
* TurboQuant outlier mitigation
* Refactor TurboQuant improvements
* Fix remap tensor bug
* Remove --importance-pct option
* Refactor llama_model_quantize_params to expose a pure C interface
* Consolidate load/save process and remove --save-state flag
* Minor log output changes
* Use the tensor statistics' schema
* Add quant types
* Release finished tensors mmap allocation
* Reuse sample buffers
* Fix C2327 error when target compilation is a MS platform
* Minor refactoring and AI assisted optimizations
* Add uv.lock
* Minor refactoring and AI assisted optimizations
* Add Halko, Martinsson & Tropp randomized SVD condition number estimator
* Add kappa squashing functio
* Remove unnecessary includes
* Add required include
* Update python dependencies
* Fine-tune kappa mapping parameters
* Fine-tune CNIF beta parameters
* Fix fallback counter error
* Move to libllama and unmap weights offloaded to backend
* Remove unmap weights offloaded to backend
* Add winsorization
* Add adaptive tensor boosting
* Minor cosmetic changes
* Refactor processing of unused kv tensors
* Minor cosmetic change
* Implement --max-buffer-size in target_bpw_type()
* Fix 32-block fallback case
* tensor_type_override_for() DRY refactoring
* Fix typo and remove unused option
* Fix #28491 linking bug when compiling with BUILD_SHARED_LIBS=OFF
* Remove GGML_USE_METAL conditional macro and let the optimizer decide\
* Add --target-exclude
* Remove and ignore uv.lock
* Fix pinned tensors safety limits calculation
* Fix truncation error
* Add downwards greedy upgrade
* Add target bpw/size tests
* Guard imatrix schema
* Update --target-bpw/size descriptions and README.md
* Harden state checkpoint's file operations
* Link model and imatrix to state checkpoint
* Enforce and consume stats schema data
* Add stats schema tests
* Refactor signal handlers out of lib and harden the logic
* Improve handling of pinned tensors
* Add tests
* Add include to keep ubuntu-webgpu happy
* Moving new API entries to prevent brittle downstream apps failing
* Fix miscellaneous issues
2026-11-23 18:06:26 +01:00
Georgi Gerganov 87f816e87f metal : support BF16/F32 src1 for MUL_MAT and MUL_MAT_ID (#32677)
* llama, metal : support BF16 src1 for MUL_MAT and MUL_MAT_ID

Add GGML_PREC_BF16 handling for src1 on the Metal backend when the tensor
API is available: MUL_MAT with an F32 src0 stages the A tile as bfloat, and
MUL_MAT_ID stages src1 as bfloat instead of F16. The tensor path keeps src1
in F32 when it reads the operand directly.

Add a temporary LLAMA_MOE_AMAX_SKIP env var that disables the graph-level
amax rescaling for the MoE down projection and sets the BF16 src1 hint
instead. Apply the hint inside build_lora_mm_id so it reaches the matmul
before the per-expert scale and LoRA nodes wrap it.

Add MUL_MAT_ID src1 BF16 test cases to test-backend-ops.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : support BF16 src1 without the tensor API

Allow GGML_PREC_BF16 when the device has bfloat, not only when it has the
Metal4 tensor API.

Add legacy _prec_bf16 kernels for MUL_MAT and MUL_MAT_ID that stage src1 as
bfloat in the threadgroup and run the simdgroup multiply with bfloat A and B.
The F16 MUL_MAT_ID kernel uses half A on the tensor path and bfloat A on the
legacy path.

Cast the quantized dequantize outputs to the destination element type: the
older Metal compiler on M2 rejects implicit float to bfloat.

Tested on M2 Ultra (legacy): MUL_MAT_PREC_SRC1 24/24 and
MUL_MAT_ID_PREC_SRC1_BF16 30/30. Flint Q4_K_M with LLAMA_MOE_AMAX_SKIP=1:
pp512 -2.1%, tg128 +25.5% vs master. On M5 Max: pp512 +2.1%, tg128 +22.2%.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : derive matrix types with value_type helpers

Add value_type_4x4/value_type_2x4/value_type_8x8 helpers and use them in the MUL_MAT and MUL_MAT_ID kernels so the templates take only the underlying types and derive the matrix types. Add TODOs for the remaining kernels.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : derive matrix types in the remaining kernels

Use the value_type_* helpers in the flash-attention, top-k-mask, mul-mv and
count-equal kernels to derive the matrix/vector types from the underlying
scalar types, and simplify the FA_TYPES macros.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : enable BF16 in the tensor API metallib

The tensor API requires macOS 26, where bfloat is always available, so
define GGML_METAL_HAS_BF16 when compiling the tensor metallib. This makes
the bfloat specializations of the value_type helpers visible to
fa_tensor.metal and includes the prec_bf16 kernels in the prebuilt tensor
metallib.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* metal : support GGML_PREC_F32 for src1 in MUL_MAT and MUL_MAT_ID

Split the tensor-API and legacy simdgroup mul_mm/mul_mm_id kernels into
separate files and library kinds, following the fa_tensor.metal example.
The legacy kernels, including the new _prec_f32 variants that stage src0
and src1 as float in shared memory, are compiled into the default mul_mm
library; the tensor variants live in a separate mul_mm_tensor library
kind and carry a _tensor host-name infix. Tensor devices run F32 src1
matmuls on the simdgroup path instead of the tensor API, which rounds
float operands to a reduced precision. This removes the MUL_MM_SG kind
and the #undef GGML_METAL_HAS_TENSOR compile. Add
MUL_MAT_ID_PREC_SRC1_F32 tests.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* cont : indentation

* llama : move the MoE amax skip into the precision policy

Add llm_arch_mmid_down_bf16() for the architectures whose MoE down
projection uses the graph-level amax rescaling. Extract the precision
policy setup from load_tensors() into llama_model_base::load_prec_policy(),
and move the LLAMA_MOE_AMAX_SKIP handling there: it sets prec_src1 = BF16
for ffn_down_exps before the per-tensor policy is loaded. build_moe_ffn()
now skips the amax rescaling when the policy requests BF16.

Apply the policy with the original weight so cached experts get it, drop
the prec_src1 parameter from build_lora_mm_id(), and remove the prec_src1
serialization from the model saver.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* cont : minor
2026-11-23 18:46:12 +02:00
Aleksander Grygier 1d3aad2fd8 server: ask exec_shell_command for a short description of the command (#32894)
The shell tool's schema gains a required `description` argument, listed
first: a short plain-language line on what the command does. The tool
ignores it, as before; clients can show it in place of the raw command
while the call streams and in their logs. Calls without it still run.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 17:28:56 +01:00
Aleksander Grygier 325914defd ui: show an agentic reply as a grouped Agent Trace (#32879)
* ui: show tool calls in the trace as a grouped, plain-language log

Tool calls and all the reasoning around them, up to the answer, collapse
into one row whose title sums up what happened ("Ran 2 commands, read 1
file"), so a model that thinks before every call still reads as one row
of work. Two calls, or one call with reasoning beside it, make a group;
without per-turn stats a group spans turns.

Each call reads as a sentence: built-in tools get hand-written phrasing
in two tenses, MCP and unknown tools read as "Used <tool> <argument>",
and the generic block shows simple arguments as labelled fields. A call
that has the argument a display setting picks (description by default,
overridable per tool in Settings > Tools) shows it as the model wrote it
instead, for any tool that declares it. A shell row always shows the
command, after "Ran" or after that description, and opens into the
terminal; the permission card shows the command that would run.

An open group is a list of rows under one rule, with no icons in the
headings; a running row shimmers. While a group is live its title says
what is happening now ("Reading package.json", "Thinking"), with a timer
since the prompt was sent, and the loop records the task's total time,
which the response stats show. Thoughts and tool calls now stay collapsed
while generating, with a one-time migration of the saved old default.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep a live reply steady while its status changes

The status line ( Loading weights, Processing 40% ) sat above the content
before the first token and below it afterwards, and collapsed to nothing
while tokens streamed, so the stats and actions under it jumped. It is now
one row in the trace column with a trace row's box, shown only while
nothing else is moving, and while a tool group closes the reply it becomes
that group's live title instead.

The model badge shows from the start of a live reply, the user message
reserves its stats row while the prompt is processed, and a collapsed
group title is muted.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: glide a sent message to the top of the screen

Sending snapped the page to its bottom in one frame, and layout that
settled a moment later was followed with more snaps. The page now eases
there: the target is read again every frame, so late layout bends the
motion instead of ending it with a jump, and corrections shortly after a
send are glided to as well.

A frame that arrives late counts as one frame, so a busy page slows the
glide instead of skipping it. Wheel, touch and scroll keys hand the page
back at once; typing the next message does not. Reduced motion keeps the
jump.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: show tool images in the trace and in one slideshow of the thread

A closed tool group shows every image its calls produced under its title,
64px tall at their own proportions, in a carousel once they overflow; the
strip fades out when the group opens. A call with images shows tiny
thumbnails beside its title while its row is closed.

A group thumbnail, or an image in a user message, opens one slideshow of
every image, audio clip and video in the open thread, in thread order, at
the clicked item.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: quiet the conversation around its messages

Stats and actions under earlier messages stay hidden until the reader
points at the message or tabs into it, changing only opacity so nothing
moves; the latest exchange keeps them in view and touch screens keep them
shown. A Display setting, Always show message statistics, keeps every
message's statistics in view.

With them out of sight the spacing tightens: messages sit 1rem apart, the
answer sits 0.75rem from the trace rows around it, and the user message's
stats and actions sit closer together. A queued message no longer sticks
to the bottom of the screen and scrolls with the conversation.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: name the agentic reply an Agent Trace and give basic chat its own view

A reply that ran the agentic loop is now an Agent Trace: the component
that renders it is ChatMessageAgentTrace, with matching class names and
docs. A basic chat reply, with no tool calls, renders through the new
ChatMessageAssistantResponse as its reasoning and its answer, without the
trace's grouping, timer and permission handling. hasAgenticContent picks
the view, so a live reply becomes a trace the moment its first tool call
streams in.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 17:24:05 +01:00
Aleksander Grygier 1094646c1f ui: set code in messages at the size of the text around it (#32892)
Inline code and code blocks were 14px next to 16px text. Llama Mono
has Llama Sans's x-height, so the two read as one size without the
mono being scaled down. The chat form's editor follows.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:21:45 +01:00
Aleksander Grygier 27d0a1fc73 ui: unmount a closed collapsible's body after one transition (#32881)
bits-ui rebuilds the Collapsible.Content snippet args when its close
transition ends, which re-ran the region's effect and restarted the
unmount timer, so a closed body stayed mounted for two transitions
instead of one. Reading `open` through a derived keeps the effect from
rerunning when only the args object changes.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:20:15 +01:00
Aleksander Grygier b6d5ce4bc9 ui: drop tool calls cut off by Stop from the next request (#32738)
* ui: drop tool calls cut off by Stop from the next request

A tool call stopped mid-stream could stay on its message with cut-off
arguments. The server parses every call's arguments as JSON, so the next
message in that chat ("Continue") failed with "Failed to parse tool call
arguments as JSON". Requests now leave such calls out, with the tool results
that answer them, and send a call with no arguments as {}.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: add a demo trace that ends in a stopped tool call

A conversation whose last tool call was stopped while its arguments were
still streaming, for recording the fix in the previous commit.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 16:18:59 +01:00
bri-prism 1f3ea67fbf metal: resolve gpu timeout on iPhone for Bonsai (#31815) 2026-11-23 17:15:34 +02:00
Aleksander Grygier a0677c341b ui: use a red edge on the send button's error state (#32856)
The error state reused the primary button's edge, which shows as a light
ring in dark mode. Use the danger button's edge instead.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 15:47:30 +01:00
Aleksander Grygier 2359d27a36 ui: name the PWA from the build env and default it to Llama Chat (#32890)
The manifest is built in Node by its Vite plugin, where import.meta.env is not set, so it was
always named llama-ui whatever VITE_PUBLIC_APP_NAME said. The plugin now names it from the env
Vite loaded (.env files included), and the default name is Llama Chat.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 15:45:44 +01:00
51fc2f90e2 ggml-openvino: CI fixes, new model support, fixes and improvements. (#32861)
* ggml-openvino: keep the rope angle in f32 under the f16 inference hint

* ggml-openvino: add a GGML_OP_ARGMAX translator

* ggml-openvino: keep the token dim dynamic for a 2-D activation graph input

* ggml-openvino: tolerate graph inputs and outputs with no backing storage

* ggml-openvino: invalidate a cached graph when its output set changes

* ggml-openvino: bound the compiled-model cache to N shapes instead of 1

* ggml-openvino: add GGML_OPENVINO_LOG_SUPPORTS_OP diagnostic

* ggml-openvino: honour a node's dynamic-dim classification on non-split graphs too

* ggml-openvino: fold consecutive SET_ROWS column writes into one scatter

* ggml-openvino: keep the speculative decoding feature buffers in device memory

* ggml-openvino: keep the fixed token count of static graph inputs for npu
GDN

In a static (NPU) graph that overwrites the fixed token count that
get_graph_input_shape set just before, for example of inp_tokens, so the NPU
graph got a dynamic token dimension. GATED_DELTA_NET models (Qwen3.5, Qwen3.6)
then fail to translate: "GATED_DELTA_NET pad masking requires a static token
dimension". Keep the change for dynamic graphs and the previous behaviour for
static ones.

* ggml-openvino: one output in the decode model of a static NPU pair

The decode model of a static prefill/decode pair copied the compute params of the
prefill graph, including output_len. With llama-perplexity the prefill graph has many
outputs (128 at -c 256), so the decode model gathered 128 rows from its one token in
the last layer. For a MoE model that layer then differs from the others and NPUW fails
to lower its experts ("could not lower the isolated expert partition"). A decode step
outputs one token; the model cache key already assumes it (decode_signature out=1).

* ggml-openvino: fix gated delta net when v is a view with padded heads

The GDN translator assumed v is a view of the fused qkv conv output with
the heads packed in each row, and sliced H_v * S_v elements off that row.
test-backend-ops now has padded_v cases, where v views a wider tensor and
each head row is padded (nb[1] > S_v * nb[0]). The slice then read the
padding, and the results were wrong on CPU and GPU.

Take the packed path only when nb[1] == S_v * nb[0]. Any other view goes
through the generic view resolution, which already returns
[B, T, H_v, S_v], so the reshape of the packed case is skipped too. Model
graphs build v with packed heads and keep the packed path.

* ggml-openvino: make the f32 rope angle opt-in

GGML_OPENVINO_ROPE_F32_ANGLE was on by default. It changes the RoPE of
every model on every device, and it was validated on one model on the
GPU only. On the CPU device, which computes in f32, its f16 round trip
rounds cos and sin, and ROPE cases of test-backend-ops fail against the
CPU backend.

Turn it off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. Fix
the comment that called the round trip a no-op on f32 paths. Document
the variable, and the two diagnostics added with it
(GGML_OPENVINO_LOG_SUPPORTS_OP, GGML_OPENVINO_DIAG_GRAPH_IO), in the
dev_doc.

* docs : add the Muse-Glimmer-30B DFlash memory limit and env var samples

Muse-Glimmer-30B with a DFlash draft peaks at about 45 GB of RAM on an
integrated GPU. Add it to the GPU limitations as a runnable sample, and
add samples for GGML_OPENVINO_LOG_SUPPORTS_OP and
GGML_OPENVINO_DIAG_GRAPH_IO to the dev_doc.

* ggml-openvino: fix weight zero points, buffer extras and cache-key gaps

A code review of ggml/src/ggml-openvino found these bugs:

- Q4_1 weights: `extract_q4_1_data` packs two zero points per byte from a `parallel_for` over blocks, so two threads can write the same byte.
- Zero points out of the u4/u8 range wrap around instead of saturating. gemma-4-E2B has 6 Q4_K sub-blocks with a zero point of 16 or more; 16 wrapped to 0.
- `set_tensor` overwrote the extra that `init_tensor` created for a weight without deleting it.
- The two buffer constructors had separate id counters, and the buffer id is part of the shared graph key.
- A freed weight buffer stayed in the release registry, so a later release could madvise memory it no longer owned.
- `GGML_OPENVINO_ROPE_F32_ANGLE` changes the graph but was not in the compiled-model cache key.
- On NPU, group-128 requantization ignored the row width. A model whose rows are not a multiple of 128 failed to load its weights (SmolLM2-360M).
- The static Split cache held a strong reference to the Split on its own input (a reference cycle) and ignored the output port.
- `rms_norm` took op_case 3 for both a direct and a packed pre-scaled GDN output, so the packed one was not sliced.
- Smaller items: static decode read `out_ids` even when it is empty; the static path aborted where the dynamic path returns an error; a damaged weights `.meta` hash threw from `std::stoull`; `extract_layer_from_name` threw on a non-numeric suffix; `GGML_OP_FILL` was registered twice.

- ggml-quants.cpp: one `parallel_for` iteration per zero point byte for Q4_1; clamp zero points to [0, 15] (u4) and [0, 255] (u8).
- ggml-openvino.cpp: `ggml_openvino_set_extra` replaces and deletes the old extra at every site; one id counter; `ggml_openvino_unregister_weight_buffer` in the buffer destructor; a failed KV re-allocation returns `GGML_STATUS_ALLOC_FAILED`.
- model-cache.cpp: hash `GGML_OPENVINO_ROPE_F32_ANGLE`, cache version 9; `strtoull` for the `.meta` hash.
- npu_quant_policy.cpp: Q4_0_128 falls back to Q4_0_C when `ne[0] % 128 != 0`. ggml-openvino-extra.cpp: the group-64 requant targets fall back to Q8_0_C when `ne[0] % 64 != 0`.
- openvino/utils.cpp: the static Split cache uses a weak reference and the output port in its key, like the dynamic one.
- rms_norm.cpp, ggml-decoder.cpp: op_case 5 for a packed pre-scaled GDN output.
- utils.cpp: static decode writes 0 to `out_ids`; a compile after a weight release returns `GGML_STATUS_FAILED`.
- ggml-decoder.cpp: `extract_layer_from_name` returns nullopt for a non-numeric suffix.
- op_table.cpp/.h: remove the duplicate `GGML_OP_FILL`.

* ggml-openvino: copy the decoder once per graph conversion

`GgmlOvDecoder::visit_subgraph` made a full copy of the decoder for every node it visited. Translators only read the decoder, so one copy per walk is enough. Graph conversion time drops 12-24x (Qwen3.5-0.8B: 4.1 s to 0.17 s over the six graphs of a short run).

- ggml-decoder.cpp: make one decoder copy before the node loop.
- utils.cpp: `get_static_attention_size` takes the decoder by const reference and does not copy the compute params.

* ggml-openvino: remove dead code and fix stale comments

Code that nothing calls or registers, and comments that no longer match the code. No behavior change.

- Remove `translate_gated_delta_net_ref`, `translate_solve_tri` (not registered), the unused `FuseToSDPA` pass, `add_rope_sin_cos`, `checksum`, `save_ggml_tensor_data_to_txt`, `non_cont_dim`, the unused templates in openvino/utils.h and the undefined `getCurrentTime` declaration.
- ggml-decoder.cpp: drop the VIEW op_case tail that only ever set 0.
- utils.cpp: drop a duplicate `entry->ptr` store and the always-false `!model_leafs.empty() == false` term.
- `ggml_openvino_manual_gqa_enabled()` replaces two copies of the GGML_OPENVINO_MANUAL_GQA_ATTN default (flash_attn_ext.cpp and the cache key).
- ggml-openvino.cpp: remove the SSM_CONV case whose comment said it stays on CPU (it runs on OpenVINO); fix the gemma3n reason text (not GPU-only) and two typos.

* ggml-openvino: track dynamic dims through bailingmoe3's GDN views and conv state

bailingmoe3 uses GATED_DELTA_NET views to expose its attention and
state outputs. Preserve their dynamic dimensions in the decoder.

- Assign the dynamic dimensions of the translated attention and state
  outputs to the corresponding GATED_DELTA_NET result VIEWs.
- Count the convolution state slots using the rows spanned by the
  destination view. bailingmoe3 packs the q/k/v convolution states
  into a single row.
- Preserve the tracked dynamic dimension in RESHAPE op case 0 when
  the reshape only adds a trailing size-1 dimension.

* ggml-openvino: translate the per-key gate of GATED_DELTA_NET

Ling-3.0-tiny (bailingmoe3) uses a gate per key dimension (kda),
which the backend previously rejected, causing these layers to
fall back to the CPU.

- Use the fused GatedDeltaNet when the OpenVINO runtime and target
  device support a rank-4 gate.
- Detect support once by compiling a one-node GatedDeltaNet with
  a rank-4 gate and checking the target device with query_model.
  Older runtimes reject this gate, and the CPU plugin does not
  support it.
- Fall back to the reference loop when the fused path is unavailable.
- Support a dynamic token count in the reference loop by using
  dynamic reshapes and deriving the trip count from the input shape.
- Reject unsupported cases with a reason: padded chunks, recurrent
  caches, state snapshots, and the native state layout. The loop
  currently handles one state in the ggml layout.

* ggml-openvino: Fix issue highlighted by tests

* ggml-openvino: reject a padded permuted v in gated delta net

supports_op rejected a permuted v only when src2 was the PERMUTE itself. With padded heads, v is a VIEW of the PERMUTE, so the check missed it and the per-key gate reference loop ran on a v layout it does not handle. Look through the VIEW so this case falls back like the other permuted v inputs.

* ggml-openvino: write back intermediate nodes of op-test graphs

The ADD_RMS_NORM_MUL op test checks the intermediate sum of its graph as
well as the final output. compute_model_outputs() made a node a model
output only when the graph does not consume all of it, so the sum was
never written back and the test read uninitialised memory (28 failures
on GPU and CPU). MUL_MAT_ID_SHARED, which checks its routed and shared
results, failed the same way on CPU.

Op-test graphs (the naive path) can read any node, so make every
non-in-place node a model output there. Model graphs are unchanged.

---------

Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
Co-authored-by: yzhou51 <yaowei.zhou@intel.com>
Co-authored-by: Sabnis, Omkar <omkar.sabnis@intel.com>
2026-11-23 06:29:20 -08:00
Aman Gupta 03813c56e4 rpc : typed request helpers and a single validation step on the server (#32651)
* rpc : typed request helpers and a single validation step on the server

Client and server share one table (rpc_msg_types) that maps each
fixed-size command to its request and response structs. The client sends
them with dispatcher->call<CMD>() and call_async<CMD>(), the server serves
them with rpc_serve<CMD>(), so the per-command code in rpc_serve_client
and at the call sites is gone and a wrong struct for a command does not
compile. SET_TENSOR, SET_TENSOR_2D and GRAPH_COMPUTE get header structs,
written with rpc_writer and parsed with a bounds-checked rpc_reader. The
wire format is unchanged.

Validation of client data is now in one place:
- deserialize_tensor rejects what ggml_new_tensor would assert on (op
  range, ne[0] not a multiple of the block size, element count overflow)
  and computes the tensor size without overflow before the buffer check
- rpc_check_region replaces the per-handler bounds checks and checks the
  request against the tensor size, which ggml_backend_tensor_set/get/memset
  assert on, so an in-buffer but out-of-tensor request no longer aborts
- graph_compute builds the graph in one pass over the tensors, which the
  client sends in topological order: no recursion, and unknown or
  duplicate ids, duplicate nodes, sources sent after their users, compute
  nodes with unallocated operands and views outside their view_src buffer
  are rejected; a tensor may be its own source (ggml_cast)
- GET_ALLOC_SIZE fails if a source tensor is invalid
- a client-sized allocation that fails closes the connection instead of
  terminating the server

* rpc : trim comments
2026-11-23 22:28:40 +08:00
thelittlefireman 46f4da2174 ggml-cuda : handle zero blocks in few-row MMQ quantization (#32566)
Assisted-by: ChatGPT (GPT-6)
2026-11-23 15:17:15 +01:00
Aleksander Grygier 4663f9ca8a ui: smooth height transition for every collapsible (#32873)
* ui: give every collapsible the smooth height transition

Llama UI's Collapsible.Content now force-mounts the bits-ui content and
renders the animated region the chat used to keep as CollapsibleRegion:
height eases open and shut, and the body unmounts once the collapse is
over. The chat's standalone regions use Collapsible.Root/Content, so the
tool groups in settings, the tools menu and drawer and the terminal block
animate like the rest.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep collapsible spacing inside the content

Collapsible.Content now stays in the layout while closed, so a margin on
it left a gap under a closed MCP tools list, connection log or server
info. The margin moves onto the content inside, as does the story's
spacing.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-23 14:12:41 +01:00
Aaron Teo 969d733317 cmake: treat kleidiai files as vendored (#32605)
* cmake: treat kleidiai files as vendored

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* cmake: use quotes and semicolon separators

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

---------

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
2026-11-23 13:30:24 +02:00
Vladislav Merkulov a8f8294c45 tests : update Qwen3.6-27B snapshot (#32845) 2026-11-23 11:45:31 +01:00
Daniel Bevenius 7d9b931df9 ggml : update cmake MATH_LIBRARY check (#32864)
This commit updates the cmake check for `MATH_LIBRARY` and removes the
DEFINED operator for the if() command.

The motivation for this is that on windows if a parent project of ggml
calls find_library(MATH_LIBRARY) this could return
`MATH_LIBRARY-NOTFOUND` which will cause the if clause to be true.

Removing the DEFINED operator will work as intended will evaluate to
false, as specified by cmake if command docs:
```console
False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the
empty string, or ends in the suffix -NOTFOUND.
```

This commit was originally opened in a PR against whisper.cpp, see link
below.

Refs: https://github.com/ggml-org/whisper.cpp/pull/4168
Refs: https://cmake.org/cmake/help/latest/command/if.html#constant
2026-11-23 11:05:21 +01:00
Wenyu Chen 212c547fe9 ui: add cancel button to cancel model loading (#32225) 2026-11-23 09:27:44 +01:00
Leon f5e6915c28 webgpu : add ROLL support (#31887)
* webgpu : add ROLL support

* tests : keep ROLL cases portable across backends
2026-11-23 09:56:54 +02:00
Aldehir Rojas dd53f70d08 chat : improve inkling parser/grammar (#32833) 2026-11-23 09:54:42 +02:00
lhez 1f8baae28d opencl: add xielu (#32791)
Assisted-by: Codex
2026-11-22 22:26:55 -08:00
lhezandHongqiang Wang 44d50873b5 opencl: add q4_k coop-k c8 GEMM for spec verify (#32716)
* opencl: add q4_k coop-k c8 GEMM for spec verify

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
Assisted-by: Codex

* opencl: enable q4_k c8 GEMM for n >= 2 for X2

---------

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-22 18:46:40 -08:00
Aman Gupta 7778de0c3f tests : compare only the guaranteed GDN snapshot slots (#32820) 2026-11-23 10:32:56 +08:00
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
1157 changed files with 110215 additions and 40545 deletions
+5 -1
View File
@@ -18,6 +18,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -25,10 +27,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM ${CANN_BASE_IMAGE} AS build
+5 -1
View File
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,10 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
+5 -1
View File
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -23,10 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM ${BASE_CUDA_DEV_CONTAINER} AS build
+5 -1
View File
@@ -10,6 +10,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -17,10 +19,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build
+5 -1
View File
@@ -14,6 +14,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -21,10 +23,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM ${BASE_MUSA_DEV_CONTAINER} AS build
+3 -15
View File
@@ -13,7 +13,6 @@
blas,
cudaPackages,
autoAddDriverRunpath,
darwin,
rocmPackages,
vulkan-headers,
vulkan-loader,
@@ -104,19 +103,9 @@ let
ln -s /usr/bin/xcrun $out/bin
'';
# apple_sdk is supposed to choose sane defaults, no need to handle isAarch64
# separately
darwinBuildInputs =
with darwin.apple_sdk.frameworks;
[
Accelerate
CoreVideo
CoreGraphics
]
++ optionals useMetalKit [ MetalKit ];
cudaBuildInputs = with cudaPackages; [
cuda_cudart
cuda_nvml_dev
cccl # <nv/target>
libcublas
];
@@ -182,7 +171,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
webui = stdenvNoCC.mkDerivation {
pname = "webui";
version = llamaVersion;
# the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole
# the app compiles Llama UI and the harness from their sources in ../../lib, so the source is ui/ as a whole
src = lib.cleanSource ../../ui;
sourceRoot = "source/apps/chat";
@@ -243,8 +232,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
++ optionals syclAot [ oclocAot ];
buildInputs =
optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs
++ optionals useCuda cudaBuildInputs
optionals useCuda cudaBuildInputs
++ optionals useMpi [ mpi ]
++ optionals useRocm rocmBuildInputs
++ optionals useBlas [ blas ]
+5 -1
View File
@@ -27,6 +27,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -34,10 +36,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
## Build Image
+5 -1
View File
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -23,10 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
### Build image
+5 -1
View File
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,10 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
+5 -1
View File
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
FROM docker.io/node:$NODE_VERSION AS web
ARG APP_VERSION
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
ARG VITE_PUBLIC_HUGGING_FACE=false
WORKDIR /app/ui/apps/chat
@@ -15,10 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
RUN npm ci
COPY ui/apps/chat/ ./
# the app compiles Llama UI and Llama Voice from their sources next to it
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
+31 -3
View File
@@ -32,7 +32,8 @@ concurrency:
jobs:
ubuntu-26-virtgpu:
runs-on: ${{ 'ubuntu-26.04-arm' || 'ubuntu-26.04' }}
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
@@ -42,8 +43,23 @@ jobs:
- name: Dependencies
id: depends
run: |
sudo apt-get update
sudo apt-get install -y build-essential libdrm-dev pkg-config libssl-dev
apt update
apt install -y build-essential jq cmake python3 python3-venv python3-pip libdrm-dev pkg-config libssl-dev
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
with:
key: virtgpu-ubuntu-26.04-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Build
id: cmake_build
@@ -52,3 +68,15 @@ jobs:
-DGGML_VIRTGPU=ON \
-DGGML_VIRTGPU_BACKEND=ON
cmake --build build --config Release -j $(nproc)
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: virtgpu-ubuntu-26.04-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
+10 -9
View File
@@ -41,8 +41,9 @@ env:
LLAMA_ARG_LOG_TIMESTAMPS: 1
jobs:
ubuntu-arm64:
runs-on: ubuntu-26.04-arm
ubuntu:
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
@@ -52,14 +53,13 @@ jobs:
- name: Dependencies
id: depends
run: |
sudo apt-get update
sudo apt-get install -y build-essential glslc libvulkan-dev spirv-headers libssl-dev ninja-build
apt update
apt install -y build-essential jq cmake python3 python3-venv python3-pip glslc libvulkan-dev spirv-headers libssl-dev ninja-build
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
variant: ccache
save: false
- name: ccache-buckets-restore
@@ -67,7 +67,7 @@ jobs:
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
with:
key: vulkan-ubuntu-26.04-arm
key: vulkan-ubuntu-26.04-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
@@ -82,7 +82,7 @@ jobs:
- name: Build
id: cmake_build
run: |
time cmake --build build -j $(nproc)
cmake --build build -j $(nproc)
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
@@ -90,7 +90,7 @@ jobs:
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: vulkan-ubuntu-26.04-arm
key: vulkan-ubuntu-26.04-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
@@ -167,7 +167,8 @@ jobs:
export GGML_VK_VISIBLE_DEVICES=0
export GGML_VK_DISABLE_F16=1
export GGML_VK_DISABLE_COOPMAT=1
ctest -L main --verbose --timeout 900
# TODO: too slow on llvmpipe
ctest -L main -E "test-llama-context" --verbose --timeout 900
windows:
name: windows / ${{ matrix.arch }}
+7 -28
View File
@@ -49,18 +49,18 @@ env:
jobs:
ubuntu-webgpu:
runs-on: ubuntu-26.04-arm
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake ninja-build git curl python3 python-is-python3
- name: Install wasi-sdk
uses: bytecodealliance/setup-wasi-sdk-action@77d09f3df1e8da344d8403cf8631af8977938b4c # v1.0.0
@@ -92,15 +92,6 @@ jobs:
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/dawn-headers/include/webgpu_upstream;${_wasi_webgpu}")
EOF
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
with:
key: webgpu-ubuntu-26.04-arm-wasi
folder: llama.cpp
hf_bucket: ggml-org/cache
# llama-common does not build for WASI, so the executables are linked by hand
- name: Build
id: cmake_build
@@ -120,7 +111,7 @@ jobs:
-DDawn_DIR=$PWD/wasi-webgpu \
-DLLAMA_BUILD_COMMON=OFF
time cmake --build build-wasi --config Release --target llama -j $(nproc)
cmake --build build-wasi --config Release --target llama -j $(nproc)
LIBS="build-wasi/ggml/src/libggml.a build-wasi/ggml/src/ggml-webgpu/libggml-webgpu.a build-wasi/ggml/src/libggml-cpu.a build-wasi/ggml/src/libggml-base.a"
LDFLAGS="-lunwind -ldl -Wl,-z,stack-size=8388608"
@@ -128,15 +119,3 @@ jobs:
$CXX examples/simple/simple.cpp build-wasi/src/libllama.a $LIBS $LDFLAGS -o build-wasi/llama-simple.wasm
$CXX tests/test-backend-ops.cpp $LIBS $LDFLAGS -o build-wasi/test-backend-ops.wasm
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: webgpu-ubuntu-26.04-arm-wasi
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
+8 -28
View File
@@ -50,18 +50,18 @@ env:
jobs:
ubuntu-webgpu:
runs-on: ubuntu-26.04-arm
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake ninja-build git curl unzip python3
- name: Install Emscripten
run: |
@@ -79,16 +79,8 @@ jobs:
"https://github.com/google/dawn/releases/download/${DAWN_TAG}/${EMDAWN_PKG}"
unzip emdawn.zip
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
with:
key: webgpu-ubuntu-26.04-arm-wasm
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Build WASM WebGPU
shell: bash
run: |
source emsdk/emsdk_env.sh
emcmake cmake -B build-wasm \
@@ -99,16 +91,4 @@ jobs:
-DLLAMA_OPENSSL=OFF \
-DEMDAWNWEBGPU_DIR=emdawnwebgpu_pkg
time cmake --build build-wasm --config Release --target test-backend-ops -j $(nproc)
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: webgpu-ubuntu-26.04-arm-wasm
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
cmake --build build-wasm --config Release --target test-backend-ops -j $(nproc)
+7 -6
View File
@@ -49,7 +49,8 @@ env:
jobs:
gpu-cuda:
runs-on: "hf-jobs-t4-medium:cuda13"
runs-on: [self-hosted, Linux, gb10]
container: "nvidia/cuda:13.5.0-devel-ubuntu26.04"
steps:
- name: Clone
@@ -58,8 +59,8 @@ jobs:
- name: Install dependencies
run: |
sudo apt update
sudo apt install -y cmake libssl-dev time unzip wget python3 python3-venv python3-pip
apt update
apt install -y build-essential jq cmake git git-lfs libssl-dev time unzip wget python3 python3-venv python3-pip
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
@@ -70,7 +71,7 @@ jobs:
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
with:
key: self-hosted-gpu-cuda
key: self-hosted-gpu-cuda-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
@@ -78,7 +79,7 @@ jobs:
id: ggml-ci
run: |
nvidia-smi
GG_BUILD_CUDA=1 CUDACXX=/usr/local/cuda/bin/nvcc bash ./ci/run.sh ~/results/llama.cpp ~/mnt/llama.cpp
GG_BUILD_CUDA=1 CUDACXX=/usr/local/cuda/bin/nvcc bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
@@ -86,7 +87,7 @@ jobs:
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: self-hosted-gpu-cuda
key: self-hosted-gpu-cuda-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
+58 -58
View File
@@ -49,94 +49,94 @@ env:
jobs:
gpu-vulkan-nvidia-cm:
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
runs-on: [self-hosted, Linux, NVIDIA]
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
# - name: Install dependencies
# run: |
# sudo apt update
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
# - name: ccache
# uses: ggml-org/ccache-action@v1.2.24
# with:
# restore: false
# save: false
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
# - name: ccache-buckets-restore
# uses: ./.github/actions/ccache-buckets
# with:
# key: self-hosted-vulkan-nvidia-cm
# folder: llama.cpp
# hf_bucket: ggml-org/cache
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
with:
key: self-hosted-vulkan-nvidia-cm-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Test
id: ggml-ci
run: |
vulkaninfo --summary
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
# - name: ccache-buckets-save
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
# uses: ./.github/actions/ccache-buckets
# env:
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
# with:
# key: self-hosted-vulkan-nvidia-cm
# folder: llama.cpp
# evict-old-files: 1d
# hf_bucket: ggml-org/cache
# save: true
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: self-hosted-vulkan-nvidia-cm-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
gpu-vulkan-nvidia-cm2:
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
runs-on: [self-hosted, Linux, NVIDIA, COOPMAT2]
runs-on: [self-hosted, Linux, gb10]
container: "ubuntu:26.04"
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
# - name: Install dependencies
# run: |
# sudo apt update
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
- name: Install dependencies
run: |
apt update
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
# - name: ccache
# uses: ggml-org/ccache-action@v1.2.24
# with:
# restore: false
# save: false
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
with:
restore: false
save: false
# - name: ccache-buckets-restore
# uses: ./.github/actions/ccache-buckets
# with:
# key: self-hosted-vulkan-nvidia-cm2
# folder: llama.cpp
# hf_bucket: ggml-org/cache
- name: ccache-buckets-restore
uses: ./.github/actions/ccache-buckets
with:
key: self-hosted-vulkan-nvidia-cm2-gb10
folder: llama.cpp
hf_bucket: ggml-org/cache
- name: Test
id: ggml-ci
run: |
vulkaninfo --summary
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
# - name: ccache-buckets-save
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
# uses: ./.github/actions/ccache-buckets
# env:
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
# with:
# key: self-hosted-vulkan-nvidia-cm2
# folder: llama.cpp
# evict-old-files: 1d
# hf_bucket: ggml-org/cache
# save: true
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
uses: ./.github/actions/ccache-buckets
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
with:
key: self-hosted-vulkan-nvidia-cm2-gb10
folder: llama.cpp
evict-old-files: 1d
hf_bucket: ggml-org/cache
save: true
gpu-vulkan-apple:
runs-on: [self-hosted, macOS, ARM64]
+3 -3
View File
@@ -120,9 +120,6 @@ jobs:
mv build-matrix.json.tmp build-matrix.json
fi
jq 'map(select(.tag != "musa"))' build-matrix.json > build-matrix.json.tmp
mv build-matrix.json.tmp build-matrix.json
BUILD_MATRIX="$(jq -c . build-matrix.json)"
MERGE_MATRIX="$(jq -c '
reduce .[] as $entry ({}; .[$entry.tag] |= (
@@ -272,6 +269,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
@@ -309,6 +307,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
@@ -346,6 +345,7 @@ jobs:
build-args: |
BUILD_DATE=${{ steps.build_date.outputs.date }}
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
VITE_PUBLIC_HUGGING_FACE=true
APP_REVISION=${{ steps.checkout.outputs.commit }}
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
+204 -11
View File
@@ -11,7 +11,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
pull_request:
@@ -22,7 +23,8 @@ on:
'**/*.cuh',
'ggml/src/ggml-hip/CMakeLists.txt',
'ggml/src/ggml-cuda/vendors/hip.h',
'scripts/hip/gcn-cdna-vgpr-check.py'
'scripts/hip/gcn-cdna-metrics.py',
'scripts/hip/test_gcn_cdna_metrics.py'
]
cache-mode: none
@@ -45,15 +47,32 @@ jobs:
runs-on: ubuntu-22.04
container: rocm/dev-ubuntu-22.04:7.2.1
steps:
- name: Clone
id: checkout
uses: actions/checkout@v6
- name: Dependencies
id: depends
run: |
sudo apt-get update
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip jq
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip python3-yaml jq
- name: Clone
id: checkout
uses: actions/checkout@v6
with:
fetch-depth: 2
# The first parent of the tested merge commit is the exact baseline.
- name: Get baseline SHA
if: ${{ github.event_name == 'pull_request' }}
id: master_sha
run: |
git config --global --add safe.directory "$GITHUB_WORKSPACE"
git rev-parse --verify HEAD^2 > /dev/null
baseline_sha=$(git rev-parse HEAD^1)
pr_sha=$(git rev-parse HEAD)
printf 'sha=%s\npr_sha=%s\n' "$baseline_sha" "$pr_sha" >> "$GITHUB_OUTPUT"
printf 'Baseline commit: %s\nPR merge commit: %s\n' "$baseline_sha" "$pr_sha"
- name: Test HIP kernel metrics scripts
run: python3 -m unittest discover -s scripts/hip -p 'test_gcn_cdna_metrics.py'
- name: ccache
uses: ggml-org/ccache-action@v1.2.24
@@ -70,6 +89,21 @@ jobs:
folder: llama.cpp
hf_bucket: ggml-org/cache
# Verify device optimization records before starting the expensive builds.
- name: Validate HIP resource remarks
run: |
mkdir -p hip-metrics-probe
cd hip-metrics-probe
printf '%s\n' '#include <hip/hip_runtime.h>' '__global__ void metrics_probe(float * out) { *out = 1.0f; }' > probe.hip
"$(hipconfig -l)/clang" -x hip --offload-arch=gfx908 -O2 -c probe.hip -o probe.o \
-Rpass-analysis=kernel-resource-usage --save-temps \
-Xarch_device -fsave-optimization-record=yaml \
-Xarch_device -foptimization-record-passes=kernel-resource-usage
for metric in NumVGPR Occupancy VGPRSpill SGPRSpill; do
grep -q "Name: *$metric$" probe.opt.yaml || { echo "Missing $metric in GPU optimization records"; exit 1; }
done
python3 ../scripts/hip/gcn-cdna-metrics.py vgpr probe.opt.yaml
- name: Build with Werror
id: cmake_build
run: |
@@ -83,19 +117,178 @@ jobs:
cd build
make -j $(nproc)
- name: Check for major VGPR spills
- name: Build HIP kernel resource metrics
id: vgpr_check
shell: bash
run: |
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="" \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
make -j $(nproc) 2>&1 | tee metrics.log | grep -v 'Rpass-analysis=kernel-resource-usage\|remark:\|^$'
python3 ../scripts/hip/gcn-cdna-vgpr-check.py metrics.log
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
echo "Optimization record files:"
find . -type f -name '*.opt.yaml' | sed -n '1,10p'
echo "GPU kernel remarks in YAML:"
grep -rl --include='*.opt.yaml' 'kernel-resource-usage' . | sed -n '1,10p' || true
echo "First YAML record:"
first_yaml=$(find ggml/src/ggml-hip -type f -name '*.opt.yaml' -print -quit)
if [ -n "$first_yaml" ]; then head -n 35 "$first_yaml"; fi
echo "GPU resource diagnostics in compiler log:"
grep -m 3 'Function Name:' metrics.log || true
# The PR comparison evaluates every rule and reports all failures at the end.
- name: Check VGPR limit on master
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: python3 scripts/hip/gcn-cdna-metrics.py vgpr build/ggml/src/ggml-hip
# On master pushes, cache the device optimization records as the baseline for PR checks.
- name: Save master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
run: |
mkdir -p hip-baseline-metrics
find build/ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} hip-baseline-metrics/ \;
- name: Cache master metrics baseline
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -n "$HF_TOKEN" ]; then
tar -czf hip-baseline-metrics.tar.gz -C hip-baseline-metrics .
.venv-hf/bin/hf buckets cp hip-baseline-metrics.tar.gz "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ github.sha }}.tar.gz" || echo "Failed to save HIP metrics baseline"
fi
- name: Remove old HIP metrics baselines
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
shell: bash
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
run: |
if [ -z "$HF_TOKEN" ]; then
exit 0
fi
if ! cache_files=$(.venv-hf/bin/hf buckets list "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-" --json | jq -r '
.[]
| select(.type == "file")
| select(.path | endswith(".tar.gz"))
| select(try ((.uploaded_at | .[:19]+"Z" | fromdateiso8601) < (now - 30 * 24 * 60 * 60)) catch false)
| .path
'); then
echo "Failed to list HIP metrics baselines"
exit 0
fi
while IFS= read -r cache_path; do
[ -n "$cache_path" ] || continue
.venv-hf/bin/hf buckets rm "hf://buckets/ggml-org/cache/$cache_path" -y || echo "Failed to remove $cache_path"
done <<< "$cache_files"
# Restore the device optimization records for the exact baseline commit.
- name: Restore master metrics baseline
if: ${{ github.event_name == 'pull_request' }}
id: baseline_cache
env:
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
run: |
cache_url="hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ steps.master_sha.outputs.sha }}.tar.gz"
if .venv-hf/bin/hf buckets cp "$cache_url" hip-baseline-metrics.tar.gz; then
mkdir -p hip-baseline-metrics
if tar -xzf hip-baseline-metrics.tar.gz -C hip-baseline-metrics && [ -n "$(find hip-baseline-metrics -type f -name '*.opt.yaml' -print -quit)" ]; then
echo "cache-hit=true" >> "$GITHUB_OUTPUT"
echo "Restored HIP metrics baseline from HF Buckets"
else
rm -rf hip-baseline-metrics
echo "Invalid HIP metrics baseline cache"
fi
rm -f hip-baseline-metrics.tar.gz
else
echo "No HIP metrics baseline in HF Buckets; building from source"
fi
# Fallback when the baseline commit has no cached metrics.
- name: Checkout baseline (master)
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
uses: actions/checkout@v6
with:
ref: ${{ steps.master_sha.outputs.sha }}
path: hip-baseline
- name: Build master metrics baseline
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
shell: bash
run: |
cd hip-baseline
cmake -B build -S . \
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
-DGPU_TARGETS=gfx908 \
-DGGML_HIP=ON \
-DGGML_HIP_EXPORT_METRICS=On \
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
-DCMAKE_BUILD_TYPE=Release
cd build
set -o pipefail
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
mkdir -p ../../hip-baseline-metrics
find ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} ../../hip-baseline-metrics/ \;
- name: Check kernel resource rules vs master
if: ${{ github.event_name == 'pull_request' }}
id: occupancy_check
env:
BASELINE_SHA: ${{ steps.master_sha.outputs.sha }}
PR_SHA: ${{ steps.master_sha.outputs.pr_sha }}
run: |
# The PR optimization records come from the VGPR spill check build above, so
# this step adds no extra build when the baseline cache hits.
python3 scripts/hip/gcn-cdna-metrics.py compare hip-baseline-metrics build/ggml/src/ggml-hip \
--dump hip-kernel-metrics-deltas.tsv || check_failed=true
if [ ! -s hip-kernel-metrics-deltas.tsv ]; then
echo "Kernel metrics comparison failed before producing a TSV report"
exit 1
fi
python3 scripts/hip/gcn-cdna-metrics.py report hip-kernel-metrics-deltas.tsv \
-o hip-kernel-metrics-report.md
sed -i "3i\\- Baseline commit: $BASELINE_SHA\\n- PR merge commit: $PR_SHA" hip-kernel-metrics-report.md
if [ -n "$check_failed" ]; then
echo "check_failed=true" >> "$GITHUB_OUTPUT"
fi
exit 0
- name: Upload kernel metrics report
if: ${{ github.event_name == 'pull_request' }}
id: metrics_report
uses: actions/upload-artifact@v7
with:
name: hip-kernel-metrics-report
path: hip-kernel-metrics-report.md
- name: Publish kernel metrics summary
if: ${{ github.event_name == 'pull_request' }}
shell: bash
env:
ARTIFACT_URL: ${{ steps.metrics_report.outputs.artifact-url }}
run: |
{
if [ "$(wc -c < hip-kernel-metrics-report.md)" -le 1000000 ]; then
cat hip-kernel-metrics-report.md
else
sed -n -e '/^# /p' -e '/^- Baseline/p' -e '/^- PR/p' -e '/^Kernels compared:/p' -e 's/^## /- /p' hip-kernel-metrics-report.md
printf '\nThe full report exceeds the GitHub job summary size limit.\n'
fi
printf '\n[Download the full kernel metrics report](%s)\n' "$ARTIFACT_URL"
} | tee -a "$GITHUB_STEP_SUMMARY"
- name: Fail on blocking regressions
if: ${{ github.event_name == 'pull_request' && steps.occupancy_check.outputs.check_failed == 'true' }}
run: |
echo "Blocking kernel metrics regressions detected, see the job summary and hip-kernel-metrics-report artifact"
exit 1
- name: ccache-buckets-save
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
BODY: ${{ github.event.pull_request.body }}
HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }}
run: |
# sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment
# sections written by demo:pr (see ui/lib/demo/src/cli.ts): the managed comment
# markers, or a preview linking to a demo video uploaded for this PR
has_demo=false
if { grep -qF '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
+1 -1
View File
@@ -1129,7 +1129,7 @@ jobs:
target: 'ggml-vulkan'
- backend: 'opencl-adreno'
arch: 'arm64'
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON'
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF'
target: 'ggml-opencl'
steps:
@@ -33,6 +33,9 @@ jobs:
- name: Build application
run: npm run build
working-directory: ui/apps/chat
env:
# as in ui-build.yml: the UI under test has the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
- name: Upload built UI
uses: actions/upload-artifact@v6
+2
View File
@@ -47,6 +47,8 @@ jobs:
- name: Build application
env:
LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }}
# the UI that the releases and the prebuilt download are made of has the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
run: npm run build
working-directory: ui/apps/chat
+3
View File
@@ -94,6 +94,9 @@ jobs:
# This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does.
run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build
working-directory: ${{ env.APP_DIR }}
env:
# the same app as the UI llama-server embeds, with the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
- name: Test the CLI and the alias version
run: npx vitest --project=unit --run tests/unit/cli.test.ts
+7
View File
@@ -20,6 +20,8 @@ on:
'ui/apps/chat/**.*',
'ui/lib/ui/**.*',
'ui/lib/voice/**.*',
'ui/lib/harness/**.*',
'ui/lib/huggingface/**.*',
'tools/server/tests/**.*'
]
pull_request:
@@ -30,6 +32,8 @@ on:
'ui/apps/chat/**.*',
'ui/lib/ui/**.*',
'ui/lib/voice/**.*',
'ui/lib/harness/**.*',
'ui/lib/huggingface/**.*',
'tools/server/tests/**.*'
]
@@ -125,6 +129,9 @@ jobs:
if: ${{ always() && steps.setup.conclusion == 'success' }}
run: npm run build-storybook
working-directory: ui/apps/chat
env:
# its stories show the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
- name: Run UI tests
if: ${{ always() && steps.setup.conclusion == 'success' }}
+3
View File
@@ -49,6 +49,9 @@ jobs:
- name: Build Storybook
run: npm run build-storybook
working-directory: ui/apps/chat
env:
# its stories show the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
- name: Write the Space card
run: |
+163 -1
View File
@@ -83,8 +83,16 @@ jobs:
run: npm ci
working-directory: ui/apps/chat
# the app's demo helpers import the demo harness (ui/lib/demo), whose sources resolve
# @playwright/test and its other types from its own node_modules
- name: Install demo harness dependencies
id: setup-demo
if: ${{ steps.setup.conclusion == 'success' }}
run: npm ci
working-directory: ui/lib/demo
- name: Run type checking
if: ${{ always() && steps.setup.conclusion == 'success' }}
if: ${{ always() && steps.setup.conclusion == 'success' && steps.setup-demo.conclusion == 'success' }}
run: npm run check
working-directory: ui/apps/chat
@@ -181,6 +189,157 @@ jobs:
run: npm run prepack
working-directory: ui/lib/voice
harness-checks:
name: Harness checks
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/lib/harness
- name: Run type checking
run: npm run check
working-directory: ui/lib/harness
- name: Run tests
run: npm test
working-directory: ui/lib/harness
- name: Build the package
run: npm run prepack
working-directory: ui/lib/harness
demo-checks:
name: Demo harness checks
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/lib/demo
- name: Run type checking
run: npm run check
working-directory: ui/lib/demo
chat-only-build:
name: Chat-only build
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/apps/chat
- name: Build without the agentic loop
run: npm run build
working-directory: ui/apps/chat
env:
VITE_PUBLIC_AGENTIC: "false"
- name: Check the harness loop is not in the bundle
run: |
if grep -rlq "Tool execution was interrupted by a new user message" dist; then
echo "The chat-only bundle contains Llama Harness's loop" && exit 1
fi
working-directory: ui/apps/chat
huggingface-lib-bundle:
name: Hugging Face lib in the bundle
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/apps/chat
- name: Build with and without the Hugging Face lib
run: |
npm run build
VITE_PUBLIC_HUGGING_FACE=true LLAMA_UI_OUT_DIR=dist-with-sharing npm run build
working-directory: ui/apps/chat
# a text of the lib's sign-in: it is in the bundle only when the lib is
- name: Check the Hugging Face lib is only in the bundle built with it
run: |
marker="Hugging Face sent no access token back"
if ! grep -rlq "$marker" dist-with-sharing; then
echo "The bundle built with the Hugging Face lib does not contain it" && exit 1
fi
if grep -rlq "$marker" dist; then
echo "The default bundle contains the Hugging Face lib" && exit 1
fi
working-directory: ui/apps/chat
huggingface-lib-checks:
name: Hugging Face lib checks
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
package-manager-cache: false
- name: Install dependencies
run: npm ci
working-directory: ui/lib/huggingface
# its plain TypeScript; the components are checked with the app that compiles them
- name: Run type checking
run: npm run check
working-directory: ui/lib/huggingface
- name: Run tests
run: npm test
working-directory: ui/lib/huggingface
e2e-tests:
name: E2E Tests
needs: ui-build
@@ -223,6 +382,9 @@ jobs:
if: ${{ always() && steps.playwright.conclusion == 'success' }}
run: npm run build-storybook
working-directory: ui/apps/chat
env:
# its stories show the Hugging Face lib
VITE_PUBLIC_HUGGING_FACE: "true"
- name: Run UI tests
if: ${{ always() && steps.playwright.conclusion == 'success' }}
+59 -1
View File
@@ -1,4 +1,4 @@
# date: Mon Nov 16 10:05:56 EET 2026
# date: Wed Nov 25 16:07:40 EET 2026
# this file is auto-generated by scripts/gen-authors.sh
Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com>
@@ -90,6 +90,7 @@ Aidan <99101158+gSUz92nc@users.noreply.github.com>
AidanBeltonS <87009434+AidanBeltonS@users.noreply.github.com>
AidanBeltonS <aidan.belton@codeplay.com>
aiqubits <aiqubits@hotmail.com>
Aircg <64237451+cgair@users.noreply.github.com>
Aisuko <urakiny@gmail.com>
Akarshan Biswas <akarshan.biswas@gmail.com>
Akarshan Biswas <akarshan@menlo.ai>
@@ -256,6 +257,7 @@ Asghar Ghorbani <a-ghorbani@users.noreply.github.com>
Ashish <1856117+ashishdatta@users.noreply.github.com>
Ashok Gelal <401055+ashokgelal@users.noreply.github.com>
Ashraful Islam <ashraful.meche@gmail.com>
Ashutosh Singh <ashutosh.singh@intel.com>
AT <manyoso@users.noreply.github.com>
at8u <129688334+at8u@users.noreply.github.com>
Atharva Dubey <atharva.dubey@codeplay.com>
@@ -267,6 +269,7 @@ Austin <77757836+teleprint-me@users.noreply.github.com>
AustinMroz <austinmroz@utexas.edu>
AUTOMATIC1111 <16777216c@gmail.com>
automaticcat <daogiatuank54@gmail.com>
AWA <15575202581@163.com>
awatuna <23447591+awatuna@users.noreply.github.com>
Awss <gitj.18@alt.awss1i.com>
b4b4o <zwbao@foxmail.com>
@@ -277,6 +280,7 @@ Bailey Chittle <39804642+bachittle@users.noreply.github.com>
Bálint Bokros <bbalint96@gmail.com>
bandoti <141645996+bandoti@users.noreply.github.com>
Bar Haim <barvhaim@gmail.com>
Baran Bati <66915560+Batibaran@users.noreply.github.com>
BarfingLemurs <128182951+BarfingLemurs@users.noreply.github.com>
Bart Louwers <bart.louwers@gmail.com>
Bartosz Taudul <wolf@nereid.pl>
@@ -315,11 +319,13 @@ Bill Sideris <bill88t@feline.gr>
Billel Mokeddem <billel.mokeddem.ml@gmail.com>
Bingan <70050083+binganao@users.noreply.github.com>
Bipin Yadav <83943505+bipinyadav3175@users.noreply.github.com>
Birk Skyum <74932975+birkskyum@users.noreply.github.com>
bitalov <60072763+bitalov@users.noreply.github.com>
Bizhao Shi <37729561+shibizhao@users.noreply.github.com>
Bjarke Viksøe <164612031+bviksoe@users.noreply.github.com>
Björn Ganster <mail@bjoern-ganster.de>
BlackFoil <127078112+BlackFoil@users.noreply.github.com>
BlivionIaG <kev29lt@gmail.com>
BlueMöhre <bluemoehre@gmx.de>
bmwl <brian.marshall@tolko.com>
Bo Zheng <368586905@qq.com>
@@ -390,7 +396,11 @@ Chen Yuan <constantchen525@gmail.com>
Cheng Shao <terrorjack@type.dance>
Chenguang Li <757486878@qq.com>
Chenguang Li <87689256+noemotiovon@users.noreply.github.com>
Chenyang Li <cl4288@cumc.columbia.edu>
cherry77-cloud <1615405@qq.com>
chessMan <71754779+mohitmishra786@users.noreply.github.com>
chiheb ben cheikh <100644963+ChihebBENCHEIKH1@users.noreply.github.com>
Chinmay Shrivastava <cshrivastava2000@gmail.com>
chinmaykamjith001 <chinmaykamjith@gmail.com>
Chipmunk <101038159+CHIPMUNK-T0T@users.noreply.github.com>
chiranko <96988916+chiranko@users.noreply.github.com>
@@ -477,6 +487,7 @@ Daniel Varga <vargad88@gmail.com>
Daniele <57776841+daniandtheweb@users.noreply.github.com>
Daniele <daniele.dilotorres@gmail.com>
Daniele Pinna <72076821+pestopoppa@users.noreply.github.com>
Daniil Sterkhov <ngoroth@gmail.com>
Danny Milosavljevic <dannym@friendly-machines.com>
DannyDaemonic <DannyDaemonic@gmail.com>
Dante <144588016+KafKafrnZ@users.noreply.github.com>
@@ -581,6 +592,8 @@ Echo Nolan <echo@echonolan.net>
Ed Addario <29247825+EAddario@users.noreply.github.com>
Ed Lee <edilee@mozilla.com>
Ed Lepedus <ed.lepedus@googlemail.com>
Eddie Zhou <e.zhou@chocolat.chaud.io>
Eddie Zhou <eddiezhou1996@gmail.com>
Eddie-Wang <wangjinheng1120@163.com>
eddiechen <Echen1246@gmail.com>
Eden <aa9736195201@gmail.com>
@@ -596,6 +609,7 @@ Emil Askerov <56842174+EmilAskerov@users.noreply.github.com>
Emmanuel Ferdman <emmanuelferdman@gmail.com>
Empressia <sphere.soffie@gmail.com>
Emreerdog <34742675+Emreerdog@users.noreply.github.com>
En Yao <68765784+JeremyCEY@users.noreply.github.com>
Engininja2 <139037756+Engininja2@users.noreply.github.com>
Equim <sayaka@ekyu.moe>
Eric A Stalee <87948564+Eric-A-Stalee@users.noreply.github.com>
@@ -706,6 +720,7 @@ Gavin Zhao <gavinzhaojw@protonmail.com>
Genkagaku.GPT <hlhr202@163.com>
Geo Maciolek <geoffmaciolek@gmail.com>
George <35490284+noctrex@users.noreply.github.com>
George Burton <8233643+gecBurton@users.noreply.github.com>
Georgi Gerganov <ggerganov@gmail.com>
Geramy Loveless <gloveless@jqluv.com>
Gerard Guillemas Martos <gguillemas@users.noreply.github.com>
@@ -714,11 +729,13 @@ Gerben van V <gerbenvv@gmail.com>
Gezahegne <gezahegne.yirefu@gmail.com>
ghleg <aoleg@users.noreply.github.com>
Gian-Carlo Pascutto <gcp@sjeng.org>
gianni-cor <gianfranco.cordella@tether.io>
gianni-cor <gianfrancocordella@gmail.com>
GiantPrince <90118823+GiantPrince@users.noreply.github.com>
GideonSerf <gdserf.gs@gmail.com>
Gilad S <giladgd@users.noreply.github.com>
Gilad S. <7817232+giladgd@users.noreply.github.com>
Giorgio Sarno <giorgio.srn@gmail.com>
Giovanni Rivera <rivera.giovanni271@gmail.com>
github-actions[bot] <github-actions[bot]@users.noreply.github.com>
GittyBurstein <g0534163997@gmail.com>
@@ -799,6 +816,7 @@ hey-gm <heitorgm@outlook.com>
HighDoping <highdoping@gmail.com>
HimariO <dsfhe49854@gmail.com>
hipudding <huafengchun@gmail.com>
Hiroyuki Ikegami <ikegam@mixallow.net>
Hitesh Chopra <34310832+hiteshchopra11@users.noreply.github.com>
hksdpc255 <43977088+hksdpc255@users.noreply.github.com>
hmirin <hmirin@users.noreply.github.com>
@@ -866,6 +884,7 @@ Ilia Ilmer <iliailmer@users.noreply.github.com>
Ilya <ilya77105@gmail.com>
Ilya Kurdyukov <59548320+ilyakurdyukov@users.noreply.github.com>
Imad Saddik <79410781+ImadSaddik@users.noreply.github.com>
Imdadullah Mohammed <7274724+imdadvs@users.noreply.github.com>
iMil <imil@NetBSD.org>
Incarnas <119618389+bit-incarnas@users.noreply.github.com>
InflexCZE <martin.pavlicek11@gmail.com>
@@ -904,6 +923,7 @@ Jaeden Amero <jaeden@patater.com>
Jaemin Son <woalsdnd@gmail.com>
Jafar Uruç <jafar.uruc@gmail.com>
Jag Chadha <jagtesh@gmail.com>
Jai Patel <61297975+jpatel2005@users.noreply.github.com>
jaime-m-p <167997752+jaime-m-p@users.noreply.github.com>
Jake Karnes <jake.karnes@gmail.com>
Jakkala Mahesh <155058658+MaheshJakkala@users.noreply.github.com>
@@ -912,6 +932,7 @@ JamePeng <jame_peng@sina.com>
James A Capozzoli <157492257+jac-jim@users.noreply.github.com>
James Francis <6763899+JamesFranc@users.noreply.github.com>
James O'Leary <65884233+jpohhhh@users.noreply.github.com>
James Prevett <jp@jamespre.dev>
James Reynolds <magnusviri@users.noreply.github.com>
jameswu2014 <545426914@qq.com>
JamieBordoni <jamie.bordoni@protonmail.com>
@@ -932,6 +953,7 @@ Jason Ni <jason.ni.py@gmail.com>
Jason Stillerman <jason.t.stillerman@gmail.com>
jason_w <jason.wang@126.com>
Jassieluo <130133492+Jassieluo@users.noreply.github.com>
Javier Argomedo <79397619+diabluz@users.noreply.github.com>
Jay <BusyJay@users.noreply.github.com>
Jay Zenith <162098309+JayZenith@users.noreply.github.com>
Jayant Lohia <rajiblohia@gmail.com>
@@ -1070,6 +1092,7 @@ Kaben Nanlohy <kaben.nanlohy@gmail.com>
Kabir Potdar <kabirpotdar7@gmail.com>
Kabir08 <62639358+Kabir08@users.noreply.github.com>
Kai Pastor <dg0yt@darc.de>
KaiFelixBennett <83428264+KaiFelixBennett@users.noreply.github.com>
kaizau <kaizau@users.noreply.github.com>
Kakaru <97896816+KakaruHayate@users.noreply.github.com>
kallewoof <kalle.alm@gmail.com>
@@ -1080,6 +1103,7 @@ Kamil Tomšík <info@tomsik.cz>
kang <tpdns9032100@gmail.com>
Kangjia Gao <145212963+kkkzbh@users.noreply.github.com>
Kante Yin <kerthcet@gmail.com>
karan <67942227+dheepakkaran@users.noreply.github.com>
karavayev <192749314+karavayev@users.noreply.github.com>
Karol Kontny <82021046+kkontny@users.noreply.github.com>
Karsten Weiss <knweiss@gmail.com>
@@ -1097,6 +1121,7 @@ Katara <sohaib.harraoui@ostorlab.dev>
Katostrofik <georgiopapairo@gmail.com>
katsu560 <118887472+katsu560@users.noreply.github.com>
Kawrakow <48489457+ikawrakow@users.noreply.github.com>
Kazutoshi, Akao <73567414+kazutoshi-ak@users.noreply.github.com>
kbenkhaled <khalilbenkhaled01@gmail.com>
kchro3 <62481661+kchro3@users.noreply.github.com>
kdkd <2569413+kdkd@users.noreply.github.com>
@@ -1129,6 +1154,7 @@ KnightYao <KnightYao@users.noreply.github.com>
KokerZhou <111279477+KokerZhou@users.noreply.github.com>
Kolen Cheung <ickc@users.noreply.github.com>
Kong Jiale <2049447146@qq.com>
Kong Jiale <jialekong2004@mails.ccnu.edu.cn>
kononnable <kononnable@gmail.com>
Konrad Moren <kmoren@nvidia.com>
konradmb <konradmb@o2.pl>
@@ -1182,6 +1208,7 @@ Leng Yue <lengyue@lengyue.me>
Lennart Austenfeld <53152202+l-austenfeld@users.noreply.github.com>
leo-pony <nengjunma@outlook.com>
Leon <118652405+LeON-Nie-code@users.noreply.github.com>
Leon <3077740163@qq.com>
Leon Knauer <git@leonknauer.com>
Leonard Mosescu <tlemo@users.noreply.github.com>
leonardHONG <2695316095@qq.com>
@@ -1217,6 +1244,7 @@ lon <114724657+longregen@users.noreply.github.com>
loonerin <132926317+loonerin@users.noreply.github.com>
Lorenzo Bona <lorenzobona@tuta.com>
losewayy <1134285612@qq.com>
losewayy <losemywayy@gmail.com>
LostRuins <39025047+LostRuins@users.noreply.github.com>
LostRuins Concedo <39025047+LostRuins@users.noreply.github.com>
lovedheart <6277001+lovedheart@users.noreply.github.com>
@@ -1256,6 +1284,7 @@ Mahdiou Diallo <104755555+mahdiou@users.noreply.github.com>
Mahekk Shaikh <118063190+Mahekk357@users.noreply.github.com>
Mahesh Madhav <67384846+heshpdx@users.noreply.github.com>
mahorozte <41834471+mahorozte@users.noreply.github.com>
mahounairo <24420747+mahounairo@users.noreply.github.com>
makomk <makosoft@googlemail.com>
manayang <jackmanayang@gmail.com>
manikbhandari <mbbhandarimanik2@gmail.com>
@@ -1272,6 +1301,7 @@ Marcos Del Sol Vives <marcos@orca.pet>
marcoStocchi <marcostocchi77@gmail.com>
Marcus <marcusds@users.noreply.github.com>
Marcus Dunn <51931484+MarcusDunn@users.noreply.github.com>
Marcus Tillmanns <maddimax@gmail.com>
Marek Hradil jr. <marek.hradil@outlook.com>
Marian Cepok <marian.cepok@gmail.com>
Mario <191101255+wariuccio@users.noreply.github.com>
@@ -1339,6 +1369,7 @@ Matvey Soloviev <blackhole89@gmail.com>
Max Krasnyansky <max.krasnyansky@gmail.com>
Max Krasnyansky <maxk@qti.qualcomm.com>
Max Krasnyansky <quic_maxk@quicinc.com>
Max S. <rin@wantan.me>
Maxim Evtush <154841002+maximevtush@users.noreply.github.com>
Maxime <672982+maximegmd@users.noreply.github.com>
Maximilian Werk <maximilian.werk@gmx.de>
@@ -1347,6 +1378,7 @@ mdrokz <mohammadmunshi@gmail.com>
Me42019 <jeremyh88.jh@gmail.com>
meatposes <computerdork@verizon.net>
MeeMin <74113151+Meet91721@users.noreply.github.com>
Meet Amin <meetamin378@gmail.com>
megemini <megemini@outlook.com>
Mendy Berger <12537668+MendyBerger@users.noreply.github.com>
Meng Zhang <meng@tabbyml.com>
@@ -1358,6 +1390,7 @@ Merrick Christensen <merrick.christensen@gmail.com>
mgroeber9110 <45620825+mgroeber9110@users.noreply.github.com>
MiaoMing Chen <miaomingc@stumail.nwu.edu.cn>
Miaoqian Lin <linmq006@gmail.com>
Michael <michael.overhorst@gmail.com>
Michael Coppola <m18coppola@gmail.com>
Michael de Gans <michael.john.degans@gmail.com>
Michaël de Vries <vriesdemichael@gmail.com>
@@ -1456,6 +1489,7 @@ niansa/tuxifan <anton-sa@web.de>
niansa/tuxifan <tuxifan@posteo.de>
Nicholai Tukanov <nicholaitukanov@gmail.com>
Nicholas Sparks <157740354+nisparks@users.noreply.github.com>
nicholas-mainardi-domyn <nicholas.mainardi@domyn.com>
Nick <0x0b4ac@gmail.com>
Nick Farrell <nick.farrell@aiven.io>
nick huang <nickhuang99@hotmail.com>
@@ -1531,6 +1565,7 @@ PAB <pierreantoine.bannier@gmail.com>
Pablo Duboue <pablo.duboue@gmail.com>
Pádraic Slattery <pgoslatara@gmail.com>
parabelboi <parabelboi@gmail.com>
parthod0x <260393540+parthod0x@users.noreply.github.com>
Pascal <admin@serveurperso.com>
Pascal Patry <ppatry@mtacitlabs.com>
pascal-lc <49066376+pascal-lc@users.noreply.github.com>
@@ -1553,6 +1588,7 @@ Paweł Wodnicki <151604+32bitmicro@users.noreply.github.com>
pculliton <phillipculliton@gmail.com>
Pedro Cuenca <pedro@huggingface.co>
peidaqi <peidaqi@gmail.com>
Pelayo Garcia Bárcena <40317024+PelaGB17@users.noreply.github.com>
Penglin Cai <1402538448@qq.com>
pengxin99 <pengxin.yuan@intel.com>
Pepijn de Vos <me@pepijndevos.nl>
@@ -1583,6 +1619,7 @@ Piotr Kubaj <pkubaj@anongoth.pl>
Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com>
pl752 <pl752@mail.ru>
Plamen Minev <pacominev@gmail.com>
Plasmatix Ultra <stevenrichardbarnett@gmail.com>
Ploo <239304139+xinitrcn1@users.noreply.github.com>
pmaybank <113125070+pmaybank@users.noreply.github.com>
pmysl <piotr.myslinski@outlook.com>
@@ -1646,6 +1683,7 @@ Rahul Vivek Nair <68507071+RahulVivekNair@users.noreply.github.com>
Rail Chabdarov <rchabdar@amd.com>
rainred <107027757+gryffindor-rr@users.noreply.github.com>
Raj Hammeer Singh Hada <hammeerraj@gmail.com>
Rajarshi Datta <138959719+rajarshidattapy@users.noreply.github.com>
Rajendra Matcha <matcraje@qti.qualcomm.com>
Ralph Soika <ralph.soika@imixs.com>
Raman Shinde <raman.shinde15@gmail.com>
@@ -1678,6 +1716,7 @@ Ren Xuancheng <jklj077@users.noreply.github.com>
Renat <rntk@users.noreply.github.com>
Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com>
Renzis <93137239+Renzishi@users.noreply.github.com>
Revertron <105154+Revertron@users.noreply.github.com>
Reza Kakhki <rezakakhki.de@gmail.com>
Reza Rahemtola <49811529+RezaRahemtola@users.noreply.github.com>
RhinoDevel <RhinoDevel@users.noreply.github.com>
@@ -1746,6 +1785,7 @@ Ruben Ortlam <picard12@live.de>
Ruben Ortlam <rortlam@redhat.com>
Ruchira Hasaranga <ruchira66@gmail.com>
Rudi Servo <rudiservo@gmail.com>
Rudransh Shekhar <kanhaiffco2007@gmail.com>
Ruikai Peng <retr0@retr0.blog>
Ruixiang Wang <wangruixiang07@outlook.com>
Ruixin Huang <18860020911@163.com>
@@ -1759,6 +1799,7 @@ Ryan Goulden <percontation@gmail.com>
Ryan Landay <rlanday@gmail.com>
Ryan Mangeno <160974989+ryan-mangeno@users.noreply.github.com>
Ryder Wishart <ryderwishart@gmail.com>
Ryn Wang <94994001+rynwang@users.noreply.github.com>
Ryuei <louixs@users.noreply.github.com>
s-goto-11 <206795233+s-goto-11@users.noreply.github.com>
s0mecode <213953308+s0mecode@users.noreply.github.com>
@@ -1773,6 +1814,7 @@ Safi Ullah <safiullah.3915@gmail.com>
safranowith <bsh155762@gmail.com>
Said Taghadouini <84044788+staghado@users.noreply.github.com>
SaidSultani <62264302+SaidSultani@users.noreply.github.com>
saiph <cecwxf@126.com>
Sait Furkan Teke <35101659+stfurkan@users.noreply.github.com>
SakuraUmi <yukinon244@gmail.com>
Salvador E. Tropea <stropea@inti.gob.ar>
@@ -1813,6 +1855,7 @@ Seb C <47074056+Sebby37@users.noreply.github.com>
Sebastián A <sebastian.aedo29@gmail.com>
Sebastian Dröge <sebastian@centricular.com>
Sebastian Dröge <slomo@coaxion.net>
Sebastian Kuzminsky <seb@highlab.com>
SebastianApel <13675545+SebastianApel@users.noreply.github.com>
SecondSeed <38520721+SecondSeed@users.noreply.github.com>
semidark <me@semidark.net>
@@ -1873,6 +1916,7 @@ Shreya Jain <shreya94jain@gmail.com>
Shreya Jain <shreyajn@qti.qualcomm.com>
Shrivas Shankar <86219405+shrivasshankar@users.noreply.github.com>
SHUAI YANG <shuaiyang047@163.com>
Shubham Roy <roy388925@gmail.com>
Shuichi Tsutsumi <shuichi0526@gmail.com>
shun095 <8069181+shun095@users.noreply.github.com>
Shunta Saito <shunta.saito@gmail.com>
@@ -1883,6 +1927,7 @@ Siavash Norouzi <35790025+siavashnorouzi@users.noreply.github.com>
Sid Mohan <61345237+sidmohan0@users.noreply.github.com>
Sid Shaytay <2595088+SidShaytay@users.noreply.github.com>
SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com>
Sidhartha Reddy Potu <73529763+sid-rp@users.noreply.github.com>
Sigbjørn Skjæret <1629204+CISC@users.noreply.github.com>
Sigbjørn Skjæret <ggerganov@gmail.com>
Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
@@ -1926,6 +1971,7 @@ Son H. Nguyen <33925625+nhs000@users.noreply.github.com>
Song Li <songtli@outlook.com>
Sophon <strongtz@yeah.net>
Sou-ly <79574807+Sou-ly@users.noreply.github.com>
Souleyman <79574807+Sou-ly@users.noreply.github.com>
Sourab Mangrulkar <13534540+pacman100@users.noreply.github.com>
Spencer Sutton <spencersutton@users.noreply.github.com>
sprayandwipe <spray.and.wipe@gmail.com>
@@ -1935,6 +1981,7 @@ Srihari-mcw <96763064+Srihari-mcw@users.noreply.github.com>
Srijan Keshri <212402043+arcusbuilds@users.noreply.github.com>
Srinivas Billa <nivibilla@gmail.com>
srkizer <github.soreepeong.prqovzj1d@srkizer.net>
SS1618 <45392178+SS1618@users.noreply.github.com>
ssweens <1149151+ssweens@users.noreply.github.com>
standby24x7 <standby24x7@gmail.com>
staviq <staviq@gmail.com>
@@ -1969,6 +2016,8 @@ swittk <switt1995@gmail.com>
sxq <18856096915@163.com>
SXX <song_xiaoxi@126.com>
SXX <sxx1136965276@gmail.com>
sys2008 <165458212+sys2008@users.noreply.github.com>
t-kusanagi <46693526+t-kusanagi@users.noreply.github.com>
Tai Duc Nguyen <taiducnguyen.drexel@gmail.com>
Taikono-Himazin <kazu@po.harenet.ne.jp>
Taimur Ahmad <taimur.ahmad@10xengineers.ai>
@@ -1998,6 +2047,7 @@ Tei Home <taiteitonghome@proton.me>
Tekin Ertekin <tekin.ertekin@gmail.com>
Tekin Ertekin <tekinertekin@gmail.com>
tempstudio <49735574+tempstudio@users.noreply.github.com>
Teng Mei <73174080+meitmt@users.noreply.github.com>
teo <TeoZosa@users.noreply.github.com>
Terrence Zhao <32208165+Terrencezzj@users.noreply.github.com>
texasich <101962694+texasich@users.noreply.github.com>
@@ -2107,8 +2157,10 @@ Valentyn Bezshapkin <61702053+valentynbez@users.noreply.github.com>
Valeriy Dubov <dvv101111@gmail.com>
Vali Malinoiu <0x4139@gmail.com>
valiray <133289098+valiray@users.noreply.github.com>
varun <varun10221@gmail.com>
vb <vaibhavs10@gmail.com>
Vedran Miletić <vedran@miletic.net>
velonica0 <47554626+velonica0@users.noreply.github.com>
Vexxie <rainandriamusic@gmail.com>
Victor <194116445+dodekapod@users.noreply.github.com>
Victor Nogueira <felladrin@gmail.com>
@@ -2137,6 +2189,7 @@ Vladimir Sotnikov <bubert9@gmail.com>
Vladimir Vuksanovic <109677816+vvuksanovic@users.noreply.github.com>
Vladimir Zorin <vladimir@deviant.guru>
Vladislav <vladplotnikov34@gmail.com>
Vladislav Merkulov <150796351+merkulovlad@users.noreply.github.com>
Vladislav Sayapin <70110788+v-sayapin@users.noreply.github.com>
vmobilis <75476228+vmobilis@users.noreply.github.com>
vodkaslime <646329483@qq.com>
@@ -2166,6 +2219,7 @@ wencan <wencan@live.cn>
wendadawen <130649302+wendadawen@users.noreply.github.com>
WenqiangJia2026 <wenqijia@amd.com>
Wentai Zhang <rchardx@gmail.com>
Wenyu Chen <wenyuc21@gmail.com>
wes <huangwei858@126.com>
whoreson <139810751+whoreson@users.noreply.github.com>
Wilken Gottwalt <12194808+wgottwalt@users.noreply.github.com>
@@ -2211,6 +2265,7 @@ Xie Yanbo <xieyanbo@gmail.com>
Xingchen Song(宋星辰) <xingchensong1996@163.com>
Xinpeng Dou <15529241576@163.com>
Xinpeng Dou <81913537+Dou-Git@users.noreply.github.com>
xjf888800 <59639069+xjf888800@users.noreply.github.com>
xloem <0xloem@gmail.com>
xris99 <79798089+xris99@users.noreply.github.com>
Xuan Son Nguyen <son@huggingface.co>
@@ -2218,6 +2273,7 @@ Xuan Son Nguyen <thichthat@gmail.com>
Xuan-Son Nguyen <son@huggingface.co>
Xuan-Son Nguyen <thichthat@gmail.com>
Xue Zhenliang <riteme@users.noreply.github.com>
Xuejun Zhai <xuejun.zhai@intel.com>
XZiar <15145384+XZiar@users.noreply.github.com>
y198 <90976397+y198nt@users.noreply.github.com>
yael-works <106673277+yael-works@users.noreply.github.com>
@@ -2255,6 +2311,7 @@ Yishuo Wang <MeouSker77@outlook.com>
Yiwei Shao <44545837+njsyw1997@users.noreply.github.com>
ymcki <84055651+ymcki@users.noreply.github.com>
ynankani <ynankani@nvidia.com>
yoch <yoch.melka@gmail.com>
yomi <3527628634@qq.com>
Yonghye Kwon <developer.0hye@gmail.com>
Yongmin Yoo 유용민 <yymin1022@gmail.com>
@@ -2299,6 +2356,7 @@ zhangrunda <zhangrunda1234@outlook.com>
zhangtao2-1 <478679312@qq.com>
ZHAOKAI WANG <sanxianwei@163.com>
Zhaolun Yin <129580161+ZhaolunYin@users.noreply.github.com>
ZhaolunYin <129580161+ZhaolunYin@users.noreply.github.com>
zhaoyshine <30611065+zhaoyshine@users.noreply.github.com>
Zheng.Deng <32841220+dengzheng-cloud@users.noreply.github.com>
zhentaoyu <zhentao.yu@intel.com>
+1 -1
View File
@@ -4,7 +4,7 @@ include(CheckIncludeFileCXX)
### llama.cpp version
set(LLAMA_VERSION_MAJOR 1)
set(LLAMA_VERSION_MINOR 0)
set(LLAMA_VERSION_MINOR 1)
set(LLAMA_VERSION_PATCH 0)
set(LLAMA_VERSION_BASE "${LLAMA_VERSION_MAJOR}.${LLAMA_VERSION_MINOR}.${LLAMA_VERSION_PATCH}")
+2 -2
View File
@@ -171,7 +171,7 @@ if (LLAMA_LLGUIDANCE)
CONFIGURE_COMMAND ""
BUILD_COMMAND cargo build --release --package llguidance
INSTALL_COMMAND ""
BUILD_BYPRODUCTS ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME} ${LLGUIDANCE_PATH}/llguidance.h
BUILD_BYPRODUCTS ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME} ${LLGUIDANCE_SRC}/parser/llguidance.h
UPDATE_COMMAND ""
)
target_compile_definitions(${TARGET} PUBLIC LLAMA_USE_LLGUIDANCE)
@@ -180,7 +180,7 @@ if (LLAMA_LLGUIDANCE)
set_target_properties(llguidance PROPERTIES IMPORTED_LOCATION ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME})
add_dependencies(llguidance llguidance_ext)
target_include_directories(${TARGET} PRIVATE ${LLGUIDANCE_PATH})
target_include_directories(${TARGET} PRIVATE ${LLGUIDANCE_SRC}/parser)
target_link_libraries(${TARGET} PRIVATE llguidance)
if (WIN32)
target_link_libraries(${TARGET} PRIVATE ws2_32 userenv ntdll bcrypt)
+8
View File
@@ -3494,6 +3494,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
// note: do not modify cors_origins here, as the options are not evaluated in order (user may explicitly set --cors-origins before --agent)
}
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_AGENT"));
add_opt(common_arg(
{"--ui-agent"},
"enable agent mode in Llama Chat with nothing enabled on the server: the tools that run in the browser and MCP servers the browser reaches itself, no server tools and no MCP proxy (default: disabled)\n"
"note: not needed with --agent, --tools or --ui-mcp-proxy, they enable agent mode in Llama Chat too",
[](common_params & params) {
params.ui_agent = true;
}
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_AGENT"));
add_opt(common_arg(
{"--ui", "--webui"},
{"--no-ui", "--no-webui"},
+4 -4
View File
@@ -225,13 +225,13 @@ common_peg_parser analyze_tools::build_tool_parser_json_native(parser_build_cont
auto single_tool_parser = p.standard_json_tools(
format.per_call_start, format.per_call_end, inputs.tools, inputs.parallel_tool_calls,
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger);
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger, inputs.tool_choice);
tools_parser = p.trigger_rule("tool-calls", p.one_or_more(single_tool_parser + p.space()));
} else {
tools_parser = p.standard_json_tools(
format.section_start, format.section_end, inputs.tools, inputs.parallel_tool_calls,
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger);
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger, inputs.tool_choice);
}
// Handle content wrappers if present
@@ -304,7 +304,7 @@ common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context
common_peg_parser tool_choice = p.choice();
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
common_chat_foreach_tool(inputs.tools, inputs.tool_choice, [&](size_t tool_index, const json & tool) {
const auto & func = tool.at("function");
std::string name = func.at("name");
const auto schema = common_chat_tool_parameters(func);
@@ -379,7 +379,7 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
common_peg_parser tool_choice = p.choice();
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
common_chat_foreach_tool(inputs.tools, inputs.tool_choice, [&](size_t tool_index, const json & tool) {
const auto & func = tool.at("function");
std::string name = func.at("name");
+24 -32
View File
@@ -650,19 +650,16 @@ static std::pair<std::string, std::string> parse_key_spec(const std::string & ke
// Mode 1: function_is_key — parse {"function_name": {...}}
common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key(
const ordered_json & tools,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key) {
const ordered_json & tools,
const common_chat_tool_choice & tool_choice,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key) {
auto tool_choices = choice();
for (size_t i = 0; i < tools.size(); i++) {
const auto & tool_def = tools[i];
if (!tool_def.contains("function")) {
continue;
}
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
const auto & function = tool_def.at("function");
std::string name = function.at("name");
ordered_json params = common_chat_tool_parameters(function);
@@ -723,18 +720,19 @@ common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key(
);
tool_choices |= rule("tool-" + std::to_string(i), tool_parser);
}
});
return tool_choices;
}
// Mode 2: Nested keys (dot notation like "function.name")
common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
const ordered_json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key) {
const ordered_json & tools,
const common_chat_tool_choice & tool_choice,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key) {
auto tool_choices = choice();
@@ -745,11 +743,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
std::string nested_name_field = !name_spec.first.empty() ? name_spec.second : effective_name_key;
std::string nested_args_field = !args_spec.first.empty() ? args_spec.second : effective_args_key;
for (size_t i = 0; i < tools.size(); i++) {
const auto & tool_def = tools[i];
if (!tool_def.contains("function")) {
continue;
}
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
const auto & function = tool_def.at("function");
std::string name = function.at("name");
ordered_json params = common_chat_tool_parameters(function);
@@ -796,7 +790,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
tool_parser_body = tool_parser_body + nested_field + space() + tool_close(literal("}"));
tool_choices |= rule("tool-" + std::to_string(i), tool(tool_parser_body));
}
});
return tool_choices;
}
@@ -804,6 +798,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
// Mode 3: Flat keys with optional ID fields and parameter ordering
common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
const ordered_json & tools,
const common_chat_tool_choice & tool_choice,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
@@ -815,11 +810,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
auto name_key_parser = literal("\"" + effective_name_key + "\"");
auto args_key_parser = literal("\"" + effective_args_key + "\"");
for (size_t i = 0; i < tools.size(); i++) {
const auto & tool_def = tools[i];
if (!tool_def.contains("function")) {
continue;
}
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
const auto & function = tool_def.at("function");
std::string name = function.at("name");
ordered_json params = common_chat_tool_parameters(function);
@@ -888,7 +879,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
ordered_body = ordered_body + space() + tool_close(literal("}"));
tool_choices |= rule("tool-" + std::to_string(i), tool(ordered_body));
}
});
return tool_choices;
}
@@ -942,7 +933,8 @@ common_peg_parser common_chat_peg_builder::standard_json_tools(
const std::string & call_id_key,
const std::string & gen_call_id_key,
const std::vector<std::string> & parameters_order,
bool accept_openai_wrapper) {
bool accept_openai_wrapper,
const common_chat_tool_choice & tool_choice) {
if (!tools.is_array() || tools.empty()) {
return eps();
}
@@ -953,14 +945,14 @@ common_peg_parser common_chat_peg_builder::standard_json_tools(
// Dispatch to the appropriate builder based on the JSON layout mode
common_peg_parser tool_choices = eps();
if (function_is_key) {
tool_choices = build_json_tools_function_is_key(tools, args_key, effective_args_key, call_id_key, gen_call_id_key);
tool_choices = build_json_tools_function_is_key(tools, tool_choice, args_key, effective_args_key, call_id_key, gen_call_id_key);
} else {
auto name_spec = parse_key_spec(effective_name_key);
auto args_spec = parse_key_spec(effective_args_key);
if (!name_spec.first.empty() || !args_spec.first.empty()) {
tool_choices = build_json_tools_nested_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key);
tool_choices = build_json_tools_nested_keys(tools, tool_choice, effective_name_key, effective_args_key, call_id_key, gen_call_id_key);
} else {
tool_choices = build_json_tools_flat_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper);
tool_choices = build_json_tools_flat_keys(tools, tool_choice, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper);
}
}
+14 -10
View File
@@ -143,7 +143,7 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// parameters_order: order in which JSON fields should be parsed
common_peg_parser standard_json_tools(const std::string & section_start,
const std::string & section_end,
const common_json & tools,
const common_json & tools,
bool parallel_tool_calls,
bool force_tool_calls,
const std::string & name_key = "",
@@ -153,7 +153,8 @@ class common_chat_peg_builder : public common_peg_parser_builder {
const std::string & call_id_key = "",
const std::string & gen_call_id_key = "",
const std::vector<std::string> & parameters_order = {},
bool accept_openai_wrapper = false);
bool accept_openai_wrapper = false,
const common_chat_tool_choice & tool_choice = {});
// Legacy-compatible helper for building XML/tagged style tool calls
// Used by tests and manual parsers
@@ -176,18 +177,21 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// Implementation helpers for standard_json_tools — one per JSON tool call layout mode
common_peg_parser build_json_tools_function_is_key(const common_json & tools,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
const common_chat_tool_choice & tool_choice,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_nested_keys(const common_json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
const common_chat_tool_choice & tool_choice,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_flat_keys(const common_json & tools,
const common_chat_tool_choice & tool_choice,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
+54 -3
View File
@@ -322,7 +322,21 @@ struct common_chat_templates {
std::shared_ptr<common_tts_dicts> tts_dicts; // dictionaries of the model for tts_dict(), by name
};
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {
bool common_chat_tool_choice::allows(const std::string & name) const {
return !is_none() && (allowed.empty() || std::find(allowed.begin(), allowed.end(), name) != allowed.end());
}
void common_chat_foreach_tool(const common_json & tools, const common_chat_tool_choice & tool_choice,
const std::function<void(size_t, const common_json &)> & fn) {
for (size_t i = 0; i < tools.size(); i++) {
const auto & tool = tools[i];
if (tool_choice.allows(tool.at("function").at("name").get<std::string>())) {
fn(i, tool);
}
}
}
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const common_json & tool_choice, const std::vector<common_chat_tool> & tools) {
if (tool_choice == "auto") {
return COMMON_CHAT_TOOL_CHOICE_AUTO;
}
@@ -332,7 +346,44 @@ common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::strin
if (tool_choice == "required") {
return COMMON_CHAT_TOOL_CHOICE_REQUIRED;
}
throw std::invalid_argument("Invalid tool_choice: " + tool_choice);
common_chat_tool_choice choice;
const auto type = tool_choice.value("type", json());
if (type == "function") {
choice.mode = COMMON_CHAT_TOOL_CHOICE_REQUIRED;
choice.allowed.push_back(tool_choice.at("function").at("name").get<std::string>());
} else if (type == "allowed_tools") {
const auto & allowed = tool_choice.at("allowed_tools");
const auto & mode = allowed.at("mode");
const auto & allowed_tools = allowed.at("tools");
if ((mode != "auto" && mode != "required") || !allowed_tools.is_array()) {
throw std::invalid_argument("allowed_tools requires mode auto or required and a tools array");
}
choice.mode = mode == "required" ? COMMON_CHAT_TOOL_CHOICE_REQUIRED : COMMON_CHAT_TOOL_CHOICE_AUTO;
for (const auto & tool : allowed_tools) {
if (tool.value("type", json()) != "function") {
throw std::invalid_argument("allowed_tools entries must have type function");
}
choice.allowed.push_back(tool.at("function").at("name").get<std::string>());
}
if (choice.allowed.empty()) {
if (choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
throw std::invalid_argument("Required allowed_tools must contain at least one function");
}
choice.mode = COMMON_CHAT_TOOL_CHOICE_NONE;
}
} else {
throw std::invalid_argument("Invalid tool_choice: " + tool_choice.dump());
}
for (const auto & name : choice.allowed) {
const auto n_matching = std::count_if(tools.begin(), tools.end(), [&](const common_chat_tool & tool) {
return tool.name == name;
});
if (name.empty() || n_matching != 1) {
throw std::invalid_argument("tool_choice function name must match exactly one supplied tool: " + name);
}
}
return choice;
}
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates) {
@@ -1406,7 +1457,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;
+25 -2
View File
@@ -232,12 +232,35 @@ struct common_chat_tool {
bool defer_loading = false;
};
enum common_chat_tool_choice {
enum common_chat_tool_choice_mode {
COMMON_CHAT_TOOL_CHOICE_AUTO,
COMMON_CHAT_TOOL_CHOICE_REQUIRED,
COMMON_CHAT_TOOL_CHOICE_NONE,
};
struct common_chat_tool_choice {
common_chat_tool_choice_mode mode = COMMON_CHAT_TOOL_CHOICE_AUTO;
// Names of the tools the model may call, every tool when empty.
std::vector<std::string> allowed;
common_chat_tool_choice() = default;
common_chat_tool_choice(common_chat_tool_choice_mode mode) : mode(mode) {}
bool operator==(common_chat_tool_choice_mode other) const { return mode == other; }
bool operator!=(common_chat_tool_choice_mode other) const { return mode != other; }
bool allows(const std::string & name) const;
bool is_auto() const { return mode == COMMON_CHAT_TOOL_CHOICE_AUTO; }
bool is_required() const { return mode == COMMON_CHAT_TOOL_CHOICE_REQUIRED; }
bool is_none() const { return mode == COMMON_CHAT_TOOL_CHOICE_NONE; }
};
// Keep the original tool indices when restricting the parser's tool set.
void common_chat_foreach_tool(const common_json & tools, const common_chat_tool_choice & tool_choice,
const std::function<void(size_t, const common_json &)> & fn);
enum common_chat_format {
COMMON_CHAT_FORMAT_CONTENT_ONLY,
@@ -458,7 +481,7 @@ class common_chat_session {
const char * common_reasoning_format_name(common_reasoning_format format);
common_reasoning_format common_reasoning_format_from_name(const std::string & format);
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice);
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const common_json & tool_choice, const std::vector<common_chat_tool> & tools);
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates);
+1
View File
@@ -701,6 +701,7 @@ struct common_params {
// UI configs
bool ui = true;
bool ui_agent = false; // agent mode in Llama Chat, no server tools and no MCP proxy
bool ui_mcp_proxy = false;
bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses
std::string ui_config_json;
+27
View File
@@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0;
imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0;
const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA);
if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY &&
gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) {
const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx);
imatrix.stats_schema.resize(n_schema);
for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); }
} else {
if (schema_idx != -1) {
LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str());
}
imatrix.stats_schema = {
"sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance",
};
}
const std::string in_sum_suffix{ ".in_sum" };
const std::string in_sum2_suffix{ ".in_sum2" };
const std::string counts_suffix{ ".counts" };
const std::string stats_suffix{ ".stats" };
struct sum_tensors {
struct ggml_tensor * in_sum = nullptr;
struct ggml_tensor * in_sum2 = nullptr;
struct ggml_tensor * counts = nullptr;
struct ggml_tensor * stats = nullptr;
};
std::map<std::string, sum_tensors> sums_counts_for;
@@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
sums_counts_for[std::move(name)].in_sum2 = cur;
} else if (string_remove_suffix(name, counts_suffix)) {
sums_counts_for[std::move(name)].counts = cur;
} else if (string_remove_suffix(name, stats_suffix)) {
sums_counts_for[std::move(name)].stats = cur;
}
}
@@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
const struct ggml_tensor * in_sum = sc.second.in_sum;
const struct ggml_tensor * in_sum2 = sc.second.in_sum2;
const struct ggml_tensor * counts = sc.second.counts;
const struct ggml_tensor * stats = sc.second.stats;
if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) {
LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
@@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
e.activations[j] = ((const float *) in_sum->data)[j];
}
}
if (stats && stats->type == GGML_TYPE_F32) {
const int64_t n_stats = ggml_nelements(stats);
e.stats.resize(n_stats);
for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; }
}
}
gguf_free(ctx_gguf);
+2
View File
@@ -15,11 +15,13 @@ struct common_imatrix_entry {
std::vector<float> sums;
std::vector<float> activations;
std::vector<int64_t> counts;
std::vector<float> stats;
};
struct common_imatrix {
std::map<std::string, common_imatrix_entry> entries;
std::vector<std::string> datasets;
std::vector<std::string> stats_schema;
int32_t chunk_count = 0;
int32_t chunk_size = 0;
int32_t n_layer_nextn = 0;
+6
View File
@@ -244,6 +244,12 @@ class common_chat_schema_builder {
}
common_chat_schema_ptr build_node_impl(const common_json & schema, const std::string & path) {
if (schema.is_boolean()) {
if (schema.get<bool>()) {
return std::make_unique<common_chat_schema_any>(); // true matches any value, like {}
}
fail(path, "false schema is not supported"); // false matches nothing, the grammar cannot express it
}
if (!schema.is_object()) {
fail(path, "schema must be an object");
}
+36 -38
View File
@@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
auto header = p.literal(HEADER);
auto end = p.literal(END);
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
auto header = p.token(HEADER);
auto end = p.token(END);
auto think = p.literal(THINK);
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end :
p.atomic(p.content(think)) + p.content(p.until(END) + end));
auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end);
auto think = p.token(THINK);
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end :
p.atomic(p.content(think)) + p.content(p.until(end) + end));
auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end);
if (has_response_format) {
auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end;
return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end;
}
auto blocks = p.zero_or_more(header + (thinking | text));
@@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
return blocks;
}
auto tool_choice = p.choice();
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
const auto & function = tool.at("function");
std::string name = function.at("name");
auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":");
auto args = p.tool_args(p.json());
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end));
});
// tool calls are the last blocks of the turn
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
auto tool_calls = header + p.trigger_rule("tool-calls", calls);
// the call takes the name in the JSON
auto tool_json = p.token(TOOL_JSON);
auto tool_body = [&](const common_peg_parser & json_name) {
return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",")
<< p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end;
};
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
return blocks + tool_calls;
auto tool_choice = p.choice();
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
const auto & function = tool.at("function");
std::string name = function.at("name");
std::string quoted = json(name).dump();
// The research model does not generate a tool name before the tool call token
auto json_name = p.literal(quoted.substr(1, quoted.size() - 2));
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name)));
});
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
return blocks + header + calls;
}
return blocks + p.optional(tool_calls);
auto name = p.until(tool_json);
auto body = tool_body(p.string_content('"'));
auto next = p.rule("tool-call", header + p.tool(name + tool_json + body));
auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps();
auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more);
return blocks + p.optional(calls);
});
if (has_response_format || use_tools) {
data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
data.grammar_lazy = false;
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
data.parser.build_grammar(builder, data.grammar_lazy);
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
});
if (data.grammar_lazy) {
// a header followed by text and not by a content token is a tool call, the grammar starts at the name
data.grammar_triggers = {
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
};
// Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
// an output that starts with no content token is a tool call. not for a continuation, it starts with text
if (!inputs.has_continuation()) {
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" });
}
}
}
return data;
+139 -7
View File
@@ -1140,8 +1140,8 @@ protected:
llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise
}
// only LiliCorr uses this, to keep the context features for its scorer; the other heads only need the KV cache
// called after the host copy injection of a chunk, while h_nextn still holds the context features of batch_inject
// LiliCorr and the Inkling2 DSpark keep context features from h_nextn; the other heads only need the KV cache
// called after the injection of a chunk, while h_nextn still holds the context features of batch_inject
virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {}
public:
@@ -1245,6 +1245,7 @@ public:
__func__, rc, (int) n_chunk, (int) offset);
return false;
}
store_context_features(seq_id, n_chunk);
continue;
}
@@ -1374,6 +1375,19 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
// bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot
bool sample_from_anchor = true;
// the Markov head reads the context state of the last committed token (Inkling2 f_rnn)
// it comes back from the injection as h_nextn, kept for the last ctx_rows positions of each sequence
bool has_markov_context = false;
size_t ctx_rows = 0;
std::vector<float> ctx_embd;
std::vector<llama_pos> ctx_pos;
// per-token state of the block tokens, n_embd_dec wide: the context state on the anchor row, [uniform | 1/temp] on the draft rows, see llama_batch_ext_select_n_embd_state
// with probabilistic drafting the graph draws each block token from it and returns [token, k, ids, probs] in h_nextn
std::vector<float> block_state;
std::vector<std::mt19937> draw_rng;
std::vector<int64_t> draw_seed; // the seed each generator was last seeded with (-1: reseed)
common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq)
: common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK)
{
@@ -1384,6 +1398,18 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) {
sample_from_anchor = std::strcmp(buf, "true") == 0;
}
if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0) {
has_markov_context = std::strcmp(buf, "true") == 0;
}
}
if (has_markov_context) {
ctx_rows = (size_t) block_size + 1;
ctx_embd.resize((size_t) n_seq * ctx_rows * (size_t) n_embd_dec);
ctx_pos.assign((size_t) n_seq * ctx_rows, -1);
block_state.reserve((size_t) n_seq * block_size * n_embd_dec);
draw_rng.resize(n_seq);
draw_seed.assign(n_seq, -1);
}
if (this->params.p_min > 0.0f) {
@@ -1396,17 +1422,59 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
}
}
LOG_INF("%s: - sample_from_anchor=%s\n", __func__, sample_from_anchor ? "true" : "false");
LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s\n", __func__,
sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false");
// anchor-first DSpark yields a full block_size draft tokens
// the context state is read back from h_nextn at every injected row
init({
/* .n_draft_max = */ sample_from_anchor ? block_size : block_size - 1,
/* .backend_sampling = */ true,
/* .dev_features = */ true,
/* .nextn_masked = */ true,
/* .nextn_masked = */ !has_markov_context,
});
}
protected:
void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override {
if (!has_markov_context) {
return;
}
const float * state = llama_get_embeddings_nextn(params.ctx_dft);
if (!state) {
return;
}
const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size);
for (int32_t i = 0; i < n_chunk; ++i) {
const llama_pos pos = batch_inject.tokens[i].pos[0];
if (pos < pos_min) {
continue;
}
const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows;
std::memcpy(ctx_embd.data() + slot * (size_t) n_embd_dec, state + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float));
ctx_pos[slot] = pos;
}
}
// context state of the token before the block, nullptr if it was not injected
const float * get_context_state(llama_seq_id seq_id, llama_pos pos) const {
if (pos < 0) {
return nullptr;
}
const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows;
return ctx_pos[slot] == pos ? ctx_embd.data() + slot * (size_t) n_embd_dec : nullptr;
}
public:
void begin(llama_seq_id seq_id, const llama_tokens & prompt) override {
// the markov context draws: reseed per request rather than per round, or two identical requests differ
if (has_markov_context && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) {
draw_seed[seq_id] = -1;
}
common_speculative_impl_draft_dflash::begin(seq_id, prompt);
}
void draft(common_speculative_draft_params_vec & dparams) override {
auto & ctx_dft = params.ctx_dft;
@@ -1416,6 +1484,9 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
// record where each block starts and its size
std::vector<int32_t> i_block_beg(n_seq, -1);
std::vector<int32_t> n_block (n_seq, 0);
std::vector<bool> sampled (n_seq, false);
block_state.clear();
for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) {
auto & dp = dparams[seq_id];
@@ -1423,16 +1494,53 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
continue;
}
// the Markov head reads the context state of the token before the block, no draft without it
const float * state = has_markov_context ? get_context_state(seq_id, dp.pos0 - 1) : nullptr;
if (has_markov_context && !state) {
continue;
}
// the graph draws the block at the target's temperature, the verifier then does rejection sampling with q
sampled[seq_id] = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f;
if (sampled[seq_id] && draw_seed[seq_id] != dp.seed) {
draw_seed[seq_id] = dp.seed;
// the default seed means random; mixed so it differs from the target's, as in spec_retune
draw_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu);
}
common_sampler_reset(smpls[seq_id].get());
const int32_t n = (int32_t) dp.pos0;
const int32_t n_draft = params.n_max;
const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1);
// all blocks share one decode: a block that does not fit in the draft context fails every sequence's draft
if ((uint64_t) dp.pos0 + n_block_tokens > llama_n_ctx_seq(ctx_dft)) {
continue;
}
i_block_beg[seq_id] = batch.size();
n_block [seq_id] = n_block_tokens;
for (int32_t i = 0; i < n_block_tokens; ++i) {
batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true);
const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true);
if (state) {
// reserved up front, so the views of the earlier tokens stay valid
GGML_ASSERT(block_state.size() + n_embd_dec <= block_state.capacity());
float * row = block_state.data() + block_state.size();
if (i == 0) {
block_state.insert(block_state.end(), state, state + n_embd_dec);
} else {
block_state.resize(block_state.size() + n_embd_dec, 0.0f);
if (sampled[seq_id]) {
// u in [0, 1): a draw in double can round up to 1 in float
const float u = (float) std::uniform_real_distribution<double>(0.0, 1.0)(draw_rng[seq_id]);
row[0] = std::min(u, std::nextafter(1.0f, 0.0f));
row[1] = 1.0f / dp.temp;
}
}
batch.set_embd_state(idx, { row, 1, (size_t) n_embd_dec });
}
}
}
@@ -1460,10 +1568,34 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
auto & result = *dp.result;
// DSpark: read from the first draft slot, truncate below the confidence threshold
const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr;
// bonus-anchor drafts read the mask positions only, like DFlash
const int32_t i_draft_beg = sample_from_anchor ? 0 : 1;
if (sampled[seq_id]) {
// the tokens the graph drew, and the distribution q each one was drawn from
const float * draws = llama_get_embeddings_nextn(ctx_dft);
GGML_ASSERT(draws && "DSpark draws missing from h_nextn");
for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) {
const float * row = draws + (size_t) (beg + i) * n_embd_dec;
const int32_t n_cand = (int32_t) row[1];
auto & q = dp.result_q->emplace_back();
q.reserve(n_cand);
for (int32_t k = 0; k < n_cand; ++k) {
const float p = row[2 + n_cand + k];
q.push_back({ (llama_token) row[2 + k], std::log(p), p });
}
result.push_back((llama_token) row[0]);
}
if (result.size() < (size_t) params.n_min) {
result.clear();
dp.result_q->clear();
}
continue;
}
// DSpark: read from the first draft slot, truncate below the confidence threshold
const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr;
for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) {
const int32_t idx = beg + i;
+4
View File
@@ -146,6 +146,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"HrmTextForCausalLM": "hrm_text",
"HYV3ForCausalLM": "hunyuan",
"HYV4ForCausalLM": "hy_v4",
"HYV4FlashForCausalLM": "hy_v4_flash",
"IQuestCoderForCausalLM": "llama",
"Inkling2ForCausalLM": "inkling2",
"Inkling2LoopForCausalLM": "inkling2",
@@ -307,6 +308,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"RWForCausalLM": "falcon",
"RWKV6Qwen2ForCausalLM": "rwkv",
"RWKV7ForCausalLM": "rwkv",
"Raon1MiniForCausalLM": "raon1_mini",
"RobertaForSequenceClassification": "bert",
"RobertaModel": "bert",
"RuGPT3XLForCausalLM": "gpt2",
@@ -390,6 +392,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"GraniteSpeechPlusForConditionalGeneration": "granite",
"HiggsAudio3Model": "higgs_audio",
"HunYuanVLForConditionalGeneration": "hunyuan",
"HYV4FlashForCausalLM": "hy_v4_flash",
"HYV4FlashForConditionalGeneration": "hy_v4_flash",
"Idefics3ForConditionalGeneration": "smolvlm",
"Inkling2ForConditionalGeneration": "inkling2",
"Inkling2LoopForConditionalGeneration": "inkling2",
+91 -13
View File
@@ -333,13 +333,13 @@ class ModelBase:
return scale.numel() <= 1 and abs(float(scale.float().sum()) - 1.0) < 1e-6
def _write_scale_tensor(self, scale_name: str, scale: Tensor):
if not self._scale_is_trivial(scale):
if not scale_name.endswith(".input_scale") or not self._scale_is_trivial(scale):
scale_f32 = scale.float().numpy().flatten()
logger.info(f" + {scale_name} (per-tensor scale, shape [{scale_f32.size}])")
self.gguf_writer.add_tensor(scale_name, scale_f32)
def _write_scales_tensor(self, scale_name: str, scales: list[float]):
if not np.allclose(scales, 1.0, atol=1e-6):
if not scale_name.endswith(".input_scale") or not np.allclose(scales, 1.0, atol=1e-6):
scale_vals = np.array(scales, dtype=np.float32)
logger.info(f" + {scale_name} (per-expert scale, shape [{len(scales)}])")
self.gguf_writer.add_tensor(scale_name, scale_vals)
@@ -689,14 +689,34 @@ class ModelBase:
new_name = self.tensor_map.get_name(name, try_suffixes=(".weight",))
return (new_name,) if new_name is not None else ()
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
# Return scales in mapped weight order, or None to dequantize.
# A new weight transform must also provide scale handling.
if type(self).modify_tensors is ModelBase.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def _prepare_fp8_e4m3_tensors(self):
if not self._preserve_fp8:
return
quant_config = self.hparams.get("quantization_config") or {}
fp8_configs = [
group["weights"] for group in (quant_config.get("config_groups") or {}).values()
if isinstance(group, dict) and group.get("weights", {}).get("type") == "float"
and group.get("weights", {}).get("num_bits") == 8
]
unsupported_layout = quant_config.get("weight_block_size") is not None or any(
config.get("strategy") not in (None, "tensor", "channel")
or config.get("block_structure") is not None or config.get("group_size") is not None
for config in fp8_configs
)
scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
input_scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
consumed: list[str] = []
candidates: dict[str, tuple[str, Tensor, tuple[str, ...], torch.Size]] = {}
channel_scales: dict[str, tuple[Tensor, ...]] = {}
weight_dtypes: dict[str, torch.dtype] = {}
scaled_weights: set[str] = set()
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
@@ -729,8 +749,19 @@ class ModelBase:
continue
scale = self.model_tensors[scale_name]()
if prod(scale.shape) != 1:
continue
# Accept per-tensor or per-output-channel scale layouts.
scale_size = prod(scale.shape)
is_channel_scale = 1 <= scale.ndim <= weight.ndim and scale.shape[0] == weight.shape[0] and all(size == 1 for size in scale.shape[1:])
if unsupported_layout or (scale_size != 1 and not is_channel_scale):
if quant_config.get("quant_method") in ("modelopt", "modelopt_mixed") and scale_name.endswith("_scale_inv"):
continue
if self._is_nvfp4_compressed_tensors(quant_config.get("quant_method"), quant_config.get("format"), quant_config.get("config_groups") or {}):
continue
raise ValueError(
f"FP8 weight {weight_name!r} has an unsupported block/group scale "
f"(scale shape {list(scale.shape)}, weight shape {list(weight.shape)}); "
f"only per-tensor or per-output-channel scales are supported. "
f"Re-run with --fp8-as-q8 to dequantize instead.")
merged_name = expert_pattern.sub(r"\1.", weight_name)
new_names = self._map_fp8_weight_names(merged_name)
@@ -743,6 +774,12 @@ class ModelBase:
if any(new_name.endswith("_norm.weight") or self.tensor_force_quant(weight_name, new_name, bid, weight.ndim) != gguf.GGMLQuantizationType.F8_E4M3 for new_name in new_names):
self._fp8_e4m3_preserved.discard(weight_name)
continue
if scale_size != 1:
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)
continue
channel_scales[weight_name] = transformed
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
expert_groups: dict[str, list[str]] = {}
@@ -758,8 +795,13 @@ class ModelBase:
continue
if dtypes == {torch.float8_e4m3fn} and not any(name in scaled_weights for name in names):
continue
scale_sizes: dict[str, set[int]] = {}
for name in names:
if name in candidates:
proj = name.rsplit(".", 2)[1]
scale_sizes.setdefault(proj, set()).add(prod(candidates[name][1].shape))
# The converter merges expert projections together.
if not all(name in candidates for name in names):
if not all(name in candidates for name in names) or any(len(sizes) > 1 for sizes in scale_sizes.values()):
for name in names:
candidates.pop(name, None)
self._fp8_e4m3_preserved.discard(name)
@@ -769,6 +811,7 @@ class ModelBase:
for weight_name, (scale_name, scale, new_names, shape) in candidates.items():
scale = LazyTorchTensor.to_eager(scale).float().flatten()
output_scales = tuple(LazyTorchTensor.to_eager(s).float().flatten() for s in channel_scales.get(weight_name, (scale,) * len(new_names)))
weight_prefix = weight_name.removesuffix(".weight")
# Transformers fine-grained FP8 uses activation_scale while ModelOpt uses input_scale.
@@ -792,25 +835,25 @@ class ModelBase:
expert_match = expert_pattern.search(weight_name)
if expert_match:
expert_id = int(expert_match.group(2))
for new_name in new_names:
for new_name, target_scale in zip(new_names, output_scales):
target_name = new_name.replace(".weight", ".scale")
entries = scale_tensors.setdefault(target_name, [])
assert isinstance(entries, list)
cast(list[tuple[int, float]], entries).append((expert_id, float(scale[0])))
cast(list, entries).append((expert_id, target_scale.numpy().astype(np.float32)))
if input_scale is not None:
target_name = new_name.replace(".weight", ".input_scale")
entries = input_scale_tensors.setdefault(target_name, [])
assert isinstance(entries, list)
cast(list[tuple[int, float]], entries).append((expert_id, float(input_scale[0])))
else:
for new_name in new_names:
for new_name, target_scale in zip(new_names, output_scales):
mapped = self.tensor_map.get_type_and_name(new_name, try_suffixes=(".weight",)) if len(shape) == 3 else None
is_packed_expert = mapped is not None and mapped[0] in (
gguf.MODEL_TENSOR.FFN_GATE_EXP, gguf.MODEL_TENSOR.FFN_UP_EXP, gguf.MODEL_TENSOR.FFN_DOWN_EXP,
)
# Packed expert weights need one scale value per expert.
n_scales = shape[0] if is_packed_expert else 1
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(scale.numpy(), n_scales)
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(target_scale.numpy(), n_scales)
if input_scale is not None:
input_scale_tensors[new_name.replace(".weight", ".input_scale")] = np.repeat(input_scale.numpy(), n_scales)
@@ -820,11 +863,15 @@ class ModelBase:
for name, values in chain(scale_tensors.items(), input_scale_tensors.items()):
if isinstance(values, list):
values.sort(key=lambda item: item[0])
scale = np.array([item[1] for item in values], dtype=np.float32)
arrays = [np.asarray(item[1], dtype=np.float32).reshape(-1) for item in values]
if all(a.size == 1 for a in arrays):
scale = np.array([a[0] for a in arrays], dtype=np.float32)
else:
scale = np.stack(arrays, axis=0)
else:
scale = values.astype(np.float32)
if not np.allclose(scale, 1.0, atol=1e-6):
logger.info(f" + {name} (FP8 scale, shape [{scale.size}])")
if not name.endswith(".input_scale") or not np.allclose(scale, 1.0, atol=1e-6):
logger.info(f" + {name} (FP8 scale, shape {list(scale.shape)})")
self.gguf_writer.add_tensor(name, scale)
@classmethod
@@ -1359,6 +1406,8 @@ class ModelBase:
scale2_name = name.replace(".weight", ".weight_scale_2")
input_scale_name = name.replace(".weight", ".input_scale")
if scale_name not in self.model_tensors:
if self.model_tensors[name]().dtype == torch.uint8:
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source block scale {scale_name!r} is missing")
continue
weight = self.model_tensors[name]()
scale = self.model_tensors[scale_name]()
@@ -1369,9 +1418,11 @@ class ModelBase:
if weight.ndim != 2 or scale.shape[0] != weight.shape[0] or scale.shape[1] * 8 != weight.shape[1]:
raise ValueError(f"NVFP4 weight {name!r} has incompatible shapes: weight {list(weight.shape)}, scale {list(scale.shape)}")
if scale2_name not in self.model_tensors:
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source weight scale is missing ({scale2_name!r})")
weight = LazyTorchTensor.to_eager(weight)
scale = LazyTorchTensor.to_eager(scale)
scale2 = LazyTorchTensor.to_eager(self.model_tensors.get(scale2_name, lambda: torch.tensor(1.0))())
scale2 = LazyTorchTensor.to_eager(self.model_tensors[scale2_name]())
input_scale = LazyTorchTensor.to_eager(self.model_tensors.get(input_scale_name, lambda: torch.tensor(1.0))())
# Mark tensors for removal from model_tensors (already written to gguf)
@@ -1450,7 +1501,19 @@ class ModelBase:
self._has_ple |= is_ple
return is_ple if self.ple_only else not is_ple
def _has_fp8_source_scale(self, name: str) -> bool:
scale_names = (name + "_scale", name + "_scale_inv", name.removesuffix("weight") + "qscale_weight")
return any(scale_name in self.model_tensors for scale_name in scale_names)
def prepare_tensors(self):
for name, load in self.model_tensors.items():
if not name.endswith(".weight"):
continue
if load().dtype not in (torch.float8_e4m3fn, torch.float8_e5m2):
continue
if not self._has_fp8_source_scale(name):
raise ValueError(f"Cannot convert FP8 weight {name!r}: source weight scale is missing")
# detect NVFP4 quantization (ModelOpt and Compressed-tensors formats)
quantization_config = self.hparams.get("quantization_config") or {}
quant_algo = quantization_config.get("quant_algo")
@@ -1666,6 +1729,18 @@ class ModelBase:
if any(qkv_buffers):
raise ValueError("QKV fusion did not consume all buffered tensors")
tensor_names = {name for shard in self.gguf_writer.tensors for name in shard}
for shard in self.gguf_writer.tensors:
for name, tensor in shard.items():
# a PLE-only file holds just the table, its scale stays in the backbone
if self.ple_only and self._include_ple_tensor(name):
continue
# Keep in sync with needs_scale in ggml.c.
if tensor.dtype in (gguf.GGMLQuantizationType.F8_E4M3, gguf.GGMLQuantizationType.NVFP4):
scale_name = name.removesuffix(".weight") + ".scale"
if scale_name not in tensor_names:
raise ValueError(f"Cannot export {name!r} as {tensor.dtype.name}: required scale tensor {scale_name!r} is missing (implicit unit scales are not supported)")
def set_type(self):
self.gguf_writer.add_type(gguf.GGUFType.MODEL)
@@ -2473,6 +2548,9 @@ class TextModel(ModelBase):
if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
res = "domyn-edge"
if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1":
# ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview
res = "raon"
if res is None:
logger.warning("\n")
+25 -1
View File
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf, jinja_str_or_json, logger
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel", "BertForSequenceClassification")
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel")
@ModelBase.example("BAAI/bge-small-en-v1.5", "dangvantuan/sentence-camembert-base")
class BertModel(TextModel):
model_arch = gguf.MODEL_ARCH.BERT
@@ -241,6 +241,30 @@ class BertModel(TextModel):
special_vocab.add_to_gguf(self.gguf_writer)
@ModelBase.register("BertForSequenceClassification")
@ModelBase.example("cross-encoder/ms-marco-MiniLM-L-12-v2")
class BertForSequenceClassification(BertModel):
model_arch = gguf.MODEL_ARCH.BERT
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.cls_out_labels is None:
self.cls_out_labels = self.hparams.get("id2label")
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
name, gen = item
name = name.replace("pooler.dense", "classifier.dense")
return super().filter_tensors((name, gen))
def set_gguf_parameters(self):
if "classifier.dense.weight" in self.model_tensors:
self.hparams.setdefault("classifier_activation", "tanh")
super().set_gguf_parameters()
@ModelBase.register("DistilBertModel", "DistilBertForMaskedLM", "DistilBertForSequenceClassification")
@ModelBase.example("distilbert/distilbert-base-uncased")
class DistilBertModel(BertModel):
+650
View File
@@ -0,0 +1,650 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Callable, Iterable, cast
import numpy as np
import torch
from .base import LazyTorchTensor, MmprojModel, ModelBase, gguf, logger
from .deepseek41 import _StreamedBytes
from .hy_v4 import HYV4Model
# the reference derives the hash multipliers from the Engram seed, the 1-based layer id and the compressed vocab size
ENGRAM_SEED_STRIDE = 10007
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
@ModelBase.example("tencent/Hy4-Flash")
class HYV4FlashModel(HYV4Model):
"""hy_v4 with sparse and sliding-window MLA layers, sandwich norms, latent routed experts, Engram and a k-pool indexer.
The MTP draft block is exported as one extra sparse layer. The vision tower and the dfly draft layers are not converted.
"""
model_arch = gguf.MODEL_ARCH.HY_V4_FLASH
# the draft block is exported under block ids past the trunk, which skip_mtp would drop
skip_mtp = False
# dropped subsystems, see the class docstring
DROP_PREFIXES = ("vit.", "model.dfly_layers.")
DROP_SUBSTRINGS = ()
# the released config renamed sparse_attention, both name the same layer type
SPARSE_TYPES = ("sparse_attention", "deepseek_sparse_attention")
# the released checkpoints ship the token map as a tensor instead of engram_vocab_map.npz
ENGRAM_LOOKUP_TABLE = "lookup_table"
# compressed_indexer tail -> the tensor the graph reads it as
INDEXER_MAP = {
"token_key_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_K,
"token_key_norm.weight": gguf.MODEL_TENSOR.INDEXER_K_NORM,
"key_value_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_VALUE,
"key_gate_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_GATE,
"intra_group_ape": gguf.MODEL_TENSOR.INDEXER_KPOOL_APE,
"key_norm.weight": gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_NORM,
"query_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B,
"head_weight_projection.weight": gguf.MODEL_TENSOR.INDEXER_PROJ,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# the draft block is an extra block, the loader subtracts the nextn count from block_count
if not getattr(self, "no_mtp", False):
self.block_count += self._n_nextn()
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
# Engram weights arrive one at a time but are written fused, so they wait here
self._engram_buf: dict[int, dict[str, torch.Tensor]] = {}
self._engram_tables: dict[int, torch.Tensor] = {}
self._engram_done: set[str] = set()
@classmethod
def filter_tensors(cls, item):
name = item[0]
if name.startswith(cls.DROP_PREFIXES) or any(s in name for s in cls.DROP_SUBSTRINGS):
return None
if name.startswith("model.mtp_layers."):
# hy_v4 drops the draft block; this model exports it, so skip that filter
return super(HYV4Model, cls).filter_tensors(item)
return super().filter_tensors(item)
def _layer_types(self) -> list[str]:
cached = getattr(self, "_layer_types_cache", None)
if cached is not None:
return cached
layer_types = self.hparams.get("layer_types")
n_layer = self.hparams["num_hidden_layers"]
if not layer_types or len(layer_types) < n_layer:
raise ValueError("HY_V4_FLASH needs a layer_types entry per layer")
unknown = set(layer_types[:n_layer]) - set(self.SPARSE_TYPES) - {"sliding_attention"}
if unknown:
raise ValueError(f"HY_V4_FLASH unknown layer_types values: {sorted(unknown)}")
# the released config renamed the sparse layers, normalize so the rest reads one name
self._layer_types_cache = ["sparse_attention" if t in self.SPARSE_TYPES else t for t in layer_types[:n_layer]]
return self._layer_types_cache
# Engram: one n-gram hash module per Engram layer, all buckets in one table as in deepseek41
def _engram_enabled(self) -> bool:
# engram_enable is optional, a False turns Engram off
return bool(self.hparams.get("engram_enable", True)) and bool(self.hparams.get("engram_layer_ids"))
def _engram_ids(self) -> list[int]:
"""engram_layer_ids, 1-based and sorted."""
ids = sorted(int(i) for i in self.hparams["engram_layer_ids"])
n_layer = self.hparams["num_hidden_layers"]
for i in ids:
# 1-based: the tensors live at model.layers.{i-1}.engram_layer.*
if not 1 <= i <= n_layer:
raise ValueError(f"HY_V4_FLASH engram_layer_ids has {i}, outside 1..{n_layer}")
return ids
def _engram_primes(self) -> dict[int, list[int]]:
"""Per 1-based layer id, the flattened [ngram][head] bucket counts."""
raw = self.hparams.get("engram_layer_head_vocab_sizes") or {}
n_gram = self.hparams["engram_max_ngram_size"]
n_head = self.hparams["engram_n_head_per_ngram"]
out = {}
for i in self._engram_ids():
# the keys are strings in the config
groups = raw.get(str(i)) or raw.get(i)
if groups is None:
raise ValueError(f"HY_V4_FLASH engram_layer_head_vocab_sizes has no entry for layer {i}")
if len(groups) != n_gram - 1 or any(len(g) != n_head for g in groups):
raise ValueError(
f"HY_V4_FLASH engram layer {i}: expected {n_gram - 1} groups of {n_head} bucket "
f"counts, got {[len(g) for g in groups]}")
out[i] = [int(p) for g in groups for p in g]
return out
def _engram_lookup_names(self) -> list[str]:
"""The lookup_table tensor of every Engram layer, empty when the checkpoint carries the npz instead."""
names = [f"model.layers.{i - 1}.engram_layer.{self.ENGRAM_LOOKUP_TABLE}" for i in self._engram_ids()]
present = [n for n in names if n in self.model_tensors]
if present and len(present) != len(names):
raise ValueError(f"HY_V4_FLASH engram is missing the lookup table of {sorted(set(names) - set(present))}")
return present
def _engram_vocab_map(self) -> tuple[list[int], int]:
"""The token -> compressed id map, extended by identity as the reference does, and the compressed vocab size."""
names = self._engram_lookup_names()
if names:
table = LazyTorchTensor.to_eager(self.model_tensors[names[0]]()).numpy().astype(np.int64)
for other in names[1:]:
if not np.array_equal(LazyTorchTensor.to_eager(self.model_tensors[other]()).numpy().astype(np.int64), table):
raise ValueError(f"HY_V4_FLASH engram lookup table of {other} differs from {names[0]}")
# the map is onto a dense id range from 0, so its largest id gives the compressed vocab size
compressed = int(table.max()) + 1
if int(table.min()) != 0 or len(np.unique(table)) != compressed:
raise ValueError("HY_V4_FLASH engram lookup table is not a dense id range from 0, supply engram_vocab_map.npz")
else:
path = Path(self.dir_model) / "engram_vocab_map.npz"
if not path.is_file():
raise FileNotFoundError(f"HY_V4_FLASH engram needs a lookup_table tensor or {path}")
with np.load(path) as z:
table = z["lookup_table"].astype(np.int64)
meta = json.loads(bytes(z["metadata"]).decode("utf-8").rstrip("\x00"))
compressed = int(meta["compressed_vocab_size"])
if int(table.max()) + 1 > compressed:
raise ValueError("HY_V4_FLASH engram lookup table exceeds its compressed vocab size")
if int(meta["engram_seed"]) != int(self.hparams.get("engram_seed", 0)):
raise ValueError("HY_V4_FLASH engram seed disagrees between the config and the vocab map")
n_vocab = self.hparams["vocab_size"]
token_map = list(map(int, table))
token_map += list(range(len(token_map), n_vocab))
return token_map, compressed
def _engram_multipliers(self, layer_id: int, compressed: int) -> list[int]:
seed = int(self.hparams.get("engram_seed", 0))
n_gram = self.hparams["engram_max_ngram_size"]
bound = max(1, (np.iinfo(np.int64).max // compressed) // 2)
rng = np.random.default_rng(seed + ENGRAM_SEED_STRIDE * layer_id)
return [int(m) for m in rng.integers(0, bound, size=n_gram) * 2 + 1]
def _engram_set_gguf_parameters(self):
hparams = self.hparams
ids = self._engram_ids()
primes = self._engram_primes()
token_map, compressed = self._engram_vocab_map()
n_gram = hparams["engram_max_ngram_size"]
n_head = hparams["engram_n_head_per_ngram"]
head_dim, rem = divmod(hparams["engram_n_embed_per_ngram"], n_head)
if rem:
raise ValueError("HY_V4_FLASH engram_n_embed_per_ngram is not a multiple of the head count")
# rebase each module's buckets into the shared table, row ids are int32
offsets: list[int] = []
multipliers: list[int] = []
base = 0
for i in ids:
for p in primes[i]:
offsets.append(base)
base += p
multipliers += self._engram_multipliers(i, compressed)
if base > np.iinfo(np.int32).max:
raise ValueError(f"HY_V4_FLASH engram table needs {base} rows, past the int32 row id limit")
w = self.gguf_writer
w.add_ple_layers([i - 1 for i in ids])
w.add_ple_ngram_size(n_gram)
w.add_ple_heads_per_ngram(n_head)
w.add_embedding_length_per_layer_input(head_dim)
w.add_ple_layer_multipliers(multipliers)
w.add_ple_head_offsets(offsets)
w.add_ple_head_vocab_sizes([p for i in ids for p in primes[i]])
w.add_engram_pad_token_id(hparams["engram_pad_id"])
w.add_engram_token_map(token_map)
logger.info(
"HY_V4_FLASH engram: %d module(s) at 0-based layers %s, %d-gram x %d heads x %d dims, "
"%d table rows, compressed vocab %d",
len(ids), [i - 1 for i in ids], n_gram, n_head, head_dim, base, compressed)
def _n_nextn(self) -> int:
return int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
def _layer_type_of(self, bid: int) -> str:
"""Layer type of any block, draft blocks included. Only sparse draft blocks are supported."""
n_layer = self.hparams["num_hidden_layers"]
if bid < n_layer:
return self._layer_types()[bid]
types = self.hparams.get("mtp_layer_types") or []
if not types:
return "sparse_attention"
t = types[min(bid - n_layer, len(types) - 1)]
if t != "sparse_attention":
raise ValueError(
f"HY_V4_FLASH: mtp_layer_types gives {t!r} for draft block {bid}, "
"but only 'sparse_attention' draft blocks are supported")
return t
def _write_rope_sections(self, sparse_rope: dict, window_rope: dict):
"""Write the M-RoPE sections of the VL checkpoints. Text-only files keep the loader default."""
sections = sparse_rope.get("mrope_section")
if sections is None:
return
if window_rope.get("mrope_section") != sections:
raise ValueError(
f"HY_V4_FLASH needs one mrope_section for both layer types, but "
f"{window_rope.get('mrope_section')} != {sections}")
if not sparse_rope.get("mrope_interleaved", False):
raise NotImplementedError("HY_V4_FLASH expects mrope_interleaved = true")
rope_dim = self.hparams["qk_rope_head_dim"]
if len(sections) != 3 or 2 * sum(sections) != rope_dim:
raise ValueError(f"HY_V4_FLASH mrope_section {sections} must sum to qk_rope_head_dim / 2")
self.gguf_writer.add_rope_dimension_sections(list(sections) + [0])
def _rope_for(self, layer_type: str) -> dict:
params = self.hparams.get("rope_parameters")
names = self.SPARSE_TYPES if layer_type == "sparse_attention" else (layer_type,)
found = [params[n] for n in names if isinstance(params, dict) and n in params]
if not found:
raise ValueError(f"HY_V4_FLASH needs rope_parameters[{layer_type!r}]")
if any(f != found[0] for f in found[1:]):
raise ValueError(f"HY_V4_FLASH has conflicting rope_parameters for {names}")
return found[0]
def set_gguf_parameters(self):
hparams = self.hparams
layer_types = self._layer_types()
is_swa = [t == "sliding_attention" for t in layer_types]
if not any(is_swa) or all(is_swa):
raise ValueError("HY_V4_FLASH expects a mix of sparse and sliding attention layers")
# the graph always applies the sandwich post-norms
if not hparams.get("sandwich_norm", False):
raise ValueError("HY_V4_FLASH expects sandwich_norm, the graph always applies the post-norms")
if hparams.get("dsa_skip_attn_post_norm", False):
raise ValueError(
"HY_V4_FLASH: dsa_skip_attn_post_norm is not supported - the graph applies "
"attn_post_norm on the sparse layers too")
# the non-sliding rope entry is keyed "sparse_attention", not "full_attention" as the base expects
sparse_rope = self._rope_for("sparse_attention")
window_rope = self._rope_for("sliding_attention")
# hide the key from hy_v4, which warns that it drops the draft block
n_nextn = self.hparams.pop("num_nextn_predict_layers", None)
try:
super().set_gguf_parameters()
finally:
if n_nextn is not None:
self.hparams["num_nextn_predict_layers"] = n_nextn
self.gguf_writer.add_rope_freq_base(sparse_rope["rope_theta"])
# the graph reorders the rope rows itself, so the sections only say how to split them
self._write_rope_sections(sparse_rope, window_rope)
# per-layer head count: the window layers carry swa_num_attention_heads
n_head = hparams["num_attention_heads"]
n_head_swa = hparams["swa_num_attention_heads"]
self.gguf_writer.remove_key(
gguf.Keys.Attention.HEAD_COUNT.format(arch=self.gguf_writer.arch))
# the arrays cover n_layer_all, the draft block is a sparse layer
is_swa_all = is_swa + [False] * (0 if getattr(self, "no_mtp", False) else self._n_nextn())
self.gguf_writer.add_head_count(
[n_head_swa if swa else n_head for swa in is_swa_all])
# the base already derives rope.freq_base_swa from rope_parameters["sliding_attention"]
self.gguf_writer.add_sliding_window(hparams["sliding_window"])
self.gguf_writer.add_sliding_window_pattern(is_swa_all)
# routed experts run here, the router and the shared expert stay at hidden_size
latent = hparams.get("routed_expert_hidden_size")
if latent:
self.gguf_writer.add_expert_latent_length(latent)
if self._n_nextn() and not getattr(self, "no_mtp", False):
self.gguf_writer.add_nextn_predict_layers(self._n_nextn())
if self._indexer_enabled():
# the pool size is compress_ratio, and the current group is always kept
ratio = hparams["compressed_indexer_compress_ratio"]
self.gguf_writer.add_indexer_kpool(ratio)
self.gguf_writer.add_indexer_kpool_select_tail(True)
# same check as the reference
group_topk = hparams.get("compressed_indexer_group_topk")
candidate = hparams.get("compressed_indexer_candidate_topk")
if group_topk and candidate and group_topk * ratio != candidate:
raise ValueError(
f"HY_V4_FLASH indexer: candidate_topk {candidate} != "
f"group_topk {group_topk} x compress_ratio {ratio}")
if hparams["index_topk"] % ratio:
raise ValueError(
f"HY_V4_FLASH indexer: index_topk {hparams['index_topk']} is not a multiple "
f"of compress_ratio {ratio}")
is_full = self.indexer_is_full() or []
logger.info(
"HY_V4_FLASH indexer: %d pooled groups of %d, keeping the best %d plus the current group (index_topk %d)",
sum(is_full), ratio, hparams["index_topk"] // ratio, hparams["index_topk"])
if self._engram_enabled():
self._engram_set_gguf_parameters()
self._check_mla_geometry()
logger.info(
"HY_V4_FLASH: %d sparse (%d heads, rope_theta %g) + %d sliding "
"(%d heads, rope_theta %g, window %d) layers",
is_swa.count(False), n_head, sparse_rope["rope_theta"],
is_swa.count(True), n_head_swa, window_rope["rope_theta"],
hparams["sliding_window"],
)
if hparams.get("engram_layer_ids") and not self._engram_enabled():
logger.warning(
"HY_V4_FLASH: engram_enable is off, dropping %d Engram layer(s)",
len(hparams["engram_layer_ids"]))
if hparams.get("use_compressed_indexer") and not self._indexer_enabled():
logger.warning(
"HY_V4_FLASH: dropping the compressed indexer - the sparse layers will "
"attend their whole context instead of the top %s tokens",
hparams.get("index_topk"),
)
def _check_mla_geometry(self):
"""Both layer types must share one MLA geometry, only the head count may differ."""
hparams = self.hparams
for sparse_key, window_key in (
("qk_nope_head_dim", "swa_qk_nope_head_dim"),
("qk_rope_head_dim", "swa_qk_rope_head_dim"),
("v_head_dim", "swa_v_head_dim"),
("qk_head_dim", "swa_qk_head_dim"),
("kv_lora_rank", "swa_kv_lora_rank"),
):
if window_key not in hparams:
continue
if hparams[window_key] != hparams[sparse_key]:
raise NotImplementedError(
f"HY_V4_FLASH needs one MLA geometry for both layer types, but "
f"{window_key}={hparams[window_key]} != {sparse_key}={hparams[sparse_key]}"
)
def _indexer_enabled(self) -> bool:
return bool(self.hparams.get("use_dsa")) and bool(self.hparams.get("use_compressed_indexer"))
def indexer_is_full(self) -> list[bool] | None:
"""Which layers own a k-pool indexer: the sparse ones. The config indexer_types marks every layer."""
if not self._indexer_enabled():
return None
n_all = self.hparams["num_hidden_layers"] + self._n_nextn()
return [self._layer_type_of(i) == "sparse_attention" for i in range(n_all)]
def prepare_tensors(self):
"""Check the compressed_indexer tensors instead of hy_v4's self_attn.indexer ones."""
self.hparams["num_key_value_heads"] = self.hparams["num_attention_heads"]
is_full = self.indexer_is_full()
if is_full is not None:
want = set(self.INDEXER_MAP)
n_layer = self.hparams["num_hidden_layers"]
present: dict[int, set[str]] = {}
for name in self.model_tensors:
head, sep, tail = name.partition(".self_attn.compressed_indexer.")
if not sep:
continue
# the draft block carries its own indexer, under a different prefix
if head.startswith("model.layers."):
present.setdefault(int(head.split(".")[2]), set()).add(tail)
elif head.startswith("model.mtp_layers."):
present.setdefault(n_layer + int(head.split(".")[2]), set()).add(tail)
for il, expect in enumerate(is_full):
seen = present.get(il, set())
if expect and seen != want:
raise ValueError(
f"HY_V4_FLASH layer {il} owns an indexer but is missing "
f"{sorted(want - seen)}" + (f" and carries unexpected {sorted(seen - want)}"
if seen - want else ""))
if not expect and seen:
raise ValueError(
f"HY_V4_FLASH layer {il} owns no indexer but carries {sorted(seen)}")
# straight to the grandparent: hy_v4's own validation does not apply here
super(HYV4Model, self).prepare_tensors()
if self._engram_enabled():
T = gguf.MODEL_TENSOR
want = {self.format_tensor_name(T.PER_LAYER_TOKEN_EMBD)}
for i in self._engram_ids():
for t in (T.ENGRAM_KV, T.ENGRAM_KV_B, T.ENGRAM_GATE, T.ENGRAM_LOOKUP_NORM, T.ENGRAM_HC_SCALE, T.ENGRAM_PRE_GAMMA):
want.add(self.format_tensor_name(t, i - 1))
if want - self._engram_done:
raise ValueError(f"HY_V4_FLASH: incomplete Engram tensors {sorted(want - self._engram_done)}")
def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int):
# ggml_add / ggml_mul operands, kept f32 as deepseek41 does for engram_gate
if new_name.endswith((".engram_gate.weight", ".engram_kv_b.weight", ".engram_hc_scale.weight")):
return gguf.GGMLQuantizationType.F32
# the pooled-key position bias is a ggml_add operand too
if new_name.endswith(".indexer_compressor_ape.weight"):
return gguf.GGMLQuantizationType.F32
# the base rule misses the router of the renumbered draft block
if new_name.endswith((".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight")):
return gguf.GGMLQuantizationType.F32
return super().tensor_force_quant(name, new_name, bid, n_dims)
def _engram_modify(self, data_torch: torch.Tensor, name: str,
bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
"""Fuse a layer's Engram weights as deepseek41 does, once all parts of a group arrived."""
if bid is None:
raise ValueError(f"HY_V4_FLASH: engram tensor without a layer id: {name}")
hc = self.hparams["hc_mult"]
n_head = self.hparams["engram_n_head_per_ngram"] * (self.hparams["engram_max_ngram_size"] - 1)
tail = name.split(".engram_layer.", 1)[1]
if tail == self.ENGRAM_LOOKUP_TABLE:
# the token map, read through _engram_vocab_map() and written as GGUF metadata
return
buf = self._engram_buf.setdefault(bid, {})
buf[tail] = data_torch
tn = self.format_tensor_name
T = gguf.MODEL_TENSOR
def ready(*names) -> bool:
return all(n in buf for n in names)
def take(*names):
return [buf.pop(n) for n in names]
# hc key projections then the value projection, the order the graph views assume
kv_parts = [f"key_projs.{c}.weight" for c in range(hc)] + ["value_proj.weight"]
if ready(*kv_parts):
yield tn(T.ENGRAM_KV, bid), torch.cat(take(*kv_parts), dim=0)
kvb_parts = [f"key_projs.{c}.bias" for c in range(hc)] + ["value_proj.bias"]
if ready(*kvb_parts):
yield tn(T.ENGRAM_KV_B, bid), torch.stack(take(*kvb_parts), dim=0)
# engram_gate folds the key and query norms, as deepseek41 does
gate_parts = [f"norm_key.{c}.weight" for c in range(hc)] + [f"norm_query.{c}.weight" for c in range(hc)]
if ready(*gate_parts):
parts = take(*gate_parts)
yield tn(T.ENGRAM_GATE, bid), torch.stack(
[parts[c] * parts[hc + c] for c in range(hc)], dim=0)
norm_parts = [f"lookup_per_head_norms.{c}.weight" for c in range(n_head)]
if ready(*norm_parts):
yield tn(T.ENGRAM_LOOKUP_NORM, bid), torch.stack(take(*norm_parts), dim=0)
scale_parts = [f"unified_per_hc_scales.{c}" for c in range(hc)]
if ready(*scale_parts):
yield tn(T.ENGRAM_HC_SCALE, bid), torch.stack(take(*scale_parts), dim=0)
if ready("unified_pre_gamma"):
yield tn(T.ENGRAM_PRE_GAMMA, bid), take("unified_pre_gamma")[0]
# the tables of all modules are concatenated in layer order
if ready("multi_head_embedding.embedding.weight"):
self._engram_tables[bid] = take("multi_head_embedding.embedding.weight")[0]
want = [i - 1 for i in self._engram_ids()]
if all(i in self._engram_tables for i in want):
self._write_engram_tables([self._engram_tables.pop(i) for i in want])
def _write_engram_tables(self, tables: list[torch.Tensor]) -> None:
# the concatenated tables are ~127 GB in BF16, so they are streamed one table at a time as deepseek41 does
f32 = self.ftype == gguf.LlamaFileType.ALL_F32
dim = tables[0].shape[1]
if any(t.shape[1] != dim for t in tables):
raise ValueError("HY_V4_FLASH engram tables differ in width")
n_rows = sum(t.shape[0] for t in tables)
def chunks() -> Iterable[np.ndarray]:
while tables:
table = LazyTorchTensor.to_eager(tables.pop(0))
for r0 in range(0, table.shape[0], 1 << 18):
# a copy, so that no chunk still held by the writer keeps the whole table alive
rows = (table[r0:r0 + (1 << 18)].float() if f32 else table[r0:r0 + (1 << 18)].bfloat16()).clone()
yield rows.view(torch.uint8).numpy()
del table, rows
qt = gguf.GGMLQuantizationType.F32 if f32 else gguf.GGMLQuantizationType.BF16
data = cast(np.ndarray, _StreamedBytes((n_rows, dim * (4 if f32 else 2)), chunks))
name = self.format_tensor_name(gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD)
self.gguf_writer.add_tensor(name, data, raw_dtype=qt)
self._engram_done.add(name)
NEXTN_MAP = {
"eh_proj.weight": gguf.MODEL_TENSOR.NEXTN_EH_PROJ,
"enorm.weight": gguf.MODEL_TENSOR.NEXTN_ENORM,
"hnorm.weight": gguf.MODEL_TENSOR.NEXTN_HNORM,
"final_layernorm.weight": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
}
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
if name.startswith("model.mtp_layers."):
if not self._n_nextn() or getattr(self, "no_mtp", False):
return
parts = name.split(".", 3)
nbid = self.hparams["num_hidden_layers"] + int(parts[2])
tail = parts[3]
key = self.NEXTN_MAP.get(tail)
if key is not None:
yield self.format_tensor_name(key, nbid), data_torch
return
# the rest of the block is an ordinary sparse layer, so re-enter under its block index
yield from self.modify_tensors(data_torch, f"model.layers.{nbid}.{tail}", nbid)
return
if ".compressed_indexer." in name:
# dropped when the indexer is off, the sparse layers then attend their whole context
if not self._indexer_enabled():
return
tail = name.split(".compressed_indexer.", 1)[1]
key = self.INDEXER_MAP.get(tail)
if key is None:
raise ValueError(f"HY_V4_FLASH: unmapped compressed_indexer tensor {name}")
# intra_group_ape [kpool, head_dim] is already ne (head_dim, kpool)
yield self.format_tensor_name(key, bid), data_torch
return
if ".engram_layer." in name:
if not self._engram_enabled():
return
for new_name, t in self._engram_modify(data_torch, name, bid):
self._engram_done.add(new_name)
yield new_name, t
return
# split kv_b_proj with the head count of this layer, the base uses a global one
if name.endswith("kv_b_proj.weight") and bid is not None:
hparams = self.hparams
n_head = (hparams["swa_num_attention_heads"]
if self._layer_type_of(bid) == "sliding_attention"
else hparams["num_attention_heads"])
v_head_dim = hparams["v_head_dim"]
qk_nope_head_dim = hparams["qk_nope_head_dim"]
expected = n_head * (v_head_dim + qk_nope_head_dim)
if data_torch.shape[0] != expected:
raise ValueError(
f"HY_V4_FLASH layer {bid}: {name} has {data_torch.shape[0]} rows, "
f"expected {expected} = {n_head} heads x ({qk_nope_head_dim} + {v_head_dim})"
)
kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1])
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
k_b = k_b.transpose(1, 2)
tn = self.format_tensor_name
yield from ModelBase.modify_tensors(self, k_b, tn(gguf.MODEL_TENSOR.ATTN_K_B, bid), bid)
yield from ModelBase.modify_tensors(self, v_b, tn(gguf.MODEL_TENSOR.ATTN_V_B, bid), bid)
return
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
class HYV4FlashVisionModel(MmprojModel):
"""Vision tower of HY_V4_FLASH: a SigLIP-shaped encoder with a rmsnorm_mlp_adapter projector.
Positions come from a learned grid, resampled to the patch grid. The projector merges 2x2 patches with a strided conv2d, runs a 1x1 conv2d and appends a newline embedding to every row.
"""
projector_type = gguf.VisionProjectorType.HY_V4_FLASH
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
assert self.hparams_vision is not None
# there is no image_size, the position-embedding grid is max_image_size / patch_size
self.hparams_vision["image_size"] = self.hparams_vision.get("max_image_size", 2048)
def set_gguf_parameters(self):
super().set_gguf_parameters()
assert self.hparams_vision is not None
vcfg = self.hparams_vision
projector_type = vcfg.get("projector_type")
if projector_type != "rmsnorm_mlp_adapter":
raise ValueError(f"unsupported projector_type {projector_type!r}")
# the graph implements the plain variant only
unsupported = {
"use_2d_rope": bool(vcfg.get("use_2d_rope", False)),
"cat_extra_token": bool(vcfg.get("cat_extra_token", False)),
"use_image_newline_token": not vcfg.get("use_image_newline_token", True),
"perceive_post_norm": bool(vcfg.get("perceive_post_norm", False)),
"hidden_act": vcfg.get("hidden_act", "gelu") != "gelu",
"interpolate_mode": vcfg.get("interpolate_mode", "bilinear") != "bilinear",
}
for key, bad in unsupported.items():
if bad:
raise NotImplementedError(f"HY_V4_FLASH vision config {key}={vcfg.get(key)!r} is not supported")
self.gguf_writer.add_clip_projector_type(self.projector_type)
self.gguf_writer.add_vision_use_gelu(True)
# rms_norm_eps is also the LayerNorm eps of the encoder blocks
self.gguf_writer.add_vision_attention_layernorm_eps(vcfg.get("rms_norm_eps", 1e-5))
self.gguf_writer.add_vision_spatial_merge_size(vcfg.get("spatial_merge_size", 2))
self.gguf_writer.add_vision_min_pixels(int(self.preprocessor_config["min_pixels"]))
self.gguf_writer.add_vision_max_pixels(int(self.preprocessor_config["max_pixels"]))
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], torch.Tensor]]) -> tuple[str, Callable[[], torch.Tensor]] | None:
if not item[0].startswith("vit."):
return None
return super().filter_tensors(item)
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
# row 0 of the position embedding is an unused CLS slot, the reference resamples rows 1:
if "position_embedding" in name:
data_torch = data_torch[1:]
yield from super().modify_tensors(data_torch, name, bid)
def tensor_force_quant(self, name, new_name, bid, n_dims):
# conv weights in F32 or F16, BF16 IM2COL is not supported on Metal
if ("mm.0." in new_name or "mm.2." in new_name) and new_name.endswith(".weight"):
return gguf.GGMLQuantizationType.F16 if self.ftype == gguf.LlamaFileType.MOSTLY_F16 else gguf.GGMLQuantizationType.F32
return super().tensor_force_quant(name, new_name, bid, n_dims)
+240 -11
View File
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
return values
def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
if np.any(scales & 0x80) or np.any(scales == 0x7F):
raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
n_rows = packed.shape[0]
n_blocks = scales.shape[1]
nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
n_super = n_blocks // 4
blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
return blocks.reshape(n_rows, n_super * 36)
def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
if not w13:
return _repack_nvfp4_rows(packed, scales, name, expert)
return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
def _is_inkling2(dir_model: Path) -> bool:
if not (dir_model / "config.json").is_file():
return False
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
class Inkling2Model(TextModel):
model_arch = gguf.MODEL_ARCH.INKLING2
def __init__(self, dir_model: Path, *args, **kwargs):
def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
self._expert_quant: dict[str, dict] = {}
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
quant_path = dir_model / "hf_quant_config.json"
if quant_path.is_file():
with open(quant_path, encoding="utf-8") as f:
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
if name in self._expert_quant:
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
self._expert_quant[name] = group
super().__init__(dir_model, *args, **kwargs)
super().__init__(dir_model, ftype, *args, **kwargs)
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
hp = self.hparams
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
t = gen()
if t.dtype != torch.float32 or tuple(t.shape) != expected:
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
chunks: list[Callable[[], np.ndarray]] = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
if preserve_nvfp4 and cols % 64 != 0:
logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
preserve_nvfp4 = False
chunks: list[Callable[[], np.ndarray]]
if preserve_nvfp4:
assert amax is not None and denominator is not None
a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
if not np.isfinite(a).all() or (a < 0).any():
raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
if not np.isfinite(d).all() or (d <= 0).any():
raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
with np.errstate(over="ignore", invalid="ignore"):
outer_scale = a / d
if not np.isfinite(outer_scale).all():
raise ValueError(f"Inkling2: {name}: non-finite outer scale")
chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
byte_shape = (experts, rows, cols // 64 * 36)
self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
else:
chunks = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
if not nvfp4 and self._fp8_as_q8:
self._fp8_dequantized.add(name)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
for companion in required:
del self.model_tensors[companion]
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
t = gen()
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
self._is_nvfp4 = bool(self._native_experts)
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
@@ -248,6 +294,22 @@ class Inkling2Model(TextModel):
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
# PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention
# output gate (self_attn.o_proj.gate_proj.weight); neither is in the tensor map.
name = name.replace(".linear.", ".")
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._native_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
packed, scale = self._native_experts[name]
shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
@@ -329,6 +391,173 @@ class Inkling2LoopModel(Inkling2Model):
yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query
def _fold_markov_chunk(unembed: Callable[[], Tensor], weight: Tensor | None, bias: Tensor | None, rows: slice) -> np.ndarray:
head = LazyTorchTensor.to_eager(unembed()[rows]).double()
out = head @ weight if weight is not None else head @ bias
return out.float().numpy()
class Inkling2DSparkModel(Inkling2Model):
"""Inkling2 DSpark draft (mtp.safetensors) as a DFLASH GGUF, export with --dspark"""
model_arch = gguf.MODEL_ARCH.DFLASH
_TARGET = {
"model.llm.unembed.weight": "target.unembed",
"model.language_model.unembed.weight": "target.unembed",
"lm_head.weight": "target.unembed",
"model.llm.embed_norm.weight": "target.embed_norm",
"model.language_model.embed_norm.weight": "target.embed_norm",
"model.language_model.embed_tokens.embed_norm.weight": "target.embed_norm",
}
_LAYER = {
"self_attn.k_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX,
"self_attn.v_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_V_CTX,
"self_attn.k_norm_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX_NORM,
"dflare_norm.weight": gguf.MODEL_TENSOR.DFLASH_CTX_NORM,
}
_ROOT = {
"target.embed_norm": gguf.MODEL_TENSOR.TOKEN_EMBD_NORM,
"mtp.norm.weight": gguf.MODEL_TENSOR.OUTPUT_NORM,
"mtp.markov_head.markov_w1.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_W1,
"mtp.markov_head.rnn_proj.weight": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ,
"mtp.markov_head.rnn_proj.bias": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ,
"mtp.markov_head.dflare_norm.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM,
}
def __init__(self, *args, **kwargs):
self._folded: dict[str, gguf.LazyChunkedTensor] = {}
super().__init__(*args, **kwargs)
hp = self.hparams
mtp = hp.get("mtp_config")
if not mtp:
raise ValueError("Inkling2 DSpark export needs the mtp_config")
if mtp.get("markov_head_type") != "rnn_hidden" or mtp.get("q_bias") or mtp.get("o_bias") or mtp["hidden_size"] != hp["hidden_size"]:
raise ValueError(f"Inkling2 DSpark: unsupported mtp_config {mtp}")
# ids count loop passes, the last id is the final norm output
n_visits = self.block_count
if (loop := hp.get("loop_config")) is not None:
n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
targets = mtp["target_layer_ids"]
if len(targets) < 2 or targets != sorted(set(targets)) or targets[-1] != n_visits:
raise ValueError(f"Inkling2 DSpark: target_layer_ids {targets} must be sorted and end at {n_visits}")
self.mtp = mtp
self.block_count = mtp["num_hidden_layers"]
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
if remote_hf_model_id is not None:
raise NotImplementedError("Inkling2 DSpark export needs a local checkpoint")
# mtp.safetensors is not in the weight map, unembed and embed_norm come from the target
tensors = self.index_local_tensors("mtp")
tensors.update(self.index_local_tensors("model"))
return tensors
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
name, gen = item
if name in cls._TARGET:
return cls._TARGET[name], gen
if name.startswith(("model.", "lm_head.")):
return None
if name.startswith("layers."):
return f"model.{name}", gen
return f"mtp.{name}", gen
def dequant_model(self):
super().dequant_model()
if "target.unembed" not in self.model_tensors:
raise ValueError("Inkling2 DSpark: missing the target unembed")
unembed = self.model_tensors.pop("target.unembed")
weight = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.weight")()).double()
bias = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.bias")()).double()
n_vocab, n_embd = unembed().shape
if weight.shape[0] != n_embd or bias.shape != (n_embd,):
raise ValueError(f"Inkling2 DSpark: hidden_out {tuple(weight.shape)} does not match unembed {(n_vocab, n_embd)}")
# markov_w2 = unembed @ hidden_out, fp64 like vLLM, one row chunk at a time
# padded tokens are never sampled, so keep only the tokenizer rows
n_vocab = self.hparams["unpadded_vocab_size"]
row_chunks = [slice(i, min(i + 4096, n_vocab)) for i in range(0, n_vocab, 4096)]
for name, w, b, shape in (
("mtp.markov_head.fold.weight", weight, None, (n_vocab, weight.shape[1])),
("mtp.markov_head.fold.bias", None, bias, (n_vocab,)),
):
self._folded[name] = gguf.LazyChunkedTensor([partial(_fold_markov_chunk, unembed, w, b, r) for r in row_chunks], shape, np.float32)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
def prepare_metadata(self, vocab_only: bool):
from_dir = self.fname_out.is_dir()
super().prepare_metadata(vocab_only=vocab_only)
if from_dir:
self.fname_out = self.fname_out.parent / f"dspark-{self.fname_out.name}"
def set_vocab(self):
super().set_vocab()
# block uses mask_embd, mask token id is not used
self.gguf_writer.add_mask_token_id(0)
def set_gguf_parameters(self):
hp, mtp = self.hparams, self.mtp
n = self.block_count
w = self.gguf_writer
w.add_block_count(n)
w.add_context_length(mtp["max_position_embeddings"])
w.add_embedding_length(mtp["hidden_size"])
w.add_feed_forward_length(mtp["intermediate_size"])
w.add_head_count(mtp["num_attention_heads"])
w.add_head_count_kv(mtp["num_key_value_heads"])
w.add_key_length(mtp["head_dim"])
w.add_value_length(mtp["head_dim"])
w.add_rope_dimension_count(mtp["head_dim"])
w.add_rope_freq_base(float(mtp["rope_theta"]))
w.add_layer_norm_rms_eps(mtp["rms_norm_eps"])
# the block sees W positions before the anchor, llama.cpp SWA sees n_swa - 1
w.add_sliding_window(mtp["sliding_window_size"] + 1)
w.add_sliding_window_pattern([i in mtp["local_layer_ids"] for i in range(n)])
w.add_final_logit_softcapping(hp["final_logit_softcapping"])
w.add_block_size(mtp["block_size"])
w.add_target_layers(mtp["target_layer_ids"])
# slot 0 is the anchor, it does not predict a token
w.add_sample_from_anchor(False)
w.add_has_confidence_head(False)
w.add_has_markov_context(mtp["markov_head_type"] == "rnn_hidden")
w.add_file_type(self.ftype)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
if name in self._folded:
suffix = ".bias" if name.endswith(".bias") else ".weight"
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_W2, None, suffix), cast("Tensor", self._folded[name])
return
if name == "mtp.markov_head.markov_w1.weight":
data_torch = data_torch[:self.hparams["unpadded_vocab_size"]]
if name in self._ROOT:
suffix = ".bias" if name.endswith(".bias") else ".weight"
yield self.format_tensor_name(self._ROOT[name], None, suffix), data_torch
return
if name == "mtp.fuse_weight":
if tuple(data_torch.shape) != (self.block_count + 1, len(self.mtp["target_layer_ids"])):
raise ValueError(f"Inkling2 DSpark: unexpected fuse_weight shape {tuple(data_torch.shape)}")
# one row per draft layer, the last row is for the markov head
alpha = torch.softmax(data_torch.float(), dim=-1)
for i in range(self.block_count):
yield self.format_tensor_name(gguf.MODEL_TENSOR.DFLASH_CTX_MIX, i), alpha[i]
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_MIX), alpha[-1]
return
if name == "mtp.mask_embed":
# copy the one mask embedding to each mask slot
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MASK_EMBD), data_torch.unsqueeze(0).expand(self.mtp["block_size"] - 1, -1).contiguous()
return
if name.startswith("mtp."):
raise ValueError(f"Inkling2 DSpark: unexpected tensor {name!r}")
assert bid is not None
key = name.removeprefix(f"model.layers.{bid}.")
if key in self._LAYER:
yield self.format_tensor_name(self._LAYER[key], bid), data_torch
return
yield from TextModel.modify_tensors(self, data_torch, name, bid)
@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration")
class Inkling2VisionModel(MmprojModel):
def get_vision_config(self):
+12
View File
@@ -181,6 +181,18 @@ class LlamaModel(TextModel):
.swapaxes(1, 2)
.reshape(weights.shape))
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is not LlamaModel.modify_tensors:
return None
if self.undo_permute:
n_head = self.find_hparam(["n_heads", "num_attention_heads"])
n_kv_head = self.find_hparam(["n_kv_heads", "num_key_value_heads"])
if name.endswith("q_proj.weight"):
scale = self.permute(scale, n_head, n_head)
elif name.endswith("k_proj.weight"):
scale = self.permute(scale, n_head, n_kv_head)
return (scale,)
def _repack_nvfp4(self, name: str, weight: Tensor, scale: Tensor, scale2: Tensor, input_scale: Tensor):
# Mirror the BF16 Q/K RoPE permutation site in modify_tensors; the NVFP4 path bypasses it.
if self.undo_permute:
+93 -41
View File
@@ -58,6 +58,11 @@ class QwenModel(TextModel):
class Qwen2Model(TextModel):
model_arch = gguf.MODEL_ARCH.QWEN2
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is Qwen2Model.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def set_vocab(self):
# HuggingFaceBio/Carbon-14B: Qwen3 with the HybridDNATokenizer (Qwen3 BPE plus DNA 6-mers)
if self._is_hybriddna():
@@ -92,6 +97,11 @@ class Qwen2MoeModel(TextModel):
)
return super()._map_fp8_weight_names(name)
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is Qwen2MoeModel.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def set_gguf_parameters(self):
super().set_gguf_parameters()
if (moe_intermediate_size := self.hparams.get("moe_intermediate_size")) is not None:
@@ -395,13 +405,50 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
def _map_fp8_weight_names(self, name: str) -> tuple[str, ...]:
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
bid = next(int(part) for part in self.map_tensor_name(name).split(".") if part.isdecimal())
# Both split projections keep the original per-tensor scales.
return (
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid),
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid),
)
return super()._map_fp8_weight_names(name)
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is not Qwen3NextModel.modify_tensors:
return None
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
return self._split_qkvz(scale)
if len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def _split_qkvz(self, data_torch: Tensor) -> tuple[Tensor, Tensor]:
# original order: [q, k, v, z] * head_count
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
head_k_dim = self.hparams["linear_key_head_dim"]
head_v_dim = self.hparams["linear_value_head_dim"]
num_v_heads = self.hparams["linear_num_value_heads"]
num_k_heads = self.hparams["linear_num_key_heads"]
hidden_size = data_torch.shape[1]
split_arg_list_qkvz = [
head_k_dim, # q partition
head_k_dim, # k partition
(num_v_heads // num_k_heads * head_v_dim), # v partition
(num_v_heads // num_k_heads * head_v_dim), # z partition
]
# view as (n_embd, head_count, [q+k+v+z])
data_torch = data_torch.permute(1, 0).contiguous()
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
# split into q, k, v, z
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
# flatten dim + head_count
q = q.contiguous().view(hidden_size, -1)
k = k.contiguous().view(hidden_size, -1)
v = v.contiguous().view(hidden_size, -1)
z = z.contiguous().view(hidden_size, -1)
# stack back
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
z = z.permute(1, 0).contiguous()
return qkv, z
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_ssm_conv_kernel(self.hparams["linear_conv_kernel_dim"])
@@ -432,32 +479,7 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
data_torch = data_torch + 1
if "in_proj_qkvz.weight" in name:
# original order: [q, k, v, z] * head_count
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
head_k_dim = self.hparams["linear_key_head_dim"]
head_v_dim = self.hparams["linear_value_head_dim"]
num_v_heads = self.hparams["linear_num_value_heads"]
num_k_heads = self.hparams["linear_num_key_heads"]
hidden_size = self.hparams["hidden_size"]
split_arg_list_qkvz = [
head_k_dim, # q partition
head_k_dim, # k partition
(num_v_heads // num_k_heads * head_v_dim), # v partition
(num_v_heads // num_k_heads * head_v_dim), # z partition
]
# view as (n_embd, head_count, [q+k+v+z])
data_torch = data_torch.permute(1, 0).contiguous()
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
# split into q, k, v, z
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
# flatten dim + head_count
q = q.contiguous().view(hidden_size, -1)
k = k.contiguous().view(hidden_size, -1)
v = v.contiguous().view(hidden_size, -1)
z = z.contiguous().view(hidden_size, -1)
# stack back
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
z = z.permute(1, 0).contiguous()
qkv, z = self._split_qkvz(data_torch)
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid, ".weight"), qkv)
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid, ".weight"), z)
else:
@@ -868,6 +890,22 @@ class Qwen3_5MoeTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
class DFlashModel(Qwen3Model):
model_arch = gguf.MODEL_ARCH.DFLASH
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._target_is_inkling2 = False
if self.target_model_dir is not None:
target_hparams = ModelBase.load_hparams(self.target_model_dir, False)
self._target_is_inkling2 = get_model_architecture(target_hparams, ModelType.TEXT).startswith("Inkling2")
if self._target_is_inkling2:
# the target GGUF keeps only the tokenizer rows of the padded vocab
target_hparams = {**target_hparams, **target_hparams.get("text_config", {})}
self.hparams["vocab_size"] = target_hparams["unpadded_vocab_size"]
self.hparams["eos_token_id"] = target_hparams["eos_token_id"]
# the loop core runs num_passes times, other looping targets need their own visit count
self._target_n_visits = target_hparams["num_hidden_layers"]
if (loop := target_hparams.get("loop_config")) is not None:
self._target_n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
def set_vocab(self):
if self.target_model_dir is None:
raise ValueError(
@@ -917,6 +955,11 @@ class DFlashModel(Qwen3Model):
self.gguf_writer.add_conv_group_size(int(dflash_config["conv_group_size"]))
self.gguf_writer.add_selector_rank(int(dflash_config["selector_rank"]))
self.gguf_writer.add_selector_top_k(int(dflash_config["selector_top_k"]))
softcap_mode = dflash_config.get("selector_softcap_mode", "before_correction")
if softcap_mode not in ("before_correction", "after_correction"):
raise ValueError(f"DFlash2: unknown selector_softcap_mode {softcap_mode!r}")
if softcap_mode == "after_correction":
self.gguf_writer.add_selector_softcap_after_correction(True)
output_multiplier = dflash_config.get(
"output_multiplier", self.hparams.get("output_multiplier")
@@ -942,7 +985,10 @@ class DFlashModel(Qwen3Model):
target_layer_ids = dflash_config.get("target_layer_ids", self.hparams.get("target_layer_ids", []))
if target_layer_ids:
extract_layer_ids = [i + 1 for i in target_layer_ids]
# Inkling ids count loop visits, the last one is the final norm output
if self._target_is_inkling2 and target_layer_ids[-1] != self._target_n_visits:
raise ValueError(f"Inkling2 DFlash2: target_layer_ids {target_layer_ids} must end at the Inkling final norm ({self._target_n_visits})")
extract_layer_ids = target_layer_ids if self._target_is_inkling2 else [i + 1 for i in target_layer_ids]
self.gguf_writer.add_target_layers(extract_layer_ids)
use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False)
@@ -969,19 +1015,6 @@ class DFlashModel(Qwen3Model):
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
yield from super().generate_extra_tensors()
mask_path = self.dir_model / "mask_embedding.pt"
if not mask_path.is_file():
return
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
if mask_id is None or mask["mask_token_id"] != mask_id:
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
if not 0 <= mask_id < self.hparams["vocab_size"]:
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
def target_tensor(name: str) -> Tensor:
if self.target_model_dir is None:
raise ValueError("mask_embedding.pt requires --target-model-dir with the target embeddings and output head")
@@ -999,6 +1032,23 @@ class DFlashModel(Qwen3Model):
return LazyTorchTensor.from_local_tensor(part[name])
raise ValueError(f"Target tensor {name!r} was not found in safetensors")
if self._target_is_inkling2:
# the draft borrows the raw target embeddings, Inkling norms them before its first layer
yield "model.embed_norm.weight", target_tensor("model.llm.embed_norm.weight")
mask_path = self.dir_model / "mask_embedding.pt"
if not mask_path.is_file():
return
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
if mask_id is None or mask["mask_token_id"] != mask_id:
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
if not 0 <= mask_id < self.hparams["vocab_size"]:
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
embedding_name = "model.embed_tokens.weight"
if embedding_name in self.model_tensors:
embeddings = self.model_tensors.pop(embedding_name)()
@@ -1061,6 +1111,8 @@ class DFlashModel(Qwen3Model):
"model.candidate_selector.predecessor_codebook",
"model.candidate_selector.successor_codebook",
):
# padded vocabs (Inkling): the selector only indexes the draft vocab
data_torch = data_torch[:self.hparams["vocab_size"]]
name += ".weight"
yield from super().modify_tensors(data_torch, name, bid)
+1 -1
View File
@@ -209,7 +209,7 @@ class Qwen3OmniMmprojModel(Qwen3VLVisionModel, Qwen25AudioModel):
if not self.has_vision_encoder:
raise ValueError(f"Model does not have vision encoder, but found tensor {name}")
# need to transform vision tensor naming, so that modify_tensors() logic can be used correctly
name = name.replace("thinker.visual.", "model.visual.")
name = name.replace("thinker.visual.", "visual.")
if ".merger_list." in name:
name = name.replace(".merger_list.", ".deepstack_merger_list.")
name = name.replace(".ln_q", ".norm")
+6
View File
@@ -54,6 +54,12 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
self._ple_scale = float(scale[0])
super().dequant_model()
def _has_fp8_source_scale(self, name: str) -> bool:
if ".ngram_embedding.shard_" in name:
prefix = name.split(".ngram_embedding.shard_")[0]
return prefix + ".ngram_embedding.weight_scale" in self.model_tensors or self._ple_scale is not None
return super()._has_fp8_source_scale(name)
@classmethod
def filter_tensors(cls, item):
name, gen = item
+206
View File
@@ -0,0 +1,206 @@
from __future__ import annotations
from typing import Any, Callable, Iterable
import torch
from torch import Tensor
from .base import ModelBase, TextModel, gguf
_REQUIRED = object()
def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any:
# the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error
values = [config[key] for key in (new, old) if config.get(key) is not None]
if len(values) == 2 and values[0] != values[1]:
raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}")
if values:
return values[0]
if default is _REQUIRED:
raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})")
return default
def _rda_config(hp: dict[str, Any]) -> dict[str, Any]:
# rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers
if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None:
raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config")
config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"]
result = {
"num_heads": config["num_heads"],
"head_dim": config["head_dim"],
"conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"),
"full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"),
"mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"),
"rda_layers": _renamed_key(config, "rda_layers", "kda_layers"),
}
# absent and null differ here (see set_gguf_parameters), so the key is copied only when present
if "gate_lower_bound" in config:
result["gate_lower_bound"] = config["gate_lower_bound"]
return result
@ModelBase.register("Raon1MiniForCausalLM")
@ModelBase.example("KRAFTON/Raon-1-mini-preview")
class Raon1MiniModel(TextModel):
model_arch = gguf.MODEL_ARCH.RAON1_MINI
# mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale
_MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN"))
_MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z",
"alpha_pre", "alpha_post", "res.alpha_z", "res.eta")
# Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0.
_KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda")
_KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._experts: dict[tuple[int, str], dict[int, Tensor]] = {}
self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {}
self._rda_layers = set(_rda_config(self.hparams)["rda_layers"])
def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
filtered = super().filter_tensors(item)
if filtered is None:
return None
name, _ = filtered
if name.startswith("model.layers."):
layer = name.split(".", 3)[2]
# MTP layers follow the main model layers.
if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]:
return None
return filtered
def set_gguf_parameters(self):
hp = self.hparams
rda_config = _rda_config(hp)
n_layer = hp["num_hidden_layers"]
# 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers)
rda = self._rda_layers
mla = set(rda_config["mla_layers"])
if rda & mla or rda | mla != set(range(1, n_layer + 1)):
raise ValueError("Raon-1 mini attention layer lists must partition all layers")
# the hybrid memory needs both layer kinds
if not rda or not mla:
raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer")
if hp.get("tie_word_embeddings"):
raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)")
if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"]
or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ"
or hp["moe_router_activation_func"] != "sigmoid"
or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size")
or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1):
raise ValueError("Unsupported Raon-1 mini architecture variant")
if rda_config["num_heads"] != hp["num_attention_heads"]:
raise ValueError("Raon-1 mini RDA and MLA head counts must match")
super().set_gguf_parameters()
self.gguf_writer.add_vocab_size(hp["vocab_size"])
self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)])
self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"])
# the .get() defaults below are the HF config defaults
self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128))
self.gguf_writer.add_kda_head_dim(rda_config["head_dim"])
# HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate
if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None:
self.gguf_writer.add_kda_gate_lower_bound(bound)
self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"])
self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"])
self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"])
self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length(hp["kv_lora_rank"])
self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length_mla(hp["v_head_dim"])
self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6))
self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"])
self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"])
self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"])
self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"])
self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"])
self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"])
self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"])
self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4))
self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5))
self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0))
def prepare_tensors(self):
super().prepare_tensors()
if self._experts or self._mhc:
raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}")
def tensor_force_quant(self, name, new_name, bid, n_dims):
if ".hc_" in new_name and not new_name.endswith("_fn.weight"):
return gguf.GGMLQuantizationType.F32
quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0)
if self.ftype in quantized and new_name.startswith("blk."):
keep = self._KEEP_UNQUANTIZED
if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0:
keep += self._KEEP_UNQUANTIZED_Q8_0
if new_name.split(".")[2] in keep:
return gguf.GGMLQuantizationType.F16
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
for site, prefix in self._MHC_SITES:
marker = f".{site}."
if marker not in name:
continue
assert bid is not None
parts = self._mhc.setdefault((bid, site), {})
suffix = name.split(marker, 1)[1]
if suffix in parts:
raise ValueError(f"Duplicate tensor {name}")
parts[suffix] = data_torch
if len(parts) < len(self._MHC_PARTS):
return
fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")])
base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")])
scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")])
for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)):
yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid)
del self._mhc[(bid, site)]
return
# moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3}
if ".moe.experts." in name or ".block_sparse_moe.experts." in name:
assert bid is not None
tail = name.split(".experts.", 1)[1].split(".")
eid, wid = int(tail[0]), tail[1]
group = self._experts.setdefault((bid, wid), {})
if eid in group or not 0 <= eid < self.hparams["num_experts"]:
raise ValueError(f"Invalid expert tensor {name}")
group[eid] = data_torch
if len(group) == self.hparams["num_experts"]:
tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP,
"up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP,
"w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid]
yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid)
del self._experts[(bid, wid)]
return
if name.endswith("kv_b_proj.weight"):
n_head = self.hparams["num_attention_heads"]
qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"]
kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"])
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid)
yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid)
return
if name.endswith(".self_attn.g_proj.weight"):
assert bid is not None
rda = bid + 1 in self._rda_layers
tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE
yield self.format_tensor_name(tid, bid), data_torch
return
if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")):
data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1])
if name.endswith(".A_log"):
data_torch = -torch.exp(data_torch.float())
# dt_bias -> the name SSM_DT's mapping expects, as for qwen3next
if name.endswith(".dt_bias"):
name = name.removesuffix(".dt_bias") + ".dt_proj.bias"
yield from super().modify_tensors(data_torch, name, bid)
+5 -2
View File
@@ -136,7 +136,7 @@ def parse_args() -> argparse.Namespace:
)
parser.add_argument(
"--dspark", action="store_true",
help="Export only the DeepSeek-V4 or Mistral Large 4 DSpark draft tensors as a separate GGUF.",
help="Export only the DeepSeek-V4, Mistral Large 4 or Inkling 2 DSpark draft tensors as a separate GGUF.",
)
parser.add_argument(
"--mistral-format", action="store_true",
@@ -289,8 +289,11 @@ def main() -> None:
sys.exit(1)
from conversion.mistral4 import MistralLarge4DSparkModel
model_class = MistralLarge4DSparkModel
elif model_architecture in ("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM", "Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM"):
from conversion.inkling2 import Inkling2DSparkModel
model_class = Inkling2DSparkModel
elif model_architecture not in ("DeepseekV4ForCausalLM", "DeepseekV41ForCausalLM"):
logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM and Mistral Large 4")
logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM, Mistral Large 4 and Inkling 2")
sys.exit(1)
elif model_architecture == "DeepseekV41ForCausalLM":
from conversion.deepseek41 import DeepseekV41DSparkModel
+1
View File
@@ -169,6 +169,7 @@ models = [
{"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", },
{"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", },
{"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", },
{"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", },
]
# some models are known to be broken upstream, so we will skip them as exceptions
+16 -8
View File
@@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF
A prebuilt binary kernel library has been introduced for Adreno GPUs.
It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC.
The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4.
The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
Its use is subject to the license in the `license.txt` file shipped with it.
To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake.
Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables.
The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`).
On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`).
The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables.
If the download fails, configuration continues with a warning.
To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself.
If kernels compatible with the current GPU are found in the library, they will be loaded and used.
If the library is missing, the builtin kernels are used.
Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely.
## CMake Options
The OpenCL backend has the following CMake options that control the behavior of the backend.
| CMake options | Default value | Description |
|:------------------------------------:|:--------------:|:------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. |
| CMake options | Default value | Description |
|:--------------------------------------:|:--------------:|:--------------------------------------------------------|
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. |
| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). |
## Decomposed Flash Attention
@@ -311,6 +318,7 @@ ninja
## Known Issues
- Adreno E17 compiler workarounds are disabled by default. If you encounter Flash Attention compilation failures or incorrect MoE results, set `GGML_OPENCL_ADRENO_E17_QUIRKS=1` before starting llama.cpp.
- Flash attention does not always improve performance.
- Currently OpenCL backend works on A6xx GPUs with recent drivers and compilers (usually found in IoT platforms).
However, it does not work on A6xx GPUs found in phones with old drivers and compilers.
+18 -7
View File
@@ -110,7 +110,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
**NPU:**
- All other quantized tensors are requantized to `Q4_0_128`.
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout.
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding.
- The validated models use `Q4_K_M` files.
**Layout names:**
@@ -882,7 +882,9 @@ The defaults fit most models. The variables below trade one property for another
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. |
| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. |
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which otherwise keeps the 8-bit layout of the other weights; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. |
| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. |
| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
@@ -903,10 +905,10 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation.
export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
# NPU: add the weightless bank.
# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one
# shared weights file, and logs a warning.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
# NPU, later runs (optional): use less memory. The run fails if a cached model is missing.
@@ -919,12 +921,11 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
| `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode models without weights, plus one shared weights file. Later runs read the weights from that file and keep one copy in memory. |
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1` and an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing; run once without it to build the cache. |
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. |
| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
- One directory can hold the cached models of different models and settings.
- NPU: each prefill length enters the cache in a run without `GGML_OPENVINO_SELF_CONTAINED_MMAP`.
- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length.
- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
</details>
@@ -995,6 +996,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
**GPU-specific**
- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
```bash
export GGML_OPENVINO_DEVICE=GPU
export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
mkdir -p $GGML_OPENVINO_SPILL_DIR
./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
--spec-type draft-dflash --spec-draft-n-max 4
```
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
- `-sm tensor` is not supported.
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
+3 -1
View File
@@ -44,7 +44,7 @@ The following releases are verified and recommended:
### Ubuntu 24.04
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#L713](../../.github/workflows/release.yml#L713): ubuntu-24-sycl -> Download & Install oneAPI.
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#1447](../../.github/workflows/release.yml#L1447): `ubuntu-24-sycl` -> `Download & Install oneAPI`.
It is recommended to use them with [Intel Docker](https://hub.docker.com/r/intel/deep-learning-essentials).
@@ -818,10 +818,12 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
| GGML_SYCL_ENABLE_VMM | 0 or 1 (default) | Enable the virtual-memory device pool. |
| GGML_SYCL_ENABLE_MKL_FA | 1 (default) or 0 | Enable oneMKL GEMM flash attention for XMX-accelerated prompt processing with quantized KV cache. Automatically activates during prefill (prompt processing) when all conditions are met: (1) flash-attn enabled (`-fa` or `--flash-attn on`), (2) KV cache quantized (`--cache-type-k q8_0 --cache-type-v q8_0` or other `*_0/*_1` types), (3) batch size ≥ 1024 (`--batch-size 1024`), (4) prompt length ≥ 1024 tokens. Set to 0 to force the TILE kernel for A/B testing. Example minimum command: `llama-cli -m model.gguf -fa -ngl 99 --cache-type-k q8_0 --cache-type-v q8_0 --batch-size 1024 -p "your prompt"` |
| GGML_SYCL_MKL_FA_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for MKL flash attention: GEMM/softmax timings, interleaved-head detection, and buffer memory usage. |
| GGML_SYCL_FA_TILE_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for the flash-attention TILE kernel dispatcher: head dims (DKQ/DV), GQA ratio, query rows, KV length, and whether the GQA-optimized variant is selected. |
| GGML_SYCL_MEMTRACE | 0 (default), 1, 2 | Enable record and output memory allocation diagnostics. Requires `-lv 4`. <br>0 - Disable<br>1 - Basic memory info, including current and peak allocations, as well allocations from other sources, and the device free memory before each model buffer allocation, around 50 lines per model load.<br>2 - More verbose, logging around 900 specific allocations and deallocations. |
| GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. |
| GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. |
| GGML_SYCL_ENABLE_FUSION | 0 or 1 (default) | Enable fused-kernel dispatch in graph compute. Unsupported types and layouts fall back to the standalone op kernels. See `ggml_sycl_can_fuse()`. |
| GGML_SYCL_FUSE_CONV_WINDOW | 0 or 1 (default) | Fuse four-tap recurrent convolution windows, rollback cache updates and SiLU into one kernel. Other shapes use the existing kernels. |
| GGML_SYCL_ENABLE_ESIMD | 0 or 1 (default)| Enable ESIMD kernels when available. |
| GGML_SYCL_ENABLE_XMX_ESIMD | 0 or 1 (default) | Use the XMX (DPAS) multi-column mat-vec kernels for reordered Q2_K to Q6_K and Q8_0 weights on Xe2 GPUs. Speeds up speculative decoding and short prompt batches. |
| GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. |
+40
View File
@@ -304,6 +304,22 @@ Unlike host-level tensor-splitting, row-splitting is executed entirely inside th
You can also combine row-splitting with layer-splitting across multiple grouped devices (e.g. `--devices 'HTP0[0-1],HTP1[2-3]'`
on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs using virtual sessions 0 and 1).
## Numerical Precision and End-to-End Accuracy
By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong
end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX
(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element
`K`-group scale (using HVX when `M <= 4`),
and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16`
(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation
outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order:
1. `--hex-mm-select 4 --hex-oplower 1`: pure `W8A8` INT HMX everywhere + internal `FP16` lowering (maximum prefill speed)
2. `--hex-mm-select 3 --hex-oplower 1` (default): hybrid `W8A8` INT HMX (FP16 HMX on post-GLU / `GGML_PREC_F32` projections) + internal `FP16` lowering
3. `--hex-mm-select 3 --hex-oplower 0`: hybrid `W8A8` INT HMX + `FP32` intermediate activations
4. `--hex-mm-select 2 --hex-oplower 1`: `FP16` HMX everywhere + internal `FP16` lowering
5. `--hex-mm-select 2 --hex-oplower 0`: `FP16` HMX everywhere + `FP32` intermediate activations
## Environment variables
- `GGML_HEXAGON_DEVICES` (default: not set, defaults to HTP0 session)
@@ -398,3 +414,27 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
# Disable ADD and SUB on Hexagon (fall back to CPU or GPU)
./scripts/snapdragon/run.py --target adb --hex-opfilter "ADD|SUB" -- llama-cli ...
```
- `GGML_HEXAGON_OPLOWER=N`
Controls internal FP32-to-FP16 activation tensor lowering inside HTP opbatches (configurable via `--hex-oplower` in `run.py`):
- `0`: Disabled - keep internal activations in FP32
- `1`: Enabled (default) - lower internal `FP32` activation tensors across the opbatch to `FP16` while respecting `GGML_PREC_F32` hints
- `GGML_HEXAGON_MM_SELECT=N`
Selects the matrix multiplication engine on HTP (configurable via `--hex-mm-select` in `run.py`):
- `0`: Disabled (falls back to CPU or GPU)
- `1`: HVX vector kernels only
- `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`)
- `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden)
- `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`)
- `GGML_HEXAGON_OPPOLL=N`
Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
- `0`: Blocking wait (lowest host CPU usage)
- `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling)
- `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise)
The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
+73 -96
View File
@@ -30,6 +30,10 @@ The Hexagon NPU backend takes advantage of Snapdragon unified memory where all D
The NPU has dedicated tightly-coupled memory called VTCM (Vector Tightly-Coupled Memory). VTCM is used for intermediate data (such as
dynamically quantized activations) and streaming buffers (chunks of weight and activation tensors fetched via DMA).
Both DDR and VTCM reserve trailing guard space so HVX kernels can issue full-width vector loads (`vmem` / `vmemu`) on tail elements without boundary branches:
- Shared DDR buffers pad allocations to 4 KB and append a 4 KB guard page.
- Usable VTCM (`htp_vtcm_usable_size`) reserves `HTP_VTCM_GUARD_SIZE` (128 bytes) at the end of the physical VTCM page.
## Large model handling
Hexagon NPU sessions have a 32-bit virtual address space window of around 3.5GB.
@@ -72,34 +76,29 @@ For a weight matrix of logical shape `[ne0, ne1]` (where `ne0 = K`, `ne1 = N`):
### Block-32 Quantized Formats
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`).
Quants are stored in 4-K-grouped (`vrmpy`) byte order across 128-byte HVX vectors:
columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns (`j = k % 4`), stored at `4 * row + j` within each vector.
- **Q4_0** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_0`):
- **Quants** (bytes 0..511, 512 bytes):
- **Quants** (bytes 0..511, 512 bytes, 4 HVX vectors `p = 0..3`):
Contains 32 rows x 32 columns of 4-bit quants.
Divided into 16 column pairs `cp = 0..15` covering columns `2*cp` and `2*cp + 1`.
For each column pair `cp`, 32 bytes are stored consecutively for rows `row = 0..31`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Low nibble holds the even column; high nibble holds the odd column.
Vector `p` packs column group `2*p` in the low nibble and group `2*p + 1` in the high nibble:
`tile[p * 128 + row * 4 + j]` holds `(quant[row][8*p + 4 + j] << 4) | quant[row][8*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Q8_0** (1088 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q8_0`):
- **Quants** (bytes 0..1023, 1024 bytes):
- **Quants** (bytes 0..1023, 1024 bytes, 8 HVX vectors `p = 0..7`):
Contains 32 rows x 32 columns of signed 8-bit quants (`int8_t`).
Divided into 16 column pairs `cp = 0..15` covering columns `col0 = 2*cp` and `col1 = 2*cp + 1`.
For each column pair `cp`, 64 bytes store interleaved column elements for each row `row = 0..31`:
`tile[cp * 64 + 2 * row + 0] = quant[row][col0]`
`tile[cp * 64 + 2 * row + 1] = quant[row][col1]`
Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`):
`tile[p * 128 + row * 4 + j] = quant[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
- **Scales** (bytes 1024..1087, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **IQ4_NL** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_IQ4_NL`):
- **Quants** (bytes 0..511, 512 bytes):
Same nibble transposition and storage layout as `Q4_0`.
Contains 32 rows x 32 columns of non-linear 4-bit indices (values 0..15).
Divided into 16 column pairs `cp = 0..15`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit non-linear indices (values 0..15).
- **Scales** (bytes 512..575, 64 bytes):
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
- **Dequantization**:
@@ -107,10 +106,7 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **MXFP4** (544 bytes per tile, `HTP_TENSOR_TILE_SIZE_MXFP4`):
- **Quants** (bytes 0..511, 512 bytes):
Same nibble transposition and storage layout as `Q4_0`.
Contains 32 rows x 32 columns of 4-bit OCP Microscaling FP4 (E2M1) values.
Divided into 16 column pairs `cp = 0..15`:
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit OCP Microscaling FP4 (E2M1) values.
- **Scales** (bytes 512..543, 32 bytes):
32 unsigned 8-bit values (`uint8_t`), storing one 8-bit biased exponent (E8M0, bias 127) scale `e` per row `row = 0..31`.
- **Dequantization**:
@@ -119,26 +115,25 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
- **NVFP4** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_NVFP4`, lossless tiling with same size as `block_nvfp4`):
- A 64-element block spans 2 consecutive k-tiles; k-tile `h` holds sub-blocks `2h` and `2h+1`.
- **Quants** (bytes 0..511): same nibble transposition as `Q4_0`, holding E2M1 values in element order
(within a 16-element sub-block, `qs` byte `j` holds elements `j` and `j+8`).
- **Quants** (bytes 0..511, 4 HVX vectors): 4-K-grouped nibble layout per 16-element sub-block `u = 0..1` (`tile[(2*u + 0)*128 + row*4 + j]` holds low nibbles of `qs_sub[j]` and `qs_sub[4+j]`; `tile[(2*u + 1)*128 + row*4 + j]` holds high nibbles).
- **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile.
- The per-tensor F32 scale is not part of the tile.
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
- **Quants** (bytes 0..511, 512 bytes):
Same 4-bit nibble transposition and storage layout as `Q4_0`.
Same 4-K-grouped nibble layout as `Q4_0`.
- **Scales** (bytes 512..639, 128 bytes):
32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`.
- **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`):
- **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits.
- **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear.
- **Quants** (bytes 0..511): same 4-K-grouped nibble layout as `Q4_0`, holding the low 4 bits.
- **5th-bit plane** (bytes 512..639, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds a flag at bit `g` (`0..7`) for `k = 4*g + j`. The flag is set when the 5th bit of the quant is clear.
- **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`.
- **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`.
- **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile):
- **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs.
- **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set.
- **5th-bit plane** (bytes 640..767, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds bit `g` (`0..7`) for `k = 4*g + j`, set when the 5th bit of the quant is set.
- Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums).
### Q1_0 Format (1-Bit Quantization)
@@ -209,12 +204,12 @@ Byte ordering: `Q2_K`, `Q3_K`, and `Q6_K` use `vrmpy` byte order within each 128
- `bytes 384..511` (vec 3): FP16 scales `d * (scales[] - 32)`: `fp16[0..31]` for k 0..15, `fp16[32..63]` for k 16..31.
- **Q4_K** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_K`, same layout as Q4_1 tile; each 256-k super-block splits into 8 tiles of 32 k):
- `bytes 0..511` (vec 0..3): 4-bit quants; byte `32*cp + r` holds `k = 2*cp` (low nibble) and `2*cp + 1` (high nibble).
- `bytes 0..511` (vec 0..3): 4-bit quants in 4-K-grouped order; `tile[p * 128 + row * 4 + j]` holds `k = 8*p + j` (low nibble) and `k = 8*p + 4 + j` (high nibble).
- `bytes 512..639` (vec 4): 32x2 FP16 per row: `(d * sc, -dmin * m)`.
- **Q5_K** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_K`):
- `bytes 0..639` (vec 0..4): Q4_K tile (low 4 bits + FP16 scale/min pairs).
- `bytes 640..767` (vec 5): 5th-bit plane; byte `l` holds the 8 high bits for lane `l` across vec `i = 0..3` (`bit 2i = lo, 2i+1 = hi`).
- `bytes 640..767` (vec 5): 5th-bit plane in 4-K-grouped order; `plane[row * 4 + j]` holds bit `g` (`0..7`) for `k = 4*g + j`.
- **Q6_K** (896 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q6_K`):
- `bytes 0..511` (vec 0..3): low 4 bits; vec `i` holds group `2i` (low nibble) and `2i+1` (high nibble).
@@ -227,8 +222,9 @@ Writing high-performance operators for Hexagon requires following specific guide
### DDR -> DMA -> VTCM Execution Pipeline
- Strongly prefer the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
- Direct HVX reads/writes from/to DDR are less efficient and should only be used as a fallback.
- All operators must use the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
- **No direct reads or writes to `tensor->data`**: Do not dereference `tensor->data` pointers directly (scalar or HVX). All tensor transfers must go through DMA, because bypass DMA writes are not L1D/L2 coherent and tensors may reside in 40-bit extended address space.
- **Rare exception (small index/position tensors)**: For small metadata tensors that require scalar indexing (such as `ids`, `pos`, or row indices), use [`htp_tensor_read()`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) to copy into a 128-byte aligned local DDR buffer (`ddr_spad_base` or stack). It handles extended addresses, arbitrary strides, and `dccleaninva` + `syncht` cache maintenance in one place.
- Use `dma_addr_t` only for DMA base and final addresses. Form a final address by adding a 32-bit byte offset to a
`dma_addr_t` tensor base address. This permits a 64-bit mapped base address on newer platforms while retaining 32-bit
relative addressing.
@@ -244,8 +240,12 @@ Writing high-performance operators for Hexagon requires following specific guide
properly. Flushing is only used in rare exceptions where a batch of operations is pushed without individual pops.
- Use the DMA queue interface from [`dma-queue.h`](../../../ggml/src/ggml-hexagon/htp/dma-queue.h)
(`dma_queue_push()`, `dma_queue_pop()`, and `dma_queue_flush()`).
See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c) and
[`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c) for reference implementations.
- For new simple ops, prefer the generic double-buffered pipeline drivers in
[`dma-pipeline.h`](../../../ggml/src/ggml-hexagon/htp/dma-pipeline.h) (`dma_pipe_io_run`, `dma_pipe_in_run`,
`dma_pipe_out_run`), which use dummy pushes, `dma_queue_pop().src`/`.dst` slot recycling, and `dma_queue_flush()`
at the end of the op. See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c),
[`diag-ops.c`](../../../ggml/src/ggml-hexagon/htp/diag-ops.c), and
[`pad-ops.c`](../../../ggml/src/ggml-hexagon/htp/pad-ops.c) for reference implementations.
### Avoid Scalar Reads and Writes to VTCM
@@ -256,22 +256,22 @@ Writing high-performance operators for Hexagon requires following specific guide
- Hexagon cores do not have hardware division instructions.
- For recurring divisions across iterations or threads, use `fastdiv` from
[`hex-fastdiv.h`](../../../ggml/src/ggml-hexagon/htp/hex-fastdiv.h) with precomputed divisors (such as
`octx->ctx->mdev.count_div` or `octx->n_threads_div`).
`octx->ctx->mdev.count_div` or `octx->n_hvx_div`).
- Do not call `init_fastdiv_values()` for single-use divisions; use standard compiler division (`/`) instead.
### Host-Side Precomputation via `kernel_params`
- Precompute tensor shapes, strides, scale conversions, tiling layouts, and validation checks on the host CPU during graph
preparation in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp).
preparation in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp).
- Pack precomputed parameters into the operator's fixed `kernel_params` structure in `htp_op_node` (such as
`htp_mm_kernel_params`, `htp_unary_kernel_params`, `htp_fa_kernel_params`, `htp_get_rows_kernel_params`).
- The NPU executes directly using `octx->kernel_params` without redundant runtime metadata extraction or validation.
- **Strict Host-Kernel Alignment**:
- Verify that parameters calculated by the host CPU are strictly honored by the NPU kernel.
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_threads` instead of
using `kparams->n_threads`, or ignoring precomputed `tasks_per_thread` and chunk counts).
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_hvx` instead of
using `kparams->n_hvx`, or ignoring precomputed `tasks_per_hvx` and chunk counts).
- Both human developers and coding agents must audit both sides of the interface: ensure fields populated in `kernel_params`
in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp) are actively and consistently utilized by the
in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp) are actively and consistently utilized by the
corresponding operator entry point and worker threads in `htp/*-ops.c`.
### Tracing Instrumentation
@@ -292,7 +292,7 @@ Writing high-performance operators for Hexagon requires following specific guide
- Distribute parallel work across NPU worker threads using the thread pool work queue:
```c
work_queue_run(ctx->work_queue, worker_func, &op_ctx, n_threads);
work_queue_run(ctx->hvx_queue, worker_func, &op_ctx, n_hvx);
```
- Keep worker functions independent and re-entrant. Worker threads should only operate on their designated chunk of rows or elements.
@@ -307,6 +307,12 @@ Writing high-performance operators for Hexagon requires following specific guide
- **Distinction**: `octx->src[N]` pointers *can* be NULL by design and must be checked when optional.
Examples include attention masks, optional bias or weights in fused kernels, and frequency factors.
### Prefer Early Dispatch and Specialized Micro-Kernels
- Avoid peppering micro-kernels, row or tile compute loops, or DMA worker loops with runtime checks for operand types, optional inputs, broadcast modes, or layout variants.
- Resolve execution variants early during operator setup (`op_*` / `execute_op_*`) via function pointers or dispatch tables so each micro-kernel and inner loop handles a single clean path that the compiler can unroll and software-pipeline without extra branch or register pressure.
- Prefer clean standalone specialized functions; use macros only to avoid genuine code duplication across type or mode instantiations.
### `supports_op` Independence from Buffer and Repack State
- `supports_op` (and op-specific checkers such as `supported_mul_mat()`, `supported_get_rows()`) runs during GGML graph scheduling **before** buffers are allocated and before tensor data is populated.
@@ -319,6 +325,10 @@ Writing high-performance operators for Hexagon requires following specific guide
- Repacking (converting weights to tiled layout) is an internal optimization applied during `set_tensor()` or rt-repack. Non-weight tensors or test harness tensors with the same type remain in flat layout.
- Therefore, any supported type (such as BF16, F16, quantized types) must be supported both when repacked into tiles and when stored flat in memory.
### FP16 and Mixed-Precision Operator Support
- New and updated Hexagon compute operators must support `F16` (and mixed `F16`/`F32` where applicable for graph lowering) across activation inputs and outputs, even when `ggml-cpu` only implements `F32`.
### Multiline Macro Formatting
- Keep trailing backslashes in multiline `#define` macros cleanly aligned to a consistent column.
@@ -361,56 +371,37 @@ python3 scripts/snapdragon/ggml-hexagon-inspect.py --addr2line 0x51a30 0x5ba54
Multi-device (mdev) mode enables row-level tensor parallel execution across multiple physical NPU cores or virtual NPU
sessions.
### 128-Byte Cache Line Alignment
### Non-Overlapping Output Ranges
- Shared tensor buffers reside in DDR (RPCMEM) with a 128-byte cache line granularity
(`HEX_L2_LINE_SIZE` = 128 bytes, `HTP_TENSOR_MDEV_LINE_SIZE`).
- **Rule**: Multi-device work partitions that write directly to DDR through HVX/L2 must align destination write regions to
128-byte cache line boundaries so distinct devices never share or overwrite the same cache line.
- DMA writes to DDR are not subject to this cache-line ownership rule. They may use smaller non-overlapping destination
ranges when the operator only writes through DMA.
- Because all DDR writes go through bypass DMA, multi-device partitions are **not** subject to 128-byte cache-line
alignment rules.
- Devices only need non-overlapping destination output ranges and any kernel-specific tile or vector granularity
(for example, 32 rows for tiled matmul or 128-byte vector chunks for flat 1D element-wise ops).
### Partitioning Helpers in `htp-tensor.h`
### Partitioning Helper in `htp-tensor.h`
Common partitioning logic is factored into reusable inline helpers in
[`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
Common partitioning logic is factored into [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h)
in [`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
1. [`htp_tensor_mdev_rows_per_chunk`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L104):
Determines the minimum number of rows per chunk so that the chunk byte size is a multiple of 128 bytes:
```
rows_per_chunk = 128 / hex_gcd_u32(row_size, 128)
```
If the active row and outer strides are already multiples of 128 bytes, `rows_per_chunk = 1`.
Returns `false` if the tensor cannot be safely row-partitioned (such as unaligned base pointer, permuted layout,
or non-128-byte aligned outer strides).
2. [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131):
Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
Handles chunk distribution across devices, assigns remainder units to the last device, and automatically triggers
single-device fallback when partitioning is unsafe.
- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically falls back
to Device 0 when `units_per_chunk == 0` or `total_units / units_per_chunk < mdev_count`.
### Row-Partitioned Operators
For row-wise operators that write directly to DDR
(such as activations in [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c),
binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c),
For row-wise operators (such as binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c)
and unary ops in [`unary-ops.c`](../../../ggml/src/ggml-hexagon/htp/unary-ops.c)):
```c
const uint32_t total_rows = ne01 * ne02 * ne03;
const size_t dst_row_size = dst->ne[0] * elem_size;
const uint32_t total_rows = ne01 * ne02 * ne03;
uint32_t row_start = 0;
uint32_t nrows = total_rows;
if (octx->ctx->mdev.count > 1) {
uint32_t rows_per_chunk = 0;
htp_tensor_mdev_rows_per_chunk(dst, elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
row_start = range.start;
nrows = range.count;
}
@@ -422,24 +413,16 @@ if (nrows == 0) {
### Element-Partitioned Operators
For flat element-wise operations that write directly to DDR:
- Partition total linear elements N = ne0 * ne1 * ne2 * ne3 in 128-byte cache line chunks (`elems_per_line = (elem_size == 4) ? 32 : 64`).
- Requires strict 1D contiguity:
[`htp_tensor_is_contiguous(dst, elem_size)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L65)
and 128-byte aligned destination pointer
[`htp_tensor_mdev_data_aligned(dst)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L84).
- If contiguous and aligned, pass `elems_per_line` to
[`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131);
otherwise pass 0 to trigger Device 0 fallback.
For flat 1D element-wise operations:
- Partition total linear elements `N = ne0 * ne1 * ne2 * ne3` in HVX vector-sized chunks (`elems_per_line = 128 / elem_size`).
- Requires 1D contiguity via [`htp_tensor_is_contiguous`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h); otherwise pass
`0` to trigger Device 0 fallback.
### Single-Device Fallback (Device 0)
- Fallback to Device 0 (`mdev.idx == 0`) when partitioning would cause cache line tearing or there are too few aligned chunks.
- Triggers:
1. Destination tensor cannot be safely partitioned (`rows_per_chunk == 0` or non-contiguous/unaligned buffer).
2. Total aligned chunks < `mdev_count`.
- Fallback to Device 0 (`mdev.idx == 0`) happens when `units_per_chunk == 0` or `total_chunks < mdev_count`.
- Device 0 processes the entire tensor `[0, total_units)`.
- Devices 1 ... N-1 receive `count = 0` and return `HTP_STATUS_OK` immediately.
- Devices `1 ... N-1` receive `count = 0` and return `HTP_STATUS_OK` immediately.
### Flatten Outer Dimensions Globally
@@ -494,10 +477,7 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
| |
Kernel Execution Kernel Execution
(Output Slice 0) (Output Slice 1)
| |
Tensor Cache Flush Tensor Cache Flush
(htp_dcache_flush_dirty_tensors) (htp_dcache_flush_dirty_tensors)
(Output Slice 0, via bypass DMA) (Output Slice 1, via bypass DMA)
| |
Post-Op/Batch Barrier ---------------------- Post-Op/Batch Barrier
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
@@ -532,11 +512,8 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
misaligned barrier arrivals across iterations.
- If any peer reports an error status (`peer_status > HTP_STATUS_OK`), the barrier propagates the error and unblocks immediately.
### Tensor Cache Flush and Pipeline Completion
### Pipeline Completion
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order to drain the queue.
- Use [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) to flush specific dirty tensors back to DDR:
- [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) flushes modified tensor address ranges, or the
full D-cache when their total size exceeds the flush threshold, ensuring peer devices and the host CPU observe consistent
data in DDR.
- Never signal completion before all DMA transfers are drained and dirty tensor flushes have completed.
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order (or flushed via `dma_queue_flush()`) to drain the queue.
- Because all DDR writes use bypass DMA, no per-tensor output cache flush is needed.
- Never signal completion before all DMA transfers are drained.
+31
View File
@@ -50,6 +50,37 @@ export RISCV_ROOT_PATH_IME1={your RISC-V compiler path}
${QEMU_ROOT_PATH}/bin/qemu-riscv64 -L ${RISCV_ROOT_PATH_IME1}/sysroot -cpu max,vlen=256,elen=64,vext_spec=v1.0 ${PWD}/build/bin/llama-cli -m ${PWD}/models/Qwen2.5-0.5B-Instruct-Q4_0.gguf -t 1
~~~
## Run On Device
On a SpacemiT board the backend reads `marchid` from `/proc/cpuinfo` and selects cores with the variables below. `SPACEMIT_CORE_ARCH` is read only when `/proc/cpuinfo` has no SpacemiT core, which is the QEMU case above. A `0x` prefix on the arch id is optional.
| Variable | Default | Value |
| --- | --- | --- |
| `SPACEMIT_PERFER_CORE_ARCH` | cores with arch id high bits `0xA` (`arch >> 12 == 0xA`) | `503c` X60, `5064` X100, `50c8` X200, `a03c` A60, `a064` A100, `a0c8` A200 |
| `SPACEMIT_PERFER_CORE_ID` | every core selected above | comma-separated `processor` ids from `/proc/cpuinfo` |
| `SPACEMIT_CORE_ARCH` | parse `/proc/cpuinfo` | same hex arch id as `SPACEMIT_PERFER_CORE_ARCH` |
| `SPACEMIT_MEM_BACKEND` | `HPAGE` | `NONE`, `POSIX`, `HPAGE`, `HPAGE1GB` |
| `SPACEMIT_DISABLE_TCM` | use TCM when the device provides it | any value other than `0` disables TCM |
X100 (`5064`) and A60 (`a03c`) enable IME1. A100 (`a064`) enables IME2. X60, X200 and A200 do not enable IME1 or IME2.
To make any child processes get sent to the A100 cores, you need to write the PID of the current process to `/proc/set_ai_thread`. In many shell programs, such as bash or zsh, this can be done with `echo $$ > /proc/set_ai_thread`.
~~~
echo $$ > /proc/set_ai_thread
~~~
Set them in the environment of the process you start. For example, to run on A100 cores 8-15:
~~~
echo $$ > /proc/set_ai_thread
export SPACEMIT_PERFER_CORE_ARCH=a064
export SPACEMIT_PERFER_CORE_ID=8,9,10,11,12,13,14,15
${PWD}/build/bin/llama-cli -m ${PWD}/models/Qwen2.5-0.5B-Instruct-Q4_0.gguf -t 8
~~~
The same variables can be written in front of the command: `SPACEMIT_PERFER_CORE_ARCH=a064 SPACEMIT_PERFER_CORE_ID=8,9,10,11,12,13,14,15 ${PWD}/build/bin/llama-cli ...`. They are read when the process starts.
Each id in `SPACEMIT_PERFER_CORE_ID` must be in range and must have the arch given by `SPACEMIT_PERFER_CORE_ARCH`, otherwise the process aborts. An unknown `SPACEMIT_MEM_BACKEND` aborts with the four names above.
## Quantization Support For Matrix
| Quantization Type | X60 | A100 |
+10 -8
View File
@@ -27,7 +27,7 @@ Legend:
| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ |
| CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
| CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
| CONV_1D_DW | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
| CONV_1D_DW | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
| CONV_2D | ❌ | ❌ | 🟡 | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
| CONV_2D_DW | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ❌ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| CONV_3D | ❌ | ❌ | ✅ | ✅ | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
@@ -77,9 +77,9 @@ Legend:
| MUL_MAT_ID | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ❌ |
| MUL_MAT_ID_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_ID_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| MUL_MAT_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
| NEG | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
@@ -89,7 +89,7 @@ Legend:
| OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
| PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
| PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ |
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
@@ -97,7 +97,7 @@ Legend:
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
@@ -108,9 +108,11 @@ Legend:
| SET_ROWS | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
| SGN | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| SIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| SIGMOID_BACK | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| SILU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| SILU_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
| SIN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| SLEEP | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| SOFTPLUS | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| SOFT_MAX | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
| SOFT_MAX_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ |
@@ -129,8 +131,8 @@ Legend:
| TANH | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| TIMESTEP_EMBEDDING | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
| TOP_K | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
| TOP_K_MASK | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
| TOP_K_MASK | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
+12673 -9001
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -16812,11 +16812,11 @@
"OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL"
"OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL"
"OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL"
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
"OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL"
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL"
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL"
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL"
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL"
"OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL"
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL"
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL"
Can't render this file because it is too large.
+247 -49
View File
@@ -1283,54 +1283,246 @@
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f32,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f16,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
@@ -12345,7 +12537,13 @@
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU"
"WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU"
"WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU"
"WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU"
Can't render this file because it is too large.
+14
View File
@@ -132,6 +132,20 @@ llama-server -m Qwen3-4B.gguf -md Qwen3-4B-DSpark.gguf \
acceptance (from the draft's confidence head) falls below `P` (default 0 = disabled).
Values above 0 require a draft with a confidence head.
Inkling 2 ships its DSpark drafter as `mtp.safetensors` in the model directory. Export it from a local
checkpoint with `--dspark`; the converter also reads the target's lm head and embedding norm from there:
```bash
python convert_hf_to_gguf.py /path/to/Inkling-2-Mini --dspark --outtype bf16 --outfile Inkling-2-Mini-DSpark.gguf
llama-server -m Inkling-2-Mini.gguf -md Inkling-2-Mini-DSpark.gguf \
--spec-type draft-dspark --spec-draft-n-max 3 -fa on --jinja
```
The Inkling 2 drafter supports `--spec-draft-sampling probabilistic`:
at a positive request temperature, each drawn token conditions the next one, and the target verifies the draft by
rejection sampling.
Currently only drafts with a Qwen3 backbone are supported; support for other backbones
(e.g. Gemma4) is planned.
-1
View File
@@ -112,7 +112,6 @@
systems = [
"aarch64-darwin"
"aarch64-linux"
"x86_64-darwin" # x86_64-darwin isn't tested (and likely isn't relevant)
"x86_64-linux"
];
+4 -2
View File
@@ -4,8 +4,8 @@ project("ggml" C CXX ASM)
### GGML Version
set(GGML_VERSION_MAJOR 1)
set(GGML_VERSION_MINOR 0)
set(GGML_VERSION_PATCH 0)
set(GGML_VERSION_MINOR 1)
set(GGML_VERSION_PATCH 1)
set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}")
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/")
@@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL"
option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF)
option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON)
option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON)
option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON)
option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON)
set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING
"ggml: OpenCL API version to target")
+8 -2
View File
@@ -56,8 +56,8 @@ function(ggml_get_system_arch)
endif()
endfunction()
# Determines which FlashAttention vector kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
# Determines which FlashAttention kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_instances DIR OUT_SRCS)
set(FA_TYPES q4_0 q4_1 q5_0 q5_1 q8_0 bf16 f16 f8_e4m3)
string(TOLOWER "${GGML_CUDA_FA_QUANTS}" FA_QUANTS)
@@ -122,6 +122,12 @@ function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
message(FATAL_ERROR "FlashAttention template instance \"${SRC}\" does not exist")
endif()
list(APPEND SRCS "${SRC}")
file(GLOB TILE_SRCS "${DIR}/template-instances/fattn-tile-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${TILE_SRCS})
file(GLOB MMA_SRCS "${DIR}/template-instances/fattn-mma-f16-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${MMA_SRCS})
endforeach()
set(${OUT_SRCS} ${SRCS} PARENT_SCOPE)
+2
View File
@@ -161,6 +161,8 @@ extern "C" {
bool events;
// mmap is supported for loading
bool mmap_support;
// set_tensor_async from host memory can be ordered with the graph computation and can therefore be faster than a blocking write
bool fast_async_host_input;
};
// all the device properties
+64 -7
View File
@@ -607,6 +607,7 @@ extern "C" {
GGML_API size_t ggml_element_size(const struct ggml_tensor * tensor);
GGML_API bool ggml_is_quantized(enum ggml_type type);
GGML_API bool ggml_needs_scale(enum ggml_type type);
// TODO: temporary until model loading of ggml examples is refactored
GGML_API enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype);
@@ -1322,6 +1323,16 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * b);
// scale_weight is F32, either a scalar or one value per output channel.
// scale_activations is an optional F32 scalar for activation quantization.
// Divide activations by the scale before quantization, then multiply the matmul result by the scale.
GGML_API struct ggml_tensor * ggml_mul_mat_ext(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations);
// change the hint of a matrix multiplication
GGML_API void ggml_mul_mat_set_hint(
struct ggml_tensor * a,
@@ -1335,6 +1346,16 @@ extern "C" {
struct ggml_tensor * b,
struct ggml_tensor * ids);
// scale_weight: [1], [n_as] or [n_out, n_as], selected by ids
// scale_activations: [1] or [n_as], selected by ids
GGML_API struct ggml_tensor * ggml_mul_mat_id_ext(
struct ggml_context * ctx,
struct ggml_tensor * as,
struct ggml_tensor * b,
struct ggml_tensor * ids,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations);
// A: m columns, n rows,
// B: p columns, n rows,
// result is m columns, p rows
@@ -2292,6 +2313,15 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * sinks);
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
// Add table[indices[key, query], head, query] to the mask, in F32.
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices);
// TODO: needs to be adapted to ggml_flash_attn_ext
GGML_API struct ggml_tensor * ggml_flash_attn_back(
struct ggml_context * ctx,
@@ -2426,11 +2456,17 @@ extern "C" {
// beta : [1, H_v, n_tokens, n_seqs]
// state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0
//
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state
// snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1
// keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written.
// when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_API struct ggml_tensor * ggml_gated_delta_net(
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs]
//
// replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the
// previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot
// pend_k : [S_k, H_k, n_pend, n_seqs]
// pend_v : [S_v, H_v, n_pend, n_seqs]
// pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0)
// n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend)
// the state output is the state after the replay if keep is true, else the final state.
// op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set
GGML_API struct ggml_tensor * ggml_gated_delta_net_ext(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
@@ -2438,7 +2474,25 @@ extern "C" {
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K);
struct ggml_tensor * pend_k,
struct ggml_tensor * pend_v,
struct ggml_tensor * pend_gb,
struct ggml_tensor * n_rep,
bool keep);
// the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state,
// slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only
// slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net(
struct ggml_context * ctx,
struct ggml_tensor * q,
struct ggml_tensor * k,
struct ggml_tensor * v,
struct ggml_tensor * g,
struct ggml_tensor * beta,
struct ggml_tensor * state,
int64_t K),
"use ggml_gated_delta_net_ext instead");
// DSA lightning indexer
//
@@ -2780,12 +2834,14 @@ extern "C" {
typedef void (*ggml_to_float_t) (const void * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k);
typedef void (*ggml_from_float_t)(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k);
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
struct ggml_type_traits {
const char * type_name;
int64_t blck_size;
int64_t blck_size_interleave; // interleave elements in blocks
size_t type_size;
bool is_quantized;
bool is_quantized; // whether it's a block-quantized data-type
//bool needs_scale; // add this flag in the next update [TAG_GGML_VERSION_MAJOR_UPDATE]
ggml_to_float_t to_float;
ggml_from_float_t from_float_ref;
};
@@ -2807,6 +2863,7 @@ extern "C" {
// threadpool params
// Use ggml_threadpool_params_default() or ggml_threadpool_params_init() to populate the defaults
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
struct ggml_threadpool_params {
bool cpumask[GGML_MAX_N_THREADS]; // mask of cpu cores (all-zeros means use default affinity settings)
int n_threads; // number of threads
+1 -1
View File
@@ -621,7 +621,7 @@ endforeach()
target_link_libraries(ggml-base PRIVATE Threads::Threads)
if (DEFINED MATH_LIBRARY)
if (MATH_LIBRARY)
target_link_libraries(ggml-base PRIVATE ${MATH_LIBRARY})
elseif (NOT WIN32 AND NOT DEFINED ENV{ONEAPI_ROOT})
target_link_libraries(ggml-base PRIVATE m)
+11 -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
@@ -124,6 +125,15 @@ extern "C" {
// keep `tensor` allocated at least until `until` (a node of the same graph) has been computed
// can be called multiple times for the same tensor: the longest lifetime applies
void (*add_alloc_dep)(void * user_data, struct ggml_tensor * tensor, struct ggml_tensor * until);
// reserve `nbytes` of memory in the compute buffer of the backend, e.g. for data that several nodes share
// the memory is reserved from before `first` is computed until `last` has been computed: outside of that range the
// allocator can give it to other tensors, so its contents do not carry over between evaluations of the graph
// `first` and `last` are nodes of the same graph, and `last` must not come before `first` in the optimized graph
// returns a 1-d GGML_TYPE_I8 tensor that is not a node of the graph, its data is set when the graph is allocated
// the backend can keep references to the tensor itself until the scheduler splits the next graph
struct ggml_tensor * (*add_scratch)(void * user_data, size_t nbytes, struct ggml_tensor * first, struct ggml_tensor * last);
void * user_data;
};
+20 -3
View File
@@ -133,6 +133,7 @@ static void ggml_backend_meta_device_get_props(ggml_backend_dev_t dev, ggml_back
/* .buffer_from_host_ptr = */ false, // Not implemented.
/* .events = */ false, // Not implemented.
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
};
for (ggml_backend_dev_t simple_dev : meta_dev_ctx->simple_devs) {
ggml_backend_dev_props tmp_props;
@@ -152,6 +153,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
GGML_ASSERT(ggml_backend_dev_is_meta(dev));
const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context;
return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(),
@@ -699,11 +704,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_view = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
return handle_reshape(src_ss);
}
const int axis = src_ss[0].axis;
{
// Keep the split axis when strides match; reshape is ambiguous across singleton dimensions.
bool all_strides_the_same = true;
for (int dim = 0; dim < GGML_MAX_DIMS; dim++) {
if (tensor->ne[dim] == 1 && tensor->src[0]->ne[dim] == 1) {
@@ -718,6 +721,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
return src_ss[0];
}
}
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
return handle_reshape(src_ss);
}
if (!ggml_is_permuted(tensor) && !ggml_is_permuted(tensor->src[0]) && axis >= 0 && axis < GGML_MAX_DIMS-1) {
for (int dim = 0; dim < GGML_MAX_DIMS-1; dim++) {
if (tensor->nb[dim+1] == tensor->src[0]->nb[axis+1]) {
@@ -871,11 +877,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_gated_delta_net = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
// replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq
const bool replay = tensor->src[6] != nullptr;
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
for (int i = 6; replay && i < 10; i++) {
GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
return src_ss[0];
}
if (replay) {
GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
}
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1);
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1);
+91 -12
View File
@@ -21,6 +21,7 @@
#include <string.h>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#ifdef __APPLE__
@@ -761,7 +762,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);
}
@@ -1251,6 +1262,9 @@ struct ggml_backend_sched {
// inputs of the next split read from the backend of the current split before it computes, see ggml_backend_sched_prefetch_inputs
ggml_backend_event_t prefetch_events[GGML_SCHED_MAX_BACKENDS]; // created on first use, NULL if the backend has no events
bool prefetch_tried [GGML_SCHED_MAX_BACKENDS];
// backends that take host inputs with set_tensor_async, see ggml_backend_dev_caps
bool fast_async_host_input[GGML_SCHED_MAX_BACKENDS];
struct ggml_tensor * prefetched[GGML_SCHED_MAX_SPLIT_INPUTS];
int n_prefetched;
int prefetch_split; // the split that reads the prefetched inputs
@@ -1880,20 +1894,38 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
sched->prev_leaf_backend_ids = tmp;
}
// optimize the split graphs and collect the allocation dependencies added by the backends
// optimize the split graphs and collect the allocation dependencies and scratch tensors added by the backends
// this needs to happen before we make graph_copy, so they are in sync
// TODO: this may create many small allocations in the scheduler, restructure to use a flat array
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
struct optimize_state {
ggml_context * ctx;
// node -> tensors kept allocated until the node has been computed
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
// node -> scratch tensors allocated before the node is computed
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> scratch;
} opt_state;
opt_state.ctx = sched->ctx;
struct ggml_backend_graph_optimize_params opt_params = {
/* .add_alloc_dep = */ [](void * user_data, ggml_tensor * tensor, ggml_tensor * until) {
auto & deps = *(std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> *) user_data;
std::vector<ggml_tensor *> & keep = deps[until];
auto & state = *(optimize_state *) user_data;
std::vector<ggml_tensor *> & keep = state.alloc_deps[until];
if (std::find(keep.begin(), keep.end(), tensor) == keep.end()) {
keep.push_back(tensor);
}
},
/* .user_data = */ &alloc_deps,
/* .add_scratch = */ [](void * user_data, size_t nbytes, ggml_tensor * first, ggml_tensor * last) {
auto & state = *(optimize_state *) user_data;
GGML_ASSERT(nbytes > 0);
ggml_tensor * t = ggml_new_tensor_1d(state.ctx, GGML_TYPE_I8, (int64_t) nbytes);
std::vector<ggml_tensor *> & first_scratch = state.scratch[first];
ggml_format_name(t, "scratch-%zu (%s)", first_scratch.size(), first->name);
first_scratch.push_back(t);
// the scratch tensor has no other users, the dep at `last` is what frees it
state.alloc_deps[last].push_back(t);
return t;
},
/* .user_data = */ &opt_state,
};
for (int i = 0; i < sched->n_splits; i++) {
@@ -1903,17 +1935,27 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
ggml_backend_graph_optimize(sched->backends[split->backend_id], &split->graph, &opt_params);
}
const auto & alloc_deps = opt_state.alloc_deps;
// each dep is added to graph_copy as a GGML_OP_NONE node with the kept tensors as srcs
int n_dep_nodes = 0;
for (const auto & it : alloc_deps) {
n_dep_nodes += (it.second.size() + GGML_MAX_SRC - 1) / GGML_MAX_SRC;
}
// each scratch tensor is added to graph_copy as a GGML_OP_NONE node right before its first user
// scratch tensors not yet added to graph_copy
std::unordered_set<ggml_tensor *> scratch_pending;
for (const auto & it : opt_state.scratch) {
scratch_pending.insert(it.second.begin(), it.second.end());
}
const int n_scratch_nodes = (int) scratch_pending.size();
int total_inputs = sched->n_graph_inputs;
for (int i = 0; i < sched->n_splits; i++) {
total_inputs += sched->splits[i].n_inputs;
}
int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes;
int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes + n_scratch_nodes;
// remember the actual graph_size for performing reallocation checks later
sched->prev_graph_size = sched->graph_size;
@@ -1956,6 +1998,19 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
}
for (int j = split->i_start; j < split->i_end; j++) {
// add the scratch tensors first so that they are allocated before this node is computed
if (!scratch_pending.empty()) {
auto it = opt_state.scratch.find(graph->nodes[j]);
if (it != opt_state.scratch.end()) {
for (ggml_tensor * t : it->second) {
assert(graph_copy->size > graph_copy->n_nodes);
sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
graph_copy->nodes[graph_copy->n_nodes++] = t;
scratch_pending.erase(t);
}
}
}
assert(graph_copy->size > graph_copy->n_nodes);
sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]);
graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
@@ -1971,6 +2026,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
for (size_t k = 0; k < keep.size(); k += GGML_MAX_SRC) {
struct ggml_tensor * dep = ggml_view_tensor(sched->ctx, keep[k]);
for (size_t s = 0; s < GGML_MAX_SRC && k + s < keep.size(); s++) {
// a scratch tensor freed before it was allocated: its `last` comes before its `first`
GGML_ASSERT(scratch_pending.count(keep[k + s]) == 0 && "add_scratch: last is before first");
dep->src[s] = keep[k + s];
}
assert(graph_copy->size > graph_copy->n_nodes);
@@ -1984,6 +2041,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
// a mismatch means a backend added a dep with an `until` tensor that is not a node of the optimized graph
GGML_ASSERT(n_dep_nodes_added == n_dep_nodes);
// a scratch tensor left over means a backend passed a `first` tensor that is not a node of the optimized graph
GGML_ASSERT(scratch_pending.empty() && "add_scratch: first is not a node of the graph");
if (sched->n_copies > 1) {
// add input copies as leafs so that they are allocated first
@@ -2097,7 +2156,8 @@ static bool ggml_backend_sched_is_host_weight(const struct ggml_tensor * t) {
ggml_backend_buffer_is_host(t->buffer);
}
static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) {
// returns true if the copy is reading asynchronously from host memory, to safely write to the memory a synchronization on the split backend is then needed
static bool ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) {
const int split_backend_id = split->backend_id;
ggml_backend_t split_backend = sched->backends[split_backend_id];
ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, input);
@@ -2108,11 +2168,20 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
for (int i = 0; i < sched->n_prefetched; i++) {
if (sched->prefetched[i] == input) {
ggml_backend_event_synchronize(sched->prefetch_events[sched->prefetch_backend_id]);
return;
return false;
}
}
}
// without pipeline parallelism the input copy has a single slot, so it can be written in order on the split backend
ggml_backend_buffer_t input_buf = input->view_src ? input->view_src->buffer : input->buffer;
if (sched->fast_async_host_input[split_backend_id] && sched->events[split_backend_id][sched->cur_copy] == NULL &&
ggml_backend_dev_type(ggml_backend_get_device(input_backend)) == GGML_BACKEND_DEVICE_TYPE_CPU &&
ggml_backend_buffer_is_host(input_buf) && !ggml_backend_sched_is_host_weight(input) && ggml_nbytes(input) > 0) {
ggml_backend_tensor_set_async(split_backend, input_cpy, input->data, 0, ggml_nbytes(input));
return true;
}
if (input->flags & GGML_TENSOR_FLAG_INPUT) {
// inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
@@ -2121,7 +2190,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
ggml_backend_synchronize(split_backend);
}
ggml_backend_tensor_copy(input, input_cpy);
return;
return false;
}
// wait for the split backend to finish using the input before overwriting it
@@ -2133,7 +2202,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
if (sched->callback_copy != NULL && ggml_backend_sched_is_host_weight(input) &&
sched->callback_copy(split_backend, input, input_cpy, &split->graph, sched->callback_copy_user_data)) {
return;
return false;
}
// try async copy, but if not possible, we can still use a sync copy without synchronizing the dst backend, since we handle the synchronization here with multiple copies and events
@@ -2147,6 +2216,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
}
ggml_backend_tensor_copy(input, input_cpy);
}
return false;
}
// the inputs of the next split that are computed on the backend of this split before it, and copied to host memory,
@@ -2233,12 +2303,17 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s
// copy the input tensors to the split backend
// the weights in host memory are copied last, so that the copy callback can read the other inputs of the split
bool host_read_pending = false;
for (int input_id = 0; input_id < split->n_inputs; input_id++) {
struct ggml_tensor * input = split->inputs[input_id];
if (!ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) {
ggml_backend_sched_copy_input(sched, split, input);
host_read_pending |= ggml_backend_sched_copy_input(sched, split, input);
}
}
// the host data of async copies can be overwritten by later splits or by the user after this function returns
if (host_read_pending) {
ggml_backend_synchronize(split_backend);
}
// after the copies above, which may read host memory reused by the copies of the next split
// before the weights, whose copy callback may queue large uploads
ggml_backend_sched_prefetch_inputs(sched, split_id);
@@ -2357,6 +2432,10 @@ ggml_backend_sched_t ggml_backend_sched_new(
sched->bufts[b] = bufts ? bufts[b] : ggml_backend_get_default_buffer_type(backends[b]);
GGML_ASSERT(ggml_backend_supports_buft(backends[b], sched->bufts[b]));
struct ggml_backend_dev_props props;
ggml_backend_dev_get_props(ggml_backend_get_device(backends[b]), &props);
sched->fast_async_host_input[b] = props.caps.fast_async_host_input && backends[b]->iface.set_tensor_async != NULL && !ggml_backend_is_meta(backends[b]);
if (sched->n_copies > 1) {
for (int c = 0; c < sched->n_copies; c++) {
sched->events[b][c] = ggml_backend_event_new(backends[b]->device);
+5
View File
@@ -370,6 +370,7 @@ static void ggml_backend_blas_device_get_props(ggml_backend_dev_t dev, struct gg
/* .buffer_from_host_ptr = */ true,
/* .events = */ false,
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
};
}
@@ -397,6 +398,10 @@ static bool ggml_backend_blas_device_supports_op(ggml_backend_dev_t dev, const s
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * src1 = op->src[1];
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
case GGML_OP_RESHAPE:
+12 -4
View File
@@ -2405,6 +2405,10 @@ static enum ggml_status ggml_backend_cann_graph_compute(ggml_backend_t backend,
* otherwise false.
*/
static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_UNARY:
switch (ggml_get_unary_op(op)) {
@@ -2449,10 +2453,12 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
switch (op->src[0]->type) {
#ifndef ASCEND_310P
case GGML_TYPE_BF16:
return true;
#endif
case GGML_TYPE_F16:
case GGML_TYPE_F32:
return true;
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
return op->src[1]->type != GGML_TYPE_BF16;
case GGML_TYPE_Q8_0:
case GGML_TYPE_Q4_0:
#ifdef ASCEND_310P
@@ -2470,7 +2476,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
switch (op->src[0]->type) {
case GGML_TYPE_F16:
case GGML_TYPE_F32:
return true;
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
return op->src[1]->type != GGML_TYPE_BF16;
case GGML_TYPE_Q8_0:
case GGML_TYPE_Q4_0:
#ifdef ASCEND_310P
@@ -2679,8 +2686,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
return true;
case GGML_OP_FLASH_ATTN_EXT:
{
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
if (op->src[5] != nullptr) {
// K/V row lists and indexed bias are not supported
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
#ifdef ASCEND_310P
@@ -2847,6 +2854,7 @@ static void ggml_backend_cann_device_get_props(ggml_backend_dev_t dev, ggml_back
/* .buffer_from_host_ptr = */ false,
/* .events = */ true,
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
};
}
+232 -3
View File
@@ -35,8 +35,10 @@
// precomputed tables for expanding 8bits to 8 bytes:
static const uint64_t table_b2b_0[1 << 8] = { B8(00, 10) }; // ( b) << 4
#if !defined(__ARM_FEATURE_SVE)
static const uint64_t table_b2b_1[1 << 8] = { B8(10, 00) }; // (!b) << 4
#endif
#endif
void quantize_row_q8_0(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
@@ -920,6 +922,27 @@ void ggml_vec_dot_nvfp4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
*s = sumf;
}
#if defined(__ARM_FEATURE_SVE)
static inline svbool_t load_as_svbool(const uint8_t * p, uint64_t vector_length) {
#if defined(__GNUC__) || defined(__clang__)
if (vector_length < 512) {
svbool_t r;
__asm__("ldr %0, %1"
: "=Upa"(r)
: "Q"(*(const struct { char bytes[32]; } *) p));
return r;
}
#endif
const svbool_t active = vector_length >= 512 ? svptrue_pat_b8(SV_VL32) : svptrue_b8();
const uint64_t load_bytes = vector_length >= 512 ? 4 : svcntd();
const svbool_t load = svwhilelt_b8_u64(0, load_bytes);
const svuint8_t raw = svld1_u8(load, p);
const svuint8_t sel = svlsr_n_u8_x(active, svindex_u8(0, 1), 3);
const svuint8_t msk = svdupq_n_u8(1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128);
return svcmpne_n_u8(active, svand_u8_x(active, svtbl_u8(raw, sel), msk), 0);
}
#endif
void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const void * GGML_RESTRICT vx, size_t bx, const void * GGML_RESTRICT vy, size_t by, int nrc) {
const int qk = QK8_0;
const int nb = n / qk;
@@ -938,7 +961,106 @@ void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
const block_q5_0 * GGML_RESTRICT x = vx;
const block_q8_0 * GGML_RESTRICT y = vy;
#if defined(__ARM_NEON)
#if defined(__ARM_FEATURE_SVE)
svfloat32_t sumv0 = svdup_n_f32(0.0f);
svfloat32_t sumv1 = svdup_n_f32(0.0f);
const int vector_length = ggml_cpu_get_sve_cnt()*8;
switch (vector_length) {
case 128:
{
const svbool_t p16 = svptrue_pat_b8(SV_VL16);
const svbool_t p4 = svptrue_pat_b32(SV_VL4);
for (; ib + 1 < nb; ib += 2) {
const block_q5_0 * GGML_RESTRICT x0 = &x[ib];
const block_q5_0 * GGML_RESTRICT x1 = &x[ib + 1];
const block_q8_0 * GGML_RESTRICT y0 = &y[ib];
const block_q8_0 * GGML_RESTRICT y1 = &y[ib + 1];
const svbool_t qhl0p = load_as_svbool(x0->qh, vector_length);
const svbool_t qhh0p = load_as_svbool(((const uint8_t *) x0->qh + 2), vector_length);
const svbool_t qhl1p = load_as_svbool(x1->qh, vector_length);
const svbool_t qhh1p = load_as_svbool(((const uint8_t *) x1->qh + 2), vector_length);
const svint8_t qhl0 = svdup_n_s8_z(svnot_b_z(p16, qhl0p), 0x10);
const svint8_t qhh0 = svdup_n_s8_z(svnot_b_z(p16, qhh0p), 0x10);
const svint8_t qhl1 = svdup_n_s8_z(svnot_b_z(p16, qhl1p), 0x10);
const svint8_t qhh1 = svdup_n_s8_z(svnot_b_z(p16, qhh1p), 0x10);
const svuint8_t qx0r = svld1rq_u8(p16, x0->qs);
const svuint8_t qx1r = svld1rq_u8(p16, x1->qs);
const svint8_t qx0l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx0r, 0x0F));
const svint8_t qx0h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx0r, 0x04));
const svint8_t qx1l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx1r, 0x0F));
const svint8_t qx1h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx1r, 0x04));
const svint8_t qx0lf = svsub_s8_x(p16, qx0l, qhl0);
const svint8_t qx0hf = svsub_s8_x(p16, qx0h, qhh0);
const svint8_t qx1lf = svsub_s8_x(p16, qx1l, qhl1);
const svint8_t qx1hf = svsub_s8_x(p16, qx1h, qhh1);
const svint8_t qy0l = svld1_s8(p16, y0->qs);
const svint8_t qy0h = svld1_s8(p16, y0->qs + 16);
const svint8_t qy1l = svld1_s8(p16, y1->qs);
const svint8_t qy1h = svld1_s8(p16, y1->qs + 16);
sumv0 = svmla_n_f32_x(p4, sumv0, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
svdot_s32(svdup_n_s32(0), qx0lf, qy0l),
svdot_s32(svdup_n_s32(0), qx0hf, qy0h))), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
sumv1 = svmla_n_f32_x(p4, sumv1, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
svdot_s32(svdup_n_s32(0), qx1lf, qy1l),
svdot_s32(svdup_n_s32(0), qx1hf, qy1h))), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
}
sumf = svaddv_f32(p4, svadd_f32_x(p4, sumv0, sumv1));
} break;
case 256:
case 512:
{
const svbool_t p32 = svptrue_pat_b8(SV_VL32);
const svbool_t p16h = svptrue_pat_b8(SV_VL16);
const svbool_t p16l = svnot_b_z(p32, p16h);
const svbool_t p8 = svptrue_pat_b32(SV_VL8);
for (; ib + 1 < nb; ib += 2) {
const block_q5_0 * GGML_RESTRICT x0 = &x[ib];
const block_q5_0 * GGML_RESTRICT x1 = &x[ib + 1];
const block_q8_0 * GGML_RESTRICT y0 = &y[ib];
const block_q8_0 * GGML_RESTRICT y1 = &y[ib + 1];
svbool_t qhbits0p = load_as_svbool(x0->qh, vector_length);
svbool_t qhbits1p = load_as_svbool(x1->qh, vector_length);
const svint8_t qhbits0 = svdup_n_s8_z(svnot_b_z(p32, qhbits0p), 0x10);
const svint8_t qhbits1 = svdup_n_s8_z(svnot_b_z(p32, qhbits1p), 0x10);
const svuint8_t qx0r = svld1rq_u8(p32, x0->qs);
const svuint8_t qx1r = svld1rq_u8(p32, x1->qs);
const svint8_t qx0 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx0r, 0x0F), 0x04));
const svint8_t qx1 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx1r, 0x0F), 0x04));
const svint8_t qx0f = svsub_s8_x(p32, qx0, qhbits0);
const svint8_t qx1f = svsub_s8_x(p32, qx1, qhbits1);
const svint8_t qy0 = svld1_s8(p32, y0->qs);
const svint8_t qy1 = svld1_s8(p32, y1->qs);
sumv0 = svmla_n_f32_x(p8, sumv0, svcvt_f32_s32_x(p8,
svdot_s32(svdup_n_s32(0), qx0f, qy0)), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
sumv1 = svmla_n_f32_x(p8, sumv1, svcvt_f32_s32_x(p8,
svdot_s32(svdup_n_s32(0), qx1f, qy1)), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
}
sumf = svaddv_f32(p8, svadd_f32_x(p8, sumv0, sumv1));
} break;
default:
break;
}
#elif defined(__ARM_NEON)
float32x4_t sumv0 = vdupq_n_f32(0.0f);
float32x4_t sumv1 = vdupq_n_f32(0.0f);
@@ -1050,7 +1172,115 @@ void ggml_vec_dot_q5_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
const block_q5_1 * GGML_RESTRICT x = vx;
const block_q8_1 * GGML_RESTRICT y = vy;
#if defined(__ARM_NEON)
#if defined(__ARM_FEATURE_SVE)
svfloat32_t sumv0 = svdup_n_f32(0.0f);
svfloat32_t sumv1 = svdup_n_f32(0.0f);
float summs0 = 0.0f;
float summs1 = 0.0f;
const int vector_length = ggml_cpu_get_sve_cnt()*8;
switch (vector_length) {
case 128:
{
const svbool_t p16 = svptrue_pat_b8(SV_VL16);
const svbool_t p4 = svptrue_pat_b32(SV_VL4);
for (; ib + 1 < nb; ib += 2) {
const block_q5_1 * GGML_RESTRICT x0 = &x[ib];
const block_q5_1 * GGML_RESTRICT x1 = &x[ib + 1];
const block_q8_1 * GGML_RESTRICT y0 = &y[ib];
const block_q8_1 * GGML_RESTRICT y1 = &y[ib + 1];
summs0 += GGML_CPU_FP16_TO_FP32(x0->m) * GGML_CPU_FP16_TO_FP32(y0->s);
summs1 += GGML_CPU_FP16_TO_FP32(x1->m) * GGML_CPU_FP16_TO_FP32(y1->s);
const svbool_t qhl0p = load_as_svbool(x0->qh, vector_length);
const svbool_t qhh0p = load_as_svbool(((const uint8_t *) x0->qh + 2), vector_length);
const svbool_t qhl1p = load_as_svbool(x1->qh, vector_length);
const svbool_t qhh1p = load_as_svbool(((const uint8_t *) x1->qh + 2), vector_length);
const svint8_t qhl0 = svdup_n_s8_z(qhl0p, 0x10);
const svint8_t qhh0 = svdup_n_s8_z(qhh0p, 0x10);
const svint8_t qhl1 = svdup_n_s8_z(qhl1p, 0x10);
const svint8_t qhh1 = svdup_n_s8_z(qhh1p, 0x10);
const svuint8_t qx0r = svld1rq_u8(p16, x0->qs);
const svuint8_t qx1r = svld1rq_u8(p16, x1->qs);
const svint8_t qx0l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx0r, 0x0F));
const svint8_t qx0h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx0r, 0x04));
const svint8_t qx1l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx1r, 0x0F));
const svint8_t qx1h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx1r, 0x04));
const svint8_t qx0lf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx0l), svreinterpret_u8_s8(qhl0)));
const svint8_t qx0hf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx0h), svreinterpret_u8_s8(qhh0)));
const svint8_t qx1lf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx1l), svreinterpret_u8_s8(qhl1)));
const svint8_t qx1hf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx1h), svreinterpret_u8_s8(qhh1)));
const svint8_t qy0l = svld1_s8(p16, y0->qs);
const svint8_t qy0h = svld1_s8(p16, y0->qs + 16);
const svint8_t qy1l = svld1_s8(p16, y1->qs);
const svint8_t qy1h = svld1_s8(p16, y1->qs + 16);
sumv0 = svmla_n_f32_x(p4, sumv0, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
svdot_s32(svdup_n_s32(0), qx0lf, qy0l),
svdot_s32(svdup_n_s32(0), qx0hf, qy0h))), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
sumv1 = svmla_n_f32_x(p4, sumv1, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
svdot_s32(svdup_n_s32(0), qx1lf, qy1l),
svdot_s32(svdup_n_s32(0), qx1hf, qy1h))), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
}
sumf = svaddv_f32(p4, svadd_f32_x(p4, sumv0, sumv1)) + summs0 + summs1;
} break;
case 256:
case 512:
{
const svbool_t p32 = svptrue_pat_b8(SV_VL32);
const svbool_t p16h = svptrue_pat_b8(SV_VL16);
const svbool_t p16l = svnot_b_z(p32, p16h);
const svbool_t p8 = svptrue_pat_b32(SV_VL8);
for (; ib + 1 < nb; ib += 2) {
const block_q5_1 * GGML_RESTRICT x0 = &x[ib];
const block_q5_1 * GGML_RESTRICT x1 = &x[ib + 1];
const block_q8_1 * GGML_RESTRICT y0 = &y[ib];
const block_q8_1 * GGML_RESTRICT y1 = &y[ib + 1];
summs0 += GGML_CPU_FP16_TO_FP32(x0->m) * GGML_CPU_FP16_TO_FP32(y0->s);
summs1 += GGML_CPU_FP16_TO_FP32(x1->m) * GGML_CPU_FP16_TO_FP32(y1->s);
const svbool_t qhbits0p = load_as_svbool(x0->qh, vector_length);
const svbool_t qhbits1p = load_as_svbool(x1->qh, vector_length);
const svint8_t qhbits0 = svdup_n_s8_z(qhbits0p, 0x10);
const svint8_t qhbits1 = svdup_n_s8_z(qhbits1p, 0x10);
const svuint8_t qx0r = svld1rq_u8(p32, x0->qs);
const svuint8_t qx1r = svld1rq_u8(p32, x1->qs);
const svint8_t qx0 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx0r, 0x0F), 0x04));
const svint8_t qx1 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx1r, 0x0F), 0x04));
const svint8_t qx0f = svreinterpret_s8_u8(svorr_u8_x(p32, svreinterpret_u8_s8(qx0), svreinterpret_u8_s8(qhbits0)));
const svint8_t qx1f = svreinterpret_s8_u8(svorr_u8_x(p32, svreinterpret_u8_s8(qx1), svreinterpret_u8_s8(qhbits1)));
const svint8_t qy0 = svld1_s8(p32, y0->qs);
const svint8_t qy1 = svld1_s8(p32, y1->qs);
sumv0 = svmla_n_f32_x(p8, sumv0, svcvt_f32_s32_x(p8,
svdot_s32(svdup_n_s32(0), qx0f, qy0)), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
sumv1 = svmla_n_f32_x(p8, sumv1, svcvt_f32_s32_x(p8,
svdot_s32(svdup_n_s32(0), qx1f, qy1)), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
}
sumf = svaddv_f32(p8, svadd_f32_x(p8, sumv0, sumv1)) + summs0 + summs1;
} break;
default:
break;
}
#elif defined(__ARM_NEON)
float32x4_t sumv0 = vdupq_n_f32(0.0f);
float32x4_t sumv1 = vdupq_n_f32(0.0f);
@@ -4319,4 +4549,3 @@ void ggml_vec_dot_iq4_xs_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const v
ggml_vec_dot_iq4_xs_q8_K_generic(n, s, bs, vx, bx, vy, by, nrc);
#endif
}
+252
View File
@@ -66,6 +66,70 @@ static inline int8x16_t ggml_q1_0_unpack_pair(uint8_t bits0, uint8_t bits1) {
}
#endif
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
// Split repacked q4_0 bytes into sign-extended low and high nibbles
static inline void ggml_q4_0x4_unpack(int8x16_t b, int8x16_t * lo, int8x16_t * hi) {
*lo = vshrq_n_s8(vshlq_n_s8(b, 4), 4);
*hi = vshrq_n_s8(b, 4);
}
// w holds 8 bytes of 2 columns, a holds the same 8 bytes twice: acc[c] += column c * a
static inline void ggml_mla_2x8_s16(int16x8_t * acc, int8x16_t w, int8x16_t a) {
acc[0] = vmlal_s8(acc[0], vget_low_s8(w), vget_low_s8(a));
acc[1] = vmlal_high_s8(acc[1], w, a);
}
// w holds 8 bytes of 2 columns, a holds 8 bytes of 2 rows: r0[c] += column c * row 0, r1[c] += column c * row 1
static inline void ggml_mla_2x2x8_s16(int16x8_t * r0, int16x8_t * r1, int8x16_t w, int8x16_t a) {
const int8x16_t as = vextq_s8(a, a, 8);
r0[0] = vmlal_s8(r0[0], vget_low_s8(w), vget_low_s8(a));
r1[1] = vmlal_high_s8(r1[1], w, a);
r1[0] = vmlal_s8(r1[0], vget_low_s8(w), vget_low_s8(as));
r0[1] = vmlal_high_s8(r0[1], w, as);
}
// Same as ggml_mla_2x8_s16 for two chunks, widened to int32
static inline void ggml_dot2_2x8_s32(int32x4_t * acc, int8x16_t w0, int8x16_t a0, int8x16_t w1, int8x16_t a1) {
int16x8_t p0 = vmull_s8(vget_low_s8(w0), vget_low_s8(a0));
int16x8_t p1 = vmull_high_s8(w0, a0);
p0 = vmlal_s8(p0, vget_low_s8(w1), vget_low_s8(a1));
p1 = vmlal_high_s8(p1, w1, a1);
acc[0] = vpadalq_s16(acc[0], p0);
acc[1] = vpadalq_s16(acc[1], p1);
}
// Same as ggml_mla_2x2x8_s16 for two chunks, widened to int32
static inline void ggml_dot2_2x2x8_s32(int32x4_t * r0,
int32x4_t * r1,
int8x16_t w0,
int8x16_t a0,
int8x16_t w1,
int8x16_t a1) {
const int8x16_t as0 = vextq_s8(a0, a0, 8);
const int8x16_t as1 = vextq_s8(a1, a1, 8);
const int8x8_t w0l = vget_low_s8(w0);
const int8x8_t w1l = vget_low_s8(w1);
r0[0] = vpadalq_s16(r0[0], vmlal_s8(vmull_s8(w0l, vget_low_s8(a0)), w1l, vget_low_s8(a1)));
r1[1] = vpadalq_s16(r1[1], vmlal_high_s8(vmull_high_s8(w0, a0), w1, a1));
r1[0] = vpadalq_s16(r1[0], vmlal_s8(vmull_s8(w0l, vget_low_s8(as0)), w1l, vget_low_s8(as1)));
r0[1] = vpadalq_s16(r0[1], vmlal_high_s8(vmull_high_s8(w0, as0), w1, as1));
}
// Sum each of 4 int16 accumulators into one int32 lane, the lanes must be below 16384
static inline int32x4_t ggml_hsum_4x_s16(const int16x8_t * acc) {
return vpaddq_s32(vpaddlq_s16(vpaddq_s16(acc[0], acc[1])), vpaddlq_s16(vpaddq_s16(acc[2], acc[3])));
}
// Sum each of 4 int32 accumulators into one int32 lane
static inline int32x4_t ggml_hsum_4x_s32(const int32x4_t * acc) {
return vpaddq_s32(vpaddq_s32(acc[0], acc[1]), vpaddq_s32(acc[2], acc[3]));
}
#endif
void ggml_quantize_mat_q8_0_4x4(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
assert(k % QK8_0 == 0);
@@ -351,6 +415,46 @@ void ggml_gemv_q4_0_4x8_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
}
return;
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
#if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
// No dotprod: sum products in int16 lanes. Sign-extended nibbles allow 8 products per lane (8 * 8 * 127 < 32767), nibbles << 4 only 2.
// A 16-byte load holds 8 bytes of 2 columns, each column has its own accumulator with 4 products per lane.
const block_q4_0x4 * b_ptr = (const block_q4_0x4 *) vx;
for (int c = 0; c < nc; c += ncols_interleaved) {
const block_q8_0 * a_ptr = (const block_q8_0 *) vy;
float32x4_t acc = vdupq_n_f32(0);
for (int b = 0; b < nb; b++) {
int16x8_t sum[4] = { vdupq_n_s16(0), vdupq_n_s16(0), vdupq_n_s16(0), vdupq_n_s16(0) };
for (int k = 0; k < 2; k++) {
const int8x8_t al8 = vld1_s8(a_ptr->qs + 8 * k);
const int8x8_t ah8 = vld1_s8(a_ptr->qs + qk/2 + 8 * k);
const int8x16_t al = vcombine_s8(al8, al8);
const int8x16_t ah = vcombine_s8(ah8, ah8);
int8x16_t wl, wh;
ggml_q4_0x4_unpack(vld1q_s8(b_ptr->qs + 32 * k), &wl, &wh);
ggml_mla_2x8_s16(&sum[0], wl, al);
ggml_mla_2x8_s16(&sum[0], wh, ah);
ggml_q4_0x4_unpack(vld1q_s8(b_ptr->qs + 32 * k + 16), &wl, &wh);
ggml_mla_2x8_s16(&sum[2], wl, al);
ggml_mla_2x8_s16(&sum[2], wh, ah);
}
const float32x4_t bd = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr->d));
acc = vfmaq_f32(acc, vcvtq_f32_s32(ggml_hsum_4x_s16(sum)),
vmulq_n_f32(bd, GGML_CPU_FP16_TO_FP32(a_ptr->d)));
a_ptr++;
b_ptr++;
}
vst1q_f32(s, acc);
s += ncols_interleaved;
}
return;
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
ggml_gemv_q4_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
}
@@ -1957,6 +2061,43 @@ void ggml_gemv_q8_0_4x8_q8_0(int n,
return;
#endif // defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
// No dotprod: two products fit an int16 lane (2 * 128 * 127 < 32767), then widen to int32.
// A 16-byte load holds 8 bytes of 2 columns, each column has its own int32 accumulator.
const block_q8_0x4 * b_ptr = (const block_q8_0x4 *) vx;
for (int c = 0; c < nc; c += ncols_interleaved) {
const block_q8_0 * a_ptr = (const block_q8_0 *) vy;
float32x4_t acc = vdupq_n_f32(0);
for (int b = 0; b < nb; b++) {
int32x4_t sum[4] = { vdupq_n_s32(0), vdupq_n_s32(0), vdupq_n_s32(0), vdupq_n_s32(0) };
for (int k = 0; k < 4; k += 2) {
const int8x8_t a08 = vld1_s8(a_ptr->qs + 8 * k);
const int8x8_t a18 = vld1_s8(a_ptr->qs + 8 * (k + 1));
const int8x16_t a0 = vcombine_s8(a08, a08);
const int8x16_t a1 = vcombine_s8(a18, a18);
const int8_t * w0 = b_ptr->qs + 32 * k;
const int8_t * w1 = b_ptr->qs + 32 * (k + 1);
ggml_dot2_2x8_s32(&sum[0], vld1q_s8(w0), a0, vld1q_s8(w1), a1);
ggml_dot2_2x8_s32(&sum[2], vld1q_s8(w0 + 16), a0, vld1q_s8(w1 + 16), a1);
}
const float32x4_t bd = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr->d));
acc =
vfmaq_f32(acc, vcvtq_f32_s32(ggml_hsum_4x_s32(sum)), vmulq_n_f32(bd, GGML_CPU_FP16_TO_FP32(a_ptr->d)));
a_ptr++;
b_ptr++;
}
vst1q_f32(s, acc);
s += ncols_interleaved;
}
return;
#endif // defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
ggml_gemv_q8_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
}
@@ -2985,6 +3126,64 @@ void ggml_gemm_q4_0_4x8_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
);
return;
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_MATMUL_INT8)
#if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
// No dotprod: see ggml_gemv_q4_0_4x8_q8_0, one int16 accumulator per (row, column). The high nibbles go with the activations at qs + 64.
for (int y = 0; y < nr / 4; y++) {
const block_q8_0x4 * a_ptr = (const block_q8_0x4 *) vy + (y * nb);
for (int x = 0; x < nc / ncols_interleaved; x++) {
const block_q4_0x4 * b_ptr = (const block_q4_0x4 *) vx + (x * nb);
float32x4_t sumf[4];
for (int m = 0; m < 4; m++) {
sumf[m] = vdupq_n_f32(0);
}
for (int l = 0; l < nb; l++) {
int16x8_t sum[4][4];
for (int m = 0; m < 4; m++) {
for (int j = 0; j < 4; j++) {
sum[m][j] = vdupq_n_s16(0);
}
}
for (int k = 0; k < 2; k++) {
int8x16_t w01l, w01h, w23l, w23h;
ggml_q4_0x4_unpack(vld1q_s8(b_ptr[l].qs + 32 * k), &w01l, &w01h);
ggml_q4_0x4_unpack(vld1q_s8(b_ptr[l].qs + 32 * k + 16), &w23l, &w23h);
const int8x16_t a01l = vld1q_s8(a_ptr[l].qs + 32 * k);
const int8x16_t a23l = vld1q_s8(a_ptr[l].qs + 32 * k + 16);
const int8x16_t a01h = vld1q_s8(a_ptr[l].qs + 64 + 32 * k);
const int8x16_t a23h = vld1q_s8(a_ptr[l].qs + 64 + 32 * k + 16);
ggml_mla_2x2x8_s16(&sum[0][0], &sum[1][0], w01l, a01l);
ggml_mla_2x2x8_s16(&sum[0][2], &sum[1][2], w23l, a01l);
ggml_mla_2x2x8_s16(&sum[2][0], &sum[3][0], w01l, a23l);
ggml_mla_2x2x8_s16(&sum[2][2], &sum[3][2], w23l, a23l);
ggml_mla_2x2x8_s16(&sum[0][0], &sum[1][0], w01h, a01h);
ggml_mla_2x2x8_s16(&sum[0][2], &sum[1][2], w23h, a01h);
ggml_mla_2x2x8_s16(&sum[2][0], &sum[3][0], w01h, a23h);
ggml_mla_2x2x8_s16(&sum[2][2], &sum[3][2], w23h, a23h);
}
const float32x4_t b_d = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr[l].d));
const float32x4_t a_d = vcvt_f32_f16(vld1_f16((const __fp16 *) a_ptr[l].d));
sumf[0] = vfmaq_f32(sumf[0], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[0])), vmulq_laneq_f32(b_d, a_d, 0));
sumf[1] = vfmaq_f32(sumf[1], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[1])), vmulq_laneq_f32(b_d, a_d, 1));
sumf[2] = vfmaq_f32(sumf[2], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[2])), vmulq_laneq_f32(b_d, a_d, 2));
sumf[3] = vfmaq_f32(sumf[3], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[3])), vmulq_laneq_f32(b_d, a_d, 3));
}
for (int m = 0; m < 4; m++) {
vst1q_f32(s + (y * 4 + m) * bs + x * ncols_interleaved, sumf[m]);
}
}
}
return;
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
ggml_gemm_q4_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
}
@@ -5602,6 +5801,59 @@ void ggml_gemm_q8_0_4x8_q8_0(int n,
}
return;
#endif // defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_MATMUL_INT8)
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
// No dotprod: see ggml_gemv_q8_0_4x8_q8_0, one int32 accumulator per (row, column)
for (int y = 0; y < nr / 4; y++) {
const block_q8_0x4 * a_ptr = (const block_q8_0x4 *) vy + (y * nb);
for (int x = 0; x < nc / ncols_interleaved; x++) {
const block_q8_0x4 * b_ptr = (const block_q8_0x4 *) vx + (x * nb);
float32x4_t sumf[4];
for (int m = 0; m < 4; m++) {
sumf[m] = vdupq_n_f32(0);
}
for (int l = 0; l < nb; l++) {
int32x4_t sum[4][4];
for (int m = 0; m < 4; m++) {
for (int j = 0; j < 4; j++) {
sum[m][j] = vdupq_n_s32(0);
}
}
for (int k = 0; k < 4; k += 2) {
const int8x16_t w01_0 = vld1q_s8(b_ptr[l].qs + 32 * k);
const int8x16_t w23_0 = vld1q_s8(b_ptr[l].qs + 32 * k + 16);
const int8x16_t w01_1 = vld1q_s8(b_ptr[l].qs + 32 * (k + 1));
const int8x16_t w23_1 = vld1q_s8(b_ptr[l].qs + 32 * (k + 1) + 16);
const int8x16_t a01_0 = vld1q_s8(a_ptr[l].qs + 32 * k);
const int8x16_t a23_0 = vld1q_s8(a_ptr[l].qs + 32 * k + 16);
const int8x16_t a01_1 = vld1q_s8(a_ptr[l].qs + 32 * (k + 1));
const int8x16_t a23_1 = vld1q_s8(a_ptr[l].qs + 32 * (k + 1) + 16);
ggml_dot2_2x2x8_s32(&sum[0][0], &sum[1][0], w01_0, a01_0, w01_1, a01_1);
ggml_dot2_2x2x8_s32(&sum[0][2], &sum[1][2], w23_0, a01_0, w23_1, a01_1);
ggml_dot2_2x2x8_s32(&sum[2][0], &sum[3][0], w01_0, a23_0, w01_1, a23_1);
ggml_dot2_2x2x8_s32(&sum[2][2], &sum[3][2], w23_0, a23_0, w23_1, a23_1);
}
const float32x4_t a_d = vcvt_f32_f16(vld1_f16((const float16_t *) a_ptr[l].d));
const float32x4_t b_d = vcvt_f32_f16(vld1_f16((const float16_t *) b_ptr[l].d));
sumf[0] = vfmaq_f32(sumf[0], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[0])), vmulq_laneq_f32(b_d, a_d, 0));
sumf[1] = vfmaq_f32(sumf[1], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[1])), vmulq_laneq_f32(b_d, a_d, 1));
sumf[2] = vfmaq_f32(sumf[2], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[2])), vmulq_laneq_f32(b_d, a_d, 2));
sumf[3] = vfmaq_f32(sumf[3], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[3])), vmulq_laneq_f32(b_d, a_d, 3));
}
for (int m = 0; m < 4; m++) {
vst1q_f32(s + (y * 4 + m) * bs + x * ncols_interleaved, sumf[m]);
}
}
}
return;
#endif // defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
ggml_gemm_q8_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
}
+128 -15
View File
@@ -1287,6 +1287,57 @@ static void ggml_compute_forward_mul_mat_one_chunk(
}
}
// converts n BF16 values (whole blocks of vec_dot_type) to vec_dot_type: widened directly to F32, otherwise via F32 in chunks
static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64_t n, enum ggml_type vec_dot_type) {
if (vec_dot_type == GGML_TYPE_F32) {
ggml_cpu_bf16_to_fp32(x, (float *) y, n);
return;
}
ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
const int64_t bs = ggml_blck_size(vec_dot_type);
float tmp[1024];
const int64_t chunk = (1024/bs)*bs;
for (int64_t i = 0; i < n; i += chunk) {
const int64_t nc = MIN(chunk, n - i);
ggml_cpu_bf16_to_fp32(x + i, tmp, nc);
from_float(tmp, (char *) y + (i/bs)*ggml_type_size(vec_dot_type), nc);
}
}
// apply the weight scale (src[2]) carried by ggml_mul_mat_ext, broadcast over dst
static void ggml_compute_forward_mul_mat_scale(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
const struct ggml_tensor * scale = dst->src[2];
if (!scale) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2], ne3 = dst->ne[3];
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3];
ggml_barrier(params->threadpool);
const char * sd = (const char *) scale->data;
const int64_t sne0 = scale->ne[0], sne1 = scale->ne[1], sne2 = scale->ne[2], sne3 = scale->ne[3];
const int64_t nr = ne1 * ne2 * ne3;
for (int64_t ir = ith; ir < nr; ir += nth) {
const int64_t i1 = ir % ne1;
const int64_t i2 = (ir / ne1) % ne2;
const int64_t i3 = ir / (ne1 * ne2);
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2 + i3*nb3);
const size_t so = (i1 % sne1)*scale->nb[1] + (i2 % sne2)*scale->nb[2] + (i3 % sne3)*scale->nb[3];
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= *(const float *) (sd + (i0 % sne0)*scale->nb[0] + so);
}
}
}
void ggml_compute_forward_mul_mat(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1302,6 +1353,7 @@ void ggml_compute_forward_mul_mat(
// If tiled is supported, it will execute the full op here and we return
if (ggml_compute_forward_mul_mat_tiled(params, dst)) {
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
@@ -1358,6 +1410,7 @@ void ggml_compute_forward_mul_mat(
src1->type,
dst->type))
goto UseGgmlGemm1;
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
UseGgmlGemm1:;
@@ -1372,11 +1425,9 @@ UseGgmlGemm1:;
const size_t nbw3 = nbw2*ne12;
assert(params->wsize >= ne13*nbw3);
// src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
const bool widen = src1->type != GGML_TYPE_F32;
GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32);
GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16);
// src1 is either packed from F32 or BF16 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
(src1->type == GGML_TYPE_F16 && vec_dot_type == GGML_TYPE_F32));
#if 0
for (int64_t i13 = 0; i13 < ne13; ++i13) {
@@ -1404,7 +1455,7 @@ UseGgmlGemm1:;
if (src1->type == GGML_TYPE_F16) {
ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size);
} else if (src1->type == GGML_TYPE_BF16) {
ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size);
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, ne10_block_size, vec_dot_type);
} else {
from_float((const float *) src1_row, wdata_row, ne10_block_size);
}
@@ -1440,6 +1491,7 @@ UseGgmlGemm1:;
vec_dot_type,
dst->type))
goto UseGgmlGemm2;
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
UseGgmlGemm2:;
@@ -1507,6 +1559,8 @@ UseGgmlGemm2:;
current_chunk = atomic_fetch_add_explicit(&params->threadpool->current_chunk, 1, memory_order_relaxed);
}
ggml_compute_forward_mul_mat_scale(params, dst);
}
// ggml_compute_forward_mul_mat_id
@@ -1589,6 +1643,53 @@ static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
return ptr;
}
// apply the weight scale (src[3]) carried by ggml_mul_mat_id_ext: per-tensor [1],
// per-expert [n_expert] or per-channel-per-expert [n_out, n_expert], indexed via ids
static void ggml_compute_forward_mul_mat_id_scale(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
const struct ggml_tensor * scale = dst->src[3];
if (!scale) {
return;
}
const struct ggml_tensor * ids = dst->src[2];
const int ith = params->ith;
const int nth = params->nth;
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2];
const int64_t ne02 = dst->src[0]->ne[2];
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2];
ggml_barrier(params->threadpool);
const char * sd = (const char *) scale->data;
const bool per_ch_exp = scale->ne[0] == ne0 && scale->ne[1] == ne02;
const bool per_expert = ggml_nelements(scale) == ne02;
const int64_t nr = ne1 * ne2;
for (int64_t ir = ith; ir < nr; ir += nth) {
const int64_t i1 = ir % ne1;
const int64_t i2 = ir / ne1;
const int32_t expert = *(const int32_t *) ((const char *) ids->data + i1*ids->nb[0] + i2*ids->nb[1]);
if (expert < 0) {
continue;
}
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2);
if (per_ch_exp) {
const char * sp = sd + expert*scale->nb[1];
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= *(const float *) (sp + i0*scale->nb[0]);
}
} else {
const float s = *(const float *) (sd + (per_expert ? expert*scale->nb[0] : 0));
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= s;
}
}
}
}
static void ggml_compute_forward_mul_mat_id(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1656,7 +1757,7 @@ static void ggml_compute_forward_mul_mat_id(
const size_t nbw3 = nbw2*ne12;
assert(params->wsize >= ne13*nbw3);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
#if 0
for (int64_t i13 = 0; i13 < ne13; ++i13) {
@@ -1675,9 +1776,13 @@ static void ggml_compute_forward_mul_mat_id(
size_t bs = ggml_blck_size(vec_dot_type);
int64_t ne10_block_start = (ith * ne10/bs) / nth;
int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
(void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
(ne10_block_end - ne10_block_start) * bs);
const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10;
void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0;
if (src1->type == GGML_TYPE_BF16) {
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs, vec_dot_type);
} else {
from_float((const float *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs);
}
}
}
}
@@ -1779,6 +1884,8 @@ static void ggml_compute_forward_mul_mat_id(
current_chunk = atomic_fetch_add_explicit(current_chunk_ctr, 1, memory_order_relaxed);
}
}
ggml_compute_forward_mul_mat_id_scale(params, dst);
}
/////////////////////////////////
@@ -1792,6 +1899,11 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm
// extra_buffer op?
if (ggml_cpu_extra_compute_forward(params, tensor)) {
if (tensor->op == GGML_OP_MUL_MAT) {
ggml_compute_forward_mul_mat_scale(params, tensor);
} else if (tensor->op == GGML_OP_MUL_MAT_ID) {
ggml_compute_forward_mul_mat_id_scale(params, tensor);
}
return;
}
@@ -2909,7 +3021,7 @@ struct ggml_cplan ggml_graph_plan(
case GGML_OP_ADD:
case GGML_OP_ADD_ID:
{
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3) {
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type)) {
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
}
} break;
@@ -2957,7 +3069,7 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_OUT_PROD:
{
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3 ||
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type) ||
node->src[0]->type == GGML_TYPE_F16) {
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
}
@@ -3068,9 +3180,10 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_GATED_DELTA_NET:
{
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
const int64_t S_v = node->src[2]->ne[0];
const int64_t K = ggml_get_op_params_i32(node, 0);
const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
cur = per_thread * sizeof(float) * n_tasks;
} break;
case GGML_OP_COUNT:
+17 -6
View File
@@ -398,6 +398,7 @@ static void ggml_backend_cpu_device_get_props(ggml_backend_dev_t dev, struct ggm
/* .buffer_from_host_ptr = */ true,
/* .events = */ false,
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
};
}
@@ -440,6 +441,8 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
}
switch (op->op) {
case GGML_OP_FLASH_ATTN_EXT:
return ggml_validate_flash_attn_ext_indexed_bias(op);
case GGML_OP_CPY:
case GGML_OP_SET_ROWS:
return
@@ -452,14 +455,19 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
case GGML_OP_MUL_MAT:
if (ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD &&
src0->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) {
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16;
src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) {
// the hinted matmul is an FWHT of src1 for every src0 type, which reads F32 or F16 only;
// with use_ref it takes the general path instead, so src1 has to pass the check below too
return false;
}
// F16 or BF16 in src1 is widened into the F32 work buffer
return src1->type == GGML_TYPE_F32 ||
// F16 in src1 is widened into the F32 work buffer, BF16 is widened or converted to vec_dot_type
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type ||
((src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16) &&
ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
(src1->type == GGML_TYPE_F16 && ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
case GGML_OP_MUL_MAT_ID:
// src1 is converted to vec_dot_type from F32 or BF16 only
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type;
case GGML_OP_SOFT_MAX_BACK: {
if (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32) {
return false;
@@ -688,6 +696,9 @@ static void * ggml_backend_cpu_get_proc_address(ggml_backend_reg_t reg, const ch
if (strcmp(name, "ggml_threadpool_free") == 0) {
return (void *)ggml_threadpool_free;
}
if (strcmp(name, "ggml_threadpool_pause") == 0) {
return (void *)ggml_threadpool_pause;
}
if (strcmp(name, "ggml_backend_cpu_set_threadpool") == 0) {
return (void *)ggml_backend_cpu_set_threadpool;
}
+2 -2
View File
@@ -8,7 +8,7 @@ if (NOT TARGET kleidiai)
endif()
if (MSVC)
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:/WX->)
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:/WX-;/w>")
else()
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error>)
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error;-w>")
endif()
+82 -7
View File
@@ -615,7 +615,7 @@ static void ggml_compute_forward_add_q_f32(
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(ne00 % ggml_blck_size(type) == 0);
@@ -965,7 +965,7 @@ static void ggml_compute_forward_add1_q_f32(
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
GGML_ASSERT(dst->type == src0->type);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
@@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
@@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int64_t rv2 = neq2/nev2;
const int64_t rv3 = neq3/nev3;
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
// parallelize by q rows using ggml_vec_dot_f32
float scale = 1.0f;
@@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
// bias rows of this query and head, queries of all streams are flattened
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
// online softmax / attention
// loop over n_kv and n_head_kv
// ref: https://arxiv.org/pdf/2112.05682.pdf
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
if (bias) {
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
mv += bias[bins[ic]];
}
mv *= slope;
if (mv == -INFINITY) {
continue;
}
@@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
const ggml_tensor * kv_rows = dst->src[5];
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
const ggml_tensor * bias_table = dst->src[6];
const ggml_tensor * bias_indices = dst->src[7];
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
int ir = ir0;
while (ir < ir1) {
// q indices for the start of this tile
@@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
bool can_skip = true;
for (int tq = 0; tq < tile_rows; tq++) {
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
for (int tk = 0; tk < kv_tile; tk++) {
mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
if (bias) {
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
m += bias[bins[ic + tk]];
}
mask32[tq * KV_TILE_SZ + tk] = slope * m;
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
can_skip = false;
}
@@ -9698,6 +9722,7 @@ static void ggml_compute_forward_flash_attn_ext_f16(
void ggml_compute_forward_flash_attn_ext(
const ggml_compute_params * params,
ggml_tensor * dst) {
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(dst));
switch (ggml_prec_get_acc(dst)) {
case GGML_PREC_UNDEFINED:
case GGML_PREC_F32:
@@ -11289,11 +11314,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// per-seq stride in floats (seq s starts at state + s * seq_stride)
const int64_t state_seq_stride = src_state->nb[3] / sizeof(float);
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
const ggml_tensor * src_pk = dst->src[6];
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_n_rep = dst->src[9];
const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0;
const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0;
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
const int ith = params->ith;
float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32;
float * state_work = K > 1 ? (delta + S_v) : nullptr;
float * state_work = K > 1 || keep ? (delta + S_v) : nullptr;
// output layout: [attn_scores | new_states]
// attn_scores: S_v * H * n_tokens * n_seqs floats
@@ -11327,7 +11360,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
// For K=1, write directly to the single output slot to avoid an extra memcpy at the end.
// For K>1, work in scratch and copy out per-token when the slot is in range.
float * s_out = (K > 1)
float * s_out = (K > 1 || keep)
? state_work
: state_out_base + (iv3 * H + iv1) * S_v * S_v;
@@ -11336,6 +11369,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v;
memcpy(s_out, s_in, S_v * S_v * sizeof(float));
if (src_pk) {
const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3];
GGML_ASSERT(n_r >= 0 && n_r <= n_pend);
const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1];
const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1];
const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1];
for (int64_t t = 0; t < n_r; t++) {
const float * k_d = (const float *) (pk + t*src_pk->nb[2]);
const float * v_d = (const float *) (pv + t*src_pv->nb[2]);
const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]);
const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]);
if (kda) {
for (int64_t i = 0; i < S_v; ++i) {
delta[i] = expf(g_d[i]);
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta);
}
} else {
ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0]));
}
for (int64_t j = 0; j < S_v; ++j) {
float sum = 0.0f;
ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1);
delta[j] = (v_d[j] - sum) * beta_val;
}
for (int64_t j = 0; j < S_v; ++j) {
ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]);
}
}
// the committed state, the new tokens go on in the scratch
if (keep) {
memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float));
}
}
// attn output pointer for first token of this (head, seq)
float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v;
+18
View File
@@ -4992,6 +4992,15 @@ static const ggml::cpu::tensor_traits * ggml_repack_get_optimal_repack_type(cons
return &q4_0_4x4_q8_0;
}
}
#if defined(__aarch64__) && !defined(__APPLE__)
// no dotprod (e.g. Cortex-A53): AArch64 only, on 32-bit ARM the 4x8 kernels run scalar code
// not on Apple: repacked weights cannot go to BLAS (Accelerate), which is faster there for large batches
if (ggml_cpu_has_neon() && !ggml_cpu_has_dotprod()) {
if (cur->ne[1] % 4 == 0) {
return &q4_0_4x8_q8_0;
}
}
#endif
if (ggml_cpu_has_vxe()) {
if (cur->ne[1] % 4 == 0) {
return &q4_0_4x4_q8_0;
@@ -5118,6 +5127,15 @@ static const ggml::cpu::tensor_traits * ggml_repack_get_optimal_repack_type(cons
return &q8_0_4x4_q8_0;
}
}
#if defined(__aarch64__) && !defined(__APPLE__)
// no dotprod (e.g. Cortex-A53): AArch64 only, on 32-bit ARM the 4x8 kernels run scalar code
// not on Apple: repacked weights cannot go to BLAS (Accelerate), which is faster there for large batches
if (ggml_cpu_has_neon() && !ggml_cpu_has_dotprod()) {
if (cur->ne[1] % 4 == 0) {
return &q8_0_4x8_q8_0;
}
}
#endif
if (ggml_cpu_has_riscv_v()) {
#if defined __riscv_zvfh
switch (__riscv_vlenb() * 8) {
+4 -3
View File
@@ -1047,8 +1047,8 @@ class tensor_traits_common : public tensor_traits_base {
return true;
}
case GGML_OP_FLASH_ATTN_EXT:
// K/V row lists are handled by the generic CPU path
if (op->src[5] != nullptr) {
// K/V row lists and the indexed bias are handled by the generic CPU path
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
return false;
}
forward_flash_attn_ext_f16(params, op);
@@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base {
}
return true;
case GGML_OP_GATED_DELTA_NET:
if (params->use_ref) {
// the generic kernel does the replay of pending tokens (op param 1)
if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) {
return false;
}
switch (op->src[0]->type) {
+13 -11
View File
@@ -1199,13 +1199,15 @@ void forward_flash_attn_ext_f16_one_chunk_vlen1024_vf16(const ggml_compute_param
(iq3 % mask->ne[3]) * mask->nb[3]) :
NULL;
const bool mp_equal_2 = iq1_1 == iq1 && (iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) &&
(iq3 % mask->ne[3]) == (iq3_1 % mask->ne[3]);
// the multi-row kernels share one mask row and one ALiBi slope across the grouped q rows
const bool mp_equal_2 =
max_bias == 0.0f && iq1_1 == iq1 &&
(!mask || ((iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_1 % mask->ne[3])));
const bool mp_equal_4 = mp_equal_2 && iq1_2 == iq1 && (iq2 % mask->ne[2]) == (iq2_2 % mask->ne[2]) &&
(iq3 % mask->ne[3]) == (iq3_2 % mask->ne[3]) && iq1_3 == iq1 &&
(iq2 % mask->ne[2]) == (iq2_3 % mask->ne[2]) &&
(iq3 % mask->ne[3]) == (iq3_3 % mask->ne[3]);
const bool mp_equal_4 =
mp_equal_2 && iq1_2 == iq1 && iq1_3 == iq1 &&
(!mask || ((iq2 % mask->ne[2]) == (iq2_2 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_2 % mask->ne[3]) &&
(iq2 % mask->ne[2]) == (iq2_3 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_3 % mask->ne[3])));
// k indices
const int ik3 = iq3 / rk3;
@@ -1514,7 +1516,11 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(const ggml_compute_params *
}
}
// Set padded KQ entries to -inf so softmax gives them zero weight
if (logit_softcap != 0.0f) {
rvv_softcap_tanh_inplace_f32(KQ, KV_TILE_SZ, tile_rows, KV_TILE_SZ, logit_softcap);
}
// Set padded KQ entries to -inf so softmax gives them zero weight (after softcap, which would make them finite)
if (kv_tile < KV_TILE_SZ) {
for (int tq = 0; tq < tile_rows; tq++) {
for (int tk = kv_tile; tk < KV_TILE_SZ; tk++) {
@@ -1523,10 +1529,6 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(const ggml_compute_params *
}
}
if (logit_softcap != 0.0f) {
rvv_softcap_tanh_inplace_f32(KQ, KV_TILE_SZ, tile_rows, KV_TILE_SZ, logit_softcap);
}
if (mask) {
rvv_add_inplace_f32(KQ, KV_TILE_SZ, mask32, KV_TILE_SZ, tile_rows, KV_TILE_SZ);
}
+1 -1
View File
@@ -627,7 +627,7 @@ static bool ggml_tiled_supported(const struct ggml_tensor * src0,
case GGML_TYPE_IQ3_S:
case GGML_TYPE_IQ1_S:
case GGML_TYPE_IQ1_M:
return true;
break;
default:
return false;
}
+1 -5
View File
@@ -116,16 +116,12 @@ if (CUDAToolkit_FOUND)
list(APPEND GGML_HEADERS_CUDA "../../include/ggml-cuda.h")
file(GLOB GGML_SOURCES_CUDA "*.cu")
file(GLOB SRCS "template-instances/fattn-tile*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/fattn-mma*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmq*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmf*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_add_backend_library(ggml-cuda
+14 -12
View File
@@ -2,26 +2,28 @@
static __global__ void add_id_kernel(
const float * src0, const float * src1, const int32_t * src2, float * dst,
int64_t ne0, int64_t ne1,
int64_t ne0, int64_t ne1, int64_t ne2,
size_t nb01, size_t nb02,
size_t nb11,
size_t nb21
) {
const int64_t i1 = blockIdx.x;
const int64_t i2 = blockIdx.y;
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
// gridDim.y is capped at 65535, blocks stride over larger ne2
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
}
}
}
@@ -47,10 +49,10 @@ void ggml_cuda_op_add_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
float * dst_d = (float *)dst->data;
int threads = std::min((int)ne00, 768); // cols
dim3 blocks(ne01, ne02); // n_experts_used, n_tokens
dim3 blocks(ne01, std::min(ne02, (int64_t)65535)); // n_experts_used, n_tokens
add_id_kernel<<<blocks, threads, 0, ctx.stream()>>>(
src0_d, src1_d, src2_d, dst_d,
ne0, ne1,
ne0, ne1, ne2,
nb01, nb02,
nb11,
nb21
+12
View File
@@ -256,6 +256,18 @@ static void launch_bin_bcast_pack(const ggml_tensor * src0, const ggml_tensor *
size_t s02 = nb02 / sizeof(src0_t);
size_t s03 = nb03 / sizeof(src0_t);
// the index of a dim of size 1 is always 0, so its stride is never applied,
// but after collapsing contiguous dims it can be the whole tensor size and exceed 32 bits
if (cne0[1] == 1) { s01 = 0; }
if (cne0[2] == 1) { s02 = 0; }
if (cne0[3] == 1) { s03 = 0; }
if (cne1[1] == 1) { s11 = 0; }
if (cne1[2] == 1) { s12 = 0; }
if (cne1[3] == 1) { s13 = 0; }
if (ne1 == 1) { s1 = 0; }
if (ne2 == 1) { s2 = 0; }
if (ne3 == 1) { s3 = 0; }
GGML_ASSERT(ne0 <= std::numeric_limits<uint32_t>::max());
GGML_ASSERT(ne1 <= std::numeric_limits<uint32_t>::max());
GGML_ASSERT(ne2 <= std::numeric_limits<uint32_t>::max());
+6
View File
@@ -412,6 +412,11 @@ static bool ggml_cuda_is_aligned(const ggml_tensor * tensor, const size_t alignm
tensor->nb[3] % alignment == 0;
}
static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) {
return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE ||
t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE;
}
static constexpr __device__ int ggml_cuda_get_physical_warp_size() {
#if defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__))
return 64;
@@ -1304,6 +1309,7 @@ struct ggml_cuda_device_info {
size_t smpb; // max. shared memory per block
size_t smpbo; // max. shared memory per block (with opt-in)
bool integrated; // Device is integrated as opposed to discrete
enum ggml_backend_dev_type type; // GPU or IGPU, from cudaDeviceProp::integrated
bool vmm; // virtual memory support
size_t vmm_granularity; // granularity of virtual memory
size_t total_vram;
+24 -21
View File
@@ -104,38 +104,41 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
uint64_t nb13,
int64_t ne0,
int64_t /*ne1*/,
int64_t /*ne2*/,
int64_t /*ne3*/,
int64_t ne2,
int64_t ne3,
uint64_t nb0,
uint64_t nb1,
uint64_t nb2,
uint64_t nb3) {
static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]");
const int64_t i3 = blockIdx.z;
const int64_t i2 = blockIdx.y;
const int64_t i1 = blockIdx.x;
const T * x;
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else if constexpr (dim == 3) {
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
// gridDim.y and gridDim.z are capped at 65535, loop over the rest of ne2 and ne3
for (int64_t i3 = blockIdx.z; i3 < ne3; i3 += gridDim.z) {
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
} else {
if constexpr (dim == 0) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
} else if constexpr (dim == 1) {
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
} else if constexpr (dim == 2) {
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
} else if constexpr (dim == 3) {
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
}
}
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
}
}
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
*y = *x;
}
}
@@ -163,7 +166,7 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml
} else {
GGML_ASSERT(!ggml_is_quantized(src0->type));
dim3 grid_dim(dst->ne[1], dst->ne[2], dst->ne[3]);
dim3 grid_dim(dst->ne[1], std::min<int64_t>(dst->ne[2], 65535), std::min<int64_t>(dst->ne[3], 65535));
auto launch_kernel = [&](auto dim) {
concat_non_cont<T, dim><<<grid_dim, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
+2 -2
View File
@@ -385,7 +385,7 @@ static __global__ void dequantize_block_nvfp4(
const void * __restrict__ vx,
dst_t * __restrict__ yy,
const int64_t ne) {
const int64_t i = blockIdx.x;
const int64_t i = (int64_t) blockIdx.x*blockDim.y + threadIdx.y;
const int tid = threadIdx.x;
const int64_t base = i * QK_NVFP4;
@@ -417,7 +417,7 @@ static void dequantize_row_nvfp4_cuda(
cudaStream_t stream) {
GGML_ASSERT(k % QK_NVFP4 == 0);
const int nb = k / QK_NVFP4;
dequantize_block_nvfp4<<<nb, 32, 0, stream>>>(vx, y, k);
dequantize_block_nvfp4<<<(nb + 7)/8, dim3(32, 8), 0, stream>>>(vx, y, k);
}
template <typename src_t, typename dst_t>
static __global__ void convert_unary(
+2
View File
@@ -1,3 +1,5 @@
#pragma once
// Simplified API for asynchronous data loading.
#include "common.cuh"
+330 -29
View File
@@ -2,6 +2,8 @@
#include "common.cuh"
#include "convert.cuh"
#include "cp-async.cuh"
#include "mma.cuh"
#include "vecdotq.cuh"
#include <cstdint>
@@ -18,16 +20,38 @@
// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
typedef void (* fattn_kernel_t)(
const char * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const char * __restrict__ mask,
const char * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
struct fattn_indexed_bias {
const float * table;
const int32_t * indices;
int64_t n_bins;
int64_t n_keys;
int64_t query_stride;
__device__ fattn_indexed_bias for_head(int64_t first_query, int head) const {
return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride};
}
__device__ float add(float mask, int query, int key) const {
const int bin = indices[query*n_keys + key];
return bin >= 0 && bin < n_bins ? mask + table[query*query_stride + bin] : mask;
}
};
// ggml-cpu returns zero for the 0/0 of a fully masked query.
static __device__ __forceinline__ float fattn_normalize(float value, float rowsum) {
return value == 0.0f && rowsum == 0.0f ? 0.0f : value/rowsum;
}
using fattn_kernel_t = void (*)(
const float2 * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const half * __restrict__ mask,
const float * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
const float scale,
const float max_bias,
const float m0,
@@ -35,16 +59,22 @@ typedef void (* fattn_kernel_t)(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33);
const int32_t s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias);
typedef float (*vec_dot_KQ_t)(
const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds);
template <typename T_src, typename T_dst>
using fattn_load_tile_t = void (*)(
const T_src * __restrict__ KV, T_dst * __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * __restrict__ indices);
struct ggml_cuda_flash_attn_ext_f16_extra_data {
uintptr_t K;
uintptr_t V;
@@ -669,6 +699,253 @@ static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict
}
}
template <int warp_size, int nwarps, int I, int J, int stride_tile,
bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle,
typename T_src, typename T_dst>
struct flash_attn_load_tile_impl;
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, true, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if constexpr (KV_indirection) {
// K/V rows given per mask column, negative rows are padding
i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
uint32_t offset = i*stride_tile*sizeof(half2) + k*cpy_nb;
if constexpr (use_swizzle) {
offset = ggml_cuda_mma::swizzle<stride_tile*sizeof(half2), char>(offset, i);
}
cp_async_cg_16<preload>(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*cpy_ne : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*cpy_ne;
} else {
src = KV + int64_t(k_VKQ_0 + i)*stride_KV + k*cpy_ne;
}
} else {
src = zero;
}
half2 * dst;
if constexpr (use_swizzle) {
dst = ggml_cuda_mma::swizzle<stride_tile>(tile_KV, i*stride_tile + k*cpy_ne, i);
} else {
dst = tile_KV + i*stride_tile + k*cpy_ne;
}
ggml_cuda_memcpy_1<cpy_nb>(dst, src);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, false, half2, float> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int h2_per_chunk = cpy_ne / 2;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / h2_per_chunk;
const half2 * const __restrict__ KV_0 = use_sparse || (KV_indirection && indices) ? KV : KV + int64_t(k_VKQ_0)*stride_KV;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[h2_per_chunk] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
if (indices) {
const int64_t i_KV = max(indices[k_VKQ_0 + i], 0);
src = KV_0 + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = zero;
}
__align__(16) half2 tmp_h2[h2_per_chunk];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(tmp_h2, src);
__align__(16) float2 tmp_f2[h2_per_chunk];
#pragma unroll
for (int l = 0; l < h2_per_chunk; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle, typename T_src, typename T_dst>
static __device__ __forceinline__ void flash_attn_load_tile(
const T_src * const __restrict__ KV, T_dst * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, use_cp_async, oob_check, use_sparse, KV_indirection, use_swizzle, T_src, T_dst>::load(
KV, tile_KV, D2, stride_KV, k_VKQ_0, i_sup, indices);
}
// Helper function to get a C++ type for calculating pointer offsets from a ggml type:
template <ggml_type type>
static __host__ __device__ auto ggml_cuda_fattn_kv_dtype() {
if constexpr (type == GGML_TYPE_F16) {
return half2{};
} else {
static_assert(type == -1, "bad type");
}
}
template <ggml_type type_K, int D, int nthreads>
constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() {
if constexpr (type_K == GGML_TYPE_F16) {
@@ -856,7 +1133,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform(
}
// Write back final result:
*dst = dst_val / rowsum;
*dst = fattn_normalize(dst_val, rowsum);
}
// General fixup kernel for the case where the number of blocks per tile is not uniform across tiles
@@ -967,7 +1244,7 @@ static __global__ void flash_attn_stream_k_fixup_general(
}
// Write back final result:
*dst = dst_val / rowsum;
*dst = fattn_normalize(dst_val, rowsum);
}
template<int D> // D == head size
@@ -1025,12 +1302,13 @@ static __global__ void flash_attn_combine_results(
VKQ_denominator += KQ_max_scale * meta[l].y;
}
dst[tid] = VKQ_numerator / VKQ_denominator;
dst[tid] = fattn_normalize(VKQ_numerator, VKQ_denominator);
}
template <int DV, int ncols1, int ncols2>
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
void launch_fattn(
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared,
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel,
const int nwarps, const size_t nbytes_shared,
const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse,
const int warp_size = WARP_SIZE, const bool async_kv_preload = false
) {
@@ -1046,6 +1324,10 @@ void launch_fattn(
const ggml_tensor * sinks = dst->src[4];
const ggml_tensor * kv_rows = dst->src[5];
const bool has_bias = ggml_flash_attn_ext_has_indexed_bias(dst);
const ggml_tensor * bias_table = has_bias ? dst->src[6] : nullptr;
const ggml_tensor * bias_indices = has_bias ? dst->src[7] : nullptr;
// with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1];
GGML_ASSERT(!kv_rows || !use_sparse);
@@ -1148,6 +1430,14 @@ void launch_fattn(
}
}
GGML_ASSERT(nb11 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb12 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb13 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb21 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb22 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb23 % sizeof(T_V_stride) == 0);
const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1);
const int gqa_ratio = Q->ne[2] / K->ne[2];
const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2);
@@ -1170,7 +1460,9 @@ void launch_fattn(
// Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped.
// Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
// multiple sequences of possibly different lengths, or kv_rows lists that end with padding.
const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
// The scan reads ncols1 mask rows per tile, including the last tile.
const bool scan_mask = !has_bias && !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
if (scan_mask) {
const int64_t s31 = mask->nb[1] / sizeof(half2);
const int64_t s33 = mask->nb[3] / sizeof(half2);
@@ -1311,20 +1603,29 @@ void launch_fattn(
ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream);
ggml_cuda_kernel_launch(fattn_kernel, launch_params,
(const char *) Q->data,
K_data,
V_data,
mask ? ((const char *) mask->data) : nullptr,
sinks ? ((const char *) sinks->data) : nullptr,
(const float2 *) Q->data,
(const char *) K_data,
(const char *) V_data,
mask ? ((const half *) mask->data) : nullptr,
sinks ? ((const float *) sinks->data) : nullptr,
KV_max.ptr,
kv_rows ? (const int *) kv_rows->data : nullptr,
!stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr,
scale, max_bias, m0, m1, n_head_log2, logit_softcap,
Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3],
K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13,
nb21, nb22, nb23,
Q->ne[0], ne01, Q->ne[2], Q->ne[3],
int32_t(Q->nb[1] / sizeof(float2)), int32_t(Q->nb[2] / sizeof(float2)), int32_t(Q->nb[3] / sizeof(float2)),
K->ne[0], n_kv, K->ne[2], K->ne[3],
int32_t(nb11 / sizeof(T_K_stride)), int32_t(nb12 / sizeof(T_K_stride)), int64_t(nb13 / sizeof(T_K_stride)),
int32_t(nb21 / sizeof(T_V_stride)), int32_t(nb22 / sizeof(T_V_stride)), int64_t(nb23 / sizeof(T_V_stride)),
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0
mask ? int32_t(mask->nb[1] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[2] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0,
fattn_indexed_bias{has_bias ? (const float *) bias_table->data : nullptr,
has_bias ? (const int32_t *) bias_indices->data : nullptr,
has_bias ? bias_table->ne[0] : 0,
has_bias ? bias_indices->ne[0] : 0,
has_bias ? bias_table->ne[0]*bias_table->ne[1] : 0}
);
CUDA_CHECK(cudaGetLastError());
+151 -243
View File
@@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages(
// ------------------------------------------------------------------------------------------------------------------
template<int stride_tile, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
// The minimum granularity is 16 bytes.
constexpr int chunk_size = 16;
constexpr int h2_per_chunk = chunk_size / sizeof(half2);
const int chunks_per_row = D2 / h2_per_chunk;
if constexpr (use_cp_async) {
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
auto load = [&] __device__ (auto n) {
const int stride_k = warp_size >> n;
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if (indices) {
// K/V rows given per mask column, negative rows are padding
i_KV = max(indices[k_VKQ_0 + i], 0);
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
cp_async_cg_16<preload>(tile_KV_32 + swizzle<stride_tile*sizeof(half2), char>(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
} else {
const half2 zero[4] = {{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}};
auto load = [&] __device__ (const int n) {
const int stride_k = 32 >> n;
const int k0_start = stride_k == 32 ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = zero;
}
ggml_cuda_memcpy_1<16>(swizzle<stride_tile>(tile_KV, i*stride_tile + k*h2_per_chunk, i), src);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
}
}
template<int ncols1, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
const half * const __restrict__ mask_h, half * const __restrict__ tile_mask,
@@ -612,11 +502,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps,
bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, bool last_iter, bool oob_check,
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ>
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ,
typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
float2 * const __restrict__ dstk,
@@ -653,6 +544,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -676,7 +574,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool use_cp_async = true;
cp_async_wait_all();
__syncthreads();
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2, tile_V, min(nbatch_V2, DV/2), stride_V, k_VKQ_0, k_VKQ_sup, indices);
} else {
// the sparse mask values are gathered per element, always load them synchronously
@@ -696,7 +594,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
if constexpr (nstages <= 1) {
const int k0_diff = min(k0_stop, DKQ/2) - k0_start; // Only load the real head size from global memory.
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1033,7 +931,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0_next*nbatch_fa, k_VKQ_sup, indices);
}
}
@@ -1049,7 +947,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const int i0_diff = min(i0_stop, DV) - i0_start; // Only load the real head size from global memory.
if (!V_is_K_view || i0_stop > 2*nbatch_K2) {
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1261,11 +1159,11 @@ template<int DKQ, int ncols> struct mma_tile_sizes {
};
#endif // defined(TURING_MMA_AVAILABLE)
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup>
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
const float * const __restrict__ sinks_f,
@@ -1310,6 +1208,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -1459,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0*nbatch_fa, k_VKQ_sup, indices);
}
@@ -1472,7 +1377,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0_next, k_VKQ_sup);
@@ -1482,7 +1387,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1493,7 +1398,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1502,7 +1407,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const int k_VKQ_sup = ne11 - kb0*nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1513,7 +1418,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1522,7 +1427,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1902,8 +1807,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
if (!needs_fixup && !is_fixup) {
const float KQ_rowsum_j = meta_j[1];
dstk_val.x /= KQ_rowsum_j;
dstk_val.y /= KQ_rowsum_j;
dstk_val.x = fattn_normalize(dstk_val.x, KQ_rowsum_j);
dstk_val.y = fattn_normalize(dstk_val.y, KQ_rowsum_j);
}
if (is_fixup) {
@@ -1936,18 +1841,18 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u
(DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8);
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse>
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, ggml_type type_K, ggml_type type_V>
__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_ext_f16(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -1955,19 +1860,24 @@ static __global__ void flash_attn_ext_f16(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
GGML_UNUSED(bias); // biased ops are never dispatched to the mma kernel
ggml_cuda_pdl_sync(); // TODO optimize placement
#if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
// sparse: one index list per (sequence, query tile), the live count of each list follows the lists
const int * GGML_CUDA_RESTRICT sparse_indices = use_sparse ? KV_max_ptr : nullptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
@@ -2024,12 +1934,7 @@ static __global__ void flash_attn_ext_f16(
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const int stride_Q1 = nb01 / sizeof(float2);
const int stride_Q2 = nb02 / sizeof(float2);
const int stride_K = nb11 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_V = V_is_K_view ? stride_K : nb21 / sizeof(half2);
const int stride_V = V_is_K_view ? s11 : s21;
const int iter_k = (ne11 + (nbatch_fa - 1)) / nbatch_fa;
const int iter_j = (ne01.z + (ncols1 - 1)) / ncols1;
@@ -2072,14 +1977,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2096,14 +2001,14 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
if (kb0_start == 0) {
constexpr bool needs_fixup = false; // CUDA block is working on an entire tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
} else {
constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
}
kbc += iter_k;
@@ -2126,14 +2031,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2149,27 +2054,30 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
constexpr bool needs_fixup = false;
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
#else
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
}
bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2);
template <int DKQ, int DV, int ncols1, int ncols2>
template <int DKQ, int DV, int ncols1, int ncols2, ggml_type type_K = GGML_TYPE_F16, ggml_type type_V = GGML_TYPE_F16>
void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * KQV = dst;
const int id = ggml_cuda_get_device();
const int cc = ggml_cuda_info().devices[id].cc;
@@ -2223,7 +2131,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) {
if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) {
constexpr bool use_sparse_kernel = true;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
use_sparse = true;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
@@ -2233,7 +2141,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
} else {
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2245,7 +2153,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
#endif // !defined(GGML_USE_MUSA)
{
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2256,7 +2164,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
} else {
constexpr bool use_logit_softcap = true;
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2266,83 +2174,83 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
const bool async_kv_preload = nstages == 2 && !use_sparse;
launch_fattn<DV, ncols1, ncols2>
launch_fattn<DV, ncols1, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload);
}
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16); \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols, type_K, type_V) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16, type_K, type_V); \
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64, GGML_TYPE_F16, GGML_TYPE_F16)
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
// The number of viable configurations for Deepseek is very limited:
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
// Mistral Small 4 (DKQ=320, DV=256), GQA=32-only build:
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
// For GLM 4.7 Flash
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
+29 -13
View File
@@ -1,59 +1,75 @@
#include "common.cuh"
#include "fattn-tile.cuh"
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_tile_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
switch (K->ne[0]) {
case 40: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 40, 40, type_K, type_V>(ctx, dst);
} break;
case 64: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 64, 64, type_K, type_V>(ctx, dst);
} break;
case 72: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 72, 72, type_K, type_V>(ctx, dst);
} break;
case 80: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 80, 80, type_K, type_V>(ctx, dst);
} break;
case 96: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 96, 96, type_K, type_V>(ctx, dst);
} break;
case 112: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<112, 112, type_K, type_V>(ctx, dst);
} break;
case 128: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<128, 128, type_K, type_V>(ctx, dst);
} break;
case 192: {
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_tile_case<192, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<192, 128, type_K, type_V>(ctx, dst);
} break;
case 256: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<256, 256, type_K, type_V>(ctx, dst);
} break;
case 320: {
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_tile_case<320, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<320, 256, type_K, type_V>(ctx, dst);
} break;
case 512: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<512, 512, type_K, type_V>(ctx, dst);
} break;
case 576: {
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_tile_case<576, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<576, 512, type_K, type_V>(ctx, dst);
} break;
default:
GGML_ABORT("Unsupported head size");
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
+159 -227
View File
@@ -373,133 +373,29 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
return (ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols) >> 23) & ((1 << 9) - 1);
}
// TODO: deduplicate with mma-f16
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (2*stride_j);
const int j0_stop = ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne;
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
ggml_cuda_memcpy_1<cpy_nb>(
tile_KV + i*(J/2 + J_padding) + j,
!oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
}
}
}
};
// 1: max 64*16=512 bytes, 512 half
// 2: max 32*16=512 bytes, 256 half
// 3: max 16*16=256 bytes, 128 half
// 4: max 8*16=128 bytes, 64 half
// 5: max 4*16= 64 bytes, 32 half
// 6: max 2*16= 32 bytes, 16 half
// 7: max 1*16= 16 bytes, 8 half
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
ggml_cuda_unroll<7>{}(load);
}
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : (J/cpy_ne) - (J/cpy_ne) % (2*stride_j);
const int j0_stop = (J/cpy_ne) - (J/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2);
const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}};
__align__(16) half2 tmp_h2[cpy_ne/2];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(
tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
__align__(16) float2 tmp_f2[cpy_ne/2];
#pragma unroll
for (int l = 0; l < cpy_ne/2; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*(J + J_padding) + 2*j, tmp_f2);
}
}
}
};
// 1: max 32*16=512 bytes, 128 float
// 2: max 16*16=256 bytes, 64 float
// 3: max 8*16=128 bytes, 32 float
// 4: max 4*16= 64 bytes, 16 float
// 5: max 2*16= 32 bytes, 8 float
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
ggml_cuda_unroll<5>{}(load);
}
// Function that performs a single iteration in for the KQ matrix multiplication:
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot>
bool use_logit_softcap, bool oob_check, bool indexed_bias, typename T_vec_dot, typename T_K>
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const T_K * const __restrict__ K_h2,
T_vec_dot * const KV_tmp,
const int stride_K2,
const int k_VKQ_0,
const int k_VKQ_sup,
const int k_KQ_0,
float * KQ_acc) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
float * KQ_acc,
const int32_t * const __restrict__ rows) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, cpy_ne, oob_check>
(K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup);
constexpr int stride_tile_K = std::is_same_v<T_vec_dot, half2> ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne;
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, indexed_bias, false, T_K, T_vec_dot>
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, rows);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -556,11 +452,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
// Function that performs a single iteration of the main loop over up to nbatch_fa tokens.
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int DV, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc>
bool use_logit_softcap, bool oob_check, bool indexed_bias, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_tile_iter(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask,
const uint3 ne01,
const float logit_softcap,
@@ -575,8 +471,10 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
T_acc * const VKQ,
const int k_VKQ_0,
const int k_VKQ_max,
const int col_Q_0) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
const int col_Q_0,
const fattn_indexed_bias bias,
const int32_t * const __restrict__ rows) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
@@ -607,13 +505,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
constexpr int nbatch_K_last = DKQ % nbatch_K;
#pragma unroll
for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) {
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
}
if (nbatch_K_last > 0) {
constexpr int k_KQ_0 = DKQ - nbatch_K_last;
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check, indexed_bias>(
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
}
// Apply logit softcap + mask, update KQ_max:
@@ -636,8 +534,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
if (!oob_check || i_KQ < k_VKQ_sup) {
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ?
slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f;
if (indexed_bias || ncols2 > 1 || mask) {
const int k = k_VKQ_0 + i_KQ;
__builtin_assume(k >= 0); // avoid sign extension and register spills on RDNA
const float m = __half2float(mask[int64_t(j)*stride_mask + k]);
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*(indexed_bias ? bias.add(m, j, k) : m);
}
KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET);
}
@@ -716,10 +618,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
constexpr int nbatch_V = (DV % nbatch_K == 0 ? nbatch_K : nbatch_K*2/3) * nbatch_fa / DV; // Number of V columns that fit in SRAM for K.
static_assert(nbatch_fa % nbatch_V == 0, "bad nbatch_V");
static_assert(nbatch_V % np == 0, "bad nbatch_V");
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
#pragma unroll
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_V, DV, 0, oob_check>
(V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0);
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, indexed_bias, false, T_V, T_vec_dot>
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, rows);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -788,18 +691,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap> // D == head size
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool indexed_bias, ggml_type type_K, ggml_type type_V, bool use_kv_rows> // D == head size
__launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_tile(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -807,22 +710,25 @@ static __global__ void flash_attn_tile(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
// Skip unused kernel variants for faster compilation:
@@ -830,15 +736,22 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
#ifdef AMD_MFMA_AVAILABLE
if (ncols1 == 64 && ncols2 == 1) {
// The tile kernel is suffering from register spills for ncols1 == 64 && ncols2 == 1.
NO_DEVICE_CODE;
return;
}
#endif // AMD_MFMA_AVAILABLE
static_assert(ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols1*ncols2) != 0, "kernel config not defined");
@@ -854,20 +767,23 @@ static __global__ void flash_attn_tile(
const int sequence = blockIdx.z / (ne02/ncols2);
const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2)
const int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
__builtin_assume(!use_kv_rows || rows != nullptr);
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio));
const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape
const float2 * Q_f2 = Q + s03*sequence + s02* head0;
const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio);
const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr;
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const int stride_K2 = nb11 / sizeof(half2);
const int stride_V2 = nb21 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_K2 = s11;
const int stride_V2 = s21;
const int stride_mask = s31;
const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, head0, n_head_log2, m0, m1) : 1.0f;
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp.
@@ -919,8 +835,7 @@ static __global__ void flash_attn_tile(
if (i0 + np*warp_size*cpy_ne_D <= DKQ || i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D < DKQ) {
__align__(16) float tmp_f[cpy_ne_D] = {0.0f};
ggml_cuda_memcpy_1<sizeof(tmp_f)>
(tmp_f, &Q_f[c*(nb02/sizeof(float)) + fastmodulo(col_Q_0 + j, ne01)*(nb01/sizeof(float))
+ i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D]);
(tmp_f, Q_f2 + c*s02 + fastmodulo(col_Q_0 + j, ne01)*s01 + i0/2 + (threadIdx.y % np)*(warp_size*(cpy_ne_D/2)) + threadIdx.x*(cpy_ne_D/2));
#pragma unroll
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
@@ -959,24 +874,24 @@ static __global__ void flash_attn_tile(
int k_VKQ_0 = blockIdx.y*nbatch_fa;
while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) {
constexpr bool oob_check = false;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
k_VKQ_0 += gridDim.y*nbatch_fa;
}
if (k_VKQ_0 < k_VKQ_max) {
constexpr bool oob_check = true;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
}
} else {
// Branch without out-of-bounds checks.
for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) {
constexpr bool oob_check = false;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
}
}
@@ -1056,7 +971,7 @@ static __global__ void flash_attn_tile(
#pragma unroll
for (int jc0 = 0; jc0 < cpw; ++jc0) {
const int jc = jc0 + (threadIdx.y/np)*cpw;
const float sink = ((const float *) sinks)[head0 + jc % ncols2];
const float sink = sinks[head0 + jc % ncols2];
float KQ_max_new_j = fmaxf(KQ_max[jc0], sink);
const float KQ_max_scale = expf(KQ_max[jc0] - KQ_max_new_j);
@@ -1093,7 +1008,7 @@ static __global__ void flash_attn_tile(
return;
}
const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f;
const float rowsum = gridDim.y == 1 ? KQ_sum[jc0] : 1.0f;
const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y;
@@ -1105,8 +1020,8 @@ static __global__ void flash_attn_tile(
#pragma unroll
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
tmp[i1] = __half22float2(VKQ[jc0*((DVp/2)/warp_size) + i0/warp_size + i1]);
tmp[i1].x *= scale;
tmp[i1].y *= scale;
tmp[i1].x = fattn_normalize(tmp[i1].x, rowsum);
tmp[i1].y = fattn_normalize(tmp[i1].y, rowsum);
}
if (i0 + warp_size*cpy_ne_D <= DV/2 || i0 + threadIdx.x*cpy_ne_D < DV/2) {
ggml_cuda_memcpy_1<sizeof(tmp)>(&dst[j_dst_unrolled*DV + 2*i0 + threadIdx.x*(2*cpy_ne_D)], tmp);
@@ -1119,8 +1034,9 @@ static __global__ void flash_attn_tile(
if (i0 + warp_size*cpy_ne_D <= DV || i0 + threadIdx.x*cpy_ne_D < DV) {
#pragma unroll
for (int i1 = 0; i1 < cpy_ne_D/2; ++i1) {
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].x *= scale;
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].y *= scale;
float2 & val = VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1];
val.x = fattn_normalize(val.x, rowsum);
val.y = fattn_normalize(val.y, rowsum);
}
ggml_cuda_memcpy_1<cpy_ne_D*4>(
&dst[j_dst_unrolled*DV + i0 + threadIdx.x*cpy_ne_D],
@@ -1137,18 +1053,21 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33, bias);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
template <int DKQ, int DV, int ncols2, bool use_logit_softcap>
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V, bool indexed_bias, bool use_kv_rows>
static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * Q = dst->src[0];
const int id = ggml_cuda_get_device();
@@ -1158,41 +1077,43 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr size_t nbytes_shared = 0;
#ifdef GGML_USE_HIP
if constexpr (DKQ <= 128) {
if (Q->ne[1] > 32/ncols2) {
// Limit indexed bias tile widths to avoid spilling registers on AMD.
// TODO: select the tile width in one function.
constexpr int max_cols = !indexed_bias ? 64 : DKQ == 64 ? 32 : use_kv_rows ? 16 : 8;
if constexpr (DKQ <= 128 && max_cols >= 64) {
if (!(amd_mfma_available(cc) && ncols2 == 1) && Q->ne[1] > 32/ncols2) {
constexpr int cols_per_block = 64;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
}
#else
constexpr int max_cols = DKQ <= 256 ? 32 : 16;
#endif // GGML_USE_HIP
#ifndef GGML_USE_HIP
if constexpr (DKQ <= 256)
#endif // GGML_USE_HIP
{
if constexpr (max_cols >= 32) {
if (Q->ne[1] > 16/ncols2) {
constexpr int cols_per_block = 32;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
}
if constexpr (ncols2 <= 16) {
if constexpr (ncols2 <= 16 && max_cols >= 16) {
if (Q->ne[1] > 8/ncols2) {
constexpr int cols_per_block = 16;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1203,8 +1124,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 8;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1215,8 +1136,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 4;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1226,8 +1147,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 2;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1235,7 +1156,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
GGML_ABORT("fatal error");
}
template <int DKQ, int DV, bool use_logit_softcap>
template <int DKQ, int DV, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -1255,6 +1176,17 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
// a mask with a head dimension is not shared by the Q heads of a K/V head
const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
if constexpr (DKQ == 64 || DKQ == 128) {
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
if (dst->src[5]) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, true>(ctx, dst);
} else {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, false>(ctx, dst);
}
return;
}
}
if constexpr (DKQ == 320) {
// This branch is only used for Mistral Small 4 which has a GQA ratio of 32.
// On AMD, simply use that GQA ratio with 32 columns / block since we always have enough SRAM.
@@ -1262,12 +1194,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
// Therefore, use a GQA ratio of 16 with 16 columns / block to stay below 48 kiB of SRAM / block.
#ifdef GGML_USE_HIP
if (use_gqa_opt && gqa_ratio % 32 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
#else
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
#endif // GGML_USE_HIP
@@ -1276,11 +1208,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 576) {
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
}
@@ -1288,11 +1220,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 192) {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8");
@@ -1300,29 +1232,29 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
if constexpr (DV <= 256) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
}
GGML_ABORT("fatal error");
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
@@ -1331,28 +1263,28 @@ void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_te
if (logit_softcap == 0.0f) {
constexpr bool use_logit_softcap = false;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
} else {
constexpr bool use_logit_softcap = true;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
#define DECL_FATTN_TILE_CASE(DKQ, DV) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
extern DECL_FATTN_TILE_CASE( 40, 40);
extern DECL_FATTN_TILE_CASE( 64, 64);
extern DECL_FATTN_TILE_CASE( 72, 72);
extern DECL_FATTN_TILE_CASE( 80, 80);
extern DECL_FATTN_TILE_CASE( 96, 96);
extern DECL_FATTN_TILE_CASE(112, 112);
extern DECL_FATTN_TILE_CASE(128, 128);
extern DECL_FATTN_TILE_CASE(192, 128);
extern DECL_FATTN_TILE_CASE(256, 256);
extern DECL_FATTN_TILE_CASE(320, 256);
extern DECL_FATTN_TILE_CASE(512, 512);
extern DECL_FATTN_TILE_CASE(576, 512);
extern DECL_FATTN_TILE_CASE( 40, 40, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 64, 64, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 72, 72, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 80, 80, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 96, 96, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16);
+77 -57
View File
@@ -16,18 +16,18 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpass-failed"
#endif // __clang__
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap> // D == head size
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap, bool indexed_bias, bool use_kv_rows> // D == head size
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
static __global__ void flash_attn_ext_vec(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -35,35 +35,35 @@ static __global__ void flash_attn_ext_vec(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
ggml_cuda_pdl_lc();
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
// Skip unused kernel variants for faster compilation:
if (use_logit_softcap && !(D == 128 || D == 256)) {
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
@@ -75,9 +75,9 @@ static __global__ void flash_attn_ext_vec(
#ifdef GGML_USE_HIP
#ifdef RDNA
constexpr int nthreads_KQ_q = 2;
constexpr int nthreads_KQ_q = indexed_bias && type_K == GGML_TYPE_F8_E4M3 ? 16 : 2;
#else
constexpr int nthreads_KQ_q = 4;
constexpr int nthreads_KQ_q = type_K == GGML_TYPE_F8_E4M3 && D == 256 && ncols == 2 ? 16 : 4;
#endif // RDNA
constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32);
#else
@@ -107,12 +107,13 @@ static __global__ void flash_attn_ext_vec(
const int sequence = blockIdx.z / ne02;
const int head = blockIdx.z - sequence*ne02;
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
Q += nb03*sequence + nb02* head + nb01*ic0;
K += nb13*sequence + nb12*(head / gqa_ratio);
V += nb23*sequence + nb22*(head / gqa_ratio);
Q += s03*sequence + s02* head + s01*ic0;
K += s13*sequence + s12*(head / gqa_ratio);
V += s23*sequence + s22*(head / gqa_ratio);
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr;
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1);
@@ -176,7 +177,7 @@ static __global__ void flash_attn_ext_vec(
tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f);
}
} else {
const float * Q_f = (const float *) (Q + j*nb01);
const float * Q_f = (const float *) (Q + j*s01);
constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE;
#pragma unroll
for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) {
@@ -206,7 +207,7 @@ static __global__ void flash_attn_ext_vec(
} else if constexpr (type_K == GGML_TYPE_F8_E4M3) {
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float * Q_j = (const float *) (Q + j*nb01);
const float * Q_j = (const float *) (Q + j*s01);
#pragma unroll
for (int i0 = 0; i0 < D; i0 += nthreads_KQ*4) {
const int i = i0 + (threadIdx.x % nthreads_KQ)*4;
@@ -229,7 +230,7 @@ static __global__ void flash_attn_ext_vec(
const half2 scale_h2 = make_half2(scale, scale);
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -252,7 +253,7 @@ static __global__ void flash_attn_ext_vec(
#else
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -271,12 +272,15 @@ static __global__ void flash_attn_ext_vec(
}
const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
K += blockIdx.y*nthreads * nb11;
V += blockIdx.y*nthreads * nb21;
const int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
if constexpr (!use_kv_rows) {
K += blockIdx.y*nthreads * s11;
V += blockIdx.y*nthreads * s21;
}
maskh += blockIdx.y*nthreads;
for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads,
// Increment pointers after each loop:
K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) {
K += use_kv_rows ? 0 : gridDim.y*nthreads*s11, V += use_kv_rows ? 0 : gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
// Calculate KQ tile and keep track of new maximum KQ values:
float KQ_reg[ncols]; // KQ in registers.
@@ -290,21 +294,24 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) {
const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0;
const char * K_row = use_kv_rows ? K + int64_t(max(rows[k_VKQ_0 + i_KQ], 0))*s11 : K + i_KQ*s11;
#pragma unroll
for (int j = 0; j < ncols; ++j) {
float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]);
float sum = vec_dot_KQ(K_row, Q_reg[j], Q_i32[j], Q_ds[j]);
sum = warp_reduce_sum<nthreads_KQ>(sum);
if (use_logit_softcap) {
sum = logit_softcap*tanhf(sum);
}
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
}
if constexpr (!indexed_bias) {
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
}
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
}
if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) {
KQ_reg[j] = sum;
@@ -314,8 +321,14 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int j = 0; j < ncols; ++j) {
if constexpr (indexed_bias) {
const int k = k_VKQ_0 + tid;
const float m = head_bias.add(__half2float(maskh[j*ne11 + tid]), ic0 + j, k);
KQ_reg[j] += slope*m;
KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET);
}
#pragma unroll
for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE));
}
const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]);
@@ -345,6 +358,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) {
const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V);
const char * V_row = V + (use_kv_rows ? int64_t(max(rows[k_VKQ_0 + k], 0))*s21 : k*s21);
#ifdef V_DOT2_F32_F16_AVAILABLE
half2 KQ_k[ncols];
@@ -357,14 +371,14 @@ static __global__ void flash_attn_ext_vec(
half2 tmp[V_rows_per_thread/2];
if constexpr (type_V == GGML_TYPE_BF16) {
float2 tmp_f[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp_f,
dequantize_V(V_row, tmp_f,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]);
}
} else {
dequantize_V(V + k*nb21, tmp,
dequantize_V(V_row, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
}
#pragma unroll
@@ -384,7 +398,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) {
float2 tmp[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp,
dequantize_V(V_row, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
@@ -402,7 +416,7 @@ static __global__ void flash_attn_ext_vec(
}
if (sinks && blockIdx.y == 0) {
const float sink = ((const float *) sinks)[head];
const float sink = sinks[head];
#pragma unroll
for (int j0 = 0; j0 < ncols; j0 += nwarps) {
@@ -521,7 +535,7 @@ static __global__ void flash_attn_ext_vec(
}
}
if (gridDim.y == 1) {
dst_val /= KQ_sum[j_VKQ];
dst_val = fattn_normalize(dst_val, KQ_sum[j_VKQ]);
}
dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val;
}
@@ -540,12 +554,12 @@ static __global__ void flash_attn_ext_vec(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33, bias);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
@@ -559,11 +573,17 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc);
const int nwarps = nthreads / WARP_SIZE;
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap>;
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
: flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, false>;
}
}
const bool need_f16_K = type_K == GGML_TYPE_F16;
const bool need_f16_V = type_V == GGML_TYPE_F16;
constexpr size_t nbytes_shared = 0;
launch_fattn<D, cols_per_block, 1>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
launch_fattn<D, cols_per_block, 1, char, char>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
}
template <int D, ggml_type type_K, ggml_type type_V>
+91 -53
View File
@@ -159,7 +159,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_
#endif // !defined(GGML_USE_MUSA)
}
template <int DKQ, int DV, int ncols2>
template <int DKQ, int DV, int ncols2, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * Q = dst->src[0];
@@ -169,7 +169,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
// a sparse variant at the full tile width gathers the union of its queries once, prefer it for large batches
constexpr bool has_wide_sparse = ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 64/ncols2, ncols2);
if (!(has_wide_sparse && Q->ne[1] > 32/ncols2) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, ncols2)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
@@ -177,38 +177,39 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
if constexpr (ncols2 <= 8) {
if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if constexpr (ncols2 <= 16) {
if (Q->ne[1] <= 16/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) ||
(GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2, type_K, type_V>(ctx, dst);
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * kv_rows = dst->src[5];
// with kv_rows the kernel iterates over the mask columns
const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1];
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
float max_bias = 0.0f;
memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
@@ -235,22 +236,22 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute:
if (cc == GGML_CUDA_CC_VOLTA) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
return;
} else {
GGML_ABORT("fatal error");
@@ -260,44 +261,45 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask.
if (amd_wmma_available(cc)) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
}
if (use_gqa_opt && gqa_ratio > 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 2) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 1) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
} else {
GGML_ABORT("fatal error");
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -308,31 +310,31 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
switch (Q->ne[0]) {
case 40:
GGML_ASSERT(V->ne[0] == 40);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40, type_K, type_V>(ctx, dst);
break;
case 64:
GGML_ASSERT(V->ne[0] == 64);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64, type_K, type_V>(ctx, dst);
break;
case 72:
GGML_ASSERT(V->ne[0] == 72);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72, type_K, type_V>(ctx, dst);
break;
case 80:
GGML_ASSERT(V->ne[0] == 80);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80, type_K, type_V>(ctx, dst);
break;
case 96:
GGML_ASSERT(V->ne[0] == 96);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96, type_K, type_V>(ctx, dst);
break;
case 112:
GGML_ASSERT(V->ne[0] == 112);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112, type_K, type_V>(ctx, dst);
break;
case 128:
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128, type_K, type_V>(ctx, dst);
break;
case 192: {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
@@ -344,15 +346,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16, type_K, type_V>(ctx, dst);
} else {
GGML_ASSERT(gqa_ratio % 8 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8, type_K, type_V>(ctx, dst);
}
} break;
case 256:
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256, type_K, type_V>(ctx, dst);
break;
case 320:
// For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build).
@@ -367,12 +369,12 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
const int gqa_ratio = Q->ne[2] / K->ne[2];
GGML_ASSERT(gqa_ratio % 32 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32, type_K, type_V>(ctx, dst);
}
break;
case 512:
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512, type_K, type_V>(ctx, dst);
break;
case 576: {
// For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels.
@@ -386,50 +388,50 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (amd_mfma_available(cc) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, 16)) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else if (gqa_ratio == 20 && GGML_CUDA_CC_IS_NVIDIA(cc)) { // GLM 4.7 Flash
if (cc >= GGML_CUDA_CC_GB10) {
if (Q->ne[1] <= 8) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_BLACKWELL) {
if (Q->ne[1] <= 4 && K->ne[1] >= 65536) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
if (Q->ne[1] <= 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_TURING) {
if (Q->ne[1] <= 4) {
if (K->ne[1] <= 16384) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
// Volta:
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
} else if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
}
} break;
default:
@@ -437,6 +439,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
#define FATTN_VEC_CASE(D, type_K_case, type_V_case) \
if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) { \
if (head_size == (D) && type_K == GGML_TYPE_##type_K_case && type_V == GGML_TYPE_##type_V_case) { \
@@ -589,6 +606,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * kv_rows = dst->src[5];
if (!ggml_validate_flash_attn_ext_indexed_bias(dst)) {
return BEST_FATTN_KERNEL_NONE;
}
// with kv_rows the kernel iterates over the mask columns
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
@@ -669,6 +690,20 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_NONE;
}
// the tile and vec kernels implement the indexed bias, the mma kernel does not
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
float logit_softcap;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && logit_softcap == 0.0f)) {
return BEST_FATTN_KERNEL_NONE;
}
if (logit_softcap == 0.0f && Q->ne[1] == 1 && n_kv % FATTN_KQ_STRIDE == 0 &&
ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type)) {
return BEST_FATTN_KERNEL_VEC;
}
return BEST_FATTN_KERNEL_TILE;
}
if (mask && mask->ne[2] != 1) {
// the kv_rows mask is compacted per sequence, it has no head dimension
if (kv_rows) {
@@ -682,7 +717,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
}
// only the MMA kernel reads K/V through kv_rows
// without a bias only the MMA kernel reads K/V through kv_rows
if (kv_rows) {
return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ?
BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
@@ -728,12 +763,15 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
gqa_ratio_eff *= 2;
}
// the tile kernel for DKQ=576 only has the ncols2 = 4 and 16 variants
const best_fattn_kernel tile_kernel = Q->ne[0] == 576 && gqa_ratio % 4 != 0 ? BEST_FATTN_KERNEL_NONE : BEST_FATTN_KERNEL_TILE;
if (volta_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
if (can_use_vector_kernel && Q->ne[1] * gqa_ratio_eff <= 2) {
return BEST_FATTN_KERNEL_VEC;
}
if (Q->ne[1] * gqa_ratio_eff <= 16) {
return BEST_FATTN_KERNEL_TILE; // On Volta tensor cores are only faster for sufficiently large matrices.
return tile_kernel; // On Volta tensor cores are only faster for sufficiently large matrices.
}
return BEST_FATTN_KERNEL_MMA_F16;
}
@@ -779,7 +817,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
}
}
return BEST_FATTN_KERNEL_TILE;
return tile_kernel;
}
size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) {
+36 -19
View File
@@ -1,9 +1,11 @@
#include "convert.cuh"
#include "fp8.cuh"
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080
template <typename src_t>
struct fp8_abs_src {
const float * x;
const src_t * x;
int64_t ne0;
int64_t ne1;
int64_t ne2;
@@ -18,12 +20,13 @@ struct fp8_abs_src {
i /= ne1;
const int64_t i2 = i % ne2;
const int64_t i3 = i / ne2;
const float value = fabsf(x[i0 + i1*s1 + i2*s2 + i3*s3]);
const float value = fabsf(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]));
return isfinite(value) ? value : 448.0f;
}
};
static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) {
template <typename src_t>
static __global__ void fp8_amax_partials(fp8_abs_src<src_t> src, int64_t ne, float * partials) {
float amax = 0.0f;
for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < ne; i += (int64_t) blockDim.x*gridDim.x) {
amax = fmaxf(amax, src(i));
@@ -49,8 +52,9 @@ static __global__ void fp8_amax_final(const float * partials, int n, float * ama
}
}
template <typename src_t>
static __global__ void quantize_fp8_e4m3(
const float * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
const src_t * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
float * __restrict__ scale, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3) {
const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x;
if (i >= ne) {
@@ -65,12 +69,26 @@ static __global__ void quantize_fp8_e4m3(
const int64_t i3 = tmp / ne2;
const float d = *amax > 0.0f ? *amax / 448.0f : 1.0f;
y[i] = ggml_cuda_fp32_to_f8_e4m3(x[i0 + i1*s1 + i2*s2 + i3*s3] / d);
y[i] = ggml_cuda_fp32_to_f8_e4m3(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]) / d);
if (i == 0) {
*scale = d;
}
}
// src1 (F32 or BF16) to FP8 with one scale for the whole tensor: amax / 448
template <typename src_t>
static void fp8_quantize_src1(
ggml_backend_cuda_context & ctx, const src_t * x, uint8_t * y, float * amax, float * scale,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3, cudaStream_t stream) {
const fp8_abs_src<src_t> abs_src = { x, ne0, ne1, ne2, s1, s2, s3 };
const int reduce_blocks = std::min<int64_t>((ne + 255)/256, 1024);
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne, reduce_tmp.ptr);
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, amax);
quantize_fp8_e4m3<<<(ne + 255)/256, 256, 0, stream>>>(x, y, amax, scale, ne0, ne1, ne2, ne, s1, s2, s3);
}
static void fp8_set_batch(cublasLtMatrixLayout_t desc, int32_t count, int64_t stride) {
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &count, sizeof(count)));
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride, sizeof(stride)));
@@ -89,9 +107,9 @@ bool ggml_cuda_mul_mat_fp8(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
const ggml_tensor * weight_scale) {
const int cc = ggml_cuda_info().devices[ctx.device].cc;
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || src1->type != GGML_TYPE_F32 ||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) ||
dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst) || src0->ne[0] % 16 != 0 || src0->ne[1] % 16 != 0 ||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != sizeof(float) ||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != ggml_type_size(src1->type) ||
!ggml_cuda_is_aligned(src0, 16) || !ggml_cuda_is_aligned(dst, 16)) {
return false;
}
@@ -110,18 +128,17 @@ bool ggml_cuda_mul_mat_fp8(
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool(), 1);
ggml_cuda_pool_alloc<float> src1_amax(ctx.pool(), 1);
const fp8_abs_src abs_src = {
(const float *) src1->data, ne10, ne11, ne12,
(int64_t) (nb11 / sizeof(float)), (int64_t) (nb12 / sizeof(float)), (int64_t) (nb13 / sizeof(float))
};
const int reduce_blocks = std::min<int64_t>((ne_src1 + 255)/256, 1024);
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne_src1, reduce_tmp.ptr);
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, src1_amax.ptr);
quantize_fp8_e4m3<<<(ne_src1 + 255)/256, 256, 0, stream>>>(
(const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, ne10, ne11, ne12, ne_src1,
nb11 / sizeof(float), nb12 / sizeof(float), nb13 / sizeof(float));
const int64_t s11 = nb11 / nb10;
const int64_t s12 = nb12 / nb10;
const int64_t s13 = nb13 / nb10;
if (src1->type == GGML_TYPE_BF16) {
fp8_quantize_src1(ctx, (const nv_bfloat16 *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
} else {
GGML_ASSERT(src1->type == GGML_TYPE_F32);
fp8_quantize_src1(ctx, (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
}
CUDA_CHECK(cudaGetLastError());
cublasLtMatmulDesc_t op_desc;
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More