Compare commits

..
28 Commits
Author SHA1 Message Date
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
192 changed files with 12953 additions and 6143 deletions
+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]
+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"; } ||
+32 -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
@@ -212,6 +220,29 @@ jobs:
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
+44 -14
View File
@@ -868,6 +868,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 +933,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 +963,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 +993,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 +1010,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 +1089,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)
+8 -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>
+1
View File
@@ -818,6 +818,7 @@ 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. |
-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"
];
+5 -2
View File
@@ -2449,10 +2449,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 +2472,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
+31 -10
View File
@@ -1287,6 +1287,25 @@ 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);
}
}
void ggml_compute_forward_mul_mat(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1372,11 +1391,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 +1421,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);
}
@@ -1656,7 +1673,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 +1692,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);
}
}
}
}
+13 -6
View File
@@ -441,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
@@ -453,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;
+1
View File
@@ -9722,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:
+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;
}
+5
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;
+40 -6
View File
@@ -20,6 +20,28 @@
// 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)
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,
@@ -42,7 +64,8 @@ using fattn_kernel_t = void (*)(
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 s31, const int64_t s32, const int64_t s33);
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);
@@ -1110,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
@@ -1221,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
@@ -1279,7 +1302,7 @@ 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, typename T_K_stride, typename T_V_stride>
@@ -1301,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);
@@ -1433,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);
@@ -1591,7 +1620,12 @@ void launch_fattn(
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[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
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());
+5 -3
View File
@@ -1807,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) {
@@ -1865,7 +1865,9 @@ static __global__ void flash_attn_ext_f16(
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 s31, const int64_t s32, const int64_t s33) {
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))
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
+77 -53
View File
@@ -375,7 +375,7 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
// 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, typename T_K>
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 T_K * const __restrict__ K_h2,
@@ -384,7 +384,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
const int k_VKQ_0,
const int k_VKQ_sup,
const int k_KQ_0,
float * KQ_acc) {
float * KQ_acc,
const int32_t * const __restrict__ rows) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
@@ -393,8 +394,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
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, false, 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, nullptr);
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
@@ -451,7 +452,7 @@ 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, typename T_K, typename T_V>
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 T_K * const __restrict__ K_h2,
@@ -470,7 +471,9 @@ 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) {
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;
@@ -502,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:
@@ -531,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);
}
@@ -614,8 +621,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
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_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, false, false, T_V, T_vec_dot>
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr);
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
@@ -684,7 +691,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V> // 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 float2 * Q_ptr,
@@ -708,7 +715,8 @@ static __global__ void flash_attn_tile(
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 s31, const int64_t s32, const int64_t s33) {
const int32_t s31, const int64_t s32, const int64_t s33,
const fattn_indexed_bias bias) {
#ifdef FLASH_ATTN_AVAILABLE
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
@@ -721,7 +729,6 @@ static __global__ void flash_attn_tile(
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);
// Skip unused kernel variants for faster compilation:
@@ -760,12 +767,15 @@ 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 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 ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const int stride_K2 = s11;
const int stride_V2 = s21;
@@ -864,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);
}
}
@@ -998,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;
@@ -1010,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);
@@ -1024,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],
@@ -1047,12 +1058,12 @@ static __global__ void flash_attn_tile(
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
s31, s32, s33);
s31, s32, s33, bias);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
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>());
@@ -1066,40 +1077,42 @@ 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) {
// 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, type_K, type_V>;
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, type_K, type_V>;
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, type_K, type_V>;
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;
@@ -1111,7 +1124,7 @@ 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, type_K, type_V>;
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;
@@ -1123,7 +1136,7 @@ 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, type_K, type_V>;
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;
@@ -1134,7 +1147,7 @@ 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, type_K, type_V>;
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;
@@ -1163,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.
@@ -1170,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, type_K, type_V>(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, type_K, type_V>(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
@@ -1184,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, type_K, type_V>(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, type_K, type_V>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
}
@@ -1196,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, type_K, type_V>(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, type_K, type_V>(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");
@@ -1208,22 +1232,22 @@ 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, type_K, type_V>(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, type_K, type_V>(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, type_K, type_V>(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, type_K, type_V>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
return;
}
}
+41 -21
View File
@@ -16,7 +16,7 @@ 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 float2 * Q_ptr,
@@ -40,7 +40,8 @@ static __global__ void flash_attn_ext_vec(
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 s31, const int64_t s32, const int64_t s33) {
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 float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
@@ -51,7 +52,6 @@ static __global__ void flash_attn_ext_vec(
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);
// Skip unused kernel variants for faster compilation:
if (use_logit_softcap && !(D == 128 || D == 256)) {
@@ -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 += s03*sequence + s02* head + s01*ic0;
K += s13*sequence + s12*(head / gqa_ratio);
V += s23*sequence + s22*(head / gqa_ratio);
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*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);
@@ -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 * s11;
V += blockIdx.y*nthreads * s21;
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*s11, V += gridDim.y*nthreads*s21, 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*s11, 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*s21, 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*s21, 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*s21, 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) {
@@ -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;
}
@@ -545,7 +559,7 @@ static __global__ void flash_attn_ext_vec(
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
s31, s32, s33);
s31, s32, s33, bias);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
@@ -559,7 +573,13 @@ 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;
+19 -5
View File
@@ -599,10 +599,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
return BEST_FATTN_KERNEL_NONE;
#endif// FLASH_ATTN_AVAILABLE
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
return BEST_FATTN_KERNEL_NONE;
}
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
@@ -610,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];
@@ -690,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) {
@@ -703,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;
+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
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include "common.cuh"
#include "ggml-backend-impl.h"
// try and fuse nodes starting at node i and return the number of nodes to skip
int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i);
// add alloc deps for the fusions that need their inputs to stay alive (called from graph_optimize)
void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params);
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu and fusion.cu
#include "common.cuh"
+396
View File
@@ -0,0 +1,396 @@
#include "inkling2.cuh"
// the fused kernels keep the operation order of the unfused graph where it is cheap to do so,
// __fmul_rn/__fadd_rn stop the compiler from contracting a separate MUL and ADD into one FMA
static __global__ void situ_f32(
const float * gate, const float * up, float * dst, const int ne0, const int ne1, const int ne2, const int64_t nrows,
const int64_t g_s1, const int64_t g_s2, const int64_t g_s3, const int64_t u_s1, const int64_t u_s2, const int64_t u_s3,
const float s0, const float b0, const float s1, const float b1, const float s2, const float b2, const float s3, const float b3) {
ggml_cuda_pdl_lc();
const int i0 = blockIdx.x*blockDim.x + threadIdx.x;
ggml_cuda_pdl_sync();
if (i0 >= ne0) {
return;
}
for (int64_t row = blockIdx.y; row < nrows; row += gridDim.y) {
const int64_t i1 = row % ne1;
const int64_t i2 = (row / ne1) % ne2;
const int64_t i3 = row / ((int64_t) ne1*ne2);
const float g = gate[i3*g_s3 + i2*g_s2 + i1*g_s1 + i0];
const float u = up [i3*u_s3 + i2*u_s2 + i1*u_s1 + i0];
const float act = s1*tanhf(s0*g + b0) + b1;
const float sig = 1.0f/(1.0f + expf(-g));
const float lin = s3*tanhf(s2*u + b2) + b3;
dst[row*ne0 + i0] = __fmul_rn(__fmul_rn(act, sig), lin);
}
}
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
const float * s, const float * b, ggml_tensor * dst) {
GGML_ASSERT(gate->type == GGML_TYPE_F32 && up->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
GGML_ASSERT(gate->nb[0] == sizeof(float) && up->nb[0] == sizeof(float) && ggml_is_contiguous(dst));
GGML_ASSERT(ggml_are_same_shape(gate, up) && ggml_are_same_shape(gate, dst));
const int64_t ne0 = gate->ne[0];
const int64_t nrows = ggml_nrows(gate);
const int block_size = 256;
const dim3 grid((ne0 + block_size - 1)/block_size, std::min<int64_t>(nrows, 65535), 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
ggml_cuda_kernel_launch(situ_f32, params,
(const float *) gate->data, (const float *) up->data, (float *) dst->data, (int) ne0, (int) gate->ne[1], (int) gate->ne[2], nrows,
(int64_t) (gate->nb[1]/sizeof(float)), (int64_t) (gate->nb[2]/sizeof(float)), (int64_t) (gate->nb[3]/sizeof(float)),
(int64_t) (up->nb[1]/sizeof(float)), (int64_t) (up->nb[2]/sizeof(float)), (int64_t) (up->nb[3]/sizeof(float)),
s[0], b[0], s[1], b[1], s[2], b[2], s[3], b[3]);
}
// one thread per (channel, run of tokens of one sequence). the last K columns of x stay in registers, right-aligned in
// M = GGML_CUDA_SHORT_CONV_MAX_K slots with zero weights in front, so K needs no template and the sums keep their order.
// a thread reads cur at a token before it writes dst there and never again, so dst may be cur itself when a thread has
// the whole sequence
template <bool has_dyn, bool has_res>
static __global__ void short_conv_f32(const ggml_cuda_short_conv_args a) {
ggml_cuda_pdl_lc();
constexpr int M = GGML_CUDA_SHORT_CONV_MAX_K;
const int K = a.K;
const int K1 = K - 1;
const int c = blockIdx.x*blockDim.x + threadIdx.x;
ggml_cuda_pdl_sync();
if (c >= a.C) {
return;
}
float w[M];
#pragma unroll
for (int m = 0; m < M; ++m) {
w[m] = m >= M - K ? a.w[c*K + m - (M - K)] : 0.0f;
}
const int n_runs = (a.Ts + a.run - 1)/a.run;
for (int r = blockIdx.y; r < a.S*n_runs; r += gridDim.y) {
const int s = r / n_runs;
const int t0 = (r - s*n_runs)*a.run;
const int t1 = min(t0 + a.run, a.Ts);
const float * pc = a.past + c*a.past_s1 + s*a.past_s2;
const float * xc = a.cur + (int64_t) s*a.Ts*a.C + c;
// x[M - K + k] is column ts + k of [past; cur^T]
float x[M];
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
const int j = t0 + m - (M - K);
x[m] = j < 0 ? 0.0f : j < K1 ? pc[j] : xc[(int64_t) (j - K1)*a.C];
}
for (int ts = t0; ts < t1; ++ts) {
const int64_t t = (int64_t) s*a.Ts + ts;
x[M - 1] = xc[(int64_t) ts*a.C];
float y = 0.0f;
#pragma unroll
for (int m = 0; m < M; ++m) {
y += x[m]*w[m];
}
if constexpr (has_dyn) {
const float * d = a.dyn + t*a.dyn_s1 + (c / (a.C / a.n_heads))*K;
#pragma unroll
for (int lag = 0; lag < M; ++lag) {
if (lag < K) {
y = __fadd_rn(y, __fmul_rn(x[M - 1 - lag], d[lag]));
}
}
}
float o = a.scale*__fadd_rn(x[M - 1], y) + a.bias;
if constexpr (has_res) {
o = __fadd_rn(a.res[t*a.C + c], o);
}
a.dst[t*a.C + c] = o;
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
x[m] = x[m + 1];
}
// x now holds the K - 1 columns that end at token ts: the conv state of slot Ts - 1 - ts, if it is kept
if (ts >= a.Ts - a.kw) {
float * st = a.state + (a.Ts - 1 - ts)*a.state_slot_s + c*a.state_ch_s + s*a.state_seq_s;
#pragma unroll
for (int m = 0; m < M - 1; ++m) {
if (m >= M - K) {
st[m - (M - K)] = x[m];
}
}
}
}
}
}
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & a) {
GGML_ASSERT(a.K >= 2 && a.K <= GGML_CUDA_SHORT_CONV_MAX_K);
const int block_size = 128;
const int n_runs = (a.Ts + a.run - 1)/a.run;
const dim3 grid((a.C + block_size - 1)/block_size, std::min(a.S*n_runs, 65535), 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
if (a.dyn) {
if (a.res) {
ggml_cuda_kernel_launch(short_conv_f32<true, true>, params, a);
} else {
ggml_cuda_kernel_launch(short_conv_f32<true, false>, params, a);
}
} else {
if (a.res) {
ggml_cuda_kernel_launch(short_conv_f32<false, true>, params, a);
} else {
ggml_cuda_kernel_launch(short_conv_f32<false, false>, params, a);
}
}
}
// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the
// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product
template <int block_size>
static __global__ void depth_mix_f32(
const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q,
const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1,
const bool norm_cur, const float eps, const float scale) {
ggml_cuda_pdl_lc();
constexpr int MAX = GGML_CUDA_DEPTH_MIX_MAX_ROWS;
constexpr int NW = block_size/WARP_SIZE;
const int q = blockIdx.x;
const int t = blockIdx.y;
const int tid = threadIdx.x;
const int lane = tid % WARP_SIZE;
const int warp = tid / WARP_SIZE;
const float * qv = query + q*query_s1;
const float * st = stack + t*stack_s2;
const float * xc = cur + t*cur_s1;
// [0, B): the stack rows, MAX: cur, MAX + 1: the sum of squares of cur
float acc[MAX + 2];
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
acc[r] = 0.0f;
}
ggml_cuda_pdl_sync();
for (int i = tid; i < n; i += block_size) {
const float qi = qv[i];
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] += st[r*stack_s1 + i]*qi;
}
}
const float xi = xc[i];
acc[MAX] += xi*qi;
acc[MAX + 1] += xi*xi;
}
__shared__ float s_acc[NW][MAX + 2];
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
if (r < B || r >= MAX) {
acc[r] = warp_reduce_sum(acc[r]);
if (lane == 0) {
s_acc[warp][r] = acc[r];
}
}
}
__syncthreads();
#pragma unroll
for (int r = 0; r < MAX + 2; ++r) {
if (r < B || r >= MAX) {
acc[r] = 0.0f;
#pragma unroll
for (int w = 0; w < NW; ++w) {
acc[r] += s_acc[w][r];
}
}
}
const float sc = norm_cur ? rsqrtf(acc[MAX + 1]/n + eps) : 1.0f;
float mx = scale*(sc*acc[MAX]);
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] = scale*acc[r];
mx = fmaxf(mx, acc[r]);
}
}
float p_cur = expf(scale*(sc*acc[MAX]) - mx);
float sum = 0.0f;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
acc[r] = expf(acc[r] - mx);
sum += acc[r];
}
}
sum += p_cur;
const float inv = 1.0f/sum;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
acc[r] *= inv;
}
p_cur *= inv*sc;
for (int i = tid; i < n; i += block_size) {
float o = 0.0f;
#pragma unroll
for (int r = 0; r < MAX; ++r) {
if (r < B) {
o += acc[r]*st[r*stack_s1 + i];
}
}
o += p_cur*xc[i];
dst[((int64_t) t*n + i)*Q + q] = o;
}
}
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst) {
const int64_t n = cur->ne[0];
const int64_t B = stack->ne[1];
const int64_t T = stack->ne[2];
const int64_t Q = query->ne[1];
GGML_ASSERT(B >= 1 && B <= GGML_CUDA_DEPTH_MIX_MAX_ROWS);
GGML_ASSERT(stack->nb[0] == sizeof(float) && cur->nb[0] == sizeof(float) && query->nb[0] == sizeof(float));
GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T);
GGML_ASSERT(T <= 65535 && Q <= 65535);
const int block_size = 256;
const dim3 grid(Q, T, 1);
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
ggml_cuda_kernel_launch(depth_mix_f32<block_size>, params,
(const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data,
(int) n, (int) B, (int) Q,
(int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)),
(int64_t) (cur->nb[2]/sizeof(float)), (int64_t) (query->nb[1]/sizeof(float)),
norm_cur, eps, scale);
}
// one block per (rank row, token): the sums of squares of cur and msg and their dot products with the two halves of the row
template <int block_size>
static __global__ void loop_ctrl_down_f32(
const float * cur, const float * msg, const float * w, float * gate, const int n,
const int64_t cur_s1, const int64_t msg_s1, const int64_t w_s1, const int64_t gate_s1, const float eps) {
ggml_cuda_pdl_lc();
const int r = blockIdx.x;
const int t = blockIdx.y;
const int tid = threadIdx.x;
const float * xc = cur + t*cur_s1;
const float * xm = msg + t*msg_s1;
const float * wr = w + r*w_s1;
ggml_cuda_pdl_sync();
float2 ss = make_float2(0.0f, 0.0f);
float2 dd = make_float2(0.0f, 0.0f);
for (int i = tid; i < n; i += block_size) {
const float c = xc[i];
const float m = xm[i];
ss.x += c*c;
ss.y += m*m;
dd.x += wr[i]*c;
dd.y += wr[n + i]*m;
}
__shared__ float2 s_ss[32];
__shared__ float2 s_dd[32];
ss = block_reduce<block_reduce_method::SUM, block_size>(ss, s_ss);
dd = block_reduce<block_reduce_method::SUM, block_size>(dd, s_dd);
if (tid == 0) {
gate[t*gate_s1 + r] = rsqrtf(ss.x/n + eps)*dd.x + rsqrtf(ss.y/n + eps)*dd.y;
}
}
// one warp per (output channel, token): the gain and forget dot products over the rank and the combine
static __global__ void loop_ctrl_up_f32(
const float * cur, const float * msg, const float * gate, const float * wg, const float * wf, float * dst,
const int n, const int rank, const int64_t cur_s1, const int64_t msg_s1, const int64_t gate_s1,
const int64_t wg_s1, const int64_t wf_s1, const int64_t dst_s1) {
ggml_cuda_pdl_lc();
const int i = blockIdx.x*blockDim.y + threadIdx.y;
const int t = blockIdx.y;
const int lane = threadIdx.x;
ggml_cuda_pdl_sync();
if (i >= n) {
return;
}
const float * gt = gate + t*gate_s1;
float g = 0.0f;
float f = 0.0f;
for (int k = lane; k < rank; k += WARP_SIZE) {
const float x = gt[k];
g += wg[i*wg_s1 + k]*x;
f += wf[i*wf_s1 + k]*x;
}
g = warp_reduce_sum(g);
f = warp_reduce_sum(f);
if (lane == 0) {
const float c = cur[t*cur_s1 + i];
const float m = msg[t*msg_s1 + i];
const float a = __fsub_rn(c, __fmul_rn(tanhf(f), c));
dst[t*dst_s1 + i] = __fadd_rn(a, __fmul_rn(tanhf(g), m));
}
}
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst) {
const int64_t n = cur->ne[0];
const int64_t T = cur->ne[1];
const int64_t rank = w_down->ne[1];
GGML_ASSERT(cur->nb[0] == sizeof(float) && msg->nb[0] == sizeof(float) && gate->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float));
GGML_ASSERT(w_down->ne[0] == 2*n && w_gain->ne[0] == rank && w_forget->ne[0] == rank && w_gain->ne[1] == n && w_forget->ne[1] == n);
GGML_ASSERT(T <= GGML_CUDA_LOOP_CTRL_MAX_TOKENS);
cudaStream_t stream = ctx.stream();
{
const int block_size = 256;
const ggml_cuda_kernel_launch_params params(dim3(rank, T, 1), dim3(block_size, 1, 1), 0, stream);
ggml_cuda_kernel_launch(loop_ctrl_down_f32<block_size>, params,
(const float *) cur->data, (const float *) msg->data, (const float *) w_down->data, (float *) gate->data, (int) n,
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)),
(int64_t) (w_down->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), eps);
}
{
const int rows_per_block = 8;
const ggml_cuda_kernel_launch_params params(dim3((n + rows_per_block - 1)/rows_per_block, T, 1), dim3(WARP_SIZE, rows_per_block, 1), 0, stream);
ggml_cuda_kernel_launch(loop_ctrl_up_f32, params,
(const float *) cur->data, (const float *) msg->data, (const float *) gate->data,
(const float *) w_gain->data, (const float *) w_forget->data, (float *) dst->data, (int) n, (int) rank,
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)),
(int64_t) (w_gain->nb[1]/sizeof(float)), (int64_t) (w_forget->nb[1]/sizeof(float)), (int64_t) (dst->nb[1]/sizeof(float)));
}
}
+55
View File
@@ -0,0 +1,55 @@
#pragma once
#include "common.cuh"
// fused op chains of the Inkling 2 graph
// largest conv width and stack depth the fused kernels handle
#define GGML_CUDA_SHORT_CONV_MAX_K 8
#define GGML_CUDA_DEPTH_MIX_MAX_ROWS 16
// the most tokens the fused loop controller handles, larger batches use the matrix multiplications
#define GGML_CUDA_LOOP_CTRL_MAX_TOKENS 8
// situ(g, u) = (s1*tanh(s0*g + b0) + b1)*sigmoid(g)*(s3*tanh(s2*u + b2) + b3), with s and b of the four SCALE nodes
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
const float * s, const float * b, ggml_tensor * dst);
// causal short conv: x = [past; cur^T], y = conv(x, w) (+ input-dependent taps per head), dst = s*(cur + y) + b (+ res)
// the K - 1 columns of x that end at token Ts - 1 - slot are the conv state of slot, for the last kw slots (kw = 1 without rollback)
// each thread does `run` tokens of a sequence in order, run == Ts lets dst be cur
struct ggml_cuda_short_conv_args {
const float * past; // [K - 1, C, S], strides in elements
int64_t past_s1;
int64_t past_s2;
const float * cur; // [C, Ts*S], contiguous
const float * w; // [K, C], contiguous
const float * dyn; // [K*H, Ts*S] taps or nullptr
int64_t dyn_s1;
int n_heads;
const float * res; // [C, Ts*S], contiguous, or nullptr
float * dst; // [C, Ts*S], contiguous
float * state; // [K - 1, slot, C, S], strides in elements
int64_t state_slot_s;
int64_t state_ch_s;
int64_t state_seq_s;
int kw;
int run;
int C;
int K;
int Ts;
int S;
float scale;
float bias;
};
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & args);
// depth mix: states = [stack; rms_norm(cur)], p = softmax(scale*(states . query)), dst = p . states, written as [Q, n, T]
// norm_cur false: cur is already normalized
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst);
// loop controller: gate = w_down . [rms_norm(cur); rms_norm(msg)], dst = cur - tanh(w_forget . gate)*cur + tanh(w_gain . gate)*msg
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst);
+2 -2
View File
@@ -1430,14 +1430,14 @@ namespace ggml_cuda_mma {
using floatx4_t = __attribute__((ext_vector_type(4))) float;
floatx4_t& acc_frag = reinterpret_cast<floatx4_t&>(D.x[0]);
#if defined(CDNA4) || defined(CDNA3) || defined(CDNA2)
using bf16x4_t = __attribute__((ext_vector_type(4))) __bf16;
using bf16x4_t = __attribute__((ext_vector_type(4))) short;
const bf16x4_t& a_frag = reinterpret_cast<const bf16x4_t&>(A.x[0]);
const bf16x4_t& b_frag = reinterpret_cast<const bf16x4_t&>(B.x[0]);
acc_frag = __builtin_amdgcn_mfma_f32_16x16x16bf16_1k(a_frag, b_frag, acc_frag, 0, 0, 0);
#elif defined(CDNA1)
#pragma unroll
for (int i = 0; i < 2; ++i) {
using bf16x2_t = __attribute__((ext_vector_type(2))) __bf16;
using bf16x2_t = __attribute__((ext_vector_type(2))) short;
const bf16x2_t& a_frag = reinterpret_cast<const bf16x2_t&>(A.x[i]);
const bf16x2_t& b_frag = reinterpret_cast<const bf16x2_t&>(B.x[i]);
acc_frag = __builtin_amdgcn_mfma_f32_16x16x8bf16(a_frag, b_frag, acc_frag, 0, 0, 0);
+5 -5
View File
@@ -799,10 +799,10 @@ static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
GGML_TENSOR_BINARY_OP_LOCALS;
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(nb00 == ggml_type_size(src0->type));
GGML_ASSERT(nb10 == sizeof(float));
GGML_ASSERT(nb10 == ggml_type_size(src1->type));
GGML_ASSERT(nb0 == sizeof(float));
GGML_ASSERT(ne00 % QK_K == 0);
@@ -828,14 +828,14 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS);
src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4);
quantize_mmq_few_id_q8_1_cuda((const float *) src1->data, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
ne00, nb11/sizeof(float), nb12/sizeof(float), ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
} else {
GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS);
GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4);
quantize_mmq_few_q8_1_cuda((const float *) src1->data, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/sizeof(float), nb12/sizeof(float), nb13/sizeof(float),
quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10,
ne11, ne12, ne13, stream);
}
+7 -8
View File
@@ -164,7 +164,7 @@ static int ggml_cuda_mmq_get_J_best(
void ggml_cuda_mul_mat_q(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
@@ -210,7 +210,6 @@ void ggml_cuda_mul_mat_q(
GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type));
const char * src0_d = (const char *) src0->data;
const float * src1_d = (const float *) src1->data;
float * dst_d = (float *) dst->data;
// If src0 (or the fused gate weight) is a temporary compute buffer, clear any potential padding.
@@ -284,11 +283,11 @@ void ggml_cuda_mul_mat_q(
static constexpr size_t align_float8 = 32;
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
static_assert(sizeof(block_fp4_mmq) == 4 * sizeof(block_q8_1));
quantize_mmq_fp4_cuda(src1_d, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
quantize_mmq_fp4_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
ne11, ne12, ne13, stream);
} else {
quantize_mmq_q8_1_cuda(src1_d, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
quantize_mmq_q8_1_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
ne11, ne12, ne13, stream);
}
CUDA_CHECK(cudaGetLastError());
@@ -359,17 +358,17 @@ void ggml_cuda_mul_mat_q(
static constexpr size_t align_float8 = 32;
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
if (dedup_bcast) {
quantize_scatter_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
quantize_scatter_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
} else {
quantize_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
quantize_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
}
} else if (dedup_bcast) {
quantize_scatter_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
quantize_scatter_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
} else {
quantize_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
quantize_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
}
CUDA_CHECK(cudaGetLastError());
+66 -27
View File
@@ -13,15 +13,20 @@ static __device__ __forceinline__ float2 mmvf_load_fp8x2(const ggml_fp8_e4m3_t *
#endif
}
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false>
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false,
typename T_y = float>
static __global__ void mul_mat_vec_f(
const T * x_ptr, const float * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
const T * x_ptr, const T_y * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
const int ncols2, const uint3 nchannels_y, const int stride_row, const int stride_col_y2, const int stride_col_dst,
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
const uint3 sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
const int ids_stride) {
static_assert(std::is_same_v<T_y, float> || (std::is_same_v<T_y, nv_bfloat16> &&
(std::is_same_v<T, nv_bfloat16> || std::is_same_v<T, ggml_fp8_e4m3_t>)), "a BF16 src1 needs BF16 or FP8 weights");
using T_y2 = std::conditional_t<std::is_same_v<T_y, nv_bfloat16>, nv_bfloat162, float2>; // a pair of src1 values
const T * GGML_CUDA_RESTRICT x = x_ptr;
const float * GGML_CUDA_RESTRICT y = y_ptr;
const T_y * GGML_CUDA_RESTRICT y = y_ptr;
const int32_t * GGML_CUDA_RESTRICT ids = ids_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
const int row = blockIdx.x;
@@ -257,7 +262,7 @@ static __global__ void mul_mat_vec_f(
#endif // FP16_AVAILABLE
}
} else if constexpr (std::is_same_v<T, nv_bfloat16>) {
const float2 * y2 = (const float2 *) y;
const T_y2 * y2 = (const T_y2 *) y;
//TODO: add support for ggml_cuda_mad for hip_bfloat162
#if defined(GGML_USE_HIP)
const int * x2 = (const int *) x;
@@ -277,7 +282,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
const float tmpx0 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[0]);
const float tmpx1 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[1]);
ggml_cuda_mad(sumf[j], tmpx0, tmpy.x);
@@ -311,7 +316,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
@@ -325,7 +330,7 @@ static __global__ void mul_mat_vec_f(
}
#endif
} else if constexpr (std::is_same_v<T, ggml_fp8_e4m3_t>) {
const float2 * y2 = (const float2 *) y;
const T_y2 * y2 = (const T_y2 *) y;
for (int col2 = tid; col2 < ncols2; col2 += block_size) {
const float2 tmpx = mmvf_load_fp8x2(x, col2);
float2 tmpx_gate = {};
@@ -336,7 +341,7 @@ static __global__ void mul_mat_vec_f(
}
#pragma unroll
for (int j = 0; j < ncols_dst; ++j) {
const float2 tmpy = y2[j*stride_col_y2 + col2];
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
ggml_cuda_mad(sumf[j], tmpx, tmpy);
if constexpr (has_fusion) {
@@ -439,9 +444,9 @@ static __global__ void mul_mat_vec_f(
}
}
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false>
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false, typename T_y = float>
static void mul_mat_vec_f_switch_fusion(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const uint3 nchannels_y,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
@@ -454,7 +459,7 @@ static void mul_mat_vec_f_switch_fusion(
fusion.x_scale != nullptr || fusion.gate_scale != nullptr;
if constexpr (ncols_dst == 1) {
if (has_fusion) {
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id>, launch_params,
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id, T_y>, launch_params,
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
@@ -464,16 +469,16 @@ static void mul_mat_vec_f_switch_fusion(
GGML_ASSERT(!has_fusion && "fusion only supported for ncols_dst=1");
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id>, launch_params,
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id, T_y>, launch_params,
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
}
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false>
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false, typename T_y = float>
void launch_mul_mat_vec_f_cuda(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -565,9 +570,9 @@ void launch_mul_mat_vec_f_cuda(
}
}
template <typename T, typename type_acc>
template <typename T, typename type_acc, typename T_y>
static void mul_mat_vec_f_cuda_switch_ncols_dst(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -661,9 +666,9 @@ static void mul_mat_vec_f_cuda_switch_ncols_dst(
}
}
template<typename T>
template<typename T, typename T_y>
static void mul_mat_vec_f_cuda(
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
const int64_t stride_row, const int64_t stride_col_y, const int stride_col_dst,
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
@@ -688,7 +693,9 @@ static void mul_mat_vec_f_cuda(
void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
// a BF16 src1 only for BF16 and FP8 weights
GGML_ASSERT( src1->type == GGML_TYPE_F32 ||
(src1->type == GGML_TYPE_BF16 && (src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3)));
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
@@ -790,12 +797,24 @@ void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor
} break;
case GGML_TYPE_BF16: {
const nv_bfloat16 * src0_d = (const nv_bfloat16 *) src0->data;
if (src1->type == GGML_TYPE_BF16) {
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
break;
}
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
} break;
case GGML_TYPE_F8_E4M3: {
const ggml_fp8_e4m3_t * src0_d = (const ggml_fp8_e4m3_t *) src0->data;
if (src1->type == GGML_TYPE_BF16) {
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
break;
}
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
@@ -866,8 +885,8 @@ void ggml_cuda_op_mul_mat_vec_f(
GGML_UNUSED_VARS(ctx, src1, dst, src1_ddq_i, src1_ncols, src1_padded_row_size);
}
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11) {
const ggml_type type = src0->type;
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id) {
const ggml_type type_src0 = src0->type;
const int64_t * src0_ne = src0->ne;
const size_t * src0_nb = src0->nb;
@@ -875,7 +894,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
return false;
}
const size_t ts = ggml_type_size(type);
const size_t ts = ggml_type_size(type_src0);
if (src0_nb[0] != ts) {
return false;
}
@@ -884,7 +903,27 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
return false;
}
switch (type) {
// MMVF reads a BF16 src1 only for BF16 and FP8 weights
if (type_src1 == GGML_TYPE_BF16 && type_src0 != GGML_TYPE_BF16 && type_src0 != GGML_TYPE_F8_E4M3) {
return false;
}
if (mul_mat_id) {
// FP8 experts on all GPUs, F32/F16/BF16 experts on AMD, and BF16 experts with a BF16 src1, which MMF can not read
// (with an F32 src1 NVIDIA takes MMF where it supports the experts, otherwise the sorted fallback)
switch (type_src0) {
case GGML_TYPE_F32:
case GGML_TYPE_F16:
case GGML_TYPE_BF16:
return ne11 <= MMVF_MAX_BATCH_SIZE && (GGML_CUDA_CC_IS_AMD(cc) || type_src1 == GGML_TYPE_BF16);
case GGML_TYPE_F8_E4M3:
return ne11 <= MMVF_MAX_BATCH_SIZE;
default:
return false;
}
}
switch (type_src0) {
case GGML_TYPE_F32:
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
if (ampere_mma_available(cc)) {
@@ -905,7 +944,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (ampere_mma_available(cc)) {
@@ -919,7 +958,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
}
return ne11 <= MMVF_MAX_BATCH_SIZE;
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (fp16_mma_hardware_available(cc)) {
@@ -938,7 +977,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
// MMF tiles 32 rows per block, so a matrix of few rows leaves most SMs idle while MMVF runs a block
@@ -964,7 +1003,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
}
return ne11 <= MMVF_MAX_BATCH_SIZE;
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
return ne11 <= MMVF_MAX_BATCH_SIZE;
}
if (bf16_mma_hardware_available(cc)) {
+1 -1
View File
@@ -11,4 +11,4 @@ void ggml_cuda_op_mul_mat_vec_f(
const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
const int64_t src1_padded_row_size, cudaStream_t stream);
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11);
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id);
+2 -3
View File
@@ -1538,7 +1538,7 @@ static void mul_mat_vec_q_switch_type(
void ggml_cuda_mul_mat_vec_q(
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
const ggml_cuda_mm_fusion_args_host * fusion) {
GGML_ASSERT( src1->type == GGML_TYPE_F32);
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
GGML_ASSERT( dst->type == GGML_TYPE_F32);
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
@@ -1557,7 +1557,6 @@ void ggml_cuda_mul_mat_vec_q(
GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE);
const float * src1_d = (const float *) src1->data;
const int32_t * ids_d = ids ? (const int32_t *) ids->data : nullptr;
float * dst_d = (float *) dst->data;
@@ -1637,7 +1636,7 @@ void ggml_cuda_mul_mat_vec_q(
const int64_t s11 = src1->nb[1] / ts_src1;
const int64_t s12 = src1->nb[2] / ts_src1;
const int64_t s13 = src1->nb[3] / ts_src1;
quantize_row_q8_1_cuda(src1_d, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
quantize_row_q8_1_cuda(src1->data, src1->type, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
}
const int64_t s01 = src0->nb[1] / ts_src0;
+113
View File
@@ -399,6 +399,54 @@ static __global__ void l2_norm_f32(
}
}
// l2_norm with an optional per-column weight before it and SCALE (+ an optional MUL by a per-channel/sample factor) after it,
// with the reduction of l2_norm_f32
template <int block_size, bool has_w, bool has_f>
static __global__ void l2_clip_f32(
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nchannels, const int nsamples,
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias) {
ggml_cuda_pdl_lc();
const int nrows = gridDim.x;
const int row = blockIdx.x;
const int tid = threadIdx.x;
extern __shared__ float s_sum[];
ggml_cuda_pdl_sync();
for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) {
for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) {
const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row;
const float * wc = has_w ? w + sample*w_stride_sample + channel*w_stride_channel + row*w_stride_row : nullptr;
float * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols;
float tmp = 0.0f;
for (int col = tid; col < ncols; col += block_size) {
const float xi = has_w ? xc[col]*wc[col] : xc[col];
tmp += xi * xi;
}
tmp = block_reduce<block_reduce_method::SUM, block_size>(tmp, s_sum);
const float l2 = rsqrtf(fmaxf(tmp, eps * eps));
const float fc = has_f ? f[sample*f_stride_sample + channel*f_stride_channel] : 1.0f;
for (int col = tid; col < ncols; col += block_size) {
const float xi = has_w ? xc[col]*wc[col] : xc[col];
const float yi = scale*(l2*xi) + bias;
dstc[col] = has_f ? yi*fc : yi;
}
if constexpr (block_size > WARP_SIZE) {
__syncthreads();
}
}
}
}
template <bool do_multiply = false, bool do_add = false>
static void norm_f32_cuda(const float * x,
float * dst,
@@ -623,6 +671,71 @@ static void l2_norm_f32_cuda(
}
}
template <bool has_w, bool has_f>
static void l2_clip_f32_cuda(
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples,
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias, cudaStream_t stream) {
const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX));
if (ncols < 1024) {
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(WARP_SIZE, 1, 1), 0, stream);
ggml_cuda_kernel_launch(l2_clip_f32<WARP_SIZE, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
f_stride_channel, f_stride_sample, eps, scale, bias);
} else {
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(1024, 1, 1), 32 * sizeof(float), stream);
ggml_cuda_kernel_launch(l2_clip_f32<1024, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
f_stride_channel, f_stride_sample, eps, scale, bias);
}
}
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst) {
GGML_ASSERT(x->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && x->nb[0] == sizeof(float));
GGML_ASSERT(ggml_is_contiguous(dst) && ggml_are_same_shape(x, dst));
GGML_TENSOR_LOCALS(int64_t, ne0, x, ne);
GGML_TENSOR_LOCALS(size_t, nb0, x, nb);
// broadcast dimensions of w and f have a stride of 0
auto bcast_stride = [](const ggml_tensor * t, int dim) -> int64_t {
return t->ne[dim] == 1 ? 0 : (int64_t) (t->nb[dim]/sizeof(float));
};
const int64_t ws1 = w ? bcast_stride(w, 1) : 0;
const int64_t ws2 = w ? bcast_stride(w, 2) : 0;
const int64_t ws3 = w ? bcast_stride(w, 3) : 0;
const int64_t fs2 = f ? bcast_stride(f, 2) : 0;
const int64_t fs3 = f ? bcast_stride(f, 3) : 0;
const float * x_d = (const float *) x->data;
const float * w_d = w ? (const float *) w->data : nullptr;
const float * f_d = f ? (const float *) f->data : nullptr;
float * d_d = (float *) dst->data;
const float eps = ggml_get_op_params_f32(l2_norm, 0);
const float s = ggml_get_op_params_f32(scale, 0);
const float b = ggml_get_op_params_f32(scale, 1);
const int64_t s01 = nb01/sizeof(float);
const int64_t s02 = nb02/sizeof(float);
const int64_t s03 = nb03/sizeof(float);
cudaStream_t stream = ctx.stream();
if (w && f) {
l2_clip_f32_cuda<true, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else if (w) {
l2_clip_f32_cuda<true, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else if (f) {
l2_clip_f32_cuda<false, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
} else {
l2_clip_f32_cuda<false, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
}
}
void ggml_cuda_op_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul, ggml_tensor * add) {
const ggml_tensor * src0 = dst->src[0];
const float * src0_d = (const float *) src0->data;
+4
View File
@@ -21,3 +21,7 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx,
void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
// [MUL by w ->] L2_NORM -> SCALE [-> MUL by f], w broadcasts over the rows, f is one value per channel/sample
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst);
+170 -59
View File
@@ -1,6 +1,21 @@
#include "quantize.cuh"
#include "convert.cuh"
#include <cstdint>
// 4 consecutive values of x as float4, x + 4*i is aligned to 4 values
template <typename src_t>
static __device__ __forceinline__ float4 quantize_load4(const src_t * x, const int64_t i) {
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
__align__(8) nv_bfloat162 v[2];
ggml_cuda_memcpy_1<sizeof(v)>(v, x + 4*i);
const float2 lo = ggml_cuda_cast<float2>(v[0]);
const float2 hi = ggml_cuda_cast<float2>(v[1]);
return make_float4(lo.x, lo.y, hi.x, hi.y);
} else {
return ((const float4 *) x)[i];
}
}
#if defined(BLACKWELL_MMA_AVAILABLE)
// this maps to 256-bit loads in PTX on supported devices,
// and otherwise falls back to 2 128-bit loads
@@ -9,6 +24,23 @@ struct __builtin_align__(32) float8 {
float p; float q; float r; float s;
};
// 8 consecutive values of x as float8, x is aligned to 8 values
// for float it returns a reference like a direct load, a copy changes the register allocation of the kernels
template <typename src_t>
static __device__ __forceinline__ decltype(auto) quantize_load8(const src_t * x) {
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
__align__(16) nv_bfloat162 v[4];
ggml_cuda_memcpy_1<sizeof(v)>(v, x);
const float2 a = ggml_cuda_cast<float2>(v[0]);
const float2 b = ggml_cuda_cast<float2>(v[1]);
const float2 c = ggml_cuda_cast<float2>(v[2]);
const float2 d = ggml_cuda_cast<float2>(v[3]);
return float8{a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y};
} else {
return reinterpret_cast<const float8 *>(x)[0];
}
}
#if CUDART_VERSION >= 12080
static __device__ __forceinline__ float nvfp4_native_scale_error(
const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) {
@@ -50,13 +82,14 @@ static __device__ __forceinline__ float nvfp4_native_scale_error(
#endif // CUDART_VERSION >= 12080
#endif // defined(BLACKWELL_MMA_AVAILABLE)
template <typename src_t>
__launch_bounds__(CUDA_QUANTIZE_BLOCK_SIZE, 1)
static __global__ void quantize_q8_1(
const float * x_ptr, void * vy_ptr,
const src_t * x_ptr, void * vy_ptr,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const uint32_t ne1, const uint3 ne2) {
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
void * GGML_CUDA_RESTRICT vy = vy_ptr;
const int64_t i0 = (int64_t)blockDim.x*blockIdx.x + threadIdx.x;
@@ -81,7 +114,7 @@ static __global__ void quantize_q8_1(
const int64_t iqs = i_cont % QK8_1; // quant index
ggml_cuda_pdl_sync();
const float xi = i0 < ne00 ? x[i03*s03 + i02*s02 + i01*s01 + i00] : 0.0f;
const float xi = i0 < ne00 ? ggml_cuda_cast<float>(x[i03*s03 + i02*s02 + i01*s01 + i00]) : 0.0f;
float amax = fabsf(xi);
amax = warp_reduce_max<QK8_1>(amax);
@@ -124,9 +157,9 @@ __device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) {
}
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <bool scatter, bool use_aligned_float8>
template <typename src_t, bool scatter, bool use_aligned_float8>
static __global__ void quantize_mmq_nvfp4(
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int n_expert_used) {
#if defined(BLACKWELL_MMA_AVAILABLE)
@@ -140,13 +173,12 @@ static __global__ void quantize_mmq_nvfp4(
const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
base_idx = i3 * s03 + i2 * s02 + i01 * s01;
}
const float * __restrict__ x_row = x + base_idx;
const src_t * __restrict__ x_row = x + base_idx;
float amax = 0.0f;
if constexpr (use_aligned_float8) {
for (int64_t i0 = 8 * threadIdx.x; i0 < ne00; i0 += 8 * blockDim.x) {
const float * x_base = x_row + i0;
const float8 v = reinterpret_cast<const float8 *>(x_base)[0];
const float8 v = quantize_load8(x_row + i0);
amax = fmaxf(amax, fabsf(v.x));
amax = fmaxf(amax, fabsf(v.y));
amax = fmaxf(amax, fabsf(v.z));
@@ -158,7 +190,7 @@ static __global__ void quantize_mmq_nvfp4(
}
} else {
for (int64_t i0 = threadIdx.x; i0 < ne00; i0 += blockDim.x) {
amax = fmaxf(amax, fabsf(x_row[i0]));
amax = fmaxf(amax, fabsf(ggml_cuda_cast<float>(x_row[i0])));
}
}
@@ -204,9 +236,9 @@ static __global__ void quantize_mmq_nvfp4(
float vals[QK_NVFP4_SUB];
if constexpr (use_aligned_float8) {
const float * x_base = x_row + i0_base;
const float8 v0 = i0_base + 7 < ne00 ? reinterpret_cast<const float8 *>(x_base)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const float8 v1 = i0_base + 15 < ne00 ? reinterpret_cast<const float8 *>(x_base + 8)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const src_t * x_base = x_row + i0_base;
const float8 v0 = i0_base + 7 < ne00 ? quantize_load8(x_base) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
const float8 v1 = i0_base + 15 < ne00 ? quantize_load8(x_base + 8) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
vals[0] = v0.x; vals[1] = v0.y; vals[2] = v0.z; vals[3] = v0.w;
vals[4] = v0.p; vals[5] = v0.q; vals[6] = v0.r; vals[7] = v0.s;
vals[8] = v1.x; vals[9] = v1.y; vals[10] = v1.z; vals[11] = v1.w;
@@ -215,7 +247,7 @@ static __global__ void quantize_mmq_nvfp4(
#pragma unroll
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
const int64_t i00 = i0_base + k;
vals[k] = i00 < ne00 ? x_row[i00] : 0.0f;
vals[k] = i00 < ne00 ? ggml_cuda_cast<float>(x_row[i00]) : 0.0f;
}
}
@@ -333,8 +365,8 @@ static __global__ void quantize_mmq_nvfp4(
// quantize values in the format mxfp4 is stored which is interleaved nibbles
// i.e. a block a0-a31 is represented as a0a16,a1a17 ...a15a31
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <bool scatter>
static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
template <typename src_t, bool scatter>
static __global__ void quantize_mmq_mxfp4(const src_t * __restrict__ x,
const int32_t * __restrict__ ids,
void * __restrict__ vy,
const int64_t ne00,
@@ -384,7 +416,7 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
#pragma unroll
for (int b = 0; b < 2; ++b) {
const int64_t i0 = warp_start_offset + b * vals_per_scale + lane_id_32;
const float xi = (i0 < ne00) ? x[base_pos + i0] : 0.0f;
const float xi = (i0 < ne00) ? ggml_cuda_cast<float>(x[base_pos + i0]) : 0.0f;
float amax = fabsf(xi);
#pragma unroll
@@ -453,9 +485,9 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
}
// scatter: grid over tokens, quantize once, write to all the token's compact rows
template <mmq_q8_1_ds_layout ds_layout, bool scatter>
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool scatter>
static __global__ void quantize_mmq_q8_1(
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int ne1, const int ne2, const int n_expert_used) {
@@ -481,14 +513,13 @@ static __global__ void quantize_mmq_q8_1(
base_idx = i3*s03 + i2*s02 + i01*s01;
}
const float4 * x4 = (const float4 *) x;
block_q8_1_mmq * y = (block_q8_1_mmq *) vy;
const int64_t k_block = i0 / QK8_1_MMQ; // column block in the channel
const int64_t iqs = i0 % QK8_1_MMQ; // quant index in block
// Load 4 floats per thread and calculate max. abs. value between them:
const float4 xi = i0 < ne00 ? x4[(base_idx + i00)/4] : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const float4 xi = i0 < ne00 ? quantize_load4(x, (base_idx + i00)/4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
float amax = fabsf(xi.x);
amax = fmaxf(amax, fabsf(xi.y));
amax = fmaxf(amax, fabsf(xi.z));
@@ -556,8 +587,20 @@ static __global__ void quantize_mmq_q8_1(
GGML_UNUSED(n_expert_used);
}
void quantize_row_q8_1_cuda(
const float * x, void * vy,
// calls launch with x as const float * or const nv_bfloat16 *, the src1 types that the quantize kernels read
template <typename F>
static void quantize_launch_typed(const void * x, const ggml_type type_src1, const F & launch) {
if (type_src1 == GGML_TYPE_BF16) {
launch((const nv_bfloat16 *) x);
} else {
GGML_ASSERT(type_src1 == GGML_TYPE_F32);
launch((const float *) x);
}
}
template <typename src_t>
static void quantize_row_q8_1_cuda(
const src_t * x, void * vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne0 % QK8_1 == 0);
@@ -568,11 +611,21 @@ void quantize_row_q8_1_cuda(
const dim3 num_blocks(block_num_x, ne1, ne2*ne3);
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE, 1, 1);
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
ggml_cuda_kernel_launch(quantize_q8_1<src_t>, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
}
void quantize_mmq_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
void quantize_row_q8_1_cuda(
const void * x, const ggml_type type_src1, void * vy,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_row_q8_1_cuda(x_t, vy, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
template <typename src_t>
static void quantize_mmq_q8_1_cuda(
const src_t * x, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne00 % 4 == 0);
@@ -584,15 +637,15 @@ void quantize_mmq_q8_1_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
switch (mmq_get_q8_1_ds_layout(type_src0)) {
case MMQ_Q8_1_DS_LAYOUT_D4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
case MMQ_Q8_1_DS_LAYOUT_D2S6:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, false>
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, false>
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
break;
default:
@@ -600,6 +653,15 @@ void quantize_mmq_q8_1_cuda(
}
}
void quantize_mmq_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_q8_1_cuda(x_t, ids, vy, type_src0, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
// Stores the 4 values xi of a thread, values [iu, iu + 4) of column g in a unit of 256 values, in the column group yg of the unit, see quantize.cuh for the layout.
template <mmq_q8_1_ds_layout ds_layout>
static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, int4 * yg, const int iu, const int g) {
@@ -635,12 +697,12 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
}
// Each thread quantizes 4 values of one column, see quantize.cuh for the layout.
template <mmq_q8_1_ds_layout ds_layout>
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
static __global__ void quantize_mmq_few_q8_1(
const float * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int ne1, const int ne2) {
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4;
@@ -651,7 +713,7 @@ static __global__ void quantize_mmq_few_q8_1(
const int64_t i2 = blockIdx.z % ne2;
const int64_t i3 = blockIdx.z / ne2;
const float4 xi = (int) blockIdx.x < ne1 ? *(const float4 *) (x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const float4 xi = (int) blockIdx.x < ne1 ? quantize_load4(x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0, 0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
const int g = blockIdx.x % MMQ_FEW_NCOLS; // column in group
int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_NCOLS) + blockIdx.x/MMQ_FEW_NCOLS)*MMQ_FEW_Q8_1_INT4;
@@ -660,9 +722,9 @@ static __global__ void quantize_mmq_few_q8_1(
// MUL_MAT_ID: block x is the (token, slot) entry, ids are as in mm_ids_helper. Each block finds the pair of its entry in shared memory, block (0, 0) also writes all pairs.
// Entry rank r = number of earlier tokens with the same expert, pair = first pair of the expert + r/MMQ_FEW_NCOLS, column = r % MMQ_FEW_NCOLS.
template <mmq_q8_1_ds_layout ds_layout>
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
static __global__ void quantize_mmq_few_id_q8_1(
const float * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
const src_t * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max) {
// per expert: bit t set if token t uses it and the index of its first pair; then the total number of pairs
extern __shared__ unsigned int data_mmq_few_id[];
@@ -671,7 +733,7 @@ static __global__ void quantize_mmq_few_id_q8_1(
int & npairs = pair0[n_experts];
ggml_cuda_pdl_lc();
const float * GGML_CUDA_RESTRICT x = x_ptr;
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
ggml_cuda_pdl_sync();
@@ -741,15 +803,16 @@ static __global__ void quantize_mmq_few_id_q8_1(
}
const int it = blockIdx.x / n_expert_used;
const int is = blockIdx.x % n_expert_used;
const float4 xi = *(const float4 *) (x + it*s12 + (is % ne11)*s11 + i0);
const float4 xi = quantize_load4(x + it*s12 + (is % ne11)*s11 + i0, 0);
const int r = rank(blockIdx.x, e);
int4 * yg = vy + (int64_t(pair0[e] + r/MMQ_FEW_NCOLS)*(ne00/QK_K) + i0/QK_K)*MMQ_FEW_Q8_1_INT4;
quantize_mmq_few_store<ds_layout>(xi, yg, i0 % QK_K, r % MMQ_FEW_NCOLS);
}
void quantize_mmq_few_q8_1_cuda(
const float * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
template <typename src_t>
static void quantize_mmq_few_q8_1_cuda(
const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(ne00 % QK_K == 0);
@@ -759,11 +822,11 @@ void quantize_mmq_few_q8_1_cuda(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
switch (ds_layout) {
case MMQ_Q8_1_DS_LAYOUT_D4:
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
break;
default:
@@ -771,8 +834,17 @@ void quantize_mmq_few_q8_1_cuda(
}
}
void quantize_mmq_few_id_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
void quantize_mmq_few_q8_1_cuda(
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_few_q8_1_cuda(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
});
}
template <typename src_t>
static void quantize_mmq_few_id_q8_1_cuda(
const src_t * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
GGML_ASSERT(ne00 % QK_K == 0);
GGML_ASSERT(n_tokens <= 32); // one bit per token
@@ -785,11 +857,11 @@ void quantize_mmq_few_id_q8_1_cuda(
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, nbytes_shared, stream);
switch (ds_layout) {
case MMQ_Q8_1_DS_LAYOUT_D4:
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
break;
default:
@@ -797,9 +869,18 @@ void quantize_mmq_few_id_q8_1_cuda(
}
}
void quantize_mmq_few_id_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max, stream);
});
}
// scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row)
void quantize_scatter_mmq_q8_1_cuda(
const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
template <typename src_t>
static void quantize_scatter_mmq_q8_1_cuda(
const src_t * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
GGML_ASSERT(ne00 % 4 == 0);
@@ -810,15 +891,15 @@ void quantize_scatter_mmq_q8_1_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
switch (mmq_get_q8_1_ds_layout(type_src0)) {
case MMQ_Q8_1_DS_LAYOUT_D4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
case MMQ_Q8_1_DS_LAYOUT_DS4:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
case MMQ_Q8_1_DS_LAYOUT_D2S6:
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
break;
default:
@@ -826,9 +907,19 @@ void quantize_scatter_mmq_q8_1_cuda(
}
}
void quantize_scatter_mmq_q8_1_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_scatter_mmq_q8_1_cuda(x_t, ids_src1_inv, vy, type_src0, ne00, stride_token, ne0, n_tokens, nrows_dst, n_expert_used, stream);
});
}
// scatter=true reuses the quant kernels: grid over tokens, ids = inverse map (token slot -> compact row)
void quantize_scatter_mmq_fp4_cuda(
const float * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
template <typename src_t>
static void quantize_scatter_mmq_fp4_cuda(
const src_t * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
GGML_ASSERT(ne0 > 0);
@@ -838,10 +929,10 @@ void quantize_scatter_mmq_fp4_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
const dim3 num_blocks(n_tokens, 1, 1);
if (use_aligned_float8) {
quantize_mmq_nvfp4<true, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, true, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
} else {
quantize_mmq_nvfp4<true, false><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, true, false><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
}
} else {
@@ -851,13 +942,24 @@ void quantize_scatter_mmq_fp4_cuda(
const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block;
const dim3 block_size(WARP_SIZE, nwarps, 1);
const dim3 num_blocks(n_tokens, block_num_y, 1);
quantize_mmq_mxfp4<true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_mxfp4<src_t, true><<<num_blocks, block_size, 0, stream>>>(
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
}
}
void quantize_mmq_fp4_cuda(
const float * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
void quantize_scatter_mmq_fp4_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0,
const bool use_aligned_float8, const int64_t ne00, const int64_t stride_token, const int64_t ne0,
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_scatter_mmq_fp4_cuda(x_t, ids_src1_inv, vy, scale, type_src0, use_aligned_float8, ne00, stride_token, ne0,
n_tokens, nrows_dst, n_expert_used, stream);
});
}
template <typename src_t>
static void quantize_mmq_fp4_cuda(
const src_t * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4 || type_src0 == GGML_TYPE_NVFP4);
@@ -869,10 +971,10 @@ void quantize_mmq_fp4_cuda(
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
const dim3 num_blocks(ne1, ne2 * ne3, 1);
if (use_aligned_float8) {
quantize_mmq_nvfp4<false, true><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, false, true><<<num_blocks, block_size, 0, stream>>>(
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
} else {
quantize_mmq_nvfp4<false, false><<<num_blocks, block_size, 0, stream>>>(
quantize_mmq_nvfp4<src_t, false, false><<<num_blocks, block_size, 0, stream>>>(
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
}
} else {
@@ -886,6 +988,15 @@ void quantize_mmq_fp4_cuda(
const dim3 num_blocks(ne1, block_num_y, ne2 * ne3);
const dim3 block_size(WARP_SIZE, nwarps, 1);
quantize_mmq_mxfp4<false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
quantize_mmq_mxfp4<src_t, false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
}
}
void quantize_mmq_fp4_cuda(
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0,
const bool use_aligned_float8, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
quantize_mmq_fp4_cuda(x_t, ids, vy, scale, type_src0, use_aligned_float8, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
});
}
+12 -7
View File
@@ -11,13 +11,15 @@
static_assert(MATRIX_ROW_PADDING % CUDA_QUANTIZE_BLOCK_SIZE == 0, "Risk of out-of-bounds access.");
static_assert(MATRIX_ROW_PADDING % (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ) == 0, "Risk of out-of-bounds access.");
// x holds the src1 values, type_src1 is GGML_TYPE_F32 or GGML_TYPE_BF16
void quantize_row_q8_1_cuda(
const float * x, void * vy,
const void * x, ggml_type type_src1, void * vy,
int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
void quantize_mmq_q8_1_cuda(
const float * x, const int32_t * ids, void * vy,
const void * x, ggml_type type_src1, const int32_t * ids, void * vy,
ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
@@ -29,7 +31,7 @@ static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group
static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group
void quantize_mmq_few_q8_1_cuda(
const float * x, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
// MUL_MAT_ID: a pair is an expert and one column group of up to MMQ_FEW_NCOLS of its (token, slot) entries. The src1 of pair p is channel p above, its columns past the entries are not written.
@@ -37,10 +39,11 @@ void quantize_mmq_few_q8_1_cuda(
static constexpr int MMQ_FEW_PAIR_INTS = 2 + MMQ_FEW_NCOLS;
void quantize_mmq_few_id_q8_1_cuda(
const float * x, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
const void * x, ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max, cudaStream_t stream);
void quantize_mmq_fp4_cuda(const float * x,
void quantize_mmq_fp4_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids,
void * vy,
float * scale,
@@ -57,7 +60,8 @@ void quantize_mmq_fp4_cuda(const float * x,
cudaStream_t stream);
// quantize each token once and scatter the block to its compact rows (via the inverse map)
void quantize_scatter_mmq_fp4_cuda(const float * x,
void quantize_scatter_mmq_fp4_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids_src1_inv,
void * vy,
float * scale,
@@ -71,7 +75,8 @@ void quantize_scatter_mmq_fp4_cuda(const float * x,
int n_expert_used,
cudaStream_t stream);
void quantize_scatter_mmq_q8_1_cuda(const float * x,
void quantize_scatter_mmq_q8_1_cuda(const void * x,
ggml_type type_src1,
const int32_t * ids_src1_inv,
void * vy,
ggml_type type_src0,
+2
View File
@@ -114,6 +114,8 @@ GGML_API void ggml_rope_yarn_corr_dims(
GGML_API bool ggml_rope_get_truncate(const struct ggml_tensor * a);
GGML_API bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a);
//
// logging
//
+5
View File
@@ -1536,6 +1536,11 @@ static bool ggml_metal_supports_mul_mat_op(
return false;
}
// BF16 src1 kernels: mul_mv for F32 and BF16 src0, mul_mm for BF16 src0
if (op->src[1]->type == GGML_TYPE_BF16) {
return op->op == GGML_OP_MUL_MAT && (op->src[0]->type == GGML_TYPE_BF16 || (op->src[0]->type == GGML_TYPE_F32 && !mm_path));
}
if (op->src[1]->type != GGML_TYPE_F16) {
return true;
}
+449 -2
View File
@@ -1215,6 +1215,14 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) q4_0 MoE prefill GEMM
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM using ldck
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 mxfp4 MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_0 MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_1 MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_0 MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_1 MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_k MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_k MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q6_k MoE prefill GEMM (A850)
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_0 MoE prefill GEMM
cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_k MoE prefill GEMM
cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q6_k MoE prefill GEMM
@@ -1241,6 +1249,7 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_mul_mv_id_mxfp4_f32_flat;
cl_kernel kernel_mul_mm_f32_f32_l4_lm;
cl_kernel kernel_gemv_f32_f32_mc; // multi-column (small-N) f32 GEMV for spec/MTP verify
cl_kernel kernel_gemv_f32_f32_mcr = nullptr;
cl_kernel kernel_mul_mm_f16_f32_l4_lm;
cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8;
cl_kernel kernel_mul_mm_q1_0_f32_l4_lm;
@@ -1563,6 +1572,7 @@ struct ggml_backend_opencl_context {
}
#endif
for (cl_kernel kernel : {
kernel_gemv_f32_f32_mcr,
kernel_xielu_f32,
kernel_xielu_f16,
kernel_mul_mm_f16_f32_kq_p8,
@@ -4274,6 +4284,16 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
CL_CHECK((backend_ctx->kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_mul_mm_f32_f32_l4_lm", &err), err));
CL_CHECK((backend_ctx->kernel_gemv_f32_f32_mc = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mc", &err), err));
cl_kernel mcr = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mcr", &err);
if (err == CL_SUCCESS) {
if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) {
backend_ctx->kernel_gemv_f32_f32_mcr = mcr;
} else {
CL_CHECK(clReleaseKernel(mcr));
}
}
GGML_LOG_CONT(".");
}
@@ -7808,6 +7828,150 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
}
}
// gemm_moe_mxfp4_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q4_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q4_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q5_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_0_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_0_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q5_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_1_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_1_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q4_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q5_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_k_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_k_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q6_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
if (backend_ctx->has_integer_dot) {
size_t bin_size = 0;
backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr;
if (use_adreno_bin_kernels(backend_ctx)) {
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila_malu", &bin_size);
if (kernel_bin && bin_size > 0) {
cl_program prog =
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila_malu", &err), err));
CL_CHECK(clReleaseProgram(prog));
GGML_LOG_CONT(".");
}
}
}
// gemm_moe_q4_0_q8_1_dp4a (dp4a prefill GEMM)
if (backend_ctx->has_integer_dot) {
#ifdef GGML_OPENCL_EMBED_KERNELS
@@ -11080,6 +11244,76 @@ static bool ggml_opencl_can_fuse_moe_bias_glu(const struct ggml_cgraph * cgraph,
return true;
}
// Run a malu int8 (dp4a ila malu bin) MoE GEMM: fused reorder + q8_1 quant of the activations, then the GEMM.
// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type.
// use_sa: the kernel takes the q8_1 block sums (min types), or an unused buffer in that slot (q4_0).
static void ggml_cl_moe_gemm_malu_bin(
ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list<cl_mem> weights, bool use_sa,
cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap,
cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst,
int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) {
cl_int status;
const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size;
const size_t n_blocks = tok_slots * (ne00 / 32);
backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char));
backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half));
backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half));
const cl_uint n_kblocks = (cl_uint)(ne00 / 32);
cl_uint ne00_u = ne00;
cl_uint tile_u = n_tile_size;
cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1;
CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre));
CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2));
CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer));
CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer)));
CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00_u));
CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio));
CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &tile_u));
CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks));
size_t rq_local[2] = { 32, 1 };
size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots };
backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst);
// dst as an image
cl_buffer_region region;
region.origin = offsetd;
region.size = n_dst * sizeof(float);
cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, &region, &status);
CL_CHECK(status);
cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT};
cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}};
cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status);
CL_CHECK(status);
int aidx = 0;
for (cl_mem w : weights) {
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &w));
}
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
if (use_sa) {
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer));
}
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2_emap));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_dst_image));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer)));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne00));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne01));
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4));
size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile };
size_t dp_local[3] = { 64, 1, 1 };
backend_ctx->enqueue_ndrange_kernel(kernel, 3, dp_global, dp_local, dst);
clReleaseMemObject(sub_buf_dst);
clReleaseMemObject(buf_dst_image);
}
// Run a cl_qcom_kernel_cooperative_matrix MoE GEMM: f16 reorder of the activations, then the GEMM.
// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type.
static void ggml_cl_moe_gemm_coopmat(
@@ -32854,6 +33088,20 @@ static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_t
backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst);
}
// reduce lanes per row for short K, down to four lanes.
static int ggml_cl_mcr_lpr_log2(int ne00) {
int lpr_log2 = 6;
while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) {
lpr_log2--;
}
return lpr_log2;
}
static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) {
const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00);
return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256;
}
static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_ASSERT(src0);
GGML_ASSERT(src0->extra);
@@ -33448,8 +33696,63 @@ static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, co
// under-occupied WG at ~2.3% tile utilization. Route to a per-output
// (m,n) GEMV (64-thread WG, K-split + __local reduce) instead.
// 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it.
static const char * f32_mc_env = getenv("GGML_OPENCL_F32_MC");
const bool f32_mc = f32_mc_env ? atoi(f32_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
static const int f32_mc_env = [] {
const char * env = getenv("GGML_OPENCL_F32_MC");
return env ? atoi(env) : -1;
}();
const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
static const int f32_mcr_env = [] {
const char * env = getenv("GGML_OPENCL_F32_MCR");
return env && *env ? atoi(env) : -1;
}();
const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 :
(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X);
const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx);
if (f32_mcr && f32_mcr_allowed && backend_ctx->kernel_gemv_f32_f32_mcr != nullptr &&
ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 &&
(size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) &&
ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 &&
dst->ne[2] == 1 && dst->ne[3] == 1 &&
ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) &&
offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 &&
ggml_cl_mcr_wide_enough((int) ne00, (int) ne01)
) {
const int K = (int) ne00;
const int M = (int) ne01;
const int N = (int) ne11;
const int stride_a = K;
const int stride_b = K;
const int stride_d = M;
const int lpr_log2 = ggml_cl_mcr_lpr_log2(K);
const int rows_per_wg = 64 >> lpr_log2;
cl_kernel mcr = backend_ctx->kernel_gemv_f32_f32_mcr;
CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device));
CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0));
CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device));
CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1));
CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K));
CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M));
CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N));
CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a));
CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b));
CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d));
CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2));
size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1};
size_t local[] = {64, 1, 1};
backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst);
return;
}
if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) &&
ne02 == 1 && ne12 == 1 && ne13 == 1 &&
ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) {
@@ -36917,6 +37220,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
unsigned short map_ratio = ne20 / ne11;
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q4_0_moe_malu_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q4_0_moe_malu_env || atoi(q4_0_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin,
{ extra0_q4_0->q_img, extra0_q4_0->d }, true,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q4_0_moe_coopmat_env = getenv("GGML_OPENCL_Q4_0_MOE_COOPMAT");
@@ -37221,6 +37542,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, &region, &status);
CL_CHECK(status);
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q4_1_moe_malu_env = getenv("GGML_OPENCL_Q4_1_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q4_1_moe_malu_env || atoi(q4_1_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin,
{ extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, true,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q4_1_moe_coopmat_env = getenv("GGML_OPENCL_Q4_1_MOE_COOPMAT");
@@ -37500,6 +37839,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
}
}
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q5_0_moe_malu_env = getenv("GGML_OPENCL_Q5_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q5_0_moe_malu_env || atoi(q5_0_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin,
{ extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, false,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q5_0_moe_coopmat_env = getenv("GGML_OPENCL_Q5_0_MOE_COOPMAT");
@@ -37699,6 +38056,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, &region, &status);
CL_CHECK(status);
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q5_1_moe_malu_env = getenv("GGML_OPENCL_Q5_1_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q5_1_moe_malu_env || atoi(q5_1_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin,
{ extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, true,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q5_1_moe_coopmat_env = getenv("GGML_OPENCL_Q5_1_MOE_COOPMAT");
@@ -38183,6 +38558,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
unsigned short map_ratio = ne20 / ne11;
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q4_k_moe_malu_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q4_k_moe_malu_env || atoi(q4_k_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin,
{ extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, true,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q4_k_moe_coopmat_env = getenv("GGML_OPENCL_Q4K_MOE_COOPMAT");
@@ -38522,6 +38915,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
}
}
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q5_k_moe_malu_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q5_k_moe_malu_env || atoi(q5_k_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin,
{ extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, true,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q5_k_moe_coopmat_env = getenv("GGML_OPENCL_Q5K_MOE_COOPMAT");
@@ -38742,6 +39153,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
unsigned short map_ratio = ne20 / ne11;
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * q6_k_moe_malu_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!q6_k_moe_malu_env || atoi(q6_k_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin,
{ extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, false,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
{
static const char * q6_k_moe_coopmat_env = getenv("GGML_OPENCL_Q6K_MOE_COOPMAT");
@@ -39042,6 +39471,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
unsigned short map_ratio = ne20 / ne11;
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
{
static const char * mxfp4_moe_malu_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A");
if (backend_ctx->has_integer_dot && (!mxfp4_moe_malu_env || atoi(mxfp4_moe_malu_env) != 0) &&
backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin != nullptr) {
unsigned short malu_map_ratio = ne20 / ne11;
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin,
{ extra0_mxfp4->q_img, extra0_mxfp4->e }, false,
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
clReleaseMemObject(sub_buf_src1_pre);
clReleaseMemObject(buf_src2);
clReleaseMemObject(buf_src2_emap);
return;
}
}
if (use_moe_coopmat) {
// f16 reordered activations, read by the coopmat kernel as a buffer
region.origin = 0;
@@ -194,3 +194,64 @@ kernel void kernel_gemv_f32_f32_mc(
}
if (lane == 0) dst[(ulong)n * (uint)stride_d + m] = red[0];
}
// Reuse each weight row across the narrow batch, with one accumulator per column.
kernel void kernel_gemv_f32_f32_mcr(
global const float * src0, ulong offset0,
global const float * src1, ulong offset1,
global float * dst, ulong offsetd,
int ne00, // K
int ne01, // M
int ne11, // N, 2..8
int stride_a,
int stride_b,
int stride_d,
int lpr_log2 // lanes per row = 1 << lpr_log2
) {
src0 = (global const float*)((global const char*)src0 + offset0);
src1 = (global const float*)((global const char*)src1 + offset1);
dst = (global float*)((global char*)dst + offsetd);
const uint lane = get_local_id(0);
const uint lpr = 1u << lpr_log2;
const uint l = lane & (lpr - 1);
const uint mr = get_group_id(0) * (64u >> lpr_log2) + (lane >> lpr_log2);
const bool valid = mr < (uint)ne01;
// Keep padded rows in the local-memory barriers.
const uint m = valid ? mr : (uint)ne01 - 1;
global const float4 * wrow = (global const float4*)(src0 + (ulong)m * (uint)stride_a);
const uint k4 = (uint)ne00 >> 2;
float acc[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
for (uint k = l; k < k4; k += lpr) {
const float4 w = wrow[k];
#pragma unroll
for (int n = 0; n < 8; n++) {
if (n < ne11) {
acc[n] += dot(w, ((global const float4*)(src1 + (ulong)n * (uint)stride_b))[k]);
}
}
}
local float red[8 * 64];
#pragma unroll
for (int n = 0; n < 8; n++) {
red[n * 64 + lane] = acc[n];
}
barrier(CLK_LOCAL_MEM_FENCE);
for (uint s = lpr >> 1; s > 0; s >>= 1) {
if (l < s) {
#pragma unroll
for (int n = 0; n < 8; n++) {
red[n * 64 + lane] += red[n * 64 + lane + s];
}
}
barrier(CLK_LOCAL_MEM_FENCE);
}
if (l == 0 && valid) {
for (int n = 0; n < ne11; n++) {
dst[(ulong)n * (uint)stride_d + m] = red[n * 64 + lane];
}
}
}
+7 -10
View File
@@ -1,3 +1,7 @@
if (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64|aarch64)$")
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
endif()
find_package(OpenVINO REQUIRED COMPONENTS Runtime Threading)
find_package(OpenCL REQUIRED)
@@ -24,17 +28,11 @@ if (WIN32)
target_link_libraries(ggml-openvino PRIVATE psapi)
endif()
if (GGML_OPENVINO)
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64")
else()
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
endif()
endif()
# Released runtimes retain the ordinary cache translators.
include(CheckCXXSourceCompiles)
include(CMakePushCheckState)
unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
check_cxx_source_compiles("#include <recurrent_cache_update.hpp>
@@ -43,8 +41,7 @@ int main() {
auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(ov::OutputVector{});
}"
GGML_OPENVINO_HAS_CACHE_UPDATE)
unset(CMAKE_REQUIRED_LIBRARIES)
unset(CMAKE_REQUIRED_INCLUDES)
cmake_pop_check_state()
if(GGML_OPENVINO_HAS_CACHE_UPDATE)
target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
endif()
+8
View File
@@ -87,3 +87,11 @@ The generic recurrent-cache translation invalidates blobs made with the former s
- File identity, size, modification/change timestamps, tensor offsets, graph structure, settings, and OpenVINO version identify cache entries. Linux uses device/inode and Windows uses volume serial/file index. Replacing, copying, or modifying a GGUF invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
- Use the same target device and compatible OpenVINO/plugin installation. Import support depends on the plugin; the tested CPU plugin cannot import MoE graphs containing `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
- Blobs contain weights and can approach model size for each compiled graph. Import still reads those blobs and initializes the device.
# KV-only prefill
On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read an earlier layer's KV get a KV-only prefill by default; `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. It compiles the static prefill graph with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). Everything that only feeds the logits is dropped from it: for models whose tail layers read an earlier layer's KV (Gemma 3n/4 E-series) that is every KV-shared layer, plus the LM head. When the batch needs logits, the decode graph is then run once on the output token; it rewrites that token's KV rows and computes the dropped layers against the complete cache. It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
# NPU host gather
`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_<node>` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to 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 Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
@@ -11,6 +11,7 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
| `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. |
| `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. |
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
| `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | Print each graph node and its sources with their shapes when a graph is decoded. `*` marks the dynamic (token) dimension. |
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
@@ -28,6 +29,9 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
@@ -50,8 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_KV_SLICE` | all | Boolean | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. CPU and GPU: a view over the cache. NPU: the prefill graph is compiled at the attended length, rounded up to a power of two, and replaced when that size changes. With `0`, `llama-bench -d` fails on the NPU. |
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | Decode attends the smallest `1024 * 2^k` rows that cover the next position, with one decode graph for each window. All windows are built, or read from the cache, together with the first prefill and decode pair. `0`: one decode graph attends the whole context. Use the same value in the run that writes the cache and in the runs that read it. |
| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. |
| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
| `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling, which keeps the GDN output above the FP16 flush-to-zero floor of the NPU. `0` or a negative value turns it off. Values below `64` are raised to `64`. |
@@ -75,7 +79,6 @@ These options are off by default. They are not validated for general use: some h
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. |
| `GGML_OPENVINO_NPU_PARALLEL_COMPILE` | NPU | Boolean | `0` | Compile the prefill and decode graphs in parallel. The load is shorter and the host memory peak during compilation is higher. |
| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). |
| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. |
@@ -90,16 +93,13 @@ These options are off by default. They are not validated for general use: some h
| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. |
| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. |
| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. |
| `GGML_OPENVINO_SELF_CONTAINED_BLOB` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode graphs as blobs with the weights inside; each blob takes about the size of the model on disk. Decode then attends the whole context. `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` is the recommended cache layout for the NPU. |
| `GGML_OPENVINO_NPU_SHARED_BANK` | NPU | Boolean | `0` | With `GGML_OPENVINO_SELF_CONTAINED_BLOB=1`: one weights bank for the prefill and decode blobs. With OpenVINO 2026.4.1 the blobs cannot be read back, so decode is compiled again. |
| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. |
```bash
# NPU cache with the weights inside the blobs (experimental). Keep all other NPU settings the same in both runs.
# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
export GGML_OPENVINO_SELF_CONTAINED_BLOB=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: log shows "model cache WROTE"
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
@@ -141,7 +141,6 @@ export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs
@@ -182,11 +181,15 @@ Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend do
| `NPUW_UNFOLD_IREQS` | Boolean | `not set` | `NO` | One infer request for each part, also for repeating blocks. |
| `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. |
Set properties with `GGML_OPENVINO_NPU_CONFIG`:
```bash
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
```
List the properties of the installed NPU plugin:
```cpp
// List the properties of the installed NPU plugin with their current values
ov::Core core;
@@ -199,6 +202,35 @@ for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
### Example: gemma-4 E2B with the model cache
`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. Run step 1 once, then start the model as in step 2 every later time.
#### Step 1: first run, compile and save the model
```bash
# This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
# (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
# Use the model as usual, then exit with /exit.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy
export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
```
#### Step 2: later runs, load the model from the cache
```bash
# Use the same exports as in step 1 (repeat them in a new shell) and the same command.
# The backend loads the compiled model instead of compiling it, so the model starts much faster
# (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
# or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
```
## GPU and CPU plugin properties
The backend sets no GPU or CPU property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
@@ -20,8 +20,12 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() {
std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor) {
// A Q6_K embedding table is stored as q8_0_c by default on the NPU. The int4 layouts only pay off for a tied
// embedding, where the table is also the lm_head weight and GET_ROWS gathers the packed rows
// before dequantizing them (see gather_compressed_rows).
if (tensor->type != GGML_TYPE_Q6_K) {
// before dequantizing them (see gather_compressed_rows). Other K-quant tables default to the channel-wise
// int8 of ggml_openvino_get_requant_type() and follow this setting only when it is set explicitly
// (Gemma 4 E2B: a tied Q4_K table is 384 MiB as int8, 198 MiB as q4_0_128).
if (tensor->type != GGML_TYPE_Q6_K &&
!((tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K) &&
ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT") != nullptr)) {
return std::nullopt;
}
const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "q8_0_c");
+133 -81
View File
@@ -12,7 +12,6 @@
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
@@ -313,6 +312,17 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
return "embd";
}
const auto & model_params = decoder->get_model_params();
if (tensor == model_params.prune_ids) {
return "inp_prune_ids";
}
if (tensor == model_params.prune_keep) {
return "inp_prune_keep";
}
if (auto it = model_params.pruned_masks.find(tensor); it != model_params.pruned_masks.end()) {
// not a graph input: get_kq_mask_input() gathers the rows from the input mask of this name
return get_tensor_graph_input_ov_name(decoder, cgraph, it->second, op) + "_pruned";
}
// gemma-4's KV-shared layers read the mask rows of their output tokens through GET_ROWS, which is not a mask
// consumer, so match the masks by identity too
if (GgmlOvDecoder::is_inp_mask(tensor, op) || decoder->is_kq_mask(tensor)) {
@@ -796,8 +806,14 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
} else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
op_case = 2;
break;
} else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
} else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW &&
node->src[1]->view_src == node->view_src &&
(is_conv_states_all_tensor(node->view_src) ||
(node->view_src->op == GGML_OP_NONE && ggml_is_contiguous(node->src[1]) &&
!is_recurrent_cache(node->view_src) &&
strncmp(node->view_src->name, "cache_", strlen("cache_")) != 0))) {
// View writeback into a contiguous block of a plain (non-KV, non-recurrent) tensor at
// a static offset, e.g. the mamba-style conv state copy into its cache row.
op_case = 4;
break;
} else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
@@ -1075,7 +1091,32 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
layer_mask.emplace(layer.value(), mask);
max_extent = std::max(max_extent, leaf->ne[1]);
if (mask->op == GGML_OP_NONE) {
model_params.kq_masks.insert(mask);
const ggml_tensor * layer_input_mask = layer_mask[layer.value()];
if (layer_input_mask != mask && layer_input_mask->op == GGML_OP_NONE) {
// a second input mask on the cache of a layer: the mask rows of gemma-4's KV-shared layers
model_params.pruned_masks.emplace(mask, layer_input_mask);
} else {
model_params.kq_masks.insert(mask);
}
}
}
if (!model_params.pruned_masks.empty()) {
// The first output row index list gathers the rows of the KV-shared layers, a later one the output rows
// among them
for (int i = 0; i < cgraph->n_nodes; i++) {
const ggml_tensor * node = cgraph->nodes[i];
if (node->op != GGML_OP_GET_ROWS || !is_output_idx(node->src[1], node)) {
continue;
}
if (model_params.prune_ids == nullptr) {
model_params.prune_ids = node->src[1];
} else if (node->src[1] != model_params.prune_ids) {
model_params.prune_keep = node->src[1];
}
}
if (model_params.prune_ids == nullptr) {
throw std::runtime_error("OpenVINO: masks of KV-shared layers without their row index list");
}
}
@@ -1210,7 +1251,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.seq_active_start = offset / seq_size;
// a mask that is itself a graph input has the shape of its OV parameter
const std::string mask_name = mask->op != GGML_OP_NONE ? std::string() :
const std::string mask_name = mask->op != GGML_OP_NONE || model_params.pruned_masks.count(mask) ?
std::string() :
mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" :
get_tensor_ov_name(cgraph, mask);
// gemma-4's KV-shared layers come last and take their mask rows from the input masks with GET_ROWS: keep
@@ -1229,7 +1271,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
}
}
if (is_static) {
const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
const bool slice_prefill =
ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
if (!slice_prefill) {
compute_params.attention_size = model_params.ctx_per_seq;
}
@@ -1261,10 +1304,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
}
// When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
// mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
// share a single precomputed rope_sin/rope_cos. Track divergence so the
// translator falls back to per-op make_sin_cos in that case.
// Multiple ROPE ops can disagree on op_params (e.g. gemma4's mixed SWA/non-SWA layers with different
// n_dims or freq_base). Track divergence for the graph key and for decoder reuse.
static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
if (!rope_seen) {
memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
@@ -1402,13 +1443,13 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
if (is_static && compute_params.output_len == 0) {
compute_params.output_len = 1;
}
// A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled
// prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch.
// Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two.
// A sliced static prefill attends base*2^k KV rows (base from GGML_OPENVINO_KV_SLICE): every attended size needs
// its own compiled prefill model, so a growing sequence compiles one when the attended length doubles, not for
// each ubatch. Rounding up adds masked rows, which cost prefill time, so it stops at the next window.
if (is_static && ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1 &&
!model_params.is_cacheless_attn && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
compute_params.attention_size =
ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
compute_params.attention_size = ggml_openvino_static_kv_window(
compute_params.attention_size, model_params.ctx_per_seq, ggml_openvino_kv_slice_base());
}
// The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
// 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step.
@@ -1478,8 +1519,8 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
// Both masks are named "attn_inp_kq_mask", so tell them apart by tensor identity.
const bool swa_mask = is_swa_mask(input);
int attention_size = swa_mask ? m_model_params.ctx_per_seq_swa * m_model_params.n_seq : m_model_params.ctx;
const bool kv_window =
m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0;
const bool kv_window = m_is_prefill ? ggml_openvino_kv_slice_enabled() :
ggml_openvino_npu_decode_bucket() > 0;
if (kv_window) {
attention_size = swa_mask ? m_compute_params.attention_size_swa : m_compute_params.attention_size;
}
@@ -1613,8 +1654,44 @@ bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
return false;
}
bool GgmlOvDecoder::is_host_gather_rows(const ggml_tensor * node) {
if (!ggml_openvino_npu_host_gather_enabled() || node == nullptr || node->op != GGML_OP_GET_ROWS) {
return false;
}
const ggml_tensor * table = node->src[0];
const ggml_tensor * ids = node->src[1];
// The table must hold raw ggml rows in host memory. OpenVINO buffers store weights in the extracted layout, except
// with the NPU weightless cache, where they keep (or, with SELF_CONTAINED_MMAP, wrap) the raw GGUF bytes.
constexpr size_t min_table_bytes = 64ull * 1024 * 1024;
if (table == nullptr || ids == nullptr || table->view_src != nullptr || table->buffer == nullptr) {
return false;
}
const bool raw_cache = ggml_openvino_npu_weightless_cache_enabled();
const bool raw_rows = ggml_backend_buffer_is_openvino(table->buffer) ? raw_cache :
ggml_backend_buffer_is_host(table->buffer);
return table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && raw_rows &&
ggml_get_type_traits(table->type)->to_float != nullptr &&
ggml_nbytes(table) >= min_table_bytes && ids->type == GGML_TYPE_I32 && ids->op == GGML_OP_NONE &&
ggml_nelements(ids) == ids->ne[0] && node->ne[1] == ids->ne[0];
}
void GgmlOvDecoder::add_extra_inputs() {
m_model_extra_inputs.clear();
m_host_gather_rows.clear();
if (m_is_static) {
for (const auto & info : m_node_info_list) {
if (is_host_gather_rows(info.node)) {
const std::string name = std::string(host_rows_prefix) + info.node_name;
m_host_gather_rows[name] = info.node;
m_model_extra_inputs[name] = {ov::element::f32,
ov::Shape{1, 1, (size_t) get_static_n_tokens(), (size_t) info.node->ne[0]},
0,
true,
{},
-1};
}
}
}
// Extra inputs:
// 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
@@ -1679,7 +1756,6 @@ void GgmlOvDecoder::add_extra_inputs() {
m_model_extra_inputs["ggml_hfa_mask"] = {
ov::element::f16, ov::Shape{1, 1, chunk_size, past_capacity + chunk_size}, 0, true, {}, -1};
}
// create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);
// n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the
// model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for
@@ -1885,6 +1961,9 @@ void GgmlOvDecoder::compute_model_inputs() {
if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
continue;
}
if (is_pruned_mask(src)) {
continue;
}
m_inputs[src_name] = src;
@@ -2087,22 +2166,6 @@ bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
return true;
}
const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
for (int i = 0; i < m_cgraph->n_nodes; i++) {
const auto * node = m_cgraph->nodes[i];
for (int j = 0; j < GGML_MAX_SRC; j++) {
const auto * src = node->src[j];
if (src == nullptr) {
break;
}
if (get_tensor_ov_name(m_cgraph, src) == name) {
return src;
}
}
}
return nullptr;
}
std::string GgmlOvDecoder::get_hfa_history_input_name() const {
for (const auto & [name, tensor] : m_inputs) {
const auto * op = get_tensor_used_op(tensor);
@@ -2143,6 +2206,10 @@ std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_no
continue;
}
// A table whose rows are gathered on the host needs no OV weight for that use.
if (i == 0 && is_host_gather_rows(node)) {
continue;
}
// A view over a weight is served by the base tensor's Constant.
ggml_tensor * base = src->view_src ? src->view_src : src;
std::string src_name = get_tensor_ov_name(cgraph, base);
@@ -2242,9 +2309,9 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
// pointer to avoid re-extracting on every recompile. Opt-in via
// GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
// for `naive` (test/naive path) since use_bias changes the produced node.
// Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
// Cached decode-window models are built after the pair; reusing the node keeps e.g. the
// token_embd vocab on the pair's NPUW bank uid instead of embedding and importing a second copy.
const bool keep_for_windows = ggml_openvino_npu_raw_weight_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
const bool keep_for_windows = ggml_openvino_npu_weightless_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
const bool cacheable_nonov = (ggml_openvino_reduce_compile_mem_enabled() || keep_for_windows) && !is_ov_buffer &&
!naive && tensor->data != nullptr;
if (cacheable_nonov) {
@@ -2273,10 +2340,10 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
if (ggml_is_quantized(tensor->type)) {
auto use_bias = naive;
if (is_ov_buffer) {
const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
const bool preserve_raw = ggml_openvino_npu_weightless_cache_enabled();
if (preserve_raw) {
// A later context must fingerprint the same raw GGUF bytes before importing its
// self-contained blob, so keep the model buffer immutable in this mode.
// cached blob, so keep the model buffer immutable in this mode.
ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
} else {
// The regular path stores extracted weights in the model buffer. Copy raw data
@@ -2689,7 +2756,10 @@ std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
// the written state block plus the full updated cache (see translate_cpy op_case 13)
return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)};
}
if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
// Naive (op test) graphs have no runtime slot inputs for the native state writeback, so they keep the packed
// [attention | state] output, which the consumers slice through the generic view path.
if (!m_naive && node->op == GGML_OP_GATED_DELTA_NET &&
(!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
std::string attn_name;
std::string state_name;
for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
@@ -2824,43 +2894,29 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
if (src == nullptr) {
continue;
}
struct ggml_tensor * root_src = nullptr;
// if (src->org_src) {
// root_src = src->org_src;
// }
if (root_src) {
if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_get_rows_input_idx(root_src, node)) {
m_node_dynamic_dims[root_src] = 0;
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
continue;
}
self(self, root_src);
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
} else {
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
m_node_dynamic_dims[src] = 0;
continue;
}
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
if (!m_is_static && is_activation_input(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
// a view of a model weight (BERT's token type row) has no token dim
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
m_node_dynamic_dims[src] = 1;
continue;
}
if (is_inp_embd_2d(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
self(self, src);
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
m_node_dynamic_dims[src] = 0;
continue;
}
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
if (!m_is_static && is_activation_input(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
// a view of a model weight (BERT's token type row) has no token dim
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
m_node_dynamic_dims[src] = 1;
continue;
}
if (is_inp_embd_2d(src, node)) {
m_node_dynamic_dims[src] = 1;
continue;
}
self(self, src);
}
switch (node->op) {
case GGML_OP_NONE:
@@ -2885,9 +2941,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
}
}
}
// OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
// "Dynamic dim value mismatch for node: " + std::string(node->name) +
// " and its src[1]: " + std::string(node->src[1]->name));
}
break;
case GGML_OP_MUL:
@@ -2904,7 +2957,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = -1;
if (m_node_dynamic_dims[node->src[0]] != -1) {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
// auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
// src dim i moves to dim op_params[i]
if (dynamic_dim_idx >= 0 && dynamic_dim_idx < GGML_MAX_DIMS) {
m_node_dynamic_dims[node] = node->op_params[dynamic_dim_idx];
@@ -3229,8 +3281,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
visit_node(visit_node, node);
}
// print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
if (0) {
// GGML_OPENVINO_DEBUG_DYNAMIC_DIMS: print each node and its sources with their shapes, '*' marking the dynamic dim
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_DYNAMIC_DIMS")) {
for (int i = 0; i < m_cgraph->n_nodes; i++) {
ggml_tensor * node = m_cgraph->nodes[i];
int dynamic_dim = m_node_dynamic_dims[node];
+39 -42
View File
@@ -47,6 +47,15 @@ struct ModelParams {
// The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through
// GET_ROWS, which must resolve to the same OV parameter as the attention ops
std::set<const ggml_tensor *> kq_masks;
// gemma-4's KV-shared layers attend for the output rows only (prune_shared in src/models/gemma4.cpp): llama.cpp
// copies their mask rows from the input masks on the host into separate inputs (out_mask, out_mask_swa), and
// gathers their activations, positions and per-layer embeddings with an index list (inp_prune_ids). The static
// models bind the input masks per prefill chunk, so these masks are not graph inputs: each maps to the input
// mask it copies, and the OV model gathers its rows from that mask with inp_prune_ids instead.
std::map<const ggml_tensor *, const ggml_tensor *> pruned_masks;
const ggml_tensor * prune_ids = nullptr;
// the output rows among the gathered rows (inp_prune_keep)
const ggml_tensor * prune_keep = nullptr;
std::vector<std::string> kv_names;
size_t kv_buffer_ctx_id = 0;
@@ -86,7 +95,6 @@ struct ComputeParams {
int swa_window = -1;
int input_len = -1;
int token_len_per_seq = -1;
int past_kv_len = -1;
int output_len = 1;
int cache_rs_reset_idx = -1;
@@ -288,16 +296,38 @@ public:
virtual std::set<std::string> get_model_output_names() const override { return m_model_output_names; }
virtual std::set<std::string> get_cache_output_names() const override {
std::set<std::string> names;
for (const auto & name : m_model_output_names) {
const ggml_tensor * tensor = m_model_outputs.at(name);
if (is_kvcache(tensor, nullptr) || is_recurrent_cache(tensor)) {
names.insert(name);
}
}
return names;
}
virtual bool is_kv_only_outputs() const override { return m_kv_only_outputs; }
// Convert the model with only the cache writes as outputs (GGML_OPENVINO_KV_ONLY_PREFILL); the conversion pipeline
// then drops everything that only feeds the other outputs, see pass::KeepCacheResults.
void set_kv_only_outputs(bool kv_only) { m_kv_only_outputs = kv_only; }
// GET_ROWS of a large host-resident weight table by graph-input ids (GGML_OPENVINO_NPU_HOST_GATHER): its rows
// are gathered on the host and fed through the "ggml_host_rows_<node>" input instead of an OV Gather.
static bool is_host_gather_rows(const ggml_tensor * node);
static constexpr const char * host_rows_prefix = "ggml_host_rows_";
const ggml_tensor * get_host_gather_rows(const std::string & input_name) const {
auto it = m_host_gather_rows.find(input_name);
return it == m_host_gather_rows.end() ? nullptr : it->second;
}
const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }
virtual int get_ctx_size() const { return m_model_params.ctx; }
virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }
virtual int get_ctx_per_seq_swa() const { return m_model_params.ctx_per_seq_swa; }
virtual int get_n_seq() const { return m_model_params.n_seq; }
virtual int is_swa_layer(int layer) const override {
return std::find(m_model_params.swa_layers.begin(), m_model_params.swa_layers.end(), layer) !=
m_model_params.swa_layers.end();
@@ -318,14 +348,10 @@ public:
return m_model_params.n_heads_kv;
}
int get_past_kv_len() const { return m_compute_params.past_kv_len; }
int get_input_len() const { return m_compute_params.input_len; }
virtual int32_t * get_rope_params() const override { return const_cast<int32_t *>(m_model_params.rope_params); }
virtual bool has_mixed_rope_params() const override { return m_model_params.mixed_rope_params; }
virtual int get_ssm_state_size() const override { return m_model_params.state_size; }
virtual std::map<std::string, std::string> get_kv_param_res_names() const override;
@@ -417,8 +443,6 @@ public:
return v;
}
const ggml_tensor * get_tensor_from_name(const std::string & name) const;
std::string get_hfa_history_input_name() const;
void clear_model_weights() { m_model_weights.clear(); }
@@ -608,10 +632,6 @@ public:
bool is_direct_gdn_view(const ggml_tensor * node) const;
static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) {
return is_recurrent_cache(tensor) || is_kvcache(tensor, op);
}
static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) {
if (tensor == nullptr || is_recurrent_cache(tensor)) {
return false;
@@ -697,6 +717,8 @@ public:
bool is_kq_mask(const ggml_tensor * tensor) const { return m_model_params.kq_masks.count(tensor) != 0; }
bool is_pruned_mask(const ggml_tensor * tensor) const { return m_model_params.pruned_masks.count(tensor) != 0; }
// A graph-input index list of GET_ROWS: out_ids, or the inp->s_copy leaf when build_rs gathers
// every recurrent state at once.
static bool is_get_rows_input_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
@@ -722,33 +744,6 @@ public:
op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
}
std::string get_graph_input_ov_name(const ggml_tensor * tensor, const ggml_tensor * op) const {
if (is_inp_pos(tensor, op)) {
return "inp_pos";
}
if (is_inp_emb(tensor, op)) {
return "embd";
}
if (is_inp_mask(tensor, op)) {
// Give the two attention masks distinct OV parameter names.
//
// An interleaved-SWA model builds one full-attention mask and one sliding-window mask,
// but build_attn_inp_kq_mask() names them identically, so keying a parameter off
// tensor->name alone makes the second mask OVERWRITE the first in m_model_inputs: both
// attention types then read a single parameter, and the windowed layers silently run
// against an unbanded mask. Disambiguate using the SWA layer set computed in
// compute_llm_params(), which classifies by mask tensor identity rather than by name.
//
// When no SWA layer was found there is only one mask in play, so the plain name is
// correct and no _swa parameter is created.
if (m_model_params.swa_layers.empty()) {
return "self_kq_mask";
}
return is_swa_mask(tensor) ? "self_kq_mask_swa" : "self_kq_mask";
}
return tensor->name;
}
private:
void set_input_output();
int compute_op_case(const ggml_tensor * node) const;
@@ -776,6 +771,8 @@ private:
std::set<std::string> m_model_output_names;
// The output set the compiled model was built from, for has_same_graph_io().
std::set<std::string> m_built_output_names;
bool m_kv_only_outputs = false;
std::map<std::string, const ggml_tensor *> m_host_gather_rows;
std::vector<NodeInfo> m_node_info_list;
std::map<ggml_tensor *, int> m_node_dynamic_dims;
std::set<const ggml_tensor *> m_kvcache_4d;
+43 -46
View File
@@ -162,6 +162,7 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_DUMP_IR", env_type::BOOL},
{"GGML_OPENVINO_DEBUG_INPUT", env_type::BOOL},
{"GGML_OPENVINO_DEBUG_OUTPUT", env_type::BOOL},
{"GGML_OPENVINO_DEBUG_DYNAMIC_DIMS", env_type::BOOL},
// Force the static (NPU-shape) compute path on any device, e.g. GGML_OPENVINO_DEVICE=CPU,
// to test the static-shape translation without NPUW/real NPU hardware in the loop.
{"GGML_OPENVINO_FORCE_STATIC", env_type::BOOL},
@@ -191,14 +192,12 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_GDN_NATIVE_STATE", env_type::BOOL},
{"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL},
{"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL},
{"GGML_OPENVINO_KV_SLICE", env_type::BOOL},
{"GGML_OPENVINO_KV_SLICE", env_type::INT},
{"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL},
{"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL},
{"GGML_OPENVINO_NPU_PARALLEL_COMPILE", env_type::BOOL},
{"GGML_OPENVINO_SELF_CONTAINED_BLOB", env_type::BOOL},
{"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL},
{"GGML_OPENVINO_NPU_SHARED_BANK", env_type::BOOL},
{"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", env_type::BOOL},
{"GGML_OPENVINO_KV_ONLY_PREFILL", env_type::BOOL},
{"GGML_OPENVINO_NPU_HOST_GATHER", env_type::BOOL},
// Build the precise (but O(n_nodes)) graph cache key. Needed by op tests.
{"GGML_OPENVINO_FULL_GRAPH_KEY", env_type::BOOL},
};
@@ -260,6 +259,12 @@ std::string checked_env_value(const env_var & var, const char * value) {
if (!parse_env_int(value, number)) {
GGML_ABORT("ggml-openvino: %s=%s is not valid, use a whole number", var.name, value);
}
if (std::strcmp(var.name, "GGML_OPENVINO_KV_SLICE") == 0 && number != 0 && number != 1 &&
(number < 0 || number % 256 != 0)) {
GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a KV window size that is a multiple "
"of 256",
var.name, value);
}
return std::to_string(number);
case env_type::FLOAT: {
char * end = nullptr;
@@ -548,10 +553,7 @@ std::string ggml_openvino_config_overrides_in_use() {
bool ggml_openvino_manual_gqa_enabled() {
// set: a positive value enables it, 0 disables it; unset: on GPU only
if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
}
return ggml_openvino_is_gpu();
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN", ggml_openvino_is_gpu() ? 1 : 0) > 0;
}
bool ggml_openvino_gdn_prescale_enabled() {
@@ -580,10 +582,7 @@ bool ggml_openvino_npu_is_4000() {
}
bool ggml_openvino_gdn_decompose_enabled() {
if (ggml_openvino_getenv_str("GGML_OPENVINO_GDN_DECOMPOSE") != nullptr) {
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE") > 0;
}
return ggml_openvino_npu_is_4000();
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0;
}
int ggml_openvino_gdn_decompose_chunk() {
@@ -607,19 +606,14 @@ float ggml_openvino_gdn_q_scale() {
}
bool ggml_openvino_reduce_compile_mem_enabled() {
const char * reduce_compile_mem = ggml_openvino_getenv_str("GGML_OPENVINO_REDUCE_COMPILE_MEM");
if (reduce_compile_mem != nullptr) {
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM") != 0;
}
return ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM",
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
}
bool ggml_openvino_release_weights_enabled() {
const char * release_weights = ggml_openvino_getenv_str("GGML_OPENVINO_RELEASE_WEIGHTS");
if (release_weights != nullptr) {
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS") != 0;
}
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
return ggml_openvino_is_gpu() &&
ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS",
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
}
// Check if running on NPU
@@ -635,8 +629,13 @@ bool ggml_openvino_is_gpu() {
return has_prefix(ggml_openvino_get_device_name(), "GPU");
}
int ggml_openvino_kv_slice_base() {
const int value = ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1);
return value <= 0 ? 0 : value == 1 ? 1024 : value;
}
bool ggml_openvino_kv_slice_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1) != 0;
return ggml_openvino_kv_slice_base() > 0;
}
bool ggml_openvino_npu_fast_mask_enabled() {
@@ -655,26 +654,15 @@ bool ggml_openvino_npu_decode_unfold_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_DECODE_UNFOLD") != 0;
}
bool ggml_openvino_npu_parallel_compile_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_PARALLEL_COMPILE") != 0;
}
int ggml_openvino_npu_decode_bucket() {
if (!ggml_openvino_is_npu()) {
return 0;
}
// A self-contained blob embeds its weights bank, and NPUW cannot load a blob into a bank that already holds
// weights, so a decode model per KV window cannot be imported next to the decode model of the pair.
if (ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") &&
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 &&
!ggml_openvino_npu_weightless_bank_enabled()) {
return 0;
}
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? 1024 : 0;
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? ggml_openvino_kv_slice_base() : 0;
}
int ggml_openvino_static_kv_window(int rows, int ctx) {
int window = 1;
int ggml_openvino_static_kv_window(int rows, int ctx, int base) {
int window = std::max(base, 1);
while (window < rows && window < ctx) {
window *= 2;
}
@@ -683,7 +671,7 @@ int ggml_openvino_static_kv_window(int rows, int ctx) {
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens) {
if (n_tokens > 16) {
return ggml_openvino_static_kv_window(rows, ctx);
return ggml_openvino_static_kv_window(rows, ctx, 1);
}
// a multiple of 256 and of 2^k / 4, where 2^k <= rows < 2^(k+1)
int step = 256;
@@ -702,13 +690,22 @@ bool ggml_openvino_npu_kv_head_major_enabled() {
ggml_openvino_kv_slice_enabled();
}
bool ggml_openvino_npu_raw_weight_cache_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 ||
ggml_openvino_npu_weightless_bank_enabled();
bool ggml_openvino_npu_host_gather_enabled() {
return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0;
}
bool ggml_openvino_npu_weightless_bank_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_WEIGHTLESS_BANK") != 0;
bool ggml_openvino_kv_only_prefill_enabled() {
// On by default; it only takes effect for graphs with KV-shared layers.
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_ONLY_PREFILL", 1) != 0;
}
bool ggml_openvino_npu_weightless_cache_enabled() {
return ggml_openvino_is_npu() && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") != nullptr;
}
bool ggml_openvino_self_contained_mmap_enabled() {
return ggml_openvino_npu_weightless_cache_enabled() &&
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0;
}
namespace {
@@ -768,8 +765,8 @@ bool kv_grow_locked(kv_storage_entry & e, size_t rows, size_t heads) {
if (rows <= e.cap_rows) {
return false;
}
const int bucket = ggml_openvino_npu_decode_bucket();
size_t cap = bucket > 0 ? static_cast<size_t>(bucket) : 1024;
const int base = ggml_openvino_kv_slice_base();
size_t cap = base > 0 ? static_cast<size_t>(base) : 1024;
while (cap < rows) {
cap *= 2;
}
+33 -18
View File
@@ -6,7 +6,6 @@
#define CL_TARGET_OPENCL_VERSION 300
#include <CL/cl.h>
#include <cstdlib>
#include <map>
#include <memory>
#include <openvino/core/node.hpp>
@@ -140,10 +139,14 @@ bool ggml_openvino_is_static();
// KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context.
// One mechanism, two modes:
// dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled.
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at the aligned
// attended length and recompiled when it changes; decode keeps the full context.
// On by default for all devices; GGML_OPENVINO_KV_SLICE=0 turns it off.
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at a KV window of
// base*2^k rows (clamped to ctx) covering the attended length and recompiled when it changes; decode keeps the
// full context unless NPU decode KV windows are on (see ggml_openvino_npu_decode_bucket).
// GGML_OPENVINO_KV_SLICE: unset or 1 = on with window base 1024, N (a multiple of 256) = on with window base N,
// 0 = off. CPU/GPU dynamic graphs only use it as on/off.
bool ggml_openvino_kv_slice_enabled();
// Static KV window base of GGML_OPENVINO_KV_SLICE, 0 = off.
int ggml_openvino_kv_slice_base();
// On by default: back NPU buffers with Level Zero host memory; GGML_OPENVINO_NPU_L0_HOST_TENSORS=0 turns it off.
bool ggml_openvino_npu_l0_host_tensors_enabled();
@@ -155,17 +158,28 @@ bool ggml_openvino_npu_fast_mask_enabled();
// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
bool ggml_openvino_npu_hfa_prefill_enabled();
bool ggml_openvino_npu_decode_unfold_enabled();
bool ggml_openvino_npu_parallel_compile_enabled();
// Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model
// and compute the logits with one decode step. Pays off for models whose tail layers share earlier layers' KV
// (Gemma 3n/4 E-series), where it skips those layers for prompt tokens. On by default (it only applies to graphs
// with KV-shared attention, at most one output token per batch, and no HFA prefill);
// GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off.
bool ggml_openvino_kv_only_prefill_enabled();
// Gather the rows of large embedding tables on the host and feed them to the static graph as an input, instead of
// binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large
// costs about as much as streaming the table).
bool ggml_openvino_npu_host_gather_enabled();
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1): static NPU graphs attend a KV window of 1024*2^k rows (clamped to ctx)
// instead of the whole ctx, with one decode model per window, all built/imported with the prefill/decode pair;
// with head-major KV the prefill models of every window are also exported and preloaded.
// Returns the window base (1024), 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0).
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV
// window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one
// decode model per window, all built/imported with the prefill/decode pair.
// The prefill windows are aligned to the decode windows, and with the weightless bank the prefill models of every
// window are exported too (and preloaded with head-major KV).
// Returns the window base, 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0 or GGML_OPENVINO_KV_SLICE=0: decode attends
// the full ctx).
int ggml_openvino_npu_decode_bucket();
// Rows a static prefill attends with GGML_OPENVINO_KV_SLICE: the attended length rounded up to a power of two,
// clamped to ctx.
int ggml_openvino_static_kv_window(int rows, int ctx);
// Smallest base*2^k covering rows, clamped to ctx.
int ggml_openvino_static_kv_window(int rows, int ctx, int base);
// Rows the dynamic GPU graph attends for a batch of n_tokens tokens per sequence, clamped to ctx. The GPU plugin keeps
// memory for each attended length, so a long context should use a few lengths:
@@ -176,18 +190,19 @@ int ggml_openvino_static_kv_window(int rows, int ctx);
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens);
// On-demand NPU KV cache (GGML_OPENVINO_NPU_KV_ON_DEMAND): the ggml KV buffer stays non-resident and the
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = decode bucket or 1024) with the rows in use.
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = KV_SLICE window base or 1024) with the rows in use.
bool ggml_openvino_npu_kv_on_demand_enabled();
// On-demand KV with BLOB_PREBUILD and KV_SLICE: K storage is [heads][rows][head_size] and V storage is
// [heads][head_size][rows] (head-major with heads * head_size channels); every static graph binds the whole storage
// as [1, heads, rows, head_size] / [1, heads, head_size, rows], and attention uses V^T.
bool ggml_openvino_npu_kv_head_major_enabled();
// NPU blob cache modes that keep the raw GGUF weights and skip requantization on a warm hit:
// GGML_OPENVINO_SELF_CONTAINED_BLOB (weights embedded in each blob) or
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK (weightless blobs plus one shared weights file).
bool ggml_openvino_npu_raw_weight_cache_enabled();
bool ggml_openvino_npu_weightless_bank_enabled();
// NPU with GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR: graphs with a KV cache are cached as weightless blobs plus one
// shared weights file. Valid blobs are imported; otherwise the models are compiled and exported. The raw GGUF
// weights are kept, and requantization is skipped on a warm hit.
bool ggml_openvino_npu_weightless_cache_enabled();
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 with the NPU weightless cache
bool ggml_openvino_self_contained_mmap_enabled();
void ggml_openvino_kv_storage_register(void * data, size_t row_bytes, size_t rows);
void ggml_openvino_kv_storage_unregister(const void * base, size_t size);
// Storage address backing ggml address `ptr` with at least `bytes` valid (grown if needed);
+18 -47
View File
@@ -31,9 +31,6 @@
#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
#include <openvino/runtime/properties.hpp>
#include <openvino/runtime/tensor.hpp>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>
@@ -98,8 +95,6 @@ struct ggml_backend_openvino_buffer_context {
std::map<const void *, uint64_t> weight_fingerprints;
std::vector<ggml_openvino_source_mapping> source_mappings;
// Used for re-allocation on device for kvcache
void * data_prev = nullptr;
// data is in the weight buffer registry
bool weight_registered = false;
@@ -149,10 +144,7 @@ struct ggml_backend_openvino_buffer_context {
// commits/zeroes it eagerly (fully resident). For such large buffers, reserve
// demand-zero pages instead (no L0, no memset) so they stay non-resident. KV and small
// I/O buffers keep the L0 host tensor for zero-copy import (decode throughput).
const bool strict_mmap = device_name == "NPU" &&
ggml_openvino_npu_raw_weight_cache_enabled() &&
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
const bool strict_mmap = device_name == "NPU" && ggml_openvino_self_contained_mmap_enabled();
// 2 GiB keeps a large-context KV cache (~1 GiB at ctx 8K) on L0 while the bigger prefill
// compute buffer still goes lazy.
const size_t lazy_host_threshold =
@@ -391,12 +383,6 @@ static bool is_stateful_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") != 0;
}
static bool is_self_contained_mmap_enabled() {
return ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
}
// Stores extra as the tensor's extra, deleting the one it replaces
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
ggml_tensor * tensor,
@@ -431,7 +417,6 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
}
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
@@ -505,7 +490,6 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf
uint8_t value,
size_t offset,
size_t size) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -617,7 +601,6 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
const void * data,
size_t offset,
size_t size) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -642,10 +625,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
bool is_supported_weight_shape = is_2d || (tensor->ne[3] == 1 && ggml_is_quantized(tensor->type));
if (is_weight_buffer && is_full_tensor_set && is_supported_weight_shape) {
if (ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR")) {
if (ggml_openvino_npu_weightless_cache_enabled()) {
// Keep raw bytes for cache fingerprint validation and compile fallback; the imported
// self-contained blob supplies the runtime weights, so eager requant is unnecessary.
// blob supplies the runtime weights, so eager requant is unnecessary.
memcpy(tensor->data, data, size);
return;
}
@@ -653,32 +635,15 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
auto result = process_weight_tensor(tensor, data, tensor->data);
result.weight_node->set_friendly_name(tensor->name);
// const auto & layout = result.layout;
ggml_openvino_extra_base * extra;
// Quantized path with extracted weight/scale/zp tensors
if (result.is_quantized()) {
extra = new ggml_openvino_quantized_weight_extra(std::move(result.weights), std::move(result.scales),
std::move(result.zp), result.weight_node);
// if (layout.is_requant) {
// GGML_LOG_DEBUG("%s: requantized %s to %s (u%d, block_size=%ld)\n", __func__, tensor->name,
// extra_quant_type_name(layout.requant_type.value()), layout.is_u4 ? 4 : 8,
// layout.weights_per_block);
// } else {
// int64_t n_blocks = ggml_nelements(tensor) / layout.weights_per_block;
// GGML_LOG_DEBUG("%s: extracted quantized weight node for %s (u%d, %zu weights, %ld blocks)\n",
// __func__, tensor->name, layout.is_u4 ? 4 : 8, layout.weights_size, n_blocks);
// }
} else {
// F16/F32/BF16 weight or F16-requant
extra = new ggml_openvino_weight_extra(std::move(result.weights), result.weight_node);
// if (layout.total_size > 0) {
// GGML_LOG_DEBUG("%s: requantized %s to F16\n", __func__, tensor->name);
// } else {
// GGML_LOG_DEBUG("%s: created shared-memory weight node for %s\n", __func__, tensor->name);
// }
}
ggml_openvino_set_extra(ctx, tensor, extra);
@@ -804,7 +769,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
void * data,
size_t offset,
size_t size) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -843,7 +807,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
const ggml_tensor * src,
ggml_tensor * dst) {
// GGML_LOG_DEBUG("%s: src tensor name=%s, dst tensor name=%s\n", __func__, src->name, dst->name);
GGML_ASSERT(src != nullptr && dst != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -978,7 +941,7 @@ static size_t ggml_backend_openvino_buffer_type_get_alloc_size(ggml_backend_buff
const ggml_tensor * tensor) {
GGML_UNUSED(buft);
if (is_self_contained_mmap_enabled()) {
if (ggml_openvino_self_contained_mmap_enabled()) {
return ggml_nbytes(tensor);
}
@@ -1178,7 +1141,6 @@ static void ggml_backend_openvino_free(ggml_backend_t backend) {
// reuses it instead of recompiling against zeroed weights.
if (!ggml_openvino_weight_buffers_released()) {
cache->graphs.clear();
ov_clear_imported_blobs();
std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
g_fallback_fingerprints.clear();
}
@@ -1455,7 +1417,7 @@ static void ggml_backend_openvino_device_get_props(ggml_backend_dev_t dev, ggml_
props->caps = {
/* .async = */ false,
/* .host_buffer = */ false,
/* .buffer_from_host_ptr = */ is_self_contained_mmap_enabled(),
/* .buffer_from_host_ptr = */ ggml_openvino_self_contained_mmap_enabled(),
/* .events = */ false,
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
@@ -1685,6 +1647,13 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) {
GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op);
}
// SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a
// state tensor) are supported only for the recognized cache writes.
static bool set_rows_output_view_is_supported(const ggml_tensor * op) {
return op->view_src == nullptr || ggml_nbytes(op) == 0 || ggml_is_contiguous(op) ||
GgmlOvDecoder::is_column_set_rows(op) || GgmlOvDecoder::is_conv_state_snapshot_writeback(op);
}
static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) {
const ggml_tensor * as = op->src[0];
const ggml_tensor * ids = op->src[2];
@@ -1795,6 +1764,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) {
return {false, "SET_ROWS with BF16 src0 is not supported"};
}
if (op->op == GGML_OP_SET_ROWS && !set_rows_output_view_is_supported(op)) {
return {false, "SET_ROWS with non-contiguous output view is not supported"};
}
if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K ||
op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) {
// These are all f16-arithmetic dequant rounding errors that intermittently exceed the
@@ -2046,6 +2018,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, "MUL_MAT_ID with single-expert or empty ne[2] <= 1 (ne[2]=" +
std::to_string(op->src[0]->ne[2]) + ") is not supported"};
}
if (op->src[1] != nullptr && op->src[1]->type == GGML_TYPE_BF16) {
return {false, "MUL_MAT_ID with a BF16 src1 is not supported"};
}
// The GPU plugin's GatherMatmul returns wrong values for the layouts test-backend-ops
// produces: it builds a rank-4 input layout ([n_used, n_tokens, k, 1]) instead of rank 3
// and the kernel misreads it, silently returning garbage (NMSE ~86) rather than asserting.
@@ -2332,10 +2307,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
if (!supported) {
return {false, "op " + std::string(ggml_op_name(op->op)) + " has no op translator"};
}
static std::set<ggml_op> ops_not_support_view_input{};
if (ops_not_support_view_input.find(op->op) != ops_not_support_view_input.end() && has_view_op_input(op)) {
return {false, "op " + std::string(ggml_op_name(op->op)) + " with VIEW input is not supported"};
}
}
}
-23
View File
@@ -8,29 +8,6 @@
static constexpr size_t GGML_QUANTIZATION_GROUP_SIZE = 32;
inline const char * extra_quant_type_name(ExtraQuantType t) {
switch (t) {
case ExtraQuantType::F16:
return "F16";
case ExtraQuantType::Q4_0_C:
return "Q4_0_C";
case ExtraQuantType::Q4_0_128:
return "Q4_0_128";
case ExtraQuantType::Q8_0_C:
return "Q8_0_C";
case ExtraQuantType::Q8_0_32:
return "Q8_0_32";
case ExtraQuantType::Q8_1_C:
return "Q8_1_C";
case ExtraQuantType::Q4_0_64:
return "Q4_0_64";
case ExtraQuantType::Q4_1_64:
return "Q4_1_64";
default:
return "unknown";
}
}
// Result from process_weight_tensor containing the weight node and tensors.
// For quantized weights, also contains the extracted layout and scale/zp tensors.
struct OvWeight {
+19 -54
View File
@@ -7,20 +7,21 @@
#include "ggml-openvino-extra.h"
#include "openvino/rt_info/weightless_caching_attributes.hpp"
#include <cerrno>
#include <sys/stat.h>
#include <sys/types.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <limits>
#include <sstream>
#include <openvino/core/model.hpp>
#include <openvino/core/version.hpp>
#include <openvino/op/constant.hpp>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <system_error>
#include <unordered_map>
#include <unordered_set>
#include <vector>
@@ -113,50 +114,12 @@ std::string hex64(uint64_t v) {
return std::string(buf);
}
// Portable mkdir for a single path component. Returns true if the directory
// exists after the call (created now or already present).
bool make_dir(const std::string & path) {
#if defined(_WIN32)
int rc = _mkdir(path.c_str());
#else
int rc = ::mkdir(path.c_str(), 0755);
#endif
if (rc == 0 || errno == EEXIST) {
return true;
}
return false;
}
// Create `path` and any missing parents (like `mkdir -p`). Best-effort:
// returns true only if the full directory exists afterwards.
bool make_dirs(const std::string & path) {
if (path.empty()) {
return false;
}
std::string acc;
for (size_t i = 0; i < path.size(); ++i) {
const char c = path[i];
acc.push_back(c);
const bool sep = (c == '/'
#if defined(_WIN32)
|| c == '\\'
#endif
);
// Create each intermediate component (skip a leading "/" root).
if (sep && acc.size() > 1) {
std::string component = acc.substr(0, acc.size() - 1);
#if defined(_WIN32)
// A drive root such as "D:" cannot be mkdir'ed (EACCES, not EEXIST).
if (component.size() == 2 && component[1] == ':') {
continue;
}
#endif
if (!make_dir(component)) {
return false;
}
}
}
return make_dir(path);
// Create `path` and any missing parents (like `mkdir -p`). True if the directory exists afterwards.
bool make_dirs(const std::string & path, std::error_code & ec) {
const auto fs_path = std::filesystem::u8path(path);
std::filesystem::create_directories(fs_path, ec);
std::error_code ec_dir;
return std::filesystem::is_directory(fs_path, ec_dir);
}
} // namespace
@@ -179,10 +142,8 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_EXACT_ZERO_POINT",
"GGML_OPENVINO_STATEFUL_EXECUTION",
"GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT",
"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS",
"GGML_OPENVINO_REDUCE_COMPILE_MEM",
"GGML_OPENVINO_MEMORY_OPTIMIZE",
"GGML_OPENVINO_PROFILING",
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
@@ -337,9 +298,10 @@ std::string ggml_openvino_model_cache_dir() {
// Create the cache directory (and parents) on first use so callers don't
// have to pre-create it; a missing dir would otherwise silently disable the
// cache (manifest/blob writes fail with no directory to write into).
if (!make_dirs(path)) {
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (errno=%d); caching disabled\n",
path.c_str(), errno);
std::error_code ec;
if (!make_dirs(path, ec)) {
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (%s); caching disabled\n", path.c_str(),
ec.message().c_str());
return std::string();
}
return path;
@@ -370,13 +332,16 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
h = fnv1a_u64(h, 9);
// Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling),
// and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings.
h = fnv1a_u64(h, 10);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
h = fnv1a(h, value, strlen(value) + 1);
}
h = fnv1a_u64(h, ggml_openvino_gdn_decompose_enabled() ? ggml_openvino_gdn_decompose_chunk() : 0);
h = fnv1a_u64(h, ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1 : 0);
if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
h = fnv1a(h, "GGML_OPENVINO_DEBUG_NODE", sizeof("GGML_OPENVINO_DEBUG_NODE"));
h = fnv1a(h, debug_nodes, strlen(debug_nodes) + 1);
+8 -12
View File
@@ -1,17 +1,13 @@
#pragma once
// Compiled blobs include weights. Cache-only execution skips weight uploads and graph compilation.
// On NPU, GGML_OPENVINO_SELF_CONTAINED_BLOB=1 exports embedded-weight prefill/decode
// blobs. A warm hit skips weight requantization, graph conversion, and compilation,
// at the cost of roughly model-size storage per blob and separate NPUW weight banks.
// After both blobs exist, GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the
// GGUF mmap instead of allocating the private OpenVINO model buffer. This mode is
// import-only and fails clearly if either required blob is missing or invalid.
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1 is the same raw-weight flow, but exports weightless
// prefill/decode blobs plus ONE <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair
// of the model (pairs differ only in KV window). Warm import reads the weights from that file
// (ov::weights_path) and NPUW deduplicates all models into one bank
// (no OpenVINO patch needed), so the weights are stored once on disk and resident once.
// On NPU, GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR imports the cached prefill/decode blobs when they are
// valid; otherwise it compiles them and exports weightless blobs plus ONE
// <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair of the model (pairs differ
// only in KV window), with a warning. Import reads the weights from that file (ov::weights_path) and NPUW
// deduplicates all models into one bank, so the weights are stored once on disk and resident once.
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the GGUF mmap instead of allocating the private
// OpenVINO model buffer. This mode is import-only and fails clearly if a required blob is missing.
#include "ggml.h"
@@ -84,7 +80,7 @@ bool ggml_openvino_model_cache_verify_manifest(const std::string & path,
std::vector<std::string> & inputs,
std::vector<std::string> & outputs);
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: a weights file shared by weightless blobs. Every weightless-tagged
// NPU cache: a weights file shared by weightless blobs. Every weightless-tagged
// Constant is one region keyed by its data pointer (NPUW maps a Constant to its file offset by pointer).
struct ggml_openvino_weights_layout {
std::string path;
+5 -2
View File
@@ -111,11 +111,14 @@ public:
virtual const std::map<std::string, ModelExtraInputInfo> & get_model_extra_inputs() const = 0;
virtual const std::map<std::string, std::shared_ptr<ov::Node>> & get_model_weights() const = 0;
virtual std::set<std::string> get_model_output_names() const = 0;
// KV-only prefill (GGML_OPENVINO_KV_ONLY_PREFILL): the model keeps only the cache outputs, see
// pass::KeepCacheResults.
virtual bool is_kv_only_outputs() const { return false; }
// The outputs that write a KV or recurrent cache.
virtual std::set<std::string> get_cache_output_names() const { return {}; }
virtual int32_t * get_rope_params() const = 0;
virtual bool has_mixed_rope_params() const = 0;
virtual int get_ssm_state_size() const = 0;
virtual std::map<std::string, std::string> get_kv_param_res_names() const = 0;
@@ -16,21 +16,15 @@ typedef std::map<std::string, Output<Node>> TensorMap;
class NodeContext : public frontend::NodeContext {
public:
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder,
std::shared_ptr<TensorMap> & tensor_map,
int node_idx,
TranslateSession * translate_session = nullptr) :
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder, std::shared_ptr<TensorMap> & tensor_map, int node_idx) :
ov::frontend::NodeContext(decoder->get_op_type(node_idx)),
m_decoder(decoder),
m_tensor_map(tensor_map),
m_node_idx(node_idx),
m_translate_session(translate_session) {
m_node_idx(node_idx) {
m_input_names = decoder->get_input_names(m_node_idx);
m_output_names = decoder->get_output_names(m_node_idx);
}
TranslateSession * get_translate_session() const { return m_translate_session; }
const std::vector<std::string> & get_input_names() const { return m_input_names; }
const std::vector<std::string> & get_output_names() const { return m_output_names; }
@@ -172,7 +166,6 @@ private:
std::shared_ptr<GgmlDecoder> m_decoder;
std::shared_ptr<TensorMap> & m_tensor_map;
int m_node_idx;
TranslateSession * m_translate_session;
std::vector<std::string> m_input_names;
std::vector<std::string> m_output_names;
};
@@ -1,10 +1,9 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#include "ggml.h"
#include "ggml-openvino/ggml-openvino-extra.h"
#include "ggml.h"
#include <climits>
#include <cstdint>
#include <openvino/frontend/exception.hpp>
#include <openvino/op/add.hpp>
+10 -4
View File
@@ -1,9 +1,9 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
#include <climits>
#include <cstdint>
#include <cstdio>
#include <memory>
#include <numeric>
#include <openvino/frontend/exception.hpp>
@@ -126,9 +126,13 @@ OutputVector translate_cpy(const NodeContext & context) {
auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);
auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);
auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
// The view offset is relative to the whole base buffer, so splice on the flattened base.
auto flat_base = std::make_shared<ov::op::v1::Reshape>(base, flat_shape, false);
auto head_part = std::make_shared<ov::op::v8::Slice>(flat_base, zero, begin, one, axis);
auto tail_part = std::make_shared<ov::op::v8::Slice>(flat_base, end, int_max, one, axis);
auto spliced = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
auto res = std::make_shared<ov::op::v1::Reshape>(
spliced, std::make_shared<ov::op::v3::ShapeOf>(base, ov::element::i64), false);
return rename_outputs_with_suffix({res}, context.get_name());
}
@@ -221,6 +225,8 @@ OutputVector translate_cpy(const NodeContext & context) {
"CPY conv state cache update requires static source feature view");
const int64_t full_feature_size = base_shape[3].get_length();
FRONT_END_OP_CONVERSION_CHECK(full_feature_size > 0,
"CPY conv state cache update requires a non-empty base cache feature size");
const int64_t update_feature_size = input_shape[2].get_length() * input_shape[3].get_length();
const auto output_stride = context.get_output_stride();
const size_t elem_size = output_stride.empty() ? context.get_output_type().size() : output_stride.back();
@@ -139,7 +139,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
float * params = reinterpret_cast<float *>(context.get_output_op_params());
float scale = params[0];
// float max_bias = params[1];
const float logit_softcap = params[2];
auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);
@@ -168,9 +167,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
false);
}
//auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {
// int64_t factor = num_heads / num_heads_kv;
// if (factor > 1 && num_heads_kv > 1) {
auto q_shape = context.get_input_shape(0).to_shape();
auto k_shape = context.get_input_shape(1).to_shape();
auto v_shape = context.get_input_shape(2).to_shape();
@@ -279,9 +275,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
new_kv_shape = ov::op::v0::Constant::create(
ov::element::i64, {4},
transposed ? std::vector<int64_t>{0, n_heads, hs, -1} : std::vector<int64_t>{0, n_heads, -1, hs});
// ov::element::i64, {5}, {(int64_t) 1, (int64_t) 1, factor, (int64_t) 1, (int64_t) 1});
//new_kv_shape =
// ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 0, num_heads, (int64_t) -1, head_size});
kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed, kv_broadcast_shape,
ov::op::BroadcastType::BIDIRECTIONAL);
@@ -294,9 +287,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
const bool v_transposed = ggml_openvino_npu_kv_head_major_enabled() && context.is_static() &&
context.get_input_names()[2].find("cache_v_l") != std::string::npos;
// the HFA prefill path has no sinks
const bool use_hfa_gate =
ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() && has_mask && !has_sink;
// the HFA prefill path has no sinks, and attends the rows of a whole chunk (not those of gemma-4's KV-shared layers)
const bool use_hfa_gate = ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() &&
has_mask && !has_sink && !is_pruned_mask_name(context.get_input_names()[3]);
if (use_hfa_gate) {
const int layer = extract_layer(context.get_input_names()[1]);
auto past_k = context.get_input("ggml_hfa_past_cache_k_l" + std::to_string(layer));
@@ -350,10 +343,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
return rename_outputs_with_suffix({res}, context.get_name());
}
//auto q_shape = context.get_input_shape(0).to_shape();
//auto k_shape = context.get_input_shape(1).to_shape();
//k = tile_kv(q_shape[1], k_shape[1], q_shape[3], k);
//v = tile_kv(q_shape[1], k_shape[1], q_shape[3], v);
k = tile_kv(num_heads, num_heads_kv, head_size, k);
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
@@ -514,10 +514,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
// << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
// << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
if (cache_inputs) {
OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
@@ -24,6 +24,13 @@ namespace op {
OutputVector translate_get_rows(const NodeContext & context) {
num_inputs_check(context, 2, 2);
// Rows gathered on the host (GGML_OPENVINO_NPU_HOST_GATHER) arrive as a [1, 1, n_tokens, row] input.
const std::string host_rows = "ggml_host_rows_" + context.get_name();
if (context.has_input(host_rows)) {
// Not renamed: the output is the Parameter itself, whose name binds the input at runtime.
return {context.get_input(host_rows)};
}
Output<Node> res;
Output<Node> data;
int64_t row_offset = 0;
@@ -2,7 +2,6 @@
#include "../op_table.h"
#include "../utils.h"
#include <climits>
#include <cstdint>
#include <memory>
#include <openvino/core/node.hpp>
@@ -3,7 +3,6 @@
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
#include <climits>
#include <cstdint>
#include <memory>
#include <openvino/core/node.hpp>
@@ -113,10 +112,6 @@ OutputVector translate_permute(const NodeContext & context) {
auto new_shape =
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, n_heads, head_size}, 0);
// // Alternative
// auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
// auto new_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, zero, zero}, 0);
auto reshaped = std::make_shared<ov::op::v1::Reshape>(src, new_shape, true);
res = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);
} else if ((op_case == 3 || op_case == 4) && is_kvcache_4d_shape(src.get_partial_shape())) {
+20 -25
View File
@@ -49,34 +49,29 @@ OutputVector translate_rope(const NodeContext & context) {
Output<Node> cos_theta_node;
Output<Node> sin_theta_node;
if (context.has_input("rope_cos")) {
cos_theta_node = context.get_input("rope_cos");
sin_theta_node = context.get_input("rope_sin");
std::string cache_key = "rope_sin_cos";
for (int i = 0; i < 15; i++) {
cache_key += "_" + std::to_string(op_params[i]);
}
if (context.get_input_size() == 3) {
cache_key += "_ff_" + context.get_input_names()[2];
}
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
cache_key += "_pos_" + context.get_input_names()[1];
if (context.has_input(cache_key + "_cos")) {
cos_theta_node = context.get_input(cache_key + "_cos");
sin_theta_node = context.get_input(cache_key + "_sin");
} else {
std::string cache_key = "rope_sin_cos";
for (int i = 0; i < 15; i++) {
cache_key += "_" + std::to_string(op_params[i]);
}
auto inp_pos = context.get_input(1).get_node_shared_ptr();
std::shared_ptr<ov::Node> rope_freqs_weight;
if (context.get_input_size() == 3) {
cache_key += "_ff_" + context.get_input_names()[2];
}
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
cache_key += "_pos_" + context.get_input_names()[1];
if (context.has_input(cache_key + "_cos")) {
cos_theta_node = context.get_input(cache_key + "_cos");
sin_theta_node = context.get_input(cache_key + "_sin");
} else {
auto inp_pos = context.get_input(1).get_node_shared_ptr();
std::shared_ptr<ov::Node> rope_freqs_weight;
if (context.get_input_size() == 3) {
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
}
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
sin_theta_node = sin_cos.first;
cos_theta_node = sin_cos.second;
context.put_shared(cache_key + "_cos", cos_theta_node);
context.put_shared(cache_key + "_sin", sin_theta_node);
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
}
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
sin_theta_node = sin_cos.first;
cos_theta_node = sin_cos.second;
context.put_shared(cache_key + "_cos", cos_theta_node);
context.put_shared(cache_key + "_sin", sin_theta_node);
}
auto output_type = context.get_output_type();
@@ -3,7 +3,6 @@
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <numeric>
+20 -24
View File
@@ -5,9 +5,7 @@
#include <openvino/op/constant.hpp>
#include <openvino/op/group_conv.hpp>
#include <openvino/op/reshape.hpp>
#include <openvino/op/squeeze.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
namespace ov {
namespace frontend {
@@ -23,34 +21,32 @@ OutputVector translate_ssm_conv(const NodeContext & context) {
auto sx_shape = context.get_input_shape(0).to_shape(); // [1, n_s, d_inner, ncs]
auto c_shape = context.get_input_shape(1).to_shape(); // [1, 1, d_inner, d_conv]
// int64_t n_s = sx_shape[1];
int64_t d_inner = sx_shape[2];
// int64_t ncs = sx_shape[3]; // d_conv - 1 + n_t
int64_t d_conv = c_shape[3];
// int64_t n_t = ncs - d_conv + 1;
int64_t d_conv = c_shape[3];
// Reshape sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, ncs] for 1D GroupConvolution
auto sx_reshaped =
std::make_shared<ov::op::v0::Squeeze>(sx, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
// The depthwise conv is expressed as a 2D GroupConvolution with a unit H dim: the GPU plugin
// (OV 2026.4, ACCURACY mode) fails to compile the 1D form ("Weights/ifm mismatch") when its
// input comes from RMSNorm -> Transpose -> Concat.
// Transpose sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, 1, ncs]
auto sx_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 2, 0, 3});
auto sx_reshaped = std::make_shared<ov::op::v1::Transpose>(sx, sx_perm);
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, d_conv]
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kernel_size]
auto c_new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{d_inner, 1, 1, d_conv});
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, 1, d_conv]
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kH, kW]
auto c_new_shape =
ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{d_inner, 1, 1, 1, d_conv});
auto c_reshaped = std::make_shared<ov::op::v1::Reshape>(c, c_new_shape, false);
// Depthwise 1D convolution: groups=d_inner, stride=1, no padding, no dilation
// Input: [n_s, d_inner, ncs], Filter: [d_inner, 1, 1, d_conv]
// Output: [n_s, d_inner, n_t]
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(
sx_reshaped, c_reshaped, ov::Strides{1}, ov::CoordinateDiff{0}, ov::CoordinateDiff{0}, ov::Strides{1});
// Depthwise convolution: groups=d_inner, stride=1, no padding, no dilation
// Input: [n_s, d_inner, 1, ncs], Filter: [d_inner, 1, 1, 1, d_conv]
// Output: [n_s, d_inner, 1, n_t]
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(sx_reshaped, c_reshaped, ov::Strides{1, 1},
ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0},
ov::Strides{1, 1});
// Transpose from [n_s, d_inner, n_t] to [n_s, n_t, d_inner]
auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
// Reshape to output shape [1, n_s, n_t, d_inner]
auto res =
std::make_shared<ov::op::v0::Unsqueeze>(transposed, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
// Transpose from [n_s, d_inner, 1, n_t] to output shape [1, n_s, n_t, d_inner]
auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{2, 0, 3, 1});
auto res = std::make_shared<ov::op::v1::Transpose>(conv, perm);
return rename_outputs_with_suffix({res}, context.get_name());
}
@@ -0,0 +1,53 @@
#include "keep_cache_results.h"
#include <openvino/core/model.hpp>
#include <openvino/op/parameter.hpp>
#include <openvino/op/result.hpp>
#include <unordered_set>
namespace ov {
namespace frontend {
namespace ggml {
namespace pass {
bool KeepCacheResults::run_on_model(const std::shared_ptr<ov::Model> & model) {
bool changed = false;
// Copies: remove_result()/remove_parameter() modify the vectors these accessors return.
const ov::ResultVector results = model->get_results();
for (const auto & result : results) {
if (m_cache_outputs.count(result->get_friendly_name()) == 0) {
model->remove_result(result);
changed = true;
}
}
if (!changed) {
return false;
}
// Removed Results leave their producers unreachable, but those nodes still hold their inputs, so a Parameter
// is unused when none of its consumers is still part of the model.
std::unordered_set<const ov::Node *> live;
for (const auto & op : model->get_ordered_ops()) {
live.insert(op.get());
}
const ov::ParameterVector params = model->get_parameters();
for (const auto & param : params) {
bool used = false;
for (const auto & input : param->output(0).get_target_inputs()) {
if (live.count(input.get_node()) != 0) {
used = true;
break;
}
}
if (!used) {
model->remove_parameter(param);
}
}
return true;
}
} // namespace pass
} // namespace ggml
} // namespace frontend
} // namespace ov
@@ -0,0 +1,30 @@
#include "openvino/pass/pass.hpp"
#include <set>
#include <string>
namespace ov {
namespace frontend {
namespace ggml {
namespace pass {
// Keeps only the Results named in |cache_outputs| (the KV / recurrent cache writes) and drops every other Result,
// so that everything that only feeds them -- for models whose tail layers read an earlier layer's KV (Gemma 3n/4
// E-series) the KV-shared layers and the LM head -- leaves the model. Parameters that nothing reads afterwards are
// removed too. Used for KV-only prefill on the static path (GGML_OPENVINO_KV_ONLY_PREFILL); the outputs of the
// batch then come from one step of the decode model.
class KeepCacheResults : public ov::pass::ModelPass {
public:
OPENVINO_MODEL_PASS_RTTI("ov::frontend::ggml::pass::KeepCacheResults")
explicit KeepCacheResults(std::set<std::string> cache_outputs) : m_cache_outputs(std::move(cache_outputs)) {}
bool run_on_model(const std::shared_ptr<ov::Model> & model) override;
private:
std::set<std::string> m_cache_outputs;
};
} // namespace pass
} // namespace ggml
} // namespace frontend
} // namespace ov
@@ -1,6 +1,5 @@
#pragma once
#include "mark_decompression_convert_constant_folding.h"
#include "openvino/core/visibility.hpp"
#include "openvino/pass/matcher_pass.hpp"
@@ -4,6 +4,7 @@
#include "ggml-openvino/openvino/decoder.h"
#include "ggml-openvino/openvino/pass/fuse_argsort_topk.h"
#include "ggml-openvino/openvino/pass/fuse_to_conv.h"
#include "ggml-openvino/openvino/pass/keep_cache_results.h"
#include "ggml-openvino/openvino/pass/kv_state_seq_axis.h"
#include "ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h"
#include "ggml-openvino/openvino/pass/mark_dequantization_subgraph.h"
@@ -21,11 +22,18 @@ GraphTraits analyze_graph(const GgmlDecoder & decoder) {
traits.device = ggml_openvino_is_npu() ? Device::NPU : ggml_openvino_is_gpu() ? Device::GPU : Device::CPU;
traits.is_static = decoder.is_static();
traits.is_stateful = decoder.is_stateful();
traits.kv_only_outputs = decoder.is_kv_only_outputs();
if (traits.kv_only_outputs) {
traits.cache_output_names = decoder.get_cache_output_names();
}
return traits;
}
void register_common_passes(ov::pass::Manager & manager, const GraphTraits & traits) {
(void) traits;
// First, so the other passes do not work on the layers it removes.
if (traits.kv_only_outputs) {
manager.register_pass<pass::KeepCacheResults>(traits.cache_output_names);
}
manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
// Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain
// (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding,
@@ -16,6 +16,9 @@
#include <openvino/pass/make_stateful.hpp>
#include <openvino/pass/manager.hpp>
#include <set>
#include <string>
namespace ov {
namespace frontend {
namespace ggml {
@@ -31,6 +34,8 @@ struct GraphTraits {
Device device = Device::CPU;
bool is_static = false; // static shapes (NPU, or GGML_OPENVINO_FORCE_STATIC)
bool is_stateful = false; // KV cache kept inside the model (GGML_OPENVINO_STATEFUL_EXECUTION)
bool kv_only_outputs = false; // static KV-only prefill: keep only the cache outputs (GGML_OPENVINO_KV_ONLY_PREFILL)
std::set<std::string> cache_output_names;
};
GraphTraits analyze_graph(const GgmlDecoder & decoder);
@@ -3,10 +3,8 @@
# include "../ggml-openvino-extra.h"
# include "ggml-impl.h"
# include "op/recurrent_cache_update.hpp"
# include "op_table.h"
# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
# include "op/recurrent_cache_update.hpp"
# endif
# include "utils.h"
# include <openvino/op/concat.hpp>
@@ -15,11 +15,9 @@
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <openvino/core/node.hpp>
#include <openvino/core/preprocess/pre_post_process.hpp>
#include <openvino/core/shape.hpp>
@@ -53,6 +51,7 @@
#include <openvino/op/unsqueeze.hpp>
#include <openvino/pass/constant_folding.hpp>
#include <openvino/pass/make_stateful.hpp>
#include <set>
#include <sstream>
#include <unordered_map>
#include <vector>
@@ -325,7 +324,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
auto it = m_translator_map.find(operation_type);
FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type,
" is not implemented.");
NodeContext node_context(decoder, tensor_map, node_idx, this);
NodeContext node_context(decoder, tensor_map, node_idx);
ov::OutputVector converted_outputs;
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
converted_outputs = recurrent_fusion.translate(node_idx, node_context);
@@ -451,9 +450,6 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
used_params.push_back(param);
}
}
// if (auto diff = params.size() - used_params.size()) {
// GGML_LOG_INFO("%zu parameters are not used in the model.", diff);
// }
resulting_model = std::make_shared<Model>(results, used_params);
apply_transformations(resulting_model);
+25 -3
View File
@@ -496,15 +496,37 @@ std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & we
return saw_compressed ? gathered : nullptr;
}
bool is_pruned_mask_name(const std::string & name) {
static const std::string suffix = "_pruned";
return name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;
}
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index) {
const auto & name = context.get_input_names()[input_index];
const auto & input_name = context.get_input_names()[input_index];
const bool pruned = is_pruned_mask_name(input_name);
const std::string name = pruned ? input_name.substr(0, input_name.size() - std::string("_pruned").size()) : input_name;
const std::string sliced = name == "self_kq_mask_swa" ? "KQ_mask_swa_sliced" :
name == "self_kq_mask" || name == "KQ_mask" ? "KQ_mask_sliced" :
std::string();
ov::Output<ov::Node> mask;
if (!sliced.empty() && context.has_input(sliced)) {
return context.get_input(sliced);
mask = context.get_input(sliced);
} else if (pruned) {
mask = context.get_input(name);
} else {
return context.get_input(input_index);
}
return context.get_input(input_index);
if (!pruned) {
return mask;
}
// gemma-4's KV-shared layers: the rows of their output tokens, gathered from the input mask (see
// ModelParams::pruned_masks)
auto ids = std::make_shared<ov::op::v1::Reshape>(context.get_input("inp_prune_ids"),
ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false);
const auto rank = mask.get_partial_shape().rank();
FRONT_END_OP_CONVERSION_CHECK(rank.is_static() && rank.get_length() >= 2, "Expected a static mask rank");
auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {rank.get_length() - 2});
return std::make_shared<ov::op::v8::Gather>(mask, ids, axis);
}
ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int input_index) {
+3
View File
@@ -49,6 +49,9 @@ OutputVector translate_recurrent_cache_reset(const NodeContext & context);
// add_sliced_mask_stateful); any other input, e.g. the mask rows gemma-4 gathers for its KV-shared layers, as is.
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index);
// The mask of gemma-4's KV-shared layers, whose rows get_kq_mask_input() gathers from an input mask
bool is_pruned_mask_name(const std::string & name);
// A stateless KV cache in the [1, ctx, n_heads_kv, head_size] layout (GgmlOvDecoder::is_kvcache_4d), as opposed to
// [1, n_seq, ctx, n_heads_kv * head_size]
inline bool is_kvcache_4d_shape(const ov::PartialShape & shape) {
File diff suppressed because it is too large Load Diff
+39 -38
View File
@@ -13,6 +13,7 @@
#include <openvino/runtime/core.hpp>
#include <openvino/runtime/infer_request.hpp>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
@@ -96,43 +97,55 @@ struct graph_key_hash {
}
};
// One compiled model of a static graph: its phase, KV window, SWA window and output count.
struct ov_static_variant_key {
bool prefill = false;
int attention_size = -1;
int attention_size_swa = -1;
int output_len = 1;
bool operator<(const ov_static_variant_key & other) const {
return std::tie(prefill, output_len, attention_size_swa, attention_size) <
std::tie(other.prefill, other.output_len, other.attention_size_swa, other.attention_size);
}
bool operator==(const ov_static_variant_key & other) const { return !(*this < other) && !(other < *this); }
};
struct ov_static_variant {
ov::CompiledModel model;
// Created on first use, so only the requests a run needs hold NPU memory.
std::shared_ptr<ov::InferRequest> request;
std::vector<std::string> input_names;
std::vector<std::string> output_names;
};
struct decoder_runtime_ctx {
decoder_runtime_ctx(std::shared_ptr<std::mutex> mutex) : mutex(std::move(mutex)) {}
std::shared_ptr<std::mutex> mutex;
std::shared_ptr<GgmlOvDecoder> ptr;
// Attention sizes and output count the cached prefill model was built with; decode calls overwrite the
// decoder's.
int prefill_attention_size = -1;
int prefill_attention_size_swa = -1;
int prefill_output_len = -1;
// KV window of the decode model in the compiled pair (GGML_OPENVINO_NPU_BLOB_PREBUILD).
int decode_attention_size = -1;
std::string shared_key;
std::map<int, std::shared_ptr<ov::InferRequest>> decode_window_requests;
// Static path: the compiled models of this graph with their requests (ov_graph_compute_static).
std::map<ov_static_variant_key, ov_static_variant> variants;
// The prefill models only write the KV cache; logits come from one decode step (GGML_OPENVINO_KV_ONLY_PREFILL).
bool kv_only_prefill = false;
bool decode_unfold = false;
uint64_t cache_base_extra = 0;
// With a model cache, every window of a phase is exported (or imported) on the first call of that phase.
bool prefill_prepared = false;
bool decode_prepared = false;
// NPU weightless bank: the weights file and NPUW bank of every blob of this graph, and the file's layout once
// it is known in this process (new blobs resolve their weights through it).
std::string weights_path;
std::string weights_bank;
std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
};
struct ov_compiled_graph {
ov::CompiledModel decode;
ov::CompiledModel prefill;
std::vector<std::string> input_names;
std::vector<std::string> output_names;
std::vector<std::string> prefill_input_names;
std::vector<std::string> prefill_output_names;
// Extra decode models for other KV windows, built on first use with the pair's settings.
int decode_attention_size = -1;
std::map<int, ov::CompiledModel> decode_windows;
ov::AnyMap decode_config;
uint64_t cache_base_extra = 0;
bool self_contained = false;
bool decode_unfold = false;
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: the pair's weights file, and its layout when the pair was compiled in
// this process (window models then resolve the shared weights through the same file).
bool weightless_bank = false;
std::string weights_path;
std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
// Compute params the pair's decode model was built with; window models derive from them.
ComputeParams decode_c_params;
};
// Only compilation and cache publication use this mutex. Requests, decoders and
@@ -154,11 +167,8 @@ struct ov_runtime_context {
bool stateful;
std::unordered_map<graph_key, std::shared_ptr<decoder_runtime_ctx>, graph_key_hash> decoder_cache;
std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache;
std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache_prefill;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
// LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
// that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
// injection graphs every round -- needs a slot per shape open at once; a single-entry cache
@@ -193,11 +203,8 @@ struct ov_runtime_context {
lru_keys.pop_front();
decoder_cache.erase(victim);
infer_request_cache.erase(victim);
infer_request_cache_prefill.erase(victim);
ov_input_names_cache.erase(victim);
ov_output_names_cache.erase(victim);
ov_input_names_cache_prefill.erase(victim);
ov_output_names_cache_prefill.erase(victim);
}
// Make room for one more graph shape if the cache is at capacity, then mark `key` as most
@@ -212,11 +219,8 @@ struct ov_runtime_context {
void clear_caches_locked() {
decoder_cache.clear();
infer_request_cache.clear();
infer_request_cache_prefill.clear();
ov_input_names_cache.clear();
ov_output_names_cache.clear();
ov_input_names_cache_prefill.clear();
ov_output_names_cache_prefill.clear();
lru_keys.clear();
kv_state_input_name_map.clear();
stateful_kv_size = 0;
@@ -230,9 +234,6 @@ struct ov_runtime_context {
enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t backend);
// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
void ov_clear_imported_blobs();
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);
+7
View File
@@ -18,6 +18,7 @@
extern int g_ggml_sycl_debug;
extern int g_ggml_sycl_dev_debug;
extern int g_ggml_sycl_fa_tile_debug;
#if defined(__clang__) && __has_builtin(__builtin_expect)
// Hint the optimizer to pipeline the more likely following instruction in branches
@@ -40,4 +41,10 @@ extern int g_ggml_sycl_dev_debug;
fprintf(stderr, __VA_ARGS__); \
} while (0)
#define GGML_SYCL_FA_TILE_DEBUG(...) \
do { \
if (UNLIKELY(g_ggml_sycl_fa_tile_debug)) \
fprintf(stderr, __VA_ARGS__); \
} while (0)
#endif // GGML_SYCL_BASE_HPP
+18 -5
View File
@@ -880,15 +880,24 @@ static void flash_attn_tile(const char * Q,
KQ_max_new_shared);
}
} else {
// Branch without out-of-bounds checks.
for (int k_VKQ_0 = item_ct1.get_group(1) * nbatch_fa; k_VKQ_0 < k_VKQ_max;
k_VKQ_0 += item_ct1.get_group_range(1) * nbatch_fa) {
// Branch without out-of-bounds checks for full chunks; the trailing partial
// chunk (n_kv not a multiple of nbatch_fa) takes the checked iteration, so
// the GQA-optimized variants no longer require K->ne[1] % FATTN_KQ_STRIDE == 0.
int k_VKQ_0 = item_ct1.get_group(1) * 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>(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,
KQ_max_new_shared);
k_VKQ_0 += item_ct1.get_group_range(1) * 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>(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,
KQ_max_new_shared);
}
}
@@ -1166,7 +1175,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_sycl_context & ctx, ggm
// However, for DKQ == 576, DV == 512 only the kernel variant with GQA optimizations is implemented.
//const bool nvidia = GGML_SYCL_CC_IS_NVIDIA(ggml_sycl_info().devices[ggml_sycl_get_device()].cc);
const int gqa_limit = gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX;
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
// n_kv need not be a multiple of FATTN_KQ_STRIDE: the kernel handles the trailing
// partial chunk with the out-of-bounds checked iteration.
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit;
GGML_SYCL_FA_TILE_DEBUG("[FA-TILE] DKQ=%d DV=%d gqa=%d q=%lld n_kv=%lld gqa_opt=%d\n",
DKQ, DV, gqa_ratio, (long long) Q->ne[1], (long long) K->ne[1], (int) use_gqa_opt);
if constexpr (DV == 512) {
if (use_gqa_opt && gqa_ratio % 16 == 0) {
+12 -2
View File
@@ -129,7 +129,9 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
float logit_softcap = 0.0f;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0;
// The GQA-optimized TILE variant handles a trailing partial chunk (out-of-bounds
// checked iteration), so n_kv no longer needs to be a multiple of FATTN_KQ_STRIDE.
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f;
// XMX-accelerated path: oneDNN SDPA (native F16 and dequant+non-F16).
// ONEDNN requires min 32 query tokens — short-circuit decode to avoid
@@ -267,7 +269,15 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
if (can_use_vector_kernel) {
if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
if (Q->ne[1] == 1) {
if (!gqa_opt_applies) {
// BMG, D=256: single-query decode runs materially faster on the vector
// kernel than on the GQA-optimized tile config (832 vs 1150 us at
// kv=65536, GQA4, B70-measured; +4..+18% end-to-end tg at 8k..64k
// context on spark2_5/qwen35 D=256 models). Other archs and head sizes
// keep the tile dispatcher's original preference.
const gpu_arch arch = ggml_sycl_info().devices[device].hw_info.arch;
const bool vec_decode = (arch == gpu_arch::intel_gpu_bmg_g21 ||
arch == gpu_arch::intel_gpu_bmg_g31) && Q->ne[0] == 256;
if (vec_decode || !gqa_opt_applies) {
return BEST_FATTN_KERNEL_VEC;
}
}
+8
View File
@@ -99,6 +99,7 @@
static bool g_sycl_loaded = false;
int g_ggml_sycl_debug = 0;
int g_ggml_sycl_dev_debug = 0;
int g_ggml_sycl_fa_tile_debug = 0;
int g_ggml_sycl_enable_optimize = 1;
int g_ggml_sycl_enable_graph = 0;
int g_ggml_sycl_enable_dnn = 1;
@@ -434,6 +435,7 @@ static void ggml_check_sycl() try {
g_ggml_sycl_debug = ggml_sycl_get_env("GGML_SYCL_DEBUG", 0);
g_ggml_sycl_dev_debug = ggml_sycl_get_env("GGML_SYCL_DEV_DEBUG", 0);
g_ggml_sycl_fa_tile_debug = ggml_sycl_get_env("GGML_SYCL_FA_TILE_DEBUG", 0);
g_ggml_sycl_enable_optimize = ggml_sycl_get_env("GGML_SYCL_ENABLE_OPT", 1);
g_ggml_sycl_enable_graph = ggml_sycl_get_env("GGML_SYCL_ENABLE_GRAPH", 0);
g_ggml_sycl_enable_dnn = ggml_sycl_get_env("GGML_SYCL_ENABLE_DNN", 1);
@@ -542,6 +544,7 @@ static void ggml_check_sycl() try {
GGML_LOG_INFO("Running with Environment Variables:\n");
GGML_LOG_INFO(" GGML_SYCL_DEBUG: %d\n", g_ggml_sycl_debug);
GGML_LOG_INFO(" GGML_SYCL_DEV_DEBUG: %d\n", g_ggml_sycl_dev_debug);
GGML_LOG_INFO(" GGML_SYCL_FA_TILE_DEBUG: %d\n", g_ggml_sycl_fa_tile_debug);
#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API
GGML_LOG_INFO(" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s)\n", g_ggml_sycl_dev2dev_memcpy, dev2dev_int2str(g_ggml_sycl_dev2dev_memcpy));
@@ -7435,6 +7438,11 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
return false;
}
// MUL_MAT_ID copies the src1 rows as F32
if (op->op == GGML_OP_MUL_MAT_ID && b->type != GGML_TYPE_F32) {
return false;
}
if (op->op == GGML_OP_MUL_MAT &&
(ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32)) {
return false;
+11 -5
View File
@@ -23,7 +23,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
}
}
if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
if (!subgroup_size_control) {
return vk_device_architecture::AMD_GCN;
}
if (!amd_shader_core_properties) {
return vk_device_architecture::OTHER;
}
@@ -33,8 +36,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
props2.pNext = &shader_core_props_amd;
shader_core_props_amd.pNext = &integer_dot_props;
integer_dot_props.pNext = &subgroup_size_control_props;
shader_core_props_amd.pNext = &subgroup_size_control_props;
if (integer_dot_product) {
subgroup_size_control_props.pNext = &integer_dot_props;
}
device.getProperties2(&props2);
@@ -49,7 +54,7 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
if (shader_float8) {
return vk_device_architecture::AMD_RDNA4;
}
if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
if (integer_dot_product && integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
return vk_device_architecture::AMD_RDNA3;
}
return vk_device_architecture::AMD_RDNA2;
@@ -1215,7 +1220,8 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device,
// Disable subgroup use due to performance issues when enforcing subgroup sizes
result.subgroup_size = 32;
result.disable_subgroups = true;
} else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN) {
} else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN &&
device->subgroup_size_control && device->subgroup_min_size <= 32) {
result.subgroup_size = n_rows < 4 ? 32 : device->subgroup_size;
} else {
result.subgroup_size = device->subgroup_size;
+5
View File
@@ -721,6 +721,11 @@ static bool ggml_backend_zendnn_device_supports_op(ggml_backend_dev_t dev, const
return false;
}
// the inputs are read as F32; only BF16 weights also take BF16 inputs as they are
if (inputs->type != GGML_TYPE_F32 && !(inputs->type == GGML_TYPE_BF16 && weights->type == GGML_TYPE_BF16)) {
return false;
}
if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) {
return false;
}
+24 -13
View File
@@ -5549,27 +5549,38 @@ bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) {
return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0;
}
bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a) {
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
const struct ggml_tensor * table = a->src[6];
const struct ggml_tensor * indices = a->src[7];
if (!ggml_flash_attn_ext_has_indexed_bias(a)) {
return !table && !indices;
}
const struct ggml_tensor * q = a->src[0];
const struct ggml_tensor * k = a->src[1];
const struct ggml_tensor * mask = a->src[3];
const struct ggml_tensor * rows = a->src[5];
return q && k && a->src[2] && mask && table && indices &&
mask->type == GGML_TYPE_F16 && ggml_is_contiguous(mask) &&
mask->ne[0] == (rows ? rows->ne[0] : k->ne[1]) && mask->ne[1] == q->ne[1] &&
mask->ne[2] == 1 && mask->ne[3] == q->ne[3] &&
(!rows || (rows->type == GGML_TYPE_I32 && ggml_is_contiguous(rows) && ggml_is_matrix(rows) && rows->ne[1] == q->ne[3])) &&
table->type == GGML_TYPE_F32 && ggml_is_contiguous(table) && table->ne[0] > 0 && table->ne[1] == q->ne[2] &&
(q->ne[1] == 0 || q->ne[3] <= INT64_MAX/q->ne[1]) && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1 &&
indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices) &&
indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2];
}
void ggml_flash_attn_ext_add_indexed_bias(
struct ggml_tensor * a,
struct ggml_tensor * table,
struct ggml_tensor * indices) {
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
GGML_ASSERT((table == NULL) == (indices == NULL));
a->src[6] = table;
a->src[7] = indices;
ggml_set_op_params_i32(a, 5, table != NULL);
if (!table) {
return;
}
const struct ggml_tensor * q = a->src[0];
const struct ggml_tensor * mask = a->src[3];
GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]);
GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]);
GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table));
GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1);
GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices));
GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]);
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(a));
}
// ggml_flash_attn_back
+1
View File
@@ -175,6 +175,7 @@ class Keys:
CONV_GROUP_SIZE = "{arch}.conv_group_size"
SELECTOR_RANK = "{arch}.selector_rank"
SELECTOR_TOP_K = "{arch}.selector_top_k"
SELECTOR_SOFTCAP_AFTER_CORRECTION = "{arch}.selector_softcap_after_correction"
SAMPLE_FROM_ANCHOR = "{arch}.sample_from_anchor"
HAS_CONFIDENCE_HEAD = "{arch}.has_confidence_head"
HAS_MARKOV_CONTEXT = "{arch}.has_markov_context"
+3
View File
@@ -1107,6 +1107,9 @@ class GGUFWriter:
def add_selector_top_k(self, value: int) -> None:
self.add_uint32(Keys.LLM.SELECTOR_TOP_K.format(arch=self.arch), value)
def add_selector_softcap_after_correction(self, value: bool) -> None:
self.add_bool(Keys.LLM.SELECTOR_SOFTCAP_AFTER_CORRECTION.format(arch=self.arch), value)
def add_sample_from_anchor(self, value: bool) -> None:
self.add_bool(Keys.LLM.SAMPLE_FROM_ANCHOR.format(arch=self.arch), value)
+365
View File
@@ -0,0 +1,365 @@
#!/usr/bin/env python3
# Check HIP VGPR limits, compare kernel resource usage, and generate a report.
# Read Clang optimization records produced with -fsave-optimization-record=yaml
# and -Rpass-analysis=kernel-resource-usage.
import argparse
import sys
from collections import defaultdict
from pathlib import Path
from typing import cast
import yaml
try:
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
except ImportError:
demangle = None
METRICS = ('occupancy', 'vgpr_spill', 'sgpr_spill')
REPORT_METRICS = METRICS + ('vgpr_total',)
RULES = {
'vgpr_limit': 'blocking',
'vgpr_spill_increase': 'blocking',
'sgpr_spill_increase': 'blocking',
'occupancy_vgpr_increase': 'blocking',
'occupancy_drop': 'warning',
}
REMARK_NAMES = {'NumVGPR': 'vgprs', 'Occupancy': 'occupancy', 'VGPRSpill': 'vgpr_spill', 'SGPRSpill': 'sgpr_spill'}
METRIC_NAMES = {'occupancy': 'Occupancy [waves/SIMD]', 'vgpr_spill': 'VGPRs Spill', 'sgpr_spill': 'SGPRs Spill', 'vgpr_total': 'Total VGPRs (limit 256)'}
IGNORED_VGPR = {
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
}
class RemarkLoader(yaml.SafeLoader):
pass
def construct_remark(loader, tag, node):
return loader.construct_mapping(node)
RemarkLoader.add_multi_constructor('!', construct_remark)
def format_name(name):
if demangle is None:
return name
try:
demangled = demangle(name)
except Exception:
return name
return f'{name} [{demangled}]' if demangled is not None else name
def parse_remarks(filepath):
path = Path(filepath)
files = sorted(path.rglob('*.opt.yaml')) if path.is_dir() else [path] if path.is_file() else []
if not files:
raise ValueError(f'No optimization records found in {filepath}')
functions = defaultdict(lambda: {'vgprs': [], 'occupancy': [], 'vgpr_spill': [], 'sgpr_spill': [], 'location': ''})
for file in files:
with file.open('r') as f:
for remark in yaml.load_all(f, Loader=RemarkLoader):
if not isinstance(remark, dict) or remark.get('Pass') != 'kernel-resource-usage':
continue
key = remark.get('Name')
if key not in REMARK_NAMES:
continue
name = remark.get('Function')
if not isinstance(name, str) or not name:
continue
values = [arg[key] for arg in remark.get('Args', []) if isinstance(arg, dict) and key in arg]
if len(values) != 1:
raise ValueError(f'Invalid {key} remark for {name} in {file}')
try:
value = int(values[0])
except (TypeError, ValueError) as exc:
raise ValueError(f'Invalid {key} value for {name} in {file}') from exc
cast(list[int], functions[name][REMARK_NAMES[key]]).append(value)
location = remark.get('DebugLoc') or {}
if location.get('File') and location.get('Line'):
functions[name]['location'] = f"{Path(location['File']).name}:{location['Line']}"
if not functions:
raise ValueError(f'No kernel resource usage remarks found in {filepath}')
return functions
def load_ignore_file(filepath):
ignored = set()
with open(filepath, 'r') as f:
for line in f:
name = line.strip()
if name and not name.startswith('#'):
ignored.add(name)
return ignored
def check_vgpr(functions, filepath, rows=None):
found_issues = False
for ignored in (True, False):
for name, data in sorted(functions.items()):
if (name in IGNORED_VGPR) != ignored:
continue
vgprs = data['vgprs'][-1] if data['vgprs'] else 0
spill = data['vgpr_spill'][-1] if data['vgpr_spill'] else 0
total_vgprs = vgprs + spill
if total_vgprs <= 256:
continue
location = data['location'] or filepath
suffix = ' [IGNORED]' if ignored else ' '
message = f"{location}: {format_name(name)} - Total VGPRs: {total_vgprs} ({vgprs} + {spill}){suffix}"
blocking = RULES['vgpr_limit'] == 'blocking'
color = '91' if blocking else '93'
print(message if ignored else f'\033[{color}m{message}\033[0m') # noqa: NP100
if not ignored:
found_issues |= blocking
if rows is not None:
rows.append(('vgpr_total', name, location, 256, total_vgprs, 'regression' if blocking else 'warning'))
return int(found_issues)
def worst(values, metric):
return min(values) if metric == 'occupancy' else max(values)
def compare_metric(base, pr, names, metric, tolerance=0):
regressions = []
gains = []
for name in names:
if not base[name][metric] or not pr[name][metric]:
continue
base_val = worst(base[name][metric], metric)
pr_val = worst(pr[name][metric], metric)
if metric == 'occupancy':
if pr_val < base_val - tolerance:
regressions.append((name, base_val, pr_val))
elif pr_val > base_val:
gains.append((name, base_val, pr_val))
else:
if pr_val > base_val:
regressions.append((name, base_val, pr_val))
elif pr_val < base_val:
gains.append((name, base_val, pr_val))
return regressions, gains
def dump_tsv(path, baseline_log, pr_log, base_count, pr_count, common_count, rows):
with open(path, 'w') as f:
f.write(f'#baseline_log\t{baseline_log}\n')
f.write(f'#pr_log\t{pr_log}\n')
f.write(f'#baseline_kernels\t{base_count}\n')
f.write(f'#pr_kernels\t{pr_count}\n')
f.write(f'#kernels_compared\t{common_count}\n')
f.write('metric\tkernel\tlocation\tbaseline\tpr\tstatus\n')
for row in rows:
f.write('\t'.join(str(col) for col in row) + '\n')
def check_comparison(base, pr, baseline_log, pr_log, tolerance=0, ignored=None, dump=None):
ignored = ignored or set()
base_names = {name for name, data in base.items() if any(data[metric] for metric in METRICS)} - ignored
pr_names = {name for name, data in pr.items() if any(data[metric] for metric in METRICS)} - ignored
common = base_names & pr_names
added = pr_names - base_names
removed = base_names - pr_names
locations = {name: data['location'] for name, data in base.items()}
locations.update({name: data['location'] for name, data in pr.items()})
changes = {metric: compare_metric(base, pr, common, metric, tolerance) for metric in METRICS}
issues = [] # metric, kernel, baseline, PR, severity, extra details
for metric, rule in (('vgpr_spill', 'vgpr_spill_increase'), ('sgpr_spill', 'sgpr_spill_increase')):
for name, base_val, pr_val in changes[metric][0]:
issues.append((metric, name, base_val, pr_val, RULES[rule], ''))
for name, base_val, pr_val in changes['occupancy'][0]:
base_vgprs = worst(base[name]['vgprs'], 'vgprs') if base[name]['vgprs'] else None
pr_vgprs = worst(pr[name]['vgprs'], 'vgprs') if pr[name]['vgprs'] else None
increasing = base_vgprs is not None and pr_vgprs is not None and pr_vgprs > base_vgprs
rule = 'occupancy_vgpr_increase' if increasing else 'occupancy_drop'
detail = f', VGPRs: {base_vgprs} -> {pr_vgprs}' if increasing else ''
issues.append(('occupancy', name, base_val, pr_val, RULES[rule], detail))
print(f'Kernels compared: {len(common)} (baseline {len(base_names)}, PR {len(pr_names)})') # noqa: NP100
print(f'Added kernels: {len(added)}, removed kernels: {len(removed)}') # noqa: NP100
for severity, color, label in (('blocking', '91', 'REGRESSION'), ('warning', '93', 'WARNING')):
for metric, name, base_val, pr_val, level, detail in sorted(issues):
if level == severity:
print(f"\033[{color}m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val}{detail} ({label})\033[0m") # noqa: NP100
for metric in METRICS:
for name, base_val, pr_val in sorted(changes[metric][1]):
print(f"\033[92m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val} (improved)\033[0m") # noqa: NP100
for name in sorted(added):
print(f'note: new kernel in PR: {name}') # noqa: NP100
for name in sorted(removed):
print(f'note: kernel only in baseline: {name}') # noqa: NP100
# Check the absolute VGPR limit as well, even for kernels excluded from comparisons.
vgpr_rows = []
vgpr_failed = check_vgpr(pr, pr_log, vgpr_rows)
if dump:
rows = []
for metric, name, base_val, pr_val, severity, _ in issues:
rows.append((metric, name, locations[name], base_val, pr_val, 'regression' if severity == 'blocking' else 'warning'))
for metric in METRICS:
for name, base_val, pr_val in sorted(changes[metric][1]):
rows.append((metric, name, locations[name], base_val, pr_val, 'improved'))
rows.extend(vgpr_rows)
for name in sorted(added):
for metric in METRICS:
if pr[name][metric]:
rows.append((metric, name, locations[name], '', worst(pr[name][metric], metric), 'added'))
for name in sorted(removed):
for metric in METRICS:
if base[name][metric]:
rows.append((metric, name, locations[name], worst(base[name][metric], metric), '', 'removed'))
dump_tsv(dump, baseline_log, pr_log, len(base_names), len(pr_names), len(common), rows)
print(f'Deltas written to {dump}') # noqa: NP100
blocking = sum(severity == 'blocking' for _, _, _, _, severity, _ in issues)
warnings = sum(severity == 'warning' for _, _, _, _, severity, _ in issues)
blocking += sum(row[5] == 'regression' for row in vgpr_rows)
warnings += sum(row[5] == 'warning' for row in vgpr_rows)
if blocking or warnings:
print(f'{blocking} blocking regression(s), {warnings} warning(s)') # noqa: NP100
else:
print('No regressions found') # noqa: NP100
return int(bool(blocking or vgpr_failed))
def read_deltas(filepath):
meta = {}
rows = []
try:
with open(filepath, 'r') as f:
for line in f:
line = line.rstrip('\n')
if line.startswith('#'):
parts = line[1:].split('\t')
if len(parts) == 2:
meta[parts[0].strip()] = parts[1].strip()
continue
cols = line.split('\t')
if len(cols) == 6 and cols[0] in REPORT_METRICS:
rows.append(cols)
except FileNotFoundError:
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
sys.exit(1)
return meta, rows
def write_report(path, meta, rows):
tables = {} # (metric, status) -> list of (kernel, location, baseline, pr)
added = {} # kernel -> [location, {metric: value}]
removed = {} # kernel -> [location, {metric: value}]
for metric, kernel, location, baseline, pr, status in rows:
if status in ('regression', 'warning', 'improved'):
tables.setdefault((metric, status), []).append((kernel, location, baseline, pr))
elif status == 'added':
added.setdefault(kernel, [location, {}])[1][metric] = pr
elif status == 'removed':
removed.setdefault(kernel, [location, {}])[1][metric] = baseline
with open(path, 'w') as f:
f.write('# HIP kernel metrics comparison\n\n')
f.write(f"- Baseline: `{meta.get('baseline_log', '?')}`\n")
f.write(f"- PR: `{meta.get('pr_log', '?')}`\n\n")
f.write(f"Kernels compared: {meta.get('kernels_compared', '?')} "
f"(baseline {meta.get('baseline_kernels', '?')}, PR {meta.get('pr_kernels', '?')}). "
f"Added kernels: {len(added)}, removed kernels: {len(removed)}.\n\n")
for metric in REPORT_METRICS:
name = METRIC_NAMES[metric]
statuses = (('regression', 'regressions'), ('improved', 'improvements'))
if metric == 'occupancy':
statuses = (('regression', 'regressions'), ('warning', 'warnings'), ('improved', 'improvements'))
elif metric == 'vgpr_total':
statuses = (('regression', 'regressions'), ('warning', 'warnings'))
if metric == 'vgpr_total':
f.write('The baseline value for total VGPRs is the 256-register threshold.\n\n')
for status, title in statuses:
entries = tables.get((metric, status), [])
f.write(f'## {name} {title} ({len(entries)})\n\n')
if entries:
f.write('| Location | Kernel | Baseline | PR |\n|---|---|---|---|\n')
for kernel, location, baseline, pr in entries:
f.write(f'| {location} | `{kernel}` | {baseline} | {pr} |\n')
else:
f.write('None.\n')
f.write('\n')
for title, kernels in (('Added kernels', added), ('Removed kernels', removed)):
f.write(f'## {title} ({len(kernels)})\n\n')
if kernels:
f.write('| Location | Kernel | Occupancy | VGPRs Spill | SGPRs Spill |\n|---|---|---|---|---|\n')
for kernel in sorted(kernels):
location, values = kernels[kernel]
occupancy = values.get('occupancy', '')
vspill = values.get('vgpr_spill', '')
sspill = values.get('sgpr_spill', '')
f.write(f'| {location} | `{kernel}` | {occupancy} | {vspill} | {sspill} |\n')
else:
f.write('None.\n')
f.write('\n')
def main():
parser = argparse.ArgumentParser(description='Check HIP kernel resource usage and generate reports')
commands = parser.add_subparsers(dest='command', required=True)
vgpr = commands.add_parser('vgpr', help='check the 256 VGPR limit')
vgpr.add_argument('records', help='directory of Clang .opt.yaml files')
compare = commands.add_parser('compare', help='compare occupancy and register spills')
compare.add_argument('baseline_log', help='baseline optimization records')
compare.add_argument('pr_log', help='PR optimization records')
compare.add_argument('-t', '--tolerance', type=int, default=0, help='allowed occupancy drop in waves/SIMD')
compare.add_argument('--ignore', help='file with kernel symbols to exclude, one per line')
compare.add_argument('--dump', help='write all deltas to a TSV file')
report = commands.add_parser('report', help='generate the Markdown report from a TSV dump')
report.add_argument('deltas_tsv', help='TSV deltas from compare --dump')
report.add_argument('-o', '--output', default='hip-kernel-metrics-report.md', help='output Markdown file')
args = parser.parse_args()
try:
if args.command == 'vgpr':
return check_vgpr(parse_remarks(args.records), args.records)
if args.command == 'compare':
ignored = load_ignore_file(args.ignore) if args.ignore else set()
return check_comparison(parse_remarks(args.baseline_log), parse_remarks(args.pr_log), args.baseline_log, args.pr_log, args.tolerance, ignored, args.dump)
meta, rows = read_deltas(args.deltas_tsv)
write_report(args.output, meta, rows)
print(f'Report written to {args.output}') # noqa: NP100
return 0
except (OSError, ValueError, yaml.YAMLError) as exc:
print(f'Error: {exc}', file=sys.stderr) # noqa: NP100
return 1
if __name__ == '__main__':
sys.exit(main())
-132
View File
@@ -1,132 +0,0 @@
#!/usr/bin/env python3
import sys
from collections import defaultdict
import re
try:
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
except ImportError:
demangle = None
def format_name(name):
if demangle is None:
return name
try:
demangled = demangle(name)
except Exception:
return name
return f"{name} [{demangled}]" if demangled is not None else name
def parse_log_file(filepath):
functions = defaultdict(lambda: {'vgprs': 0, 'spill': 0, 'location': ''})
func_stack = []
try:
with open(filepath, 'r') as f:
for line in f:
# Match function name lines
func_match = re.search(r'remark: ([^:]+):(\d+):\d+: Function Name: (\S+)', line)
if func_match:
location = func_match.group(1) + ':' + func_match.group(2)
func_name = func_match.group(3)
# Extract just the filename and line number
parts = location.split('/')
short_location = parts[-1] if len(parts) > 0 else location
functions[func_name]['location'] = short_location
# Push function onto stack with its location
func_stack.append({'name': func_name, 'location': location})
continue
# Match VGPR usage lines (only if we have functions in stack)
vgpr_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs: (\d+)', line)
if vgpr_match:
location = vgpr_match.group(1) + ':' + vgpr_match.group(2)
# Find the most recent function with matching location
for i in range(len(func_stack) - 1, -1, -1):
if func_stack[i]['location'] == location:
functions[func_stack[i]['name']]['vgprs'] = int(vgpr_match.group(3))
break
continue
spill_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs Spill: (\d+)', line)
if spill_match:
location = spill_match.group(1) + ':' + spill_match.group(2)
# Find the most recent function with matching location
for i in range(len(func_stack) - 1, -1, -1):
if func_stack[i]['location'] == location:
functions[func_stack[i]['name']]['spill'] = int(spill_match.group(3))
break
continue
except FileNotFoundError:
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
sys.exit(1)
return functions
def main():
if len(sys.argv) < 2:
print("Usage: ./vgpr_check.py <log_file>", file=sys.stderr) # noqa: NP100
sys.exit(1)
log_file = sys.argv[1]
ignored = {
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
}
functions = parse_log_file(log_file)
found_issues = False
# First print all ignored functions (deduplicated)
printed_ignored = set()
for func_name, data in sorted(functions.items()):
total_vgprs = int(data['vgprs']) + int(data['spill'])
if total_vgprs > 256 and func_name in ignored and func_name not in printed_ignored:
location = data.get('location', log_file)
print(f"{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) [IGNORED]") # noqa: NP100
printed_ignored.add(func_name)
# Then print new functions with issues in red
for func_name, data in sorted(functions.items()):
total_vgprs = int(data['vgprs']) + int(data['spill'])
if total_vgprs > 256 and func_name not in ignored:
status = "[IGNORED]" if func_name in ignored else ""
location = data.get('location', log_file)
# Print in red if not ignored
color_code = "\033[91m" if func_name not in ignored else ""
reset_code = "\033[0m" if func_name not in ignored else ""
print(f"{color_code}{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) {status}{reset_code}") # noqa: NP100
if func_name not in ignored:
found_issues = True
sys.exit(1 if found_issues else 0)
if __name__ == "__main__":
main()
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
import importlib.util
import io
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
import yaml
SCRIPT = Path(__file__).with_name('gcn-cdna-metrics.py')
spec = importlib.util.spec_from_file_location('gcn_cdna_metrics', SCRIPT)
if spec is None or spec.loader is None:
raise RuntimeError(f'Cannot load {SCRIPT}')
metrics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(metrics)
def write_records(directory, filename, kernels):
path = directory / filename
path.parent.mkdir(parents=True, exist_ok=True)
with path.open('w') as f:
for name, values in kernels.items():
for key, value in values.items():
f.write('--- !Analysis\n')
yaml.safe_dump({'Pass': 'kernel-resource-usage', 'Name': key, 'Function': name,
'DebugLoc': {'File': 'wkv.cu', 'Line': 69, 'Column': 1},
'Args': [{'String': key + ': '}, {key: str(value)}]}, f, sort_keys=False)
f.write('...\n')
return path
class MetricsTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.base = self.root / 'baseline'
self.pr = self.root / 'pr'
self.base.mkdir()
self.pr.mkdir()
def compare(self, **kwargs):
with redirect_stdout(io.StringIO()) as out:
result = metrics.check_comparison(metrics.parse_remarks(self.base), metrics.parse_remarks(self.pr),
'baseline', 'PR', **kwargs)
return result, out.getvalue()
def test_same_source_location_does_not_swap_kernel_specializations(self):
write_records(self.pr, 'kernels.opt.yaml', {'_Zkernel64': {'NumVGPR': 64, 'VGPRSpill': 360},
'_Zkernel128': {'NumVGPR': 64, 'VGPRSpill': 0}})
data = metrics.parse_remarks(self.pr)
self.assertEqual(data['_Zkernel64']['vgpr_spill'], [360])
self.assertEqual(data['_Zkernel128']['vgpr_spill'], [0])
self.assertEqual(data['_Zkernel64']['location'], 'wkv.cu:69')
def test_vgpr_limit_and_allowlist(self):
write_records(self.pr, 'kernels.opt.yaml', {'bad': {'NumVGPR': 255, 'VGPRSpill': 2},
'allowed': {'NumVGPR': 256, 'VGPRSpill': 4},
'good': {'NumVGPR': 256, 'VGPRSpill': 0}})
metrics.IGNORED_VGPR.add('allowed')
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
with redirect_stdout(io.StringIO()) as out:
code = metrics.check_vgpr(metrics.parse_remarks(self.pr), 'PR')
self.assertEqual(code, 1)
self.assertIn('allowed - Total VGPRs: 260 (256 + 4) [IGNORED]', out.getvalue())
self.assertIn('bad - Total VGPRs: 257 (255 + 2)', out.getvalue())
self.assertNotIn('good - Total VGPRs', out.getvalue())
def test_occupancy_spill_regressions_and_tolerance(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 0, 'SGPRSpill': 1}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'VGPRSpill': 1, 'SGPRSpill': 0}})
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('VGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('SGPRs Spill: 1 -> 0 (improved)', output)
code, output = self.compare(tolerance=1)
self.assertEqual(code, 1)
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
def test_duplicate_kernel_uses_worst_per_metric(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 0}})
write_records(self.base, 'sub/b.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 2}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 1}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertIn('VGPRs Spill: 2 -> 1 (improved)', output)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 6 (improved)', output)
def test_added_removed_deltas_and_markdown(self):
write_records(self.base, 'a.opt.yaml', {'removed': {'Occupancy': 5, 'VGPRSpill': 2}, 'same': {'Occupancy': 4}})
write_records(self.pr, 'a.opt.yaml', {'added': {'Occupancy': 6, 'SGPRSpill': 1}, 'same': {'Occupancy': 5}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, _ = self.compare(dump=tsv)
self.assertEqual(code, 0)
self.assertIn('occupancy\tadded\twkv.cu:69\t\t6\tadded', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
result = report.read_text()
self.assertIn('# HIP kernel metrics comparison', result)
self.assertIn('## Occupancy [waves/SIMD] improvements (1)', result)
self.assertIn('## Added kernels (1)', result)
self.assertIn('## Removed kernels (1)', result)
self.assertIn('| wkv.cu:69 | ' + chr(96) + 'same' + chr(96) + ' | 4 | 5 |', result)
def test_ignore_only_comparison_not_vgpr(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 1}})
code, output = self.compare(ignored={'same'})
self.assertEqual(code, 0)
self.assertIn('Kernels compared: 0', output)
def test_vgpr_only_records_are_not_compared(self):
write_records(self.base, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 64}, 'same': {'Occupancy': 4}})
write_records(self.pr, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 128}, 'same': {'Occupancy': 4}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertIn('Kernels compared: 1 (baseline 1, PR 1)', output)
def test_occupancy_drop_with_more_vgprs_blocks(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
tsv = self.root / 'diff.tsv'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\tregression', tsv.read_text())
def test_occupancy_drop_with_fewer_vgprs_warns(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 0)
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('0 blocking regression(s), 1 warning(s)', output)
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\twarning', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
self.assertIn('## Occupancy [waves/SIMD] warnings (1)', report.read_text())
self.assertIn('| wkv.cu:69 | `same` | 5 | 4 |', report.read_text())
def test_occupancy_drop_without_vgpr_increase_warns(self):
write_records(self.base, 'a.opt.yaml', {'unchanged': {'Occupancy': 5, 'NumVGPR': 64},
'missing': {'Occupancy': 5}})
write_records(self.pr, 'a.opt.yaml', {'unchanged': {'Occupancy': 4, 'NumVGPR': 64},
'missing': {'Occupancy': 4}})
code, output = self.compare()
self.assertEqual(code, 0)
self.assertEqual(output.count('(WARNING)'), 2)
self.assertIn('0 blocking regression(s), 2 warning(s)', output)
def test_vgpr_and_sgpr_spill_increases_block_independently(self):
write_records(self.base, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 0}, 'sgpr': {'SGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 1}, 'sgpr': {'SGPRSpill': 1}})
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('vgpr - VGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('sgpr - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
def test_vgpr_limit_blocks_comparison_and_appears_in_report(self):
write_records(self.base, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 1}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
self.assertIn('vgpr_total\tsame\twkv.cu:69\t256\t257\tregression', tsv.read_text())
meta, rows = metrics.read_deltas(tsv)
metrics.write_report(report, meta, rows)
self.assertIn('## Total VGPRs (limit 256) regressions (1)', report.read_text())
self.assertIn('| wkv.cu:69 | `same` | 256 | 257 |', report.read_text())
def test_existing_vgpr_allowlist_preserves_comparison_checks(self):
write_records(self.base, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 3}})
write_records(self.pr, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 4}})
metrics.IGNORED_VGPR.add('allowed')
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
code, output = self.compare()
self.assertEqual(code, 1)
self.assertIn('Total VGPRs: 259 (255 + 4) [IGNORED]', output)
self.assertIn('VGPRs Spill: 3 -> 4 (REGRESSION)', output)
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
def test_comparison_ignore_does_not_disable_vgpr_limit(self):
write_records(self.base, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 1}})
code, output = self.compare(ignored={'ignored'})
self.assertEqual(code, 1)
self.assertIn('Kernels compared: 0 (baseline 0, PR 0)', output)
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
def test_occupancy_tolerance_applies_to_blocking_rule(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
code, output = self.compare(tolerance=1)
self.assertEqual(code, 0)
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4', output)
self.assertIn('No regressions found', output)
def test_all_rules_complete_and_return_error_after_dump(self):
write_records(self.base, 'a.opt.yaml', {'occb': {'Occupancy': 5, 'NumVGPR': 64},
'occw': {'Occupancy': 5, 'NumVGPR': 80},
'spill': {'SGPRSpill': 0}})
write_records(self.pr, 'a.opt.yaml', {'occb': {'Occupancy': 4, 'NumVGPR': 96},
'occw': {'Occupancy': 4, 'NumVGPR': 64},
'spill': {'SGPRSpill': 1}})
tsv = self.root / 'diff.tsv'
code, output = self.compare(dump=tsv)
self.assertEqual(code, 1)
self.assertIn('occb - Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
self.assertIn('occw - Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
self.assertIn('spill - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
self.assertIn('2 blocking regression(s), 1 warning(s)', output)
self.assertTrue(tsv.is_file())
def test_cli_returns_success_for_warnings_and_generates_report_after_failure(self):
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
tsv = self.root / 'diff.tsv'
report = self.root / 'report.md'
argv = ['gcn-cdna-metrics.py', 'compare', str(self.base), str(self.pr), '--dump', str(tsv)]
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 0)
self.assertIn('warning', tsv.read_text())
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 128}})
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 1)
self.assertIn('regression', tsv.read_text())
with patch('sys.argv', ['gcn-cdna-metrics.py', 'report', str(tsv), '-o', str(report)]), redirect_stdout(io.StringIO()):
self.assertEqual(metrics.main(), 0)
self.assertIn('## Occupancy [waves/SIMD] regressions (1)', report.read_text())
def test_missing_or_invalid_records_fail(self):
with self.assertRaisesRegex(ValueError, 'No optimization records'):
metrics.parse_remarks(self.pr)
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 'invalid'}})
with self.assertRaisesRegex(ValueError, 'Invalid Occupancy value'):
metrics.parse_remarks(self.pr)
if __name__ == '__main__':
unittest.main()
+232
View File
@@ -0,0 +1,232 @@
---
name: ui-demo
description: Demo, test and document a change in Llama Chat (ui/apps/chat) or Llama UI (ui/lib/ui) with the Playwright demo harness - record a video for the PR, turn the same flow into an e2e check, and capture docs videos and screenshots. Use when a UI change needs a demo video, a Playwright check, or docs media.
---
# Demo, test and document a UI change
One scripted flow serves three ends: a **demo** video in the PR, a Playwright **check** in `tests/e2e`, and **docs** media. The harness is `ui/lib/demo/`, and Llama Chat's fixtures for it are in `ui/apps/chat/demo/` (read both `README.md` files once). Everything below runs from `ui/apps/chat`.
Use it when a change in `ui/apps/chat` or `ui/lib/ui` is visible: a new or changed screen, flow or component. Skip it for refactors with no visible effect.
AGENTS.md still applies: the contributor writes the PR description and owns the script. `demo:pr` only fills the managed `## Demo` section.
## Pick the target
| Change in | Record | How |
| --------------------------------- | ---------------------- | --------------------------------------------- |
| Llama Chat flow or screen | the app, on vite dev | default |
| Llama UI component (`ui/lib/ui`) | its Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=ui` |
| Llama Chat component in isolation | Chat's Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=chat` |
A Storybook story is the harness page for a component: if none shows the state you need, add a story next to the others (`tests/stories/` in that package) rather than a new page.
## Setup (once)
```bash
cd ui/apps/chat && npm ci
```
```bash
npx playwright install chromium
```
Also `ffmpeg`, and `npm ci` in `ui/lib/ui` for Llama UI stories. `demo:pr` needs `gh` (edit rights on the PR) and, to link the video, an `hf` login plus `DEMO_STORAGE` and `DEMO_STORAGE_PUBLIC_URL` in `ui/apps/chat/.env` (see `.env.example`).
## 1. Demo
### Write the script
Scripts get `test` and `expect` from `helpers.ts`. Drive the page with `demo.*` (visible cursor, human timing), assert with `expect`, set the scene with `test.use`:
- `demo.click`, `demo.hover`, `demo.type`, `demo.press`, `demo.scroll`, `demo.pause`, `demo.caption(text, ms)` (a chip under the window), `demo.zoom(target, scale, ms)` (the camera moves onto a small detail and back), `demo.zoomIn(target, scale)` ... `demo.zoomOut()` (the camera stays on it across the actions between).
- `test.use({ settings: {...} })` seeds UI settings, `startPath: '/#/...'` starts on a route.
- Fixtures, so no real data or third-party server is needed:
- **MCP servers:** two fixture servers (Weather, Notes) are always configured; see `demo/fixtures/demo-config.ts`.
- **Conversations:** `traces: ['long-chat', 'agentic-debugging']` imports built-in chats (`demo/fixtures/traces.ts`); other names come from `DEMO_TRACES_DATASET`.
- **Models and replies:** `mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'Markdown **reply**' }` answers llama-server's endpoints in the browser (`demo/fixtures/llama-server.ts`): the model list, props, load, tools and a streamed reply. Nothing reaches a server and no model loads. Use it for any demo that sends a message.
- **Stories:** `story: 'ui-forms-switch--default'`, the id from the Storybook URL (`?path=/story/<id>`).
Without `mockServer` the app talks to the llama-server at `DEMO_SERVER_ORIGIN` (default `:9931`, started from `build/bin/llama-server` when none runs). Sending a message there loads a model: do not do that on someone's running server without asking.
### Shape the video
The video is rendered from the recording, not the raw screencast: the app in a window on a Llama brand ground, camera moves over the whole stage with motion blur, captions under the window, and on a touch viewport taps in place of the cursor (see "The render" in the harness README). Write for that:
- **One thing per video.** A PR that changes several things gets several short `test()`s, not one long walk.
- **Captions** are in the brand's voice: plain words, real numbers, no emoji, one line. `demo.caption(text, ms)` holds the caption for `ms` and the demo waits, so show it while the screen is still (before or after an action, not over one). A demo with no captions gets no caption row, and the window is larger.
- **Zooms** are for a detail too small to read in the frame. The camera aims where the target is when the zoom starts and does not follow it, so zoom after the layout settles (wait with `expect` first), and zoom out before an action that moves the target, such as sending a message. Zoom on desktop demos; a phone's UI already fills a portrait video, so leave phone demos unzoomed unless a detail is too small to read even there.
- **Phones:** `test.use({ hasTouch: true, isMobile: true, viewport: { height: 844, width: 390 } })` gives a 1080x1920 video with a phone's corners, and every click shows as a fingertip tap.
- **Dark mode:** `test.use({ colorScheme: 'dark' })` records the dark theme on the night sky.
- **Timing:** the harness adds the render's time to the test's timeout after the demo, so a demo needs no long `test.setTimeout`.
`DEMO_POLISH_LOGO=end` adds a Llama logo card, for a video that goes out on its own; `DEMO_POLISH=0` gives the plain screencast.
### Try it locally
Save it as `demo/<name>.demo.ts` (git-ignored), importing from `./helpers.ts`, and run:
```bash
npm run demo:record -- demo/<name>
```
Add `DEMO_STORYBOOK=ui` (or `chat`) when the script has a `story`. `DEMO_POLISH=0` records faster while iterating (the render takes a few times the video's length). The mp4 lands in `demo/videos/`. Look at it before going further: a sheet of frames shows the whole flow, the camera moves and the captions at once, where one still frame misses most of it:
```bash
ffmpeg -loglevel error -i demo/videos/<name>.mp4 -vf "fps=2,scale=480:-1,tile=6x4" -frames:v 1 demo/videos/<name>-sheet.png
```
Check that each caption is readable and on screen long enough, that every zoom lands on its detail, and that nothing is cut off at the window's edge.
`npm run demo:codegen` opens Playwright codegen on `:5180` for a first draft of the selectors.
### Put it in the PR
Paste the script into the PR description as a `ts demo` block, inside the last collapsible block of Additional information:
````md
<details>
<summary>Demo script</summary>
```ts demo
test("demo", async ({ demo, page }) => {
// ...
});
```
</details>
````
Push the branch first: `demo:pr` records the PR's head commit as GitHub has it. Then record it and write the `## Demo` section (between `<!-- demo:start -->` and `<!-- demo:end -->`):
```bash
npm run demo:pr -- <number>
```
It takes a few minutes, so run it in the background. The app's UI comes from the PR's head, in a temporary worktree, but the harness and fixtures come from your checkout: a PR that changes the harness itself is recorded with the harness you have checked out. Run it again after each push that changes what the videos show.
- Each `test()` becomes its own video, shown in a table under its title. Give each test `{ annotation: { type: 'description', description: '...' } }` to get one video to a row with its description beside it, which reads better when the videos show different things (see the worked example). Group tests with their own `test.use` in `test.describe(() => { ... })`.
- In a PR block, the helpers import is replaced with `test` and `expect`, so reach fixtures through `test.use` options only.
- A PR on a fork: `DEMO_GITHUB_REPO=<owner>/llama.cpp`. A PR by someone else: read its diff and demo block, then pass `--trust <sha>`.
## 2. Test
Turn the same flow into a check in `tests/e2e/<feature>.e2e.ts`, which CI runs (`npm run test:e2e`) against the built app on `:8181`, with no llama-server:
- `@playwright/test` instead of the helpers: `locator.click()` / `fill()` for `demo.*`, keep every `expect`, drop captions and pauses.
- `mockLlamaServer(page, {...})` before `page.goto`, since nothing serves the API.
- `importTraces(page, file)` and `generateTrace(name)` seed conversations, as in a demo.
```bash
npx playwright test tests/e2e/<feature>.e2e.ts
```
Locally it uses the installed Chrome with its sandbox on; in CI, Playwright's Chromium.
For a component on its own, a `play` function on its story is the check instead (as in `ui/apps/chat/tests/stories/app/PwaRefreshAlert.stories.svelte`): both packages run their stories as vitest browser tests, `npm run test:ui` in `ui/apps/chat` and `npm test` in `ui/lib/ui`.
## 3. Document
- **Docs videos:** put the script in the storage target as `scripts/docs/<name>.demo.ts` (import `'../helpers.ts'`), then `npm run demo:docs` records every docs script and uploads `videos/docs/<name>.{mp4,gif}`. `DEMO_STORAGE=file:///some/dir` tries it without a bucket.
- **Screenshots:** in any demo, `await page.screenshot({ path: 'demo/videos/<name>.png' })` for the frame, or `await locator.screenshot({ path })` for one component, rendered at `DEMO_SCALE` (2x by default). Paths are relative to `ui/apps/chat`.
- **Component docs** belong in the package's Storybook: a story per state, prose in a `.svx` page (see `ui/apps/chat/AGENTS.md`).
## Worked example
A demo of chat search, then a reply from the mocked server, then a Llama UI story, in one PR block, each video with its description beside it in the `## Demo` table (record with `DEMO_STORYBOOK=ui npm run demo:pr -- <number>`):
```ts
const describe = (description: string) => ({
annotation: { description, type: "description" },
});
test.describe(() => {
test.use({ traces: ["long-chat", "agentic-debugging"] });
test(
"Search finds a chat by its title",
describe(
"Typing a word from a chat's title lists it, and opening the result shows the conversation.",
),
async ({ demo, page }) => {
await demo.click(page.getByLabel("Expand navigation"));
await demo.click(page.getByRole("button", { name: /^Search/ }));
const search = page.getByRole("dialog", { name: "Search" });
await demo.type(
search.getByRole("combobox", { name: "Search" }),
"flaky",
);
const result = search.getByRole("option", {
name: /Fix the flaky cache tests/,
});
await expect(result).toBeVisible();
await demo.click(result, 1200);
await expect(page.getByRole("main")).toContainText(
"All 48 cache tests pass now",
);
},
);
});
test.describe(() => {
test.use({
mockServer: {
reply: "Rust is a systems language focused on **safety** and *speed*.",
},
});
test(
"A reply from a mocked server, no model loaded",
describe(
"The reply streams from mockServer, so the video looks the same on every machine.",
),
async ({ demo, page }) => {
await demo.type(
page.getByRole("textbox", { name: "Type a message..." }),
"What is Rust?",
);
await demo.press("Enter", 1500);
await expect(page.getByRole("main")).toContainText(
"focused on safety",
);
},
);
});
test.describe(() => {
// a small viewport frames a small component, recorded at the same scale
test.use({
story: "ui-forms-switch--default",
viewport: { height: 450, width: 720 },
});
test(
"A Llama UI story: Switch",
describe(
"The Switch from Llama UI, recorded from its Storybook story.",
),
async ({ demo, page }) => {
const off = page.getByRole("switch").first();
await demo.click(off, 900);
await expect(off).toBeChecked();
},
);
});
```
The same search flow as a check is `tests/e2e/search-chats.e2e.ts`.
## Pitfalls
- **Ports:** vite dev `:5180` (`DEMO_UI_PORT`), fixture MCP `:8765`, llama-server `:9931`, Storybook `:6007` (`DEMO_STORYBOOK_PORT`), e2e `:8181`. Every server is reused when something already answers there, even another checkout's: stop stale servers, or pick other ports. `demo:pr` picks free ports itself.
- **Chrome sandbox:** demos record in Playwright's bundled Chromium with the sandbox on (headless installed Chrome ignores the viewport in screencasts); local e2e runs in the installed Chrome with the sandbox on. Do not turn the sandbox off to make a run pass: a PR demo runs that PR's code.
- **Waits:** wait on state, never on time. `expect(locator).toBeVisible()` / `toContainText()` before acting on something that appears late; `demo.pause` is pacing for the viewer only. The first load of a cold dev server reloads the page once; the harness waits for it before recording, so do not add sleeps for it.
- **Selectors:** use roles and accessible names. Some names match twice (`Expand navigation` is both the logo and the button: use `page.getByLabel('Expand navigation')`); scope to a dialog with `page.getByRole('dialog', { name })`. A strict-mode error names both matches.
- **Real server:** without `mockServer`, the model list and any reply come from the real llama-server and differ per machine. Mock them for anything a viewer should see the same way twice.
- **Preview size:** keep a demo short (under ~20 s per test): the GIF preview must stay under 5 MB, so a long one is shrunk until it is hard to read.
- **Chromium only:** the screencast and the render run on the Chrome DevTools Protocol, so a demo in Firefox or WebKit fails at its start. Show a Safari-only fix with a check in `tests/e2e`, not a demo.
+7 -6
View File
@@ -450,12 +450,13 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
{ LLM_KV_NORM_BEFORE_RESIDUAL, "%s.norm_before_residual" },
{ LLM_KV_NORM_BEFORE_FC, "%s.norm_before_fc" },
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
{ LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, "%s.selector_softcap_after_correction" },
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
{ LLM_KV_LILICORR_HIDDEN_SIZE, "lilicorr.hidden_size" },
{ LLM_KV_LILICORR_CANDIDATE_TOPK, "lilicorr.candidate_topk" },
+1
View File
@@ -501,6 +501,7 @@ enum llm_kv {
LLM_KV_DFLASH_CONV_GROUP_SIZE,
LLM_KV_DFLASH_SELECTOR_RANK,
LLM_KV_DFLASH_SELECTOR_TOP_K,
LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION,
LLM_KV_DFLASH_HAS_MARKOV_CONTEXT,
LLM_KV_LILICORR_HIDDEN_SIZE,
LLM_KV_LILICORR_CANDIDATE_TOPK,
+1
View File
@@ -305,6 +305,7 @@ struct llama_hparams {
uint32_t dflash_conv_group_size = 0;
uint32_t dflash_selector_rank = 0;
uint32_t dflash_selector_top_k = 0;
bool dflash_softcap_post = false; // DFlash2 softcaps the selector scores instead of the logits
bool dspark_f_rnn = false; // rnn markov head reads f_rnn from embd_state
uint32_t lilicorr_hidden_size = 0;
uint32_t lilicorr_candidate_topk = 0;
+6 -5
View File
@@ -189,7 +189,8 @@ ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
out = ggml_silu(ctx0, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
out = ggml_silu(ctx0, out);
out = ggml_reshape_2d(ctx0, out, d_inner, n_tokens);
return ggml_reshape_4d(ctx0, out, head_dim, n_head, n_seq_tokens, n_seqs);
}
@@ -264,15 +265,15 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
ggml_tensor * state = build_rs(inp_rs, states_all, hparams.n_embd_s(), n_seqs);
state = ggml_reshape_4d(ctx0, state, head_dim, head_dim, n_head, n_seqs);
ggml_tensor * out = ggml_cont(ctx0, build_recurrent_attn(
inp_rs, states_all, q, k, v, gate, beta, state, il));
ggml_tensor * out = build_recurrent_attn(
inp_rs, states_all, q, k, v, gate, beta, state, il);
ggml_tensor * out_gate = ggml_mul_mat(ctx0, layer.ssm_g_a, cur);
out_gate = ggml_reshape_3d(ctx0, out_gate, head_dim, n_head, n_tokens);
out = ggml_reshape_3d(ctx0, out, head_dim, n_head, n_tokens);
out = build_norm(out, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il);
out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, out_gate));
cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, out, d_inner, n_tokens));
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
cb(cur, "kda_out", il);
} else {
ggml_tensor * attn_input = cur;
@@ -322,7 +323,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
attn_gate = ggml_sigmoid(ctx0, ggml_reshape_3d(ctx0, attn_gate, 1, n_head, n_tokens));
cur = ggml_reshape_3d(ctx0, cur, v_head_dim, n_head, n_tokens);
cur = ggml_mul(ctx0, cur, attn_gate);
cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
cb(cur, "mla_out", il);
}
+5 -1
View File
@@ -47,6 +47,7 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) {
}
} else if (has_selector) {
variant = VARIANT_DFLASH2;
ml.get_key(LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, hparams.dflash_softcap_post, false);
} else if (has_lilicorr) {
variant = VARIANT_LILICORR;
load_hparams_lilicorr(ml);
@@ -447,6 +448,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
ggml_tensor * inpL = model.dspark_mask_embd
? build_dspark_inp_block(*this, model, inp_tokens)
: ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens);
if (model.tok_norm && !model.dspark_mask_embd) {
inpL = build_norm(inpL, model.tok_norm, nullptr, LLM_NORM_RMS, -1);
}
if (hparams.f_embedding_scale != 0.0f) {
inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale);
}
@@ -569,7 +573,7 @@ ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) {
if (hparams.f_logit_scale != 0.0f) {
cur = ggml_scale(ctx0, cur, hparams.f_logit_scale);
}
if (hparams.f_final_logit_softcapping > 0.0f) {
if (hparams.f_final_logit_softcapping > 0.0f && !hparams.dflash_softcap_post) {
cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
cur = ggml_tanh(ctx0, cur);
cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
+4
View File
@@ -177,6 +177,10 @@ static void build_dflash2_selector(llm_graph_context & g, const llama_model & mo
}
ggml_tensor * unary_bcast = ggml_reshape_4d(ctx0, unary_run, top_k, 1, n_pos, n_blocks);
score = ggml_add(ctx0, score, ggml_repeat(ctx0, unary_bcast, score));
if (hparams.dflash_softcap_post && hparams.f_final_logit_softcapping > 0.0f) {
const float cap = hparams.f_final_logit_softcapping;
score = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, score, 1.0f / cap)), cap);
}
ggml_tensor * row = ggml_concat(ctx0,
ggml_cast(ctx0, cand_run, GGML_TYPE_F32),
+12 -1
View File
@@ -220,6 +220,11 @@ ggml_tensor * llama_model_inkling2::graph::convolve(
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
const int64_t n_seqs = ubatch.n_seqs;
// add the taps input first and the result right after the state store, so the conv ops are consecutive and backends can fuse them
if (dynamic) {
ggml_build_forward_expand(gf, dynamic);
}
ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]);
ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs));
@@ -248,7 +253,10 @@ ggml_tensor * llama_model_inkling2::graph::convolve(
}
}
return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1));
out = ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1));
ggml_build_forward_expand(gf, out);
return out;
}
// mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message
@@ -275,6 +283,7 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() {
tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f);
tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY));
tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens);
ggml_build_forward_expand(gf, tau);
ggml_tensor * cur = build_inp_embd(model.tok_embd);
@@ -390,6 +399,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens
blocks.push_back(inpSA);
} else {
cur = ggml_add(ctx0, inpSA, cur);
ggml_build_forward_expand(gf, cur); // right after the conv, so backends can fuse the add into it
}
ggml_tensor * ffn_inp = cur;
@@ -421,6 +431,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens
cb(cur, "ffn_out", il);
cur = ggml_add(ctx0, ffn_inp, cur);
ggml_build_forward_expand(gf, cur);
cb(cur, "l_out", il);
return cur;
+191 -191
View File
@@ -5,9 +5,9 @@ afmoe ,1 ,any ,RMS_NORM+MUL , 10
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
arcee ,0 ,any ,RMS_NORM+MUL , 5
arctic ,0 ,any ,MUL+ADD , 4
arctic ,0 ,any ,RMS_NORM+MUL , 7
arctic ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
arctic ,1 ,any ,MUL+ADD , 4
arctic ,1 ,any ,RMS_NORM+MUL , 7
arctic ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
baichuan ,0 ,any ,RMS_NORM+MUL , 5
bailingmoe ,1 ,any ,ADD+ADD , 2
bailingmoe ,1 ,any ,MUL+ADD , 4
@@ -23,8 +23,8 @@ bailingmoe3 ,1 ,any ,MUL+ADD , 2
bailingmoe3 ,1 ,any ,RMS_NORM+MUL , 8
bailingmoe3 ,1 ,any ,RMS_NORM+SCALE , 2
bailingmoe3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
beam ,0 ,any ,MUL+ADD , 6
beam ,0 ,any ,RMS_NORM+MUL , 25
beam ,1 ,any ,MUL+ADD , 6
beam ,1 ,any ,RMS_NORM+MUL , 25
bloom ,0 ,any ,NORM+MUL+ADD , 6
chatglm ,0 ,any ,RMS_NORM+MUL , 5
clover_moe ,1 ,any ,ADD+ADD , 2
@@ -43,45 +43,45 @@ cohere2moe ,1 ,any ,MUL+ADD , 2
cohere2moe ,1 ,any ,RMS_NORM+MUL , 3
command-r ,0 ,any ,ADD+ADD , 2
command-r ,0 ,any ,NORM+MUL , 3
dbrx ,0 ,any ,MUL+ADD , 4
dbrx ,0 ,any ,NORM+MUL , 5
dbrx ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
dbrx ,1 ,any ,MUL+ADD , 4
dbrx ,1 ,any ,NORM+MUL , 5
dbrx ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
deci ,0 ,any ,RMS_NORM+MUL , 5
deepseek ,0 ,any ,ADD+ADD , 1
deepseek ,0 ,any ,MUL+ADD , 2
deepseek ,0 ,any ,RMS_NORM+MUL , 5
deepseek ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1
deepseek2 ,0 ,any ,ADD+ADD , 1
deepseek2 ,0 ,any ,MUL+ADD , 2
deepseek2 ,0 ,any ,RMS_NORM+MUL , 9
deepseek2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
deepseek32 ,0 ,any ,ADD+ADD , 1
deepseek32 ,0 ,any ,MUL+ADD , 2
deepseek32 ,0 ,any ,NORM+MUL+ADD , 2
deepseek32 ,0 ,any ,RMS_NORM+MUL , 9
deepseek32 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
deepseek4 ,0 ,any ,MUL+ADD , 8
deepseek4 ,0 ,any ,RMS_NORM+MUL , 20
deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4
deepseek41 ,0 ,any ,MUL+ADD , 12
deepseek41 ,0 ,any ,RMS_NORM+MUL , 31
deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6
deepseek ,1 ,any ,ADD+ADD , 1
deepseek ,1 ,any ,MUL+ADD , 2
deepseek ,1 ,any ,RMS_NORM+MUL , 5
deepseek ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1
deepseek2 ,1 ,any ,ADD+ADD , 1
deepseek2 ,1 ,any ,MUL+ADD , 2
deepseek2 ,1 ,any ,RMS_NORM+MUL , 9
deepseek2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
deepseek32 ,1 ,any ,ADD+ADD , 1
deepseek32 ,1 ,any ,MUL+ADD , 2
deepseek32 ,1 ,any ,NORM+MUL+ADD , 2
deepseek32 ,1 ,any ,RMS_NORM+MUL , 9
deepseek32 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
deepseek4 ,1 ,any ,MUL+ADD , 8
deepseek4 ,1 ,any ,RMS_NORM+MUL , 20
deepseek4 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4
deepseek41 ,1 ,any ,MUL+ADD , 12
deepseek41 ,1 ,any ,RMS_NORM+MUL , 31
deepseek41 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6
domynedge ,0 ,any ,RMS_NORM+MUL , 8
domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3
dots1 ,0 ,any ,ADD+ADD , 1
dots1 ,0 ,any ,MUL+ADD , 2
dots1 ,0 ,any ,RMS_NORM+MUL , 9
dots1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
dots3note ,0 ,any ,ADD+ADD , 1
dots3note ,0 ,any ,MUL+ADD , 2
dots3note ,0 ,any ,NORM+MUL+ADD , 1
dots3note ,0 ,any ,RMS_NORM+MUL , 11
dots3note ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
dots1 ,1 ,any ,ADD+ADD , 1
dots1 ,1 ,any ,MUL+ADD , 2
dots1 ,1 ,any ,RMS_NORM+MUL , 9
dots1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
dots3note ,1 ,any ,ADD+ADD , 1
dots3note ,1 ,any ,MUL+ADD , 2
dots3note ,1 ,any ,NORM+MUL+ADD , 1
dots3note ,1 ,any ,RMS_NORM+MUL , 11
dots3note ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
dream ,0 ,any ,RMS_NORM+MUL , 5
ernie4_5-moe ,1 ,any ,ADD+ADD , 1
ernie4_5-moe ,1 ,any ,MUL+ADD , 2
ernie4_5-moe ,1 ,any ,RMS_NORM+MUL , 5
ernie4_5 ,0 ,any ,RMS_NORM+MUL , 5
ernie4_5 ,1 ,any ,RMS_NORM+MUL , 5
exaone ,0 ,any ,RMS_NORM+MUL , 5
exaone-moe ,1 ,any ,ADD+ADD , 1
exaone-moe ,1 ,any ,MUL+ADD , 2
@@ -93,10 +93,10 @@ falcon ,0 ,any ,ADD+ADD , 2
falcon ,0 ,any ,NORM+MUL+ADD , 5
falcon-h1 ,0 ,any ,ADD+ADD , 2
falcon-h1 ,0 ,any ,RMS_NORM+MUL , 9
flint ,0 ,any ,ADD+ADD , 1
flint ,0 ,any ,MUL+ADD , 2
flint ,0 ,any ,RMS_NORM+MUL , 9
flint ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
flint ,1 ,any ,ADD+ADD , 1
flint ,1 ,any ,MUL+ADD , 2
flint ,1 ,any ,RMS_NORM+MUL , 9
flint ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
gemma ,0 ,any ,RMS_NORM+MUL , 5
gemma2 ,0 ,any ,RMS_NORM+MUL , 5
gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
@@ -104,42 +104,42 @@ gemma3 ,0 ,any ,RMS_NORM+MUL , 9
gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4
gemma4 ,0 ,any ,RMS_NORM+MUL , 37
gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 30
glm-dsa ,0 ,any ,ADD+ADD , 1
glm-dsa ,0 ,any ,MUL+ADD , 2
glm-dsa ,0 ,any ,NORM+MUL+ADD , 2
glm-dsa ,0 ,any ,RMS_NORM+MUL , 9
glm-dsa ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
glm-dsa ,1 ,any ,ADD+ADD , 1
glm-dsa ,1 ,any ,MUL+ADD , 2
glm-dsa ,1 ,any ,NORM+MUL+ADD , 2
glm-dsa ,1 ,any ,RMS_NORM+MUL , 9
glm-dsa ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
glm4 ,0 ,any ,RMS_NORM+MUL , 5
glm4 ,0 ,any ,RMS_NORM+MUL+ADD , 4
glm4moe ,1 ,any ,ADD+ADD , 1
glm4moe ,1 ,any ,MUL+ADD , 2
glm4moe ,1 ,any ,RMS_NORM+MUL , 9
glm4moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
glm5-next ,0 ,any ,ADD+ADD+ADD , 1
glm5-next ,0 ,any ,GATED_DELTA_NET+CPY , 1
glm5-next ,0 ,any ,MUL+ADD , 2
glm5-next ,0 ,any ,NORM+MUL+ADD , 1
glm5-next ,0 ,any ,RMS_NORM+MUL , 8
glm5-next ,0 ,any ,RMS_NORM+SCALE , 2
glm5-next ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
gpt-oss ,0 ,any ,MUL+ADD , 4
gpt-oss ,0 ,any ,RMS_NORM+MUL , 5
glm5-next ,1 ,any ,ADD+ADD+ADD , 1
glm5-next ,1 ,any ,GATED_DELTA_NET+CPY , 1
glm5-next ,1 ,any ,MUL+ADD , 2
glm5-next ,1 ,any ,NORM+MUL+ADD , 1
glm5-next ,1 ,any ,RMS_NORM+MUL , 8
glm5-next ,1 ,any ,RMS_NORM+SCALE , 2
glm5-next ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
gpt-oss ,1 ,any ,MUL+ADD , 4
gpt-oss ,1 ,any ,RMS_NORM+MUL , 5
gpt2 ,0 ,any ,NORM+MUL+ADD , 5
gptneox ,0 ,any ,NORM+MUL+ADD , 5
granite ,0 ,any ,RMS_NORM+MUL , 5
granite ,0 ,any ,MUL+ADD , 4
granite ,0 ,any ,RMS_NORM+MUL , 5
granite ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
granite ,1 ,any ,MUL+ADD , 4
granite ,1 ,any ,RMS_NORM+MUL , 5
granite ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
granite_swa ,0 ,any ,RMS_NORM+MUL , 5
granitehybrid ,0 ,any ,RMS_NORM+MUL , 6
granitemoe ,1 ,any ,RMS_NORM+MUL , 5
granitemoe ,0 ,any ,RMS_NORM+MUL , 5
granitemoe ,1 ,any ,MUL+ADD , 4
granitemoe ,1 ,any ,RMS_NORM+MUL , 5
granitemoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
grok ,0 ,any ,MUL+ADD , 4
grok ,0 ,any ,RMS_NORM+MUL , 5
grok ,0 ,any ,RMS_NORM+MUL+ADD , 4
grok ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
grok ,1 ,any ,MUL+ADD , 4
grok ,1 ,any ,RMS_NORM+MUL , 5
grok ,1 ,any ,RMS_NORM+MUL+ADD , 4
grok ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
grovemoe ,1 ,any ,ADD+ADD , 2
grovemoe ,1 ,any ,MUL+ADD , 8
grovemoe ,1 ,any ,RMS_NORM+MUL , 9
@@ -149,53 +149,53 @@ hunyuan-moe ,1 ,any ,MUL+ADD , 4
hunyuan-moe ,1 ,any ,RMS_NORM+MUL , 9
hunyuan-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
hunyuan_vl ,0 ,any ,RMS_NORM+MUL , 9
hy_v3 ,0 ,any ,ADD+ADD , 2
hy_v3 ,0 ,any ,MUL+ADD , 4
hy_v3 ,0 ,any ,RMS_NORM+MUL , 9
hy_v3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2
hy_v4 ,0 ,any ,MUL+ADD , 2
hy_v4 ,0 ,any ,NORM+MUL+ADD , 1
hy_v4 ,0 ,any ,RMS_NORM+MUL , 9
hy_v4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
hy_v4_flash ,0 ,any ,MUL+ADD , 6
hy_v4_flash ,0 ,any ,RMS_NORM+MUL , 32
hy_v4_flash ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3
inkling2 ,0 ,any ,MUL+ADD , 6
inkling2 ,0 ,any ,RMS_NORM+MUL , 10
inkling2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3
hy_v3 ,1 ,any ,ADD+ADD , 2
hy_v3 ,1 ,any ,MUL+ADD , 4
hy_v3 ,1 ,any ,RMS_NORM+MUL , 9
hy_v3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2
hy_v4 ,1 ,any ,MUL+ADD , 2
hy_v4 ,1 ,any ,NORM+MUL+ADD , 1
hy_v4 ,1 ,any ,RMS_NORM+MUL , 9
hy_v4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
hy_v4_flash ,1 ,any ,MUL+ADD , 6
hy_v4_flash ,1 ,any ,RMS_NORM+MUL , 32
hy_v4_flash ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3
inkling2 ,1 ,any ,MUL+ADD , 6
inkling2 ,1 ,any ,RMS_NORM+MUL , 10
inkling2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3
internlm2 ,0 ,any ,RMS_NORM+MUL , 5
jais ,0 ,any ,NORM+MUL+ADD , 5
jais2 ,0 ,any ,NORM+MUL+ADD , 5
jamba ,0 ,any ,RMS_NORM+MUL , 8
k2-horizon ,0 ,any ,RMS_NORM+MUL , 4
k2-horizon ,0 ,any ,ADD+ADD , 1
k2-horizon ,0 ,any ,MUL+ADD , 2
k2-horizon ,0 ,any ,RMS_NORM+MUL , 4
k2-horizon ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-k3 ,0 ,any ,GATED_DELTA_NET+CPY , 1
kimi-k3 ,0 ,any ,MUL+ADD , 2
kimi-k3 ,0 ,any ,RMS_NORM+MUL , 17
kimi-k3 ,0 ,any ,RMS_NORM+SCALE , 2
kimi-k3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-k31 ,0 ,any ,GATED_DELTA_NET+CPY , 1
kimi-k31 ,0 ,any ,MUL+ADD , 2
kimi-k31 ,0 ,any ,NORM+MUL+ADD , 1
kimi-k31 ,0 ,any ,RMS_NORM+MUL , 17
kimi-k31 ,0 ,any ,RMS_NORM+SCALE , 2
kimi-k31 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-linear ,0 ,any ,ADD+ADD , 1
kimi-linear ,0 ,any ,GATED_DELTA_NET+CPY , 1
kimi-linear ,0 ,any ,MUL+ADD , 2
kimi-linear ,0 ,any ,RMS_NORM+MUL , 7
kimi-linear ,0 ,any ,RMS_NORM+SCALE , 2
kimi-linear ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
kolibri1 ,0 ,any ,MUL+ADD , 4
kolibri1 ,0 ,any ,RMS_NORM+MUL , 10
kolibri1 ,0 ,any ,RMS_NORM+MUL+ADD , 3
laguna ,0 ,any ,ADD+ADD , 1
laguna ,0 ,any ,MUL+ADD , 2
laguna ,0 ,any ,RMS_NORM+MUL , 9
laguna ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
k2-horizon ,1 ,any ,ADD+ADD , 1
k2-horizon ,1 ,any ,MUL+ADD , 2
k2-horizon ,1 ,any ,RMS_NORM+MUL , 4
k2-horizon ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-k3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
kimi-k3 ,1 ,any ,MUL+ADD , 2
kimi-k3 ,1 ,any ,RMS_NORM+MUL , 17
kimi-k3 ,1 ,any ,RMS_NORM+SCALE , 2
kimi-k3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-k31 ,1 ,any ,GATED_DELTA_NET+CPY , 1
kimi-k31 ,1 ,any ,MUL+ADD , 2
kimi-k31 ,1 ,any ,NORM+MUL+ADD , 1
kimi-k31 ,1 ,any ,RMS_NORM+MUL , 17
kimi-k31 ,1 ,any ,RMS_NORM+SCALE , 2
kimi-k31 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
kimi-linear ,1 ,any ,ADD+ADD , 1
kimi-linear ,1 ,any ,GATED_DELTA_NET+CPY , 1
kimi-linear ,1 ,any ,MUL+ADD , 2
kimi-linear ,1 ,any ,RMS_NORM+MUL , 7
kimi-linear ,1 ,any ,RMS_NORM+SCALE , 2
kimi-linear ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
kolibri1 ,1 ,any ,MUL+ADD , 4
kolibri1 ,1 ,any ,RMS_NORM+MUL , 10
kolibri1 ,1 ,any ,RMS_NORM+MUL+ADD , 3
laguna ,1 ,any ,ADD+ADD , 1
laguna ,1 ,any ,MUL+ADD , 2
laguna ,1 ,any ,RMS_NORM+MUL , 9
laguna ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
lfm2 ,0 ,any ,RMS_NORM+MUL , 7
lfm2moe ,1 ,any ,MUL+ADD , 2
lfm2moe ,1 ,any ,RMS_NORM+MUL , 7
@@ -207,69 +207,69 @@ llada-moe ,1 ,any ,MUL+ADD , 4
llada-moe ,1 ,any ,RMS_NORM+MUL , 9
llada-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
llama ,0 ,any ,RMS_NORM+MUL , 5
llama ,0 ,any ,MUL+ADD , 4
llama ,0 ,any ,RMS_NORM+MUL , 5
llama ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
llama4 ,0 ,any ,ADD+ADD , 2
llama4 ,0 ,any ,MUL+ADD , 4
llama4 ,0 ,any ,RMS_NORM+MUL , 9
llama ,1 ,any ,MUL+ADD , 4
llama ,1 ,any ,RMS_NORM+MUL , 5
llama ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
llama4 ,1 ,any ,ADD+ADD , 2
llama4 ,1 ,any ,MUL+ADD , 4
llama4 ,1 ,any ,RMS_NORM+MUL , 9
maincoder ,0 ,any ,RMS_NORM+MUL , 9
maion-coder ,0 ,any ,MUL+ADD , 4
maion-coder ,0 ,any ,RMS_NORM+MUL , 17
maion-coder ,0 ,any ,RMS_NORM+MUL+ADD , 8
maion-coder ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
maion-coder ,1 ,any ,MUL+ADD , 4
maion-coder ,1 ,any ,RMS_NORM+MUL , 17
maion-coder ,1 ,any ,RMS_NORM+MUL+ADD , 8
maion-coder ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
mamba ,0 ,any ,RMS_NORM+MUL , 3
mamba2 ,0 ,any ,RMS_NORM+MUL , 5
maple ,0 ,any ,MUL+ADD , 4
maple ,0 ,any ,RMS_NORM+MUL , 9
maple ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
mellum ,0 ,any ,MUL+ADD , 4
mellum ,0 ,any ,RMS_NORM+MUL , 9
mellum ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
metis16 ,0 ,any ,MUL+ADD , 8
metis16 ,0 ,any ,RMS_NORM+MUL , 11
mimo2 ,0 ,any ,MUL+ADD , 4
mimo2 ,0 ,any ,RMS_NORM+MUL , 5
mimo2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
maple ,1 ,any ,MUL+ADD , 4
maple ,1 ,any ,RMS_NORM+MUL , 9
maple ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
mellum ,1 ,any ,MUL+ADD , 4
mellum ,1 ,any ,RMS_NORM+MUL , 9
mellum ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
metis16 ,1 ,any ,MUL+ADD , 8
metis16 ,1 ,any ,RMS_NORM+MUL , 11
mimo2 ,1 ,any ,MUL+ADD , 4
mimo2 ,1 ,any ,RMS_NORM+MUL , 5
mimo2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minicpm ,0 ,any ,RMS_NORM+MUL , 5
minicpm ,0 ,any ,MUL+ADD , 4
minicpm ,0 ,any ,RMS_NORM+MUL , 5
minicpm ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minicpm ,1 ,any ,MUL+ADD , 4
minicpm ,1 ,any ,RMS_NORM+MUL , 5
minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minicpm3 ,0 ,any ,RMS_NORM+MUL , 9
minimax-01 ,0 ,any ,MUL+ADD , 4
minimax-01 ,0 ,any ,RMS_NORM+MUL , 6
minimax-01 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minimax-m2 ,0 ,any ,MUL+ADD , 4
minimax-m2 ,0 ,any ,RMS_NORM+MUL , 9
minimax-m2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minimax-m3 ,0 ,any ,ADD+ADD , 1
minimax-m3 ,0 ,any ,MUL+ADD , 2
minimax-m3 ,0 ,any ,RMS_NORM+MUL , 11
minimax-m3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
mistral-large4 ,0 ,any ,ADD+ADD , 3
mistral-large4 ,0 ,any ,MUL+ADD , 6
mistral-large4 ,0 ,any ,NORM+MUL+ADD , 6
mistral-large4 ,0 ,any ,RMS_NORM+MUL , 12
minimax-01 ,1 ,any ,MUL+ADD , 4
minimax-01 ,1 ,any ,RMS_NORM+MUL , 6
minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minimax-m2 ,1 ,any ,MUL+ADD , 4
minimax-m2 ,1 ,any ,RMS_NORM+MUL , 9
minimax-m2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
minimax-m3 ,1 ,any ,ADD+ADD , 1
minimax-m3 ,1 ,any ,MUL+ADD , 2
minimax-m3 ,1 ,any ,RMS_NORM+MUL , 11
minimax-m3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
mistral-large4 ,1 ,any ,ADD+ADD , 3
mistral-large4 ,1 ,any ,MUL+ADD , 6
mistral-large4 ,1 ,any ,NORM+MUL+ADD , 6
mistral-large4 ,1 ,any ,RMS_NORM+MUL , 12
mistral3 ,0 ,any ,RMS_NORM+MUL , 5
mistral3 ,0 ,any ,MUL+ADD , 4
mistral3 ,0 ,any ,RMS_NORM+MUL , 5
mistral3 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
mistral4 ,0 ,any ,ADD+ADD , 1
mistral4 ,0 ,any ,MUL+ADD , 2
mistral4 ,0 ,any ,RMS_NORM+MUL , 9
mistral4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
mistral3 ,1 ,any ,MUL+ADD , 4
mistral3 ,1 ,any ,RMS_NORM+MUL , 5
mistral3 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
mistral4 ,1 ,any ,ADD+ADD , 1
mistral4 ,1 ,any ,MUL+ADD , 2
mistral4 ,1 ,any ,RMS_NORM+MUL , 9
mistral4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
moshi ,0 ,any ,RMS_NORM+MUL , 5
mpt ,0 ,any ,NORM+MUL+ADD , 5
muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10
muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3
muse-spark ,0 ,any ,MUL+ADD , 4
muse-spark ,0 ,any ,RMS_NORM+MUL , 11
muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3
muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
muse-spark ,1 ,any ,MUL+ADD , 4
muse-spark ,1 ,any ,RMS_NORM+MUL , 11
muse-spark ,1 ,any ,RMS_NORM+MUL+ADD , 3
muse-spark ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
nanbeige ,0 ,any ,RMS_NORM+MUL , 5
nemotron ,0 ,any ,NORM+MUL+ADD , 5
nemotron_h ,0 ,any ,RMS_NORM+MUL , 5
nemotron_h_moe ,1 ,any ,RMS_NORM+MUL , 5
nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5
olmo2 ,0 ,any ,RMS_NORM+MUL , 5
olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
olmoe ,1 ,any ,MUL+ADD , 4
@@ -277,7 +277,7 @@ olmoe ,1 ,any ,RMS_NORM+MUL , 9
olmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
openelm ,0 ,any ,RMS_NORM+MUL , 9
orion ,0 ,any ,NORM+MUL+ADD , 5
paddleocr ,0 ,any ,RMS_NORM+MUL , 5
paddleocr ,1 ,any ,RMS_NORM+MUL , 5
pangu-embedded ,0 ,any ,RMS_NORM+MUL , 5
phi2 ,0 ,any ,ADD+ADD , 2
phi2 ,0 ,any ,NORM+MUL+ADD , 3
@@ -315,40 +315,40 @@ qwen35moe ,1 ,any ,SSM_CONV+UNARY , 1
qwen3moe ,1 ,any ,MUL+ADD , 4
qwen3moe ,1 ,any ,RMS_NORM+MUL , 9
qwen3moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen3next ,0 ,any ,ADD+ADD , 2
qwen3next ,0 ,any ,GATED_DELTA_NET+CPY , 1
qwen3next ,0 ,any ,MUL+ADD , 4
qwen3next ,0 ,any ,RMS_NORM+MUL , 8
qwen3next ,0 ,any ,RMS_NORM+SCALE , 2
qwen3next ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen3next ,0 ,any ,SSM_CONV+UNARY , 1
qwen3next ,1 ,any ,ADD+ADD , 2
qwen3next ,1 ,any ,GATED_DELTA_NET+CPY , 1
qwen3next ,1 ,any ,MUL+ADD , 4
qwen3next ,1 ,any ,RMS_NORM+MUL , 8
qwen3next ,1 ,any ,RMS_NORM+SCALE , 2
qwen3next ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen3next ,1 ,any ,SSM_CONV+UNARY , 1
qwen3tts ,0 ,any ,RMS_NORM+MUL , 9
qwen3vl ,0 ,any ,RMS_NORM+MUL , 9
qwen3vlmoe ,1 ,any ,MUL+ADD , 4
qwen3vlmoe ,1 ,any ,RMS_NORM+MUL , 9
qwen3vlmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen4exp ,0 ,any ,ADD+ADD+ADD , 2
qwen4exp ,0 ,any ,GATED_DELTA_NET+CPY , 1
qwen4exp ,0 ,any ,MUL+ADD , 4
qwen4exp ,0 ,any ,RMS_NORM+MUL , 13
qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2
qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1
raon1 ,0 ,any ,ADD+ADD+ADD , 1
raon1 ,0 ,any ,GATED_DELTA_NET+CPY , 1
raon1 ,0 ,any ,MUL+ADD , 2
raon1 ,0 ,any ,RMS_NORM+MUL , 8
raon1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
refact ,0 ,any ,RMS_NORM+MUL , 5
qwen4exp ,1 ,any ,ADD+ADD+ADD , 2
qwen4exp ,1 ,any ,GATED_DELTA_NET+CPY , 1
qwen4exp ,1 ,any ,MUL+ADD , 4
qwen4exp ,1 ,any ,RMS_NORM+MUL , 13
qwen4exp ,1 ,any ,RMS_NORM+SCALE , 2
qwen4exp ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
qwen4exp ,1 ,any ,SSM_CONV+UNARY , 1
raon1 ,1 ,any ,ADD+ADD+ADD , 1
raon1 ,1 ,any ,GATED_DELTA_NET+CPY , 1
raon1 ,1 ,any ,MUL+ADD , 2
raon1 ,1 ,any ,RMS_NORM+MUL , 8
raon1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
refact ,0 ,any ,RMS_NORM+MUL , 5
refact ,1 ,any ,RMS_NORM+MUL , 5
ricursive ,0 ,any ,RMS_NORM+MUL , 9
ricursive ,0 ,any ,RMS_NORM+MUL+ADD , 4
rnd1 ,0 ,any ,MUL+ADD , 4
rnd1 ,0 ,any ,RMS_NORM+MUL , 9
rnd1 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
rnd1 ,1 ,any ,MUL+ADD , 4
rnd1 ,1 ,any ,RMS_NORM+MUL , 9
rnd1 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
seed_oss ,0 ,any ,RMS_NORM+MUL , 5
smallthinker ,0 ,any ,MUL+ADD , 4
smallthinker ,0 ,any ,RMS_NORM+MUL , 5
smallthinker ,1 ,any ,MUL+ADD , 4
smallthinker ,1 ,any ,RMS_NORM+MUL , 5
smollm3 ,0 ,any ,RMS_NORM+MUL , 5
spark2_5 ,0 ,any ,RMS_NORM+MUL , 5
stablelm ,0 ,any ,NORM+MUL , 4
@@ -356,14 +356,14 @@ stablelm ,0 ,any ,NORM+MUL+ADD , 5
starcoder ,0 ,any ,NORM+MUL+ADD , 5
starcoder2 ,0 ,any ,NORM+MUL+ADD , 5
talkie ,0 ,any ,ADD+ADD , 2
xing4_0 ,0 ,any ,ADD+ADD+ADD , 1
xing4_0 ,0 ,any ,MUL+ADD , 2
xing4_0 ,0 ,any ,RMS_NORM+MUL , 9
xing4_0 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
xing4_0 ,1 ,any ,ADD+ADD+ADD , 1
xing4_0 ,1 ,any ,MUL+ADD , 2
xing4_0 ,1 ,any ,RMS_NORM+MUL , 9
xing4_0 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
xverse ,0 ,any ,RMS_NORM+MUL , 5
zaya1 ,0 ,any ,RMS_NORM+MUL , 7
zonos3 ,0 ,any ,GATED_DELTA_NET+CPY , 1
zonos3 ,0 ,any ,MUL+ADD , 2
zonos3 ,0 ,any ,RMS_NORM+MUL , 12
zonos3 ,0 ,any ,RMS_NORM+SCALE , 2
zonos3 ,0 ,any ,SSM_CONV+UNARY , 1
zaya1 ,1 ,any ,RMS_NORM+MUL , 7
zonos3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
zonos3 ,1 ,any ,MUL+ADD , 2
zonos3 ,1 ,any ,RMS_NORM+MUL , 12
zonos3 ,1 ,any ,RMS_NORM+SCALE , 2
zonos3 ,1 ,any ,SSM_CONV+UNARY , 1
1 # test-fusion baseline for device MTL
5 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
6 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
7 arcee ,0 ,any ,RMS_NORM+MUL , 5
8 arctic ,0 ,any ,MUL+ADD , 4 arctic ,1 ,any ,MUL+ADD , 4
9 arctic ,0 ,any ,RMS_NORM+MUL , 7 arctic ,1 ,any ,RMS_NORM+MUL , 7
10 arctic ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 arctic ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
11 baichuan ,0 ,any ,RMS_NORM+MUL , 5
12 bailingmoe ,1 ,any ,ADD+ADD , 2
13 bailingmoe ,1 ,any ,MUL+ADD , 4
23 bailingmoe3 ,1 ,any ,RMS_NORM+MUL , 8
24 bailingmoe3 ,1 ,any ,RMS_NORM+SCALE , 2
25 bailingmoe3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
26 beam ,0 ,any ,MUL+ADD , 6 beam ,1 ,any ,MUL+ADD , 6
27 beam ,0 ,any ,RMS_NORM+MUL , 25 beam ,1 ,any ,RMS_NORM+MUL , 25
28 bloom ,0 ,any ,NORM+MUL+ADD , 6
29 chatglm ,0 ,any ,RMS_NORM+MUL , 5
30 clover_moe ,1 ,any ,ADD+ADD , 2
43 cohere2moe ,1 ,any ,RMS_NORM+MUL , 3
44 command-r ,0 ,any ,ADD+ADD , 2
45 command-r ,0 ,any ,NORM+MUL , 3
46 dbrx ,0 ,any ,MUL+ADD , 4 dbrx ,1 ,any ,MUL+ADD , 4
47 dbrx ,0 ,any ,NORM+MUL , 5 dbrx ,1 ,any ,NORM+MUL , 5
48 dbrx ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 dbrx ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
49 deci ,0 ,any ,RMS_NORM+MUL , 5
50 deepseek ,0 ,any ,ADD+ADD , 1 deepseek ,1 ,any ,ADD+ADD , 1
51 deepseek ,0 ,any ,MUL+ADD , 2 deepseek ,1 ,any ,MUL+ADD , 2
52 deepseek ,0 ,any ,RMS_NORM+MUL , 5 deepseek ,1 ,any ,RMS_NORM+MUL , 5
53 deepseek ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1 deepseek ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1
54 deepseek2 ,0 ,any ,ADD+ADD , 1 deepseek2 ,1 ,any ,ADD+ADD , 1
55 deepseek2 ,0 ,any ,MUL+ADD , 2 deepseek2 ,1 ,any ,MUL+ADD , 2
56 deepseek2 ,0 ,any ,RMS_NORM+MUL , 9 deepseek2 ,1 ,any ,RMS_NORM+MUL , 9
57 deepseek2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 deepseek2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
58 deepseek32 ,0 ,any ,ADD+ADD , 1 deepseek32 ,1 ,any ,ADD+ADD , 1
59 deepseek32 ,0 ,any ,MUL+ADD , 2 deepseek32 ,1 ,any ,MUL+ADD , 2
60 deepseek32 ,0 ,any ,NORM+MUL+ADD , 2 deepseek32 ,1 ,any ,NORM+MUL+ADD , 2
61 deepseek32 ,0 ,any ,RMS_NORM+MUL , 9 deepseek32 ,1 ,any ,RMS_NORM+MUL , 9
62 deepseek32 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 deepseek32 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
63 deepseek4 ,0 ,any ,MUL+ADD , 8 deepseek4 ,1 ,any ,MUL+ADD , 8
64 deepseek4 ,0 ,any ,RMS_NORM+MUL , 20 deepseek4 ,1 ,any ,RMS_NORM+MUL , 20
65 deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4 deepseek4 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4
66 deepseek41 ,0 ,any ,MUL+ADD , 12 deepseek41 ,1 ,any ,MUL+ADD , 12
67 deepseek41 ,0 ,any ,RMS_NORM+MUL , 31 deepseek41 ,1 ,any ,RMS_NORM+MUL , 31
68 deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 deepseek41 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6
69 domynedge ,0 ,any ,RMS_NORM+MUL , 8
70 domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3
71 dots1 ,0 ,any ,ADD+ADD , 1 dots1 ,1 ,any ,ADD+ADD , 1
72 dots1 ,0 ,any ,MUL+ADD , 2 dots1 ,1 ,any ,MUL+ADD , 2
73 dots1 ,0 ,any ,RMS_NORM+MUL , 9 dots1 ,1 ,any ,RMS_NORM+MUL , 9
74 dots1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 dots1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
75 dots3note ,0 ,any ,ADD+ADD , 1 dots3note ,1 ,any ,ADD+ADD , 1
76 dots3note ,0 ,any ,MUL+ADD , 2 dots3note ,1 ,any ,MUL+ADD , 2
77 dots3note ,0 ,any ,NORM+MUL+ADD , 1 dots3note ,1 ,any ,NORM+MUL+ADD , 1
78 dots3note ,0 ,any ,RMS_NORM+MUL , 11 dots3note ,1 ,any ,RMS_NORM+MUL , 11
79 dots3note ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 dots3note ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
80 dream ,0 ,any ,RMS_NORM+MUL , 5
81 ernie4_5-moe ,1 ,any ,ADD+ADD , 1
82 ernie4_5-moe ,1 ,any ,MUL+ADD , 2
83 ernie4_5-moe ,1 ,any ,RMS_NORM+MUL , 5
84 ernie4_5 ,0 ,any ,RMS_NORM+MUL , 5 ernie4_5 ,1 ,any ,RMS_NORM+MUL , 5
85 exaone ,0 ,any ,RMS_NORM+MUL , 5
86 exaone-moe ,1 ,any ,ADD+ADD , 1
87 exaone-moe ,1 ,any ,MUL+ADD , 2
93 falcon ,0 ,any ,NORM+MUL+ADD , 5
94 falcon-h1 ,0 ,any ,ADD+ADD , 2
95 falcon-h1 ,0 ,any ,RMS_NORM+MUL , 9
96 flint ,0 ,any ,ADD+ADD , 1 flint ,1 ,any ,ADD+ADD , 1
97 flint ,0 ,any ,MUL+ADD , 2 flint ,1 ,any ,MUL+ADD , 2
98 flint ,0 ,any ,RMS_NORM+MUL , 9 flint ,1 ,any ,RMS_NORM+MUL , 9
99 flint ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 flint ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
100 gemma ,0 ,any ,RMS_NORM+MUL , 5
101 gemma2 ,0 ,any ,RMS_NORM+MUL , 5
102 gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
104 gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4
105 gemma4 ,0 ,any ,RMS_NORM+MUL , 37
106 gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 30
107 glm-dsa ,0 ,any ,ADD+ADD , 1 glm-dsa ,1 ,any ,ADD+ADD , 1
108 glm-dsa ,0 ,any ,MUL+ADD , 2 glm-dsa ,1 ,any ,MUL+ADD , 2
109 glm-dsa ,0 ,any ,NORM+MUL+ADD , 2 glm-dsa ,1 ,any ,NORM+MUL+ADD , 2
110 glm-dsa ,0 ,any ,RMS_NORM+MUL , 9 glm-dsa ,1 ,any ,RMS_NORM+MUL , 9
111 glm-dsa ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 glm-dsa ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
112 glm4 ,0 ,any ,RMS_NORM+MUL , 5
113 glm4 ,0 ,any ,RMS_NORM+MUL+ADD , 4
114 glm4moe ,1 ,any ,ADD+ADD , 1
115 glm4moe ,1 ,any ,MUL+ADD , 2
116 glm4moe ,1 ,any ,RMS_NORM+MUL , 9
117 glm4moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
118 glm5-next ,0 ,any ,ADD+ADD+ADD , 1 glm5-next ,1 ,any ,ADD+ADD+ADD , 1
119 glm5-next ,0 ,any ,GATED_DELTA_NET+CPY , 1 glm5-next ,1 ,any ,GATED_DELTA_NET+CPY , 1
120 glm5-next ,0 ,any ,MUL+ADD , 2 glm5-next ,1 ,any ,MUL+ADD , 2
121 glm5-next ,0 ,any ,NORM+MUL+ADD , 1 glm5-next ,1 ,any ,NORM+MUL+ADD , 1
122 glm5-next ,0 ,any ,RMS_NORM+MUL , 8 glm5-next ,1 ,any ,RMS_NORM+MUL , 8
123 glm5-next ,0 ,any ,RMS_NORM+SCALE , 2 glm5-next ,1 ,any ,RMS_NORM+SCALE , 2
124 glm5-next ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 glm5-next ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
125 gpt-oss ,0 ,any ,MUL+ADD , 4 gpt-oss ,1 ,any ,MUL+ADD , 4
126 gpt-oss ,0 ,any ,RMS_NORM+MUL , 5 gpt-oss ,1 ,any ,RMS_NORM+MUL , 5
127 gpt2 ,0 ,any ,NORM+MUL+ADD , 5
128 gptneox ,0 ,any ,NORM+MUL+ADD , 5
129 granite ,0 ,any ,RMS_NORM+MUL , 5
130 granite ,0 ,any ,MUL+ADD , 4 granite ,1 ,any ,MUL+ADD , 4
131 granite ,0 ,any ,RMS_NORM+MUL , 5 granite ,1 ,any ,RMS_NORM+MUL , 5
132 granite ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 granite ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
133 granite_swa ,0 ,any ,RMS_NORM+MUL , 5
134 granitehybrid ,0 ,any ,RMS_NORM+MUL , 6
135 granitemoe ,1 ,any ,RMS_NORM+MUL , 5 granitemoe ,0 ,any ,RMS_NORM+MUL , 5
136 granitemoe ,1 ,any ,MUL+ADD , 4
137 granitemoe ,1 ,any ,RMS_NORM+MUL , 5
138 granitemoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
139 grok ,0 ,any ,MUL+ADD , 4 grok ,1 ,any ,MUL+ADD , 4
140 grok ,0 ,any ,RMS_NORM+MUL , 5 grok ,1 ,any ,RMS_NORM+MUL , 5
141 grok ,0 ,any ,RMS_NORM+MUL+ADD , 4 grok ,1 ,any ,RMS_NORM+MUL+ADD , 4
142 grok ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 grok ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
143 grovemoe ,1 ,any ,ADD+ADD , 2
144 grovemoe ,1 ,any ,MUL+ADD , 8
145 grovemoe ,1 ,any ,RMS_NORM+MUL , 9
149 hunyuan-moe ,1 ,any ,RMS_NORM+MUL , 9
150 hunyuan-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
151 hunyuan_vl ,0 ,any ,RMS_NORM+MUL , 9
152 hy_v3 ,0 ,any ,ADD+ADD , 2 hy_v3 ,1 ,any ,ADD+ADD , 2
153 hy_v3 ,0 ,any ,MUL+ADD , 4 hy_v3 ,1 ,any ,MUL+ADD , 4
154 hy_v3 ,0 ,any ,RMS_NORM+MUL , 9 hy_v3 ,1 ,any ,RMS_NORM+MUL , 9
155 hy_v3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2 hy_v3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2
156 hy_v4 ,0 ,any ,MUL+ADD , 2 hy_v4 ,1 ,any ,MUL+ADD , 2
157 hy_v4 ,0 ,any ,NORM+MUL+ADD , 1 hy_v4 ,1 ,any ,NORM+MUL+ADD , 1
158 hy_v4 ,0 ,any ,RMS_NORM+MUL , 9 hy_v4 ,1 ,any ,RMS_NORM+MUL , 9
159 hy_v4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 hy_v4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
160 hy_v4_flash ,0 ,any ,MUL+ADD , 6 hy_v4_flash ,1 ,any ,MUL+ADD , 6
161 hy_v4_flash ,0 ,any ,RMS_NORM+MUL , 32 hy_v4_flash ,1 ,any ,RMS_NORM+MUL , 32
162 hy_v4_flash ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3 hy_v4_flash ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3
163 inkling2 ,0 ,any ,MUL+ADD , 6 inkling2 ,1 ,any ,MUL+ADD , 6
164 inkling2 ,0 ,any ,RMS_NORM+MUL , 10 inkling2 ,1 ,any ,RMS_NORM+MUL , 10
165 inkling2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3 inkling2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3
166 internlm2 ,0 ,any ,RMS_NORM+MUL , 5
167 jais ,0 ,any ,NORM+MUL+ADD , 5
168 jais2 ,0 ,any ,NORM+MUL+ADD , 5
169 jamba ,0 ,any ,RMS_NORM+MUL , 8
170 k2-horizon ,0 ,any ,RMS_NORM+MUL , 4
171 k2-horizon ,0 ,any ,ADD+ADD , 1 k2-horizon ,1 ,any ,ADD+ADD , 1
172 k2-horizon ,0 ,any ,MUL+ADD , 2 k2-horizon ,1 ,any ,MUL+ADD , 2
173 k2-horizon ,0 ,any ,RMS_NORM+MUL , 4 k2-horizon ,1 ,any ,RMS_NORM+MUL , 4
174 k2-horizon ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 k2-horizon ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
175 kimi-k3 ,0 ,any ,GATED_DELTA_NET+CPY , 1 kimi-k3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
176 kimi-k3 ,0 ,any ,MUL+ADD , 2 kimi-k3 ,1 ,any ,MUL+ADD , 2
177 kimi-k3 ,0 ,any ,RMS_NORM+MUL , 17 kimi-k3 ,1 ,any ,RMS_NORM+MUL , 17
178 kimi-k3 ,0 ,any ,RMS_NORM+SCALE , 2 kimi-k3 ,1 ,any ,RMS_NORM+SCALE , 2
179 kimi-k3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 kimi-k3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
180 kimi-k31 ,0 ,any ,GATED_DELTA_NET+CPY , 1 kimi-k31 ,1 ,any ,GATED_DELTA_NET+CPY , 1
181 kimi-k31 ,0 ,any ,MUL+ADD , 2 kimi-k31 ,1 ,any ,MUL+ADD , 2
182 kimi-k31 ,0 ,any ,NORM+MUL+ADD , 1 kimi-k31 ,1 ,any ,NORM+MUL+ADD , 1
183 kimi-k31 ,0 ,any ,RMS_NORM+MUL , 17 kimi-k31 ,1 ,any ,RMS_NORM+MUL , 17
184 kimi-k31 ,0 ,any ,RMS_NORM+SCALE , 2 kimi-k31 ,1 ,any ,RMS_NORM+SCALE , 2
185 kimi-k31 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 kimi-k31 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
186 kimi-linear ,0 ,any ,ADD+ADD , 1 kimi-linear ,1 ,any ,ADD+ADD , 1
187 kimi-linear ,0 ,any ,GATED_DELTA_NET+CPY , 1 kimi-linear ,1 ,any ,GATED_DELTA_NET+CPY , 1
188 kimi-linear ,0 ,any ,MUL+ADD , 2 kimi-linear ,1 ,any ,MUL+ADD , 2
189 kimi-linear ,0 ,any ,RMS_NORM+MUL , 7 kimi-linear ,1 ,any ,RMS_NORM+MUL , 7
190 kimi-linear ,0 ,any ,RMS_NORM+SCALE , 2 kimi-linear ,1 ,any ,RMS_NORM+SCALE , 2
191 kimi-linear ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 kimi-linear ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
192 kolibri1 ,0 ,any ,MUL+ADD , 4 kolibri1 ,1 ,any ,MUL+ADD , 4
193 kolibri1 ,0 ,any ,RMS_NORM+MUL , 10 kolibri1 ,1 ,any ,RMS_NORM+MUL , 10
194 kolibri1 ,0 ,any ,RMS_NORM+MUL+ADD , 3 kolibri1 ,1 ,any ,RMS_NORM+MUL+ADD , 3
195 laguna ,0 ,any ,ADD+ADD , 1 laguna ,1 ,any ,ADD+ADD , 1
196 laguna ,0 ,any ,MUL+ADD , 2 laguna ,1 ,any ,MUL+ADD , 2
197 laguna ,0 ,any ,RMS_NORM+MUL , 9 laguna ,1 ,any ,RMS_NORM+MUL , 9
198 laguna ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 laguna ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
199 lfm2 ,0 ,any ,RMS_NORM+MUL , 7
200 lfm2moe ,1 ,any ,MUL+ADD , 2
201 lfm2moe ,1 ,any ,RMS_NORM+MUL , 7
207 llada-moe ,1 ,any ,RMS_NORM+MUL , 9
208 llada-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
209 llama ,0 ,any ,RMS_NORM+MUL , 5
210 llama ,0 ,any ,MUL+ADD , 4 llama ,1 ,any ,MUL+ADD , 4
211 llama ,0 ,any ,RMS_NORM+MUL , 5 llama ,1 ,any ,RMS_NORM+MUL , 5
212 llama ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 llama ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
213 llama4 ,0 ,any ,ADD+ADD , 2 llama4 ,1 ,any ,ADD+ADD , 2
214 llama4 ,0 ,any ,MUL+ADD , 4 llama4 ,1 ,any ,MUL+ADD , 4
215 llama4 ,0 ,any ,RMS_NORM+MUL , 9 llama4 ,1 ,any ,RMS_NORM+MUL , 9
216 maincoder ,0 ,any ,RMS_NORM+MUL , 9
217 maion-coder ,0 ,any ,MUL+ADD , 4 maion-coder ,1 ,any ,MUL+ADD , 4
218 maion-coder ,0 ,any ,RMS_NORM+MUL , 17 maion-coder ,1 ,any ,RMS_NORM+MUL , 17
219 maion-coder ,0 ,any ,RMS_NORM+MUL+ADD , 8 maion-coder ,1 ,any ,RMS_NORM+MUL+ADD , 8
220 maion-coder ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 maion-coder ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
221 mamba ,0 ,any ,RMS_NORM+MUL , 3
222 mamba2 ,0 ,any ,RMS_NORM+MUL , 5
223 maple ,0 ,any ,MUL+ADD , 4 maple ,1 ,any ,MUL+ADD , 4
224 maple ,0 ,any ,RMS_NORM+MUL , 9 maple ,1 ,any ,RMS_NORM+MUL , 9
225 maple ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 maple ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
226 mellum ,0 ,any ,MUL+ADD , 4 mellum ,1 ,any ,MUL+ADD , 4
227 mellum ,0 ,any ,RMS_NORM+MUL , 9 mellum ,1 ,any ,RMS_NORM+MUL , 9
228 mellum ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 mellum ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
229 metis16 ,0 ,any ,MUL+ADD , 8 metis16 ,1 ,any ,MUL+ADD , 8
230 metis16 ,0 ,any ,RMS_NORM+MUL , 11 metis16 ,1 ,any ,RMS_NORM+MUL , 11
231 mimo2 ,0 ,any ,MUL+ADD , 4 mimo2 ,1 ,any ,MUL+ADD , 4
232 mimo2 ,0 ,any ,RMS_NORM+MUL , 5 mimo2 ,1 ,any ,RMS_NORM+MUL , 5
233 mimo2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 mimo2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
234 minicpm ,0 ,any ,RMS_NORM+MUL , 5
235 minicpm ,0 ,any ,MUL+ADD , 4 minicpm ,1 ,any ,MUL+ADD , 4
236 minicpm ,0 ,any ,RMS_NORM+MUL , 5 minicpm ,1 ,any ,RMS_NORM+MUL , 5
237 minicpm ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
238 minicpm3 ,0 ,any ,RMS_NORM+MUL , 9
239 minimax-01 ,0 ,any ,MUL+ADD , 4 minimax-01 ,1 ,any ,MUL+ADD , 4
240 minimax-01 ,0 ,any ,RMS_NORM+MUL , 6 minimax-01 ,1 ,any ,RMS_NORM+MUL , 6
241 minimax-01 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
242 minimax-m2 ,0 ,any ,MUL+ADD , 4 minimax-m2 ,1 ,any ,MUL+ADD , 4
243 minimax-m2 ,0 ,any ,RMS_NORM+MUL , 9 minimax-m2 ,1 ,any ,RMS_NORM+MUL , 9
244 minimax-m2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 minimax-m2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
245 minimax-m3 ,0 ,any ,ADD+ADD , 1 minimax-m3 ,1 ,any ,ADD+ADD , 1
246 minimax-m3 ,0 ,any ,MUL+ADD , 2 minimax-m3 ,1 ,any ,MUL+ADD , 2
247 minimax-m3 ,0 ,any ,RMS_NORM+MUL , 11 minimax-m3 ,1 ,any ,RMS_NORM+MUL , 11
248 minimax-m3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 minimax-m3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
249 mistral-large4 ,0 ,any ,ADD+ADD , 3 mistral-large4 ,1 ,any ,ADD+ADD , 3
250 mistral-large4 ,0 ,any ,MUL+ADD , 6 mistral-large4 ,1 ,any ,MUL+ADD , 6
251 mistral-large4 ,0 ,any ,NORM+MUL+ADD , 6 mistral-large4 ,1 ,any ,NORM+MUL+ADD , 6
252 mistral-large4 ,0 ,any ,RMS_NORM+MUL , 12 mistral-large4 ,1 ,any ,RMS_NORM+MUL , 12
253 mistral3 ,0 ,any ,RMS_NORM+MUL , 5
254 mistral3 ,0 ,any ,MUL+ADD , 4 mistral3 ,1 ,any ,MUL+ADD , 4
255 mistral3 ,0 ,any ,RMS_NORM+MUL , 5 mistral3 ,1 ,any ,RMS_NORM+MUL , 5
256 mistral3 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 mistral3 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
257 mistral4 ,0 ,any ,ADD+ADD , 1 mistral4 ,1 ,any ,ADD+ADD , 1
258 mistral4 ,0 ,any ,MUL+ADD , 2 mistral4 ,1 ,any ,MUL+ADD , 2
259 mistral4 ,0 ,any ,RMS_NORM+MUL , 9 mistral4 ,1 ,any ,RMS_NORM+MUL , 9
260 mistral4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 mistral4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
261 moshi ,0 ,any ,RMS_NORM+MUL , 5
262 mpt ,0 ,any ,NORM+MUL+ADD , 5
263 muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10
264 muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3
265 muse-spark ,0 ,any ,MUL+ADD , 4 muse-spark ,1 ,any ,MUL+ADD , 4
266 muse-spark ,0 ,any ,RMS_NORM+MUL , 11 muse-spark ,1 ,any ,RMS_NORM+MUL , 11
267 muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3 muse-spark ,1 ,any ,RMS_NORM+MUL+ADD , 3
268 muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 muse-spark ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
269 nanbeige ,0 ,any ,RMS_NORM+MUL , 5
270 nemotron ,0 ,any ,NORM+MUL+ADD , 5
271 nemotron_h ,0 ,any ,RMS_NORM+MUL , 5
272 nemotron_h_moe ,1 ,any ,RMS_NORM+MUL , 5 nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5
273 olmo2 ,0 ,any ,RMS_NORM+MUL , 5
274 olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
275 olmoe ,1 ,any ,MUL+ADD , 4
277 olmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
278 openelm ,0 ,any ,RMS_NORM+MUL , 9
279 orion ,0 ,any ,NORM+MUL+ADD , 5
280 paddleocr ,0 ,any ,RMS_NORM+MUL , 5 paddleocr ,1 ,any ,RMS_NORM+MUL , 5
281 pangu-embedded ,0 ,any ,RMS_NORM+MUL , 5
282 phi2 ,0 ,any ,ADD+ADD , 2
283 phi2 ,0 ,any ,NORM+MUL+ADD , 3
315 qwen3moe ,1 ,any ,MUL+ADD , 4
316 qwen3moe ,1 ,any ,RMS_NORM+MUL , 9
317 qwen3moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
318 qwen3next ,0 ,any ,ADD+ADD , 2 qwen3next ,1 ,any ,ADD+ADD , 2
319 qwen3next ,0 ,any ,GATED_DELTA_NET+CPY , 1 qwen3next ,1 ,any ,GATED_DELTA_NET+CPY , 1
320 qwen3next ,0 ,any ,MUL+ADD , 4 qwen3next ,1 ,any ,MUL+ADD , 4
321 qwen3next ,0 ,any ,RMS_NORM+MUL , 8 qwen3next ,1 ,any ,RMS_NORM+MUL , 8
322 qwen3next ,0 ,any ,RMS_NORM+SCALE , 2 qwen3next ,1 ,any ,RMS_NORM+SCALE , 2
323 qwen3next ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 qwen3next ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
324 qwen3next ,0 ,any ,SSM_CONV+UNARY , 1 qwen3next ,1 ,any ,SSM_CONV+UNARY , 1
325 qwen3tts ,0 ,any ,RMS_NORM+MUL , 9
326 qwen3vl ,0 ,any ,RMS_NORM+MUL , 9
327 qwen3vlmoe ,1 ,any ,MUL+ADD , 4
328 qwen3vlmoe ,1 ,any ,RMS_NORM+MUL , 9
329 qwen3vlmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
330 qwen4exp ,0 ,any ,ADD+ADD+ADD , 2 qwen4exp ,1 ,any ,ADD+ADD+ADD , 2
331 qwen4exp ,0 ,any ,GATED_DELTA_NET+CPY , 1 qwen4exp ,1 ,any ,GATED_DELTA_NET+CPY , 1
332 qwen4exp ,0 ,any ,MUL+ADD , 4 qwen4exp ,1 ,any ,MUL+ADD , 4
333 qwen4exp ,0 ,any ,RMS_NORM+MUL , 13 qwen4exp ,1 ,any ,RMS_NORM+MUL , 13
334 qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2 qwen4exp ,1 ,any ,RMS_NORM+SCALE , 2
335 qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 qwen4exp ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
336 qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1 qwen4exp ,1 ,any ,SSM_CONV+UNARY , 1
337 raon1 ,0 ,any ,ADD+ADD+ADD , 1 raon1 ,1 ,any ,ADD+ADD+ADD , 1
338 raon1 ,0 ,any ,GATED_DELTA_NET+CPY , 1 raon1 ,1 ,any ,GATED_DELTA_NET+CPY , 1
339 raon1 ,0 ,any ,MUL+ADD , 2 raon1 ,1 ,any ,MUL+ADD , 2
340 raon1 ,0 ,any ,RMS_NORM+MUL , 8 raon1 ,1 ,any ,RMS_NORM+MUL , 8
341 raon1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1 raon1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
refact ,0 ,any ,RMS_NORM+MUL , 5
342 refact ,0 ,any ,RMS_NORM+MUL , 5
343 refact ,1 ,any ,RMS_NORM+MUL , 5
344 ricursive ,0 ,any ,RMS_NORM+MUL , 9
345 ricursive ,0 ,any ,RMS_NORM+MUL+ADD , 4
346 rnd1 ,0 ,any ,MUL+ADD , 4 rnd1 ,1 ,any ,MUL+ADD , 4
347 rnd1 ,0 ,any ,RMS_NORM+MUL , 9 rnd1 ,1 ,any ,RMS_NORM+MUL , 9
348 rnd1 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 rnd1 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
349 seed_oss ,0 ,any ,RMS_NORM+MUL , 5
350 smallthinker ,0 ,any ,MUL+ADD , 4 smallthinker ,1 ,any ,MUL+ADD , 4
351 smallthinker ,0 ,any ,RMS_NORM+MUL , 5 smallthinker ,1 ,any ,RMS_NORM+MUL , 5
352 smollm3 ,0 ,any ,RMS_NORM+MUL , 5
353 spark2_5 ,0 ,any ,RMS_NORM+MUL , 5
354 stablelm ,0 ,any ,NORM+MUL , 4
356 starcoder ,0 ,any ,NORM+MUL+ADD , 5
357 starcoder2 ,0 ,any ,NORM+MUL+ADD , 5
358 talkie ,0 ,any ,ADD+ADD , 2
359 xing4_0 ,0 ,any ,ADD+ADD+ADD , 1 xing4_0 ,1 ,any ,ADD+ADD+ADD , 1
360 xing4_0 ,0 ,any ,MUL+ADD , 2 xing4_0 ,1 ,any ,MUL+ADD , 2
361 xing4_0 ,0 ,any ,RMS_NORM+MUL , 9 xing4_0 ,1 ,any ,RMS_NORM+MUL , 9
362 xing4_0 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 xing4_0 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
363 xverse ,0 ,any ,RMS_NORM+MUL , 5
364 zaya1 ,0 ,any ,RMS_NORM+MUL , 7 zaya1 ,1 ,any ,RMS_NORM+MUL , 7
365 zonos3 ,0 ,any ,GATED_DELTA_NET+CPY , 1 zonos3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
366 zonos3 ,0 ,any ,MUL+ADD , 2 zonos3 ,1 ,any ,MUL+ADD , 2
367 zonos3 ,0 ,any ,RMS_NORM+MUL , 12 zonos3 ,1 ,any ,RMS_NORM+MUL , 12
368 zonos3 ,0 ,any ,RMS_NORM+SCALE , 2 zonos3 ,1 ,any ,RMS_NORM+SCALE , 2
369 zonos3 ,0 ,any ,SSM_CONV+UNARY , 1 zonos3 ,1 ,any ,SSM_CONV+UNARY , 1
+408 -10
View File
@@ -4834,6 +4834,301 @@ struct test_unary_scale_fusion : public test_case {
// SNAKE activation fusion: y = x + sin(a*x)^2 * inv_b
// CUDA backend matches the naive 5-op chain (mul, sin, sqr, mul, add)
// and dispatches a single fused kernel.
// the situ activation of the Inkling 2 experts on the halves of a merged gate_up, as build_moe_ffn builds it
struct test_situ : public test_case {
const std::array<int64_t, 3> ne; // n_ff, n_expert_used, n_tokens
const float beta;
const float lb;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "SITU";
}
bool run_whole_graph() override { return true; }
std::string vars() override {
return VARS_TO_STR3(ne, beta, lb);
}
test_situ(std::array<int64_t, 3> ne = {1152, 8, 1}, float beta = 4.0f, float lb = 25.0f) : ne(ne), beta(beta), lb(lb) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * gu = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 2*ne[0], ne[1], ne[2]);
ggml_set_name(gu, "gate_up");
gu = ggml_scale(ctx, gu, 1.0f);
ggml_tensor * g = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], 0);
ggml_tensor * u = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], ne[0]*gu->nb[0]);
ggml_tensor * act = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, g, 1.0f/beta)), beta);
act = ggml_mul(ctx, act, ggml_sigmoid(ctx, g));
u = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, u, 1.0f/lb)), lb);
ggml_tensor * out = ggml_mul(ctx, act, u);
ggml_set_name(out, "out");
return out;
}
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
init_tensor_uniform(t, -40.0f, 40.0f);
}
}
};
// the row L2 clip of Inkling 2: [x*w ->] l2_norm(x, t)*t [-> *f with one f per token]
struct test_l2_clip : public test_case {
const std::array<int64_t, 4> ne;
const bool with_w;
const bool with_f;
const float thr;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "L2_CLIP";
}
bool run_whole_graph() override { return true; }
std::string vars() override {
return VARS_TO_STR4(ne, with_w, with_f, thr);
}
test_l2_clip(std::array<int64_t, 4> ne = {128, 24, 3, 1}, bool with_w = true, bool with_f = false, float thr = 22.6f)
: ne(ne), with_w(with_w), with_f(with_f), thr(thr) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data());
ggml_set_name(a, "a");
ggml_tensor * cur = ggml_scale(ctx, a, 1.0f);
if (with_w) {
ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]);
ggml_set_name(w, "w");
cur = ggml_mul(ctx, cur, w);
}
cur = ggml_scale(ctx, ggml_l2_norm(ctx, cur, thr), thr);
if (with_f) {
ggml_tensor * f = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, 1, ne[2], ne[3]);
ggml_set_name(f, "f");
cur = ggml_mul(ctx, cur, f);
}
ggml_set_name(cur, "out");
return cur;
}
void initialize_tensors(ggml_context * ctx) override {
// rows with norms both below and above the threshold
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
init_tensor_uniform(t, -4.0f, 4.0f);
}
}
};
// the causal short conv of Inkling 2 as convolve() builds it: CONCAT(past, cur^T), the state store (a CPY of the last
// columns, or SET_ROWS of the windows of n_slots rollback slots), SSM_CONV, the optional input-dependent taps of H heads,
// the residual ADD and SCALE, and an optional residual add after it
struct test_short_conv : public test_case {
const int64_t C, Ts, S, H, n_slots;
const bool res;
const int64_t K; // the conv width
std::vector<ggml_tensor *> verify;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "SHORT_CONV";
}
bool run_whole_graph() override { return true; }
std::vector<ggml_tensor *> fusion_test_nodes() override { return verify; }
std::string vars() override {
return VARS_TO_STR7(C, Ts, S, H, n_slots, res, K);
}
test_short_conv(int64_t C = 1024, int64_t Ts = 1, int64_t S = 1, int64_t H = 0, int64_t n_slots = 0, bool res = false, int64_t K = 4)
: C(C), Ts(Ts), S(S), H(H), n_slots(n_slots), res(res), K(K) {}
// the inputs only: the rollback windows are an overlapping view
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
if (t->op == GGML_OP_NONE && t->view_src == NULL) {
init_tensor_uniform(t);
}
}
}
ggml_tensor * build_graph(ggml_context * ctx) override {
verify.clear();
const int64_t K1 = K - 1;
const int64_t T = Ts*S;
ggml_tensor * hist = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K1, C + 64, S);
ggml_tensor * past = ggml_view_3d(ctx, hist, K1, C, S, hist->nb[1], hist->nb[2], 32*hist->nb[1]);
ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), 0.5f);
ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K, C);
ggml_set_name(hist, "hist");
ggml_tensor * dyn = nullptr;
if (H) {
dyn = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K*H, T), 1.0f);
if (gf) {
ggml_build_forward_expand(gf, dyn);
}
}
const int64_t n_planes = std::max<int64_t>(1, n_slots);
ggml_tensor * state = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K1*(C + 64), S*n_planes);
ggml_set_name(state, "state");
const size_t row_size = state->nb[1];
ggml_tensor * x = ggml_concat(ctx, past, ggml_transpose(ctx, ggml_reshape_3d(ctx, cur, C, Ts, S)), 0);
ggml_tensor * st;
if (n_slots == 0) {
ggml_tensor * tail = ggml_view_3d(ctx, x, K1, C, S, x->nb[1], x->nb[2], Ts*sizeof(float));
ggml_tensor * cell = ggml_view_2d(ctx, state, K1*C, S, row_size, 32*K1*sizeof(float));
st = ggml_cpy(ctx, tail, cell);
} else {
const int64_t kw = std::min(Ts, n_slots);
ggml_tensor * order = ggml_arange(ctx, 0.0f, (float) n_slots, 1.0f);
order = ggml_cast(ctx, ggml_scale_bias(ctx, order, -1.0f, (float) (n_slots - 1)), GGML_TYPE_I32);
order = ggml_view_1d(ctx, order, kw, (n_slots - kw)*sizeof(int32_t));
ggml_tensor * windows = ggml_view_4d(ctx, x, K1, kw, C, S, sizeof(float), x->nb[1], x->nb[2], (Ts - (kw - 1))*sizeof(float));
ggml_tensor * slots = ggml_view_4d(ctx, state, K1, n_slots, C, S, S*row_size, K1*sizeof(float), row_size, 32*K1*sizeof(float));
st = ggml_set_rows(ctx, slots, windows, order);
}
if (gf) {
ggml_build_forward_expand(gf, st);
}
verify.push_back(st);
ggml_tensor * out = ggml_reshape_2d(ctx, ggml_ssm_conv(ctx, x, w), C, T);
if (dyn) {
ggml_tensor * d3 = ggml_reshape_3d(ctx, dyn, K, H, T);
for (int64_t lag = 0; lag < K; ++lag) {
ggml_tensor * tap = ggml_view_3d(ctx, d3, 1, H, T, d3->nb[1], d3->nb[2], lag*d3->nb[0]);
ggml_tensor * window = ggml_view_3d(ctx, x, Ts, C, S, x->nb[1], x->nb[2], (K1 - lag)*x->nb[0]);
window = ggml_reshape_3d(ctx, ggml_cont(ctx, ggml_transpose(ctx, window)), C/H, H, T);
out = ggml_add(ctx, out, ggml_reshape_2d(ctx, ggml_mul(ctx, window, tap), C, T));
}
}
out = ggml_scale(ctx, ggml_add(ctx, cur, out), 1.0f/sqrtf((float) ((H ? 2 : 1)*K + 1)));
if (res) {
out = ggml_add(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), out);
}
ggml_set_name(out, "out");
verify.push_back(out);
return out;
}
};
// the depth mix of Inkling 2 as mix() builds it: states = [stack; rms_norm(cur)], softmax of the scores against Q queries,
// the weighted sum as [Q, n, T]; shared_norm: the norm of cur also has another use, so it is computed before the mix
struct test_depth_mix : public test_case {
const int64_t n, B, Q, T;
const bool shared_norm;
std::vector<ggml_tensor *> verify;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "DEPTH_MIX";
}
bool run_whole_graph() override { return true; }
std::vector<ggml_tensor *> fusion_test_nodes() override { return verify; }
std::string vars() override {
return VARS_TO_STR5(n, B, Q, T, shared_norm);
}
test_depth_mix(int64_t n = 2304, int64_t B = 8, int64_t Q = 1, int64_t T = 1, bool shared_norm = false)
: n(n), B(B), Q(Q), T(T), shared_norm(shared_norm) {}
double max_nmse_err() override {
return 5e-4;
}
ggml_tensor * build_graph(ggml_context * ctx) override {
verify.clear();
ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, B, T);
ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T);
ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, Q);
ggml_set_name(stack, "stack");
ggml_set_name(cur, "cur");
ggml_tensor * norm = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), 1e-6f);
if (shared_norm) {
ggml_tensor * other = ggml_scale(ctx, norm, 2.0f);
if (gf) {
ggml_build_forward_expand(gf, other);
}
verify.push_back(other);
}
ggml_tensor * states = ggml_concat(ctx, stack, norm, 1);
ggml_tensor * queries = T == 1 ? query : ggml_repeat(ctx, query, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, Q, T));
ggml_tensor * scores = ggml_soft_max_ext(ctx, ggml_mul_mat(ctx, states, queries), nullptr, 1.0f/sqrtf((float) n), 0.0f);
ggml_tensor * out = ggml_mul_mat(ctx, scores, ggml_cont(ctx, ggml_transpose(ctx, states)));
ggml_set_name(out, "out");
verify.push_back(out);
return out;
}
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
init_tensor_uniform(t, -3.0f, 3.0f);
}
}
};
// the loop controller of Inkling 2 as control() builds it: one rms_norm of [cur; msg], the rank r down projection, the gain
// and forget projections and (cur - tanh(forget)*cur) + tanh(gain)*msg
struct test_loop_ctrl : public test_case {
const int64_t n, r, T;
std::string op_desc(ggml_tensor * t) override {
GGML_UNUSED(t);
return "LOOP_CTRL";
}
bool run_whole_graph() override { return true; }
std::string vars() override {
return VARS_TO_STR3(n, r, T);
}
test_loop_ctrl(int64_t n = 2304, int64_t r = 64, int64_t T = 1) : n(n), r(r), T(T) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
ggml_tensor * msg = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
ggml_tensor * wd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2*n, r);
ggml_tensor * wg = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
ggml_tensor * wf = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
ggml_set_name(cur, "cur");
ggml_set_name(msg, "msg");
ggml_tensor * gate = ggml_concat(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), ggml_reshape_3d(ctx, msg, n, 1, T), 1);
gate = ggml_reshape_2d(ctx, ggml_rms_norm(ctx, gate, 1e-6f), 2*n, T);
gate = ggml_mul_mat(ctx, wd, gate);
ggml_tensor * gain = ggml_tanh(ctx, ggml_mul_mat(ctx, wg, gate));
ggml_tensor * forget = ggml_tanh(ctx, ggml_mul_mat(ctx, wf, gate));
ggml_tensor * out = ggml_add(ctx, ggml_sub(ctx, cur, ggml_mul(ctx, forget, cur)), ggml_mul(ctx, gain, msg));
ggml_set_name(out, "out");
return out;
}
void initialize_tensors(ggml_context * ctx) override {
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
init_tensor_uniform(t, -0.5f, 0.5f);
}
}
};
struct test_snake_fuse : public test_case {
const ggml_type type;
const std::array<int64_t, 4> ne; // [T, C, D2, D3]
@@ -9012,19 +9307,25 @@ struct test_mul_mat_fusion : public test_case {
const bool with_lane_scale;
std::array<int64_t, 2> batch_dims;
const bool skip; // set some ids to a negative value (only for use_id)
const ggml_type type_b; // type of the input
test_mul_mat_fusion(ggml_type type, ggml_glu_op op, int64_t m, int64_t n, int64_t k,
bool use_id = false, int n_mats = 1, int n_used = 1, bool b = false, bool with_bias = false, bool with_gate = true,
bool with_lane_scale = false, std::array<int64_t, 2> batch_dims = {4, 2}, bool skip = false)
bool with_lane_scale = false, std::array<int64_t, 2> batch_dims = {4, 2}, bool skip = false,
ggml_type type_b = GGML_TYPE_F32)
: type(type), glu_op(op), m(m), n(n), k(k), use_id(use_id), n_mats(n_mats), n_used(n_used), b(b), with_bias(with_bias),
with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip) {
with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip), type_b(type_b) {
if (use_id) {
GGML_ASSERT(n_used <= n_mats);
}
}
std::string vars() override {
return VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip);
std::string s = VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip);
if (type_b != GGML_TYPE_F32) {
s += "," + VAR_TO_STR(type_b);
}
return s;
}
std::string op_desc(ggml_tensor * t) override {
@@ -9078,7 +9379,7 @@ struct test_mul_mat_fusion : public test_case {
std::array<int64_t, 4> ne = { k, m, channels, samples };
std::array<int64_t, 4> ne0 = { k, n, channels, samples };
ggml_tensor * cur = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data());
ggml_tensor * cur = ggml_new_tensor(ctx, type_b, 4, ne.data());
ggml_tensor * gate = with_gate ? ggml_new_tensor(ctx, type, 4, ne0.data()) : nullptr;
ggml_tensor * up = ggml_new_tensor(ctx, type, 4, ne0.data());
@@ -9128,7 +9429,7 @@ struct test_mul_mat_fusion : public test_case {
ids = ggml_view_2d(ctx, ids, n_used, m, ids->nb[1], 0);
}
ggml_tensor * cur = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, k, this->b ? 1 : n_used, m);
ggml_tensor * cur = ggml_new_tensor_3d(ctx, type_b, k, this->b ? 1 : n_used, m);
ggml_set_name(cur, "cur");
auto build_lane_up = [&]() {
@@ -10163,11 +10464,13 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows
const bool sinks;
const ggml_type type_KV;
const float logit_softcap;
const bool mask_row; // query 0 of each stream sees no key
std::vector<int32_t> rows;
std::string vars() override {
return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV);
return VARS_TO_STR12(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV, logit_softcap, mask_row);
}
double max_nmse_err() override {
@@ -10175,8 +10478,10 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
}
test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2,
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16)
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {}
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16,
float logit_softcap = 0.0f, bool mask_row = false)
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV),
logit_softcap(logit_softcap), mask_row(mask_row) {}
ggml_tensor * build_graph(ggml_context * ctx) override {
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream);
@@ -10202,7 +10507,7 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream);
ggml_set_name(indices, "indices");
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f);
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, logit_softcap);
if (sinks) {
ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa);
ggml_set_name(s, "s");
@@ -10243,7 +10548,7 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
for (int64_t j = 0; j < nb; ++j) {
for (int64_t i = 0; i < kv; ++i) {
const bool pad = kv_rows && rows[s*kv + i] < 0;
const bool drop = (i + 3*j + 5*s) % 11 == 0;
const bool drop = (i + 3*j + 5*s) % 11 == 0 || (mask_row && j == 0);
f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen);
}
}
@@ -11740,6 +12045,47 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_snake_fuse(type, { 64, 32, 2, 3})); // ne[2] > 1 and ne[3] > 1
}
// the fused op chains of the Inkling 2 graph
for (int64_t n_tokens : { 1, 3, 32 }) {
test_cases.emplace_back(new test_situ({1152, 8, n_tokens}, 4.0f, 25.0f));
}
test_cases.emplace_back(new test_situ({64, 2, 5}, 2.0f, 10.0f));
for (bool with_w : { false, true }) {
for (bool with_f : { false, true }) {
for (std::array<int64_t, 4> ne : std::initializer_list<std::array<int64_t, 4>>{ {128, 24, 1, 1}, {128, 4, 7, 1}, {16, 24, 3, 1}, {1500, 2, 3, 2} }) {
test_cases.emplace_back(new test_l2_clip(ne, with_w, with_f, ne[0] == 16 ? 8.0f : 22.6f));
}
}
}
for (int64_t H : { 0, 8 }) {
for (int64_t n_slots : { 0, 4 }) {
for (bool res : { false, true }) {
for (int64_t Ts : { 1, 3, 5, 33 }) {
for (int64_t S : { 1, 2 }) {
test_cases.emplace_back(new test_short_conv(1024, Ts, S, H, n_slots, res));
}
}
}
}
}
for (int64_t K : { 2, 3, 8 }) {
test_cases.emplace_back(new test_short_conv(256, 5, 2, 4, 0, true, K));
test_cases.emplace_back(new test_short_conv(256, 3, 1, 0, 6, false, K));
}
for (int64_t T : { 1, 3 }) {
for (int64_t Q : { 1, 3, 4 }) {
for (int64_t B : { 1, 3, 12 }) {
test_cases.emplace_back(new test_depth_mix(2304, B, Q, T));
}
}
test_cases.emplace_back(new test_depth_mix(2304, 5, 3, T, true));
test_cases.emplace_back(new test_depth_mix(100, 2, 2, T));
}
for (int64_t T : { 1, 4, 8 }) {
test_cases.emplace_back(new test_loop_ctrl(2304, 64, T));
}
test_cases.emplace_back(new test_loop_ctrl(256, 40, 3));
test_cases.emplace_back(new test_dsv4_hc_comb(1, 1));
test_cases.emplace_back(new test_dsv4_hc_comb(17, 4));
test_cases.emplace_back(new test_dsv4_hc_comb(257, 8));
@@ -13364,6 +13710,44 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 1, 256, {3, 2}, {2, 2}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 8, 256, {1, 1}, {1, 1}));
// BF16 in src1 (activations): MMVQ, few-row MMQ, MMQ with each layout of the Q8_1 src1 and the FP4 src1,
// cuBLAS for F16 weights, MMVF for BF16 weights and the transposed F32 vector
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q2_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 1, 16, 2048, {1, 1}, {1, 1}));
// FP8 weights with more tokens than MMVF takes: src1 quantized to FP8 for cuBLASLt
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {1, 1}));
// BF16 src1 as a permuted view (rows 4*k values apart, channels k apart): MMVQ, few-row MMQ, MMQ with the Q8_1 and the FP4 src1,
// FP8 on cuBLASLt, MMVF for BF16 and FP8 weights
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 64, 13, 4608, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
// MUL_MAT_ID: MMVQ, MMQ without and with a broadcast src1 (quantized once per token), MMVF with several tokens
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 1, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
// MUL_MAT_ID few-row MMQ (CUDA, from MMVQ's max. batch size up to 24 tokens)
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 4, false, 72, 13, 2048));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024));
// float experts (MMF reads only an F32 src1): MMVF for BF16 experts up to 8 tokens, the fallback that sorts src1 by expert for F16
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 1, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024));
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024));
// token-tile boundary coverage. With n_used == n_mats every token routes to every expert, so
// each expert receives exactly n rows, with no dependence on the random draw. mul_mm_id is used
// from 32 tokens up: n = 32, 33, 47, 48, 49 reach it, leaving a last tile of 32, 1, 15, 16 and
@@ -14471,10 +14855,16 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, GGML_TYPE_F8_E4M3));
for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type));
}
for (int64_t nb : {1, 7}) {
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 700, nb, 2, 17, kv_rows));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, 2, 17, kv_rows, true, GGML_TYPE_F16, 10.0f));
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, 2, 17, kv_rows, false, GGML_TYPE_F16, 0.0f, true));
}
}
// sparse mask with large batch size
@@ -14732,6 +15122,14 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 9, 128, 2048, false, 1, 1, false, false, true, false, { 1, 1 }));
// on DGX Spark also the expert gate and up matmuls at 8 tokens, instead of the fused MMVQ path
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 8, 128, 2048, true, 16, 4, true));
// BF16 input to MUL_MAT_ID: fused gate/up + GLU on MMVF (BF16 experts with more than 512 rows) and on MMQ (broadcast input)
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 1024, 256, true, 16, 8, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, false, { 4, 2 }, false, GGML_TYPE_BF16));
// BF16 input: fused gate/up + GLU on MMVQ, MMVF and MMQ (NVFP4 with weight scales), and the NVFP4 weight scale on MMQ
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 6912, 256, false, 1, 1, false, false, true, true, { 2, 3 }, false, GGML_TYPE_BF16));
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 }, false, GGML_TYPE_BF16));
for (int64_t n_tok : {1, 4, 16}) {
test_cases.emplace_back(new test_moe_router_prec_f32(128, 64, n_tok, 8));
+2 -1
View File
@@ -377,7 +377,8 @@ int main(int argc, char ** argv) {
for (const auto & model_path : models) {
const std::string arch = get_arch(model_path);
const bool moe = arch.find("moe") != std::string::npos;
const std::string stem = std::filesystem::path(model_path).stem().string();
const bool moe = stem.size() >= 4 && stem.compare(stem.size() - 4, 4, "-moe") == 0;
llama_model_ptr model;
llama_model_ptr model_cpu;
+37
View File
@@ -19,6 +19,7 @@
#include <memory>
#include <random>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
@@ -176,6 +177,7 @@ static void usage(char ** argv) {
LOG(" -o, --out <dir> Save generated test models to <dir> instead of running backend tests\n");
LOG(" -v <N> Set log verbosity level\n");
LOG(" -b, --backend <backend> Run only on the given backend device\n");
LOG(" --rpc <endpoints> Add RPC servers (comma-separated host:port), must precede -b\n");
LOG(" --kv-shift Check K-shift against a decode at the shifted positions (CPU only)\n");
LOG(" -h, --help Show this help message\n\n");
LOG("Examples:\n");
@@ -1982,6 +1984,31 @@ static int test_kv_shift(const std::string & arch_filter, const size_t seed, con
return n_failed == 0 ? 0 : 1;
}
static bool add_rpc_devices(const std::string & endpoints) {
ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
if (rpc_reg == nullptr) {
LOG_ERR("%s: RPC backend not available\n", __func__);
return false;
}
typedef ggml_backend_reg_t (*add_server_t)(const char * endpoint);
auto add_server = (add_server_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_server");
if (add_server == nullptr) {
LOG_ERR("%s: RPC backend has no ggml_backend_rpc_add_server\n", __func__);
return false;
}
std::stringstream ss(endpoints);
std::string endpoint;
while (std::getline(ss, endpoint, ',')) {
ggml_backend_reg_t reg = add_server(endpoint.c_str());
if (reg == nullptr) {
LOG_ERR("%s: failed to connect to RPC server %s\n", __func__, endpoint.c_str());
return false;
}
ggml_backend_register(reg);
}
return true;
}
int main(int argc, char ** argv) {
// init the logger at max verbosity. filter with a custom callback respecting the user-configure verbosity
common_log_set_verbosity_thold(LOG_LEVEL_DEBUG);
@@ -2063,6 +2090,16 @@ int main(int argc, char ** argv) {
usage(argv);
return 1;
}
} else if (strcmp(argv[i], "--rpc") == 0) {
if (i + 1 < argc) {
// must precede -b so that the RPC devices can be selected by name
if (!add_rpc_devices(argv[++i])) {
return 1;
}
} else {
usage(argv);
return 1;
}
} else if (strcmp(argv[i], "--kv-shift") == 0) {
kv_shift = true;
} else {
+1
View File
@@ -4,6 +4,7 @@
#include <atomic>
#include <cmath>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <filesystem>

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