Compare commits

...
7 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
87 changed files with 3533 additions and 1809 deletions
+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. |
+2
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
+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:
+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;
+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);
+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
//
+83 -2
View File
@@ -1249,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;
@@ -1571,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,
@@ -4282,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(".");
}
@@ -33076,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);
@@ -33670,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)) {
@@ -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);
+15 -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
@@ -2335,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;
}
}
+3
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));
+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
+22 -22
View File
@@ -32,28 +32,28 @@ METRIC_NAMES = {'occupancy': 'Occupancy [waves/SIMD]', 'vgpr_spill': 'VGPRs Spil
IGNORED_VGPR = {
'_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',
'_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',
}
+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);
}
+15 -5
View File
@@ -10464,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 {
@@ -10476,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);
@@ -10503,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");
@@ -10544,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);
}
}
@@ -14851,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
@@ -64,7 +64,6 @@
} from '#lib/types/index.ts';
import {
buildMentionInsertion,
findCommandToken,
findMentionToken,
getConversationModel,
isIMEComposing,
@@ -140,6 +139,7 @@
let pickersRef: { handleKeydown: (event: KeyboardEvent) => boolean } | undefined =
$state(undefined);
let inputRef: ChatFormInput | undefined = $state(undefined);
let workingDirectoryRef: ChatFormCurrentWorkingDirectory | undefined = $state(undefined);
// Voice input
const recorder: VoiceRecorderLike = untrack(() => voiceRecorder) ?? new VoiceRecorder();
@@ -148,8 +148,8 @@
/** Why the last start failed (denied, no microphone, busy); the next tap tries again. */
let micError = $state<string | null>(null);
// Invisible anchor the pickers' popovers float above: the form's top edge, or in the
// expanded editor the line being written
// Invisible anchor the pickers' popovers float above: the line being written, or on a
// phone the form's top edge
let pickerAnchor: HTMLDivElement | null = $state(null);
let pickerAnchorBox = $state({ height: 1, top: 0 });
@@ -174,6 +174,8 @@
conversationsStore.activeConversation ? systemMessage?.content : undefined
);
// a system message is the same whichever model answers: its editor offers no selector
let isModelSelectorShown = $derived(showModelSelector && !systemMode);
let showWorkingDirectory = $derived(conversationsStore.preferences.hasEnabledCwdTools());
// On a desktop the chip under the form shows a directory once one is set, and the + menu
// sets one until then. A phone has no chip: a chat shows it in its header (see
@@ -185,12 +187,16 @@
const pickers = useChatFormPickers({
canCompact: () => chatStore.canCompact(conversationsStore.activeMessages),
canEditSystemMessage: () => !!onSystemPromptClick && !systemMode,
// a phone picks in a drawer with its own search field, and a touch screen opens no
// typed pickers (see opensOnInput)
editsCwdInline: () => !deviceStore.isMobile && !deviceStore.isTouch,
focusInput: refocusInput,
getCaretOffset: () => inputRef?.getCaretOffset(),
getCwd: () => cwd,
getPickersRef: () => pickersRef,
getServerHome: () => toolsStore.serverHome ?? null,
getShowModelSelector: () => showModelSelector,
getShowModelSelector: () => isModelSelectorShown,
getValue: () => value,
hasCwdTools: () => conversationsStore.preferences.hasEnabledCwdTools(),
// policy-aware, same rule as the agentic flow: MCP category on and at
@@ -205,12 +211,17 @@
.some((s) => s.enabled && prefs.isServerToolsEnabled(s.id) && s.url.trim());
},
onCompact: () => chatStore.compactConversation(),
onSystemMessage: () => onSystemPromptClick?.({ files: uploadedFiles, message: value }),
openModelSelector: () => chatFormActionsRef?.openModelSelector(),
// TODO: no typed pickers with an on-screen keyboard for now: each mobile browser moves
// the page its own way as it opens, so a list by the form can not stay clear of the
// text. A drawer with its own search field (as the directory picker is) could.
opensOnInput: () => !deviceStore.isTouch,
setCaretOffset: (offset) => inputRef?.setCaretOffset(offset),
setCaretOffset: (offset) => {
inputRef?.setCaretOffset(offset);
// the caret moved without typing, e.g. onto the `/cwd` line the + menu just added
measurePickerAnchor();
},
setValue: (v) => {
value = v;
onValueChange?.(v);
@@ -237,14 +248,9 @@
});
async function handleWorkingDirectoryChange(newDir: string | null) {
// Committing a directory consumes the `/cwd` token; the chip's
// clear-X path has no token to consume.
const token = findCommandToken(value);
if (token && token.name === 'cwd') {
value = '';
onValueChange?.('');
}
// Committing a directory consumes the `/cwd` line and keeps the message below it; the
// chip's clear-X path has no line to consume.
pickers.consumeCwdCommand();
await conversationsStore.preferences.setCwd(newDir);
@@ -365,18 +371,30 @@
isExpanded && deviceStore.isMobile ? (actionsEl ?? null) : pickerAnchor
);
// The anchor covers the caret's line, kept within the form when the line is scrolled out
// of the editor's view; on a phone the form's top edge
function measurePickerAnchor() {
const line = deviceStore.isMobile ? null : inputRef?.getCaretRect();
const form = pickerAnchor?.parentElement?.getBoundingClientRect();
if (!line || !form) {
pickerAnchorBox = { height: 1, top: 0 };
return;
}
const top = Math.min(Math.max(line.top - form.top, 0), form.height);
pickerAnchorBox = { height: Math.max(line.bottom - line.top, 1), top };
}
// before the popover is drawn, and again as the query is typed and the line moves
$effect.pre(() => {
if (!isPickerOpen) return;
void value;
const line = isExpanded && !deviceStore.isMobile ? inputRef?.getCaretRect() : null;
const formTop = pickerAnchor?.parentElement?.getBoundingClientRect().top ?? 0;
pickerAnchorBox = line
? { height: line.bottom - line.top, top: line.top - formTop }
: { height: 1, top: 0 };
measurePickerAnchor();
});
// shown on hover (always on touch screens) while collapsed, always while expanded: on
// the phone sheet it keeps the collapsed card's place, below the status bar
@@ -447,7 +465,14 @@
function handleKeydown(event: KeyboardEvent) {
// Pickers consume navigation/escape keys first; when consumed, skip
// the enter-to-submit logic below and keep the key from the editor.
if (pickers.handleKeydown(event)) {
// The directory picker takes the keys typed on its `/cwd` line; in the message below
// it only Escape, so Enter and the arrows there stay the message's
const isDirectoryKey = pickers.isCaretInCwdCommand() || event.key === KeyboardKey.ESCAPE;
if (
(isDirectoryKey && workingDirectoryRef?.handleKeydown(event)) ||
pickers.handleKeydown(event)
) {
event.preventDefault();
return;
@@ -678,6 +703,13 @@
async function submit() {
if (!canSubmit || disabled || hasLoadingAttachments || isSendWaiting) return;
// sending closes the directory picker first, so its `/cwd` command is not sent as text
if (pickers.isWorkingDirectoryPickerOpen) {
pickers.handleWorkingDirectoryClose();
if (!canSubmit) return;
}
if (voice.isRefining) {
isSendWaiting = true;
@@ -809,7 +841,9 @@
'max-md:border-transparent max-md:focus-within:border-transparent max-md:dark:border-transparent max-md:dark:focus-within:border-transparent',
EXPANDED_SHEET_FILL
],
systemMode && '!border-2 !border-dashed !border-border/50 !bg-muted',
// a dashed outline stands in for the card's edge, drawn inside it: the card keeps its size
systemMode &&
'!bg-muted !outline-2 -outline-offset-2 !outline-dashed !outline-border/50 [--glass-edge-focus:transparent] [--glass-edge:transparent]',
disabled && 'cursor-not-allowed opacity-60'
]}
data-single-row={isSingleRow || undefined}
@@ -920,7 +954,7 @@
? pickers.handleWorkingDirectoryOpen
: undefined}
{showAddButton}
{showModelSelector}
showModelSelector={isModelSelectorShown}
voice={{
action: voice.label,
hint: voice.hint,
@@ -952,15 +986,21 @@
></div>
{/if}
<div class="flex flex-wrap items-center gap-x-1 self-start">
<!-- The chips sit under the card. On a new chat, where the page centres the form, they
hang below it and take no room: the card stays where it is as they come and go -->
<div
class="flex flex-wrap items-center gap-x-1 self-start md:group-data-[chat-form-lifted]/chat-form-host:absolute md:group-data-[chat-form-lifted]/chat-form-host:top-full"
>
{#if showWorkingDirectory}
<!-- opened from the chip, the + menu, a phone chat's header or `/cwd` -->
<ChatFormCurrentWorkingDirectory
bind:query={pickers.workingDirectoryQuery}
bind:this={workingDirectoryRef}
class="self-start"
customAnchor={activePickerAnchor}
directory={cwd}
{disabled}
inline={pickers.isWorkingDirectoryInline}
isOpen={pickers.isWorkingDirectoryPickerOpen}
onChange={handleWorkingDirectoryChange}
onClose={pickers.handleWorkingDirectoryClose}
@@ -8,20 +8,23 @@
import {
CHAT_FORM_CHIP_SPLIT,
CHAT_FORM_CHIP_TRANSITION_MS,
CHAT_FORM_PATH_PICKER_WIDTH_CLASS,
DEFAULT_MOBILE_BREAKPOINT,
HOME_TILDE,
SEARCH,
UI_DATA_ATTRS
} from '#lib/constants/index.ts';
import { BuiltInTool, GlobSearchType, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
import { BuiltInTool, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts';
import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts';
import { useScrollActiveRow } from '#lib/hooks/use-scroll-active-row.svelte.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import { conversationsStore, deviceStore, toolsStore } from '#lib/stores/index.ts';
import type { GlobSearchChildResult } from '#lib/types/glob.js';
import {
abbreviateHome,
runGlobSearchWithChildren,
isIMEComposing,
runFolderSearch,
toHomeRelativeQuery
} from '#lib/utils/index.ts';
import { page } from '$app/state';
@@ -37,6 +40,9 @@
/** Controlled open state; the host owns it so the chip, the + menu and the
* `/cwd` slash command open the picker through the same path. */
isOpen: boolean;
/** The path is typed on the chat input's `/cwd` line: no search field of its own, and
* the host forwards the input's keys through `handleKeydown`. */
inline?: boolean;
/** Two-way bound query, kept in sync with the text after `/cwd `. */
query: string;
/** Anchor at the form's top edge so the popover floats above the box. */
@@ -55,6 +61,7 @@
customAnchor = null,
directory = null,
disabled = false,
inline = false,
isOpen,
onChange,
onClose,
@@ -109,7 +116,7 @@
// HTML `autofocus` is unreliable on dynamically shown elements.
$effect(() => {
if (!isOpen) return;
if (!isOpen || inline) return;
setTimeout(() => searchInputRef?.focus(), FOCUS_DELAY_MS);
});
@@ -160,32 +167,14 @@
return;
}
try {
// Generous limit: ranking is client-side, only the top
// MAX_RESULTS_SHOWN are shown.
// A plain query navigates home as if typed after `~/`; a query
// starting from a root or `~` navigates the absolute tree.
const res = await runGlobSearchWithChildren(
toHomeRelativeQuery(trimmed, homeBase),
homeBase ?? HOME_TILDE,
SEARCH.MAX_DEPTH,
SEARCH.LIMIT,
signal,
{ type: GlobSearchType.DIR }
);
// Every round of results starts with its first folder highlighted. A stale
// search must not touch the list: the next one is already running.
const show = (res: GlobSearchChildResult) => {
if (!isCurrent()) return;
if (res.error) {
queryResults = [];
nav.reset(-1);
searchError = res.error;
return;
}
searchScope = res.exactDir ?? res.args.path;
queryResults = res.entries.map((e) => e.path).slice(0, SEARCH.MAX_RESULTS_SHOWN);
searchError = res.error ?? null;
if (queryResults.length > 0) {
nav.reset(0);
@@ -193,8 +182,10 @@
} else {
nav.reset(-1);
}
};
searchError = null;
try {
show(await runFolderSearch(trimmed, homeBase, signal, show));
} catch (err) {
if (!isCurrent() || signal.aborted) return;
@@ -261,25 +252,60 @@
closePicker();
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === KeyboardKey.ENTER) {
/** True when the key was the picker's: the chat input then leaves it alone. */
function handlePickerKeydown(event: KeyboardEvent): boolean {
// a key that confirms or moves within an IME composition belongs to the text
if (isIMEComposing(event)) return false;
// Enter picks a suggestion, never the typed text: before the results arrive it does
// nothing. Only without file search, where nothing is suggested, does it take the path
// as typed
if (event.key === KeyboardKey.ENTER && !event.shiftKey) {
event.preventDefault();
if (nav.hoveredIndex >= 0 && queryResults[nav.hoveredIndex]) {
commit(queryResults[nav.hoveredIndex]);
} else if (queryResults.length === 0) {
} else if (!fileSearchEnabled) {
handleSubmit();
}
} else if (event.key === KeyboardKey.ARROW_DOWN) {
if (queryResults.length > 0) {
event.preventDefault();
nav.move(1);
}
} else if (event.key === KeyboardKey.ARROW_UP) {
if (queryResults.length > 0) {
event.preventDefault();
nav.move(-1);
}
return true;
}
if (
(event.key === KeyboardKey.ARROW_DOWN || event.key === KeyboardKey.ARROW_UP) &&
queryResults.length > 0
) {
event.preventDefault();
nav.move(event.key === KeyboardKey.ARROW_DOWN ? 1 : -1);
return true;
}
if (inline && event.key === KeyboardKey.ESCAPE) {
event.preventDefault();
closePicker();
return true;
}
return false;
}
/** The chat input's keys while the path is typed on its `/cwd` line. */
export function handleKeydown(event: KeyboardEvent): boolean {
if (!isOpen || !inline) return false;
return handlePickerKeydown(event);
}
// Inline, the chat input is the picker's field: pressing in the form (to move the caret,
// say) keeps the picker open
function handleInteractOutside(event: PointerEvent) {
const target = event.target;
if (inline && target instanceof Node && customAnchor?.closest('form')?.contains(target)) {
event.preventDefault();
}
}
@@ -380,14 +406,27 @@
<!-- the drawer's version is roomier: the header's inset, rows spaced for a finger and
lined up with the search results, and text sized for a phone -->
{#snippet picker(inDrawer: boolean)}
<div class={inDrawer ? 'flex flex-col gap-1 px-4' : 'p-2 min-h-22 flex flex-col justify-between'}>
<SearchInput
bind:ref={searchInputRef}
bind:value={query}
class="w-full"
onClose={closePicker}
placeholder="Choose working directory"
/>
<!-- inline there is no search field to keep room for, only the rows below the line -->
<div
class={inDrawer
? 'flex flex-col gap-1 px-4'
: ['flex flex-col justify-between p-2', !inline && 'min-h-22']}
>
{#if inline}
{#if fileSearchEnabled && !query.trim()}
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">
Type a folder name or path after <span class="font-mono">/cwd</span>
</div>
{/if}
{:else}
<SearchInput
bind:ref={searchInputRef}
bind:value={query}
class="w-full"
onClose={closePicker}
placeholder="Choose working directory"
/>
{/if}
{#if !fileSearchEnabled}
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">{searchUnavailableMessage}</div>
@@ -460,7 +499,7 @@
<!-- a phone picks in a drawer from the screen's bottom; elsewhere a popover above the form -->
{#if deviceStore.isMobile}
<Drawer.Root onOpenChange={handleOpenChange} open={isOpen}>
<Drawer.Content class="gap-0" onkeydown={handleKeydown}>
<Drawer.Content class="gap-0" onkeydown={handlePickerKeydown}>
<Drawer.Header>
<Drawer.Title>Working directory</Drawer.Title>
@@ -484,16 +523,20 @@
<span class="sr-only">Open working directory picker</span>
</Popover.Trigger>
<!-- inline, the focus stays in the chat input, where the path is typed: a trap would
pull it into the list as the + menu closes -->
<Popover.Content
align="start"
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0"
class={[CHAT_FORM_PATH_PICKER_WIDTH_CLASS, 'rounded-xl p-0']}
{customAnchor}
onCloseAutoFocus={(event) => event.preventDefault()}
onInteractOutside={handleInteractOutside}
onOpenAutoFocus={(event) => event.preventDefault()}
onkeydown={handleKeydown}
onkeydown={handlePickerKeydown}
preventScroll={false}
side="top"
sideOffset={12}
trapFocus={!inline}
>
{@render picker(false)}
</Popover.Content>
@@ -2,7 +2,7 @@
import { cn } from '@ggml-org/llama-ui/utils';
import { Folder } from '@lucide/svelte';
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
import { highlightMatch } from '#lib/utils/index.ts';
import { hasPointerMoved, highlightMatch } from '#lib/utils/index.ts';
import { fly } from 'svelte/transition';
// Fly-in transition for the results list.
@@ -53,7 +53,9 @@
)}
data-highlighted={index === hoveredIndex ? '' : undefined}
onclick={() => onCommit?.(path)}
onmouseenter={() => onHover?.(index)}
onmousemove={(event) => {
if (hasPointerMoved(event)) onHover?.(index);
}}
>
<Folder class="size-4 shrink-0 text-muted-foreground" />
@@ -1,12 +1,14 @@
<script lang="ts">
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
import { hasPointerMoved } from '#lib/utils/index.ts';
import type { Snippet } from 'svelte';
interface Props {
isSelected?: boolean;
disabled?: boolean;
onclick: () => void;
onmouseenter?: () => void;
/** Called when the user moves the pointer over the row, not when the row renders under it. */
onhover?: () => void;
dataIndex?: number;
children: Snippet;
class?: string;
@@ -19,14 +21,16 @@
disabled = false,
isSelected = false,
onclick,
onmouseenter
onhover
}: Props = $props();
</script>
<button
{disabled}
{onclick}
{onmouseenter}
onmousemove={(event) => {
if (hasPointerMoved(event)) onhover?.();
}}
type="button"
{...{ [UI_DATA_ATTRS.PICKER_INDEX]: dataIndex }}
class="flex w-full cursor-pointer items-start gap-3 rounded-lg px-3 py-2 text-left hover:bg-accent/50 {isSelected
@@ -1,5 +1,6 @@
<script lang="ts">
import * as Popover from '@ggml-org/llama-ui/ui/popover';
import { CHAT_FORM_PICKER_WIDTH_CLASS } from '#lib/constants/index.ts';
import type { Snippet } from 'svelte';
interface Props {
@@ -42,7 +43,7 @@
<Popover.Content
align="start"
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0 {className}"
class={[CHAT_FORM_PICKER_WIDTH_CLASS, 'rounded-xl p-0', className]}
{customAnchor}
onOpenAutoFocus={(event) => event.preventDefault()}
onkeydown={onKeydown}
@@ -4,7 +4,6 @@
ChatFormPickerListItem,
ChatFormPickerPopover
} from '#lib/components/app/chat/index.ts';
import { CHAT_FORM_COMMAND_ICONS } from '#lib/constants/index.ts';
import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts';
import type { ChatFormCommand } from '#lib/types/index.ts';
@@ -121,18 +120,15 @@
showSearchInput={false}
>
{#snippet item(command, index, isSelected)}
{@const Icon = CHAT_FORM_COMMAND_ICONS[command.action]}
<ChatFormPickerListItem
dataIndex={index}
disabled={command.disabled}
{isSelected}
onclick={() => handleSelect(command)}
onmouseenter={() => {
onhover={() => {
if (!command.disabled) nav.setHover(index);
}}
>
<Icon class="mt-0.5 size-icon-md shrink-0 text-muted-foreground" />
<div class="flex min-w-0 flex-1 flex-col">
<span class="font-mono text-label">/{command.name}</span>
@@ -4,7 +4,12 @@
import { File, Folder } from '@lucide/svelte';
import { ChatFormPickerList, ChatFormPickerListItem } from '#lib/components/app/chat/index.ts';
import HighlightedMatch from '#lib/components/app/forms/HighlightedMatch.svelte';
import { FILE_GLOB_SEARCH_PICKERS, HOME_TILDE, SEARCH } from '#lib/constants/index.ts';
import {
CHAT_FORM_PATH_PICKER_WIDTH_CLASS,
FILE_GLOB_SEARCH_PICKERS,
HOME_TILDE,
SEARCH
} from '#lib/constants/index.ts';
import {
BuiltInTool,
FileMentionEntryType,
@@ -216,7 +221,7 @@
<Popover.Content
align="start"
class={['w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0', className]}
class={[CHAT_FORM_PATH_PICKER_WIDTH_CLASS, 'rounded-xl p-0', className]}
{customAnchor}
onCloseAutoFocus={(event) => event.preventDefault()}
onOpenAutoFocus={(event) => event.preventDefault()}
@@ -240,7 +245,7 @@
dataIndex={index}
{isSelected}
onclick={() => handleSelect(entry)}
onmouseenter={() => nav.setHover(index)}
onhover={() => nav.setHover(index)}
>
{@const Icon = entry.type === FileMentionEntryType.DIRECTORY ? Folder : File}
<Icon
@@ -258,10 +258,6 @@
}
}
async function handleSystemPromptAdd(draft: { message: string; files: ChatUploadedFile[] }) {
await chatStore.addSystemPrompt(draft);
}
$effect(() => {
stick.setEnabled(!settingsStore.config.disableAutoScroll);
});
@@ -337,7 +333,7 @@
class={[
// moves between the centered and bottom positions with a fade (see moveForm), at
// the same height in the page, so the messages never shift
'pointer-events-none md:sticky fixed mt-auto max-md:z-10',
'group/chat-form-host pointer-events-none md:sticky fixed mt-auto max-md:z-10',
// a phone holds it in place on screen while the page is slid aside
deviceStore.isMobile && 'sidebar-reveal-pin-bottom',
// on a phone the expanded form is a sheet: flush with the screen's sides and bottom
@@ -358,6 +354,7 @@
!isFormMoving &&
'transition-[left,right,bottom] duration-400 ease-[var(--chat-form-resize-ease,cubic-bezier(0.3,1.12,0.5,1))] max-md:transition-none motion-reduce:transition-none'
]}
data-chat-form-lifted={isFormLifted || undefined}
>
<ChatScreenGreeting
faded={uiStore.isComposerExpanded}
@@ -387,7 +384,6 @@
onFileUpload={fileUpload.handleFileUpload}
onSend={handleSendMessage}
onStop={() => chatStore.stopGeneration()}
onSystemPromptAdd={handleSystemPromptAdd}
/>
</div>
</div>
@@ -17,7 +17,6 @@
onFileUpload?: (files: File[]) => void;
onSend?: (message: string, files?: ChatUploadedFile[]) => Promise<boolean>;
onStop?: () => void;
onSystemPromptAdd?: (draft: { message: string; files: ChatUploadedFile[] }) => void;
uploadedFiles?: ChatUploadedFile[];
}
@@ -29,7 +28,6 @@
onFileUpload,
onSend,
onStop,
onSystemPromptAdd,
uploadedFiles = $bindable([])
}: Props = $props();
@@ -111,16 +109,10 @@
}
}
// With system messages hidden in the conversation there is nothing to edit in place, so the
// form itself turns into the system message editor
// The form itself turns into the system message editor, whether or not the conversation
// shows its system message
function handleSystemPromptClick() {
if (settingsStore.config[SETTINGS_KEYS.SHOW_SYSTEM_MESSAGE] ?? true) {
onSystemPromptAdd?.({ files: uploadedFiles, message });
return;
}
const existing = conversationsStore.activeMessages.find((m) => m.role === MessageRole.SYSTEM);
stashedDraft = { files: uploadedFiles, message };
@@ -2,6 +2,23 @@ export const INITIAL_FILE_SIZE = 0;
export const PROMPT_CONTENT_SEPARATOR = '\n\n';
export const CLIPBOARD_CONTENT_QUOTE_PREFIX = '"';
export const PROMPT_TRIGGER_PREFIX = '/';
/** The slash command that sets the working directory, typed as `/cwd <path>`. */
export const CWD_COMMAND_NAME = 'cwd';
/** A command's name after the `/`: letters, digits and dashes (`system-message`). */
export const COMMAND_NAME_REGEX = /^[\w-]*$/;
/** Where a working directory is typed, anywhere in the input: `/cwd <path>`. */
export const CWD_COMMAND_PREFIX = `${PROMPT_TRIGGER_PREFIX}${CWD_COMMAND_NAME} `;
/**
* The command picker fits its suggestions: as wide as the longest one, between a floor
* that keeps short lists readable and a cap no wider than the form.
*/
export const CHAT_FORM_PICKER_WIDTH_CLASS =
'w-max min-w-64 max-w-[min(36rem,var(--bits-popover-anchor-width))]';
/**
* The pickers that list paths (`@` mentions, `/cwd`) keep one width, so the list does not
* resize as the results change with every keystroke.
*/
export const CHAT_FORM_PATH_PICKER_WIDTH_CLASS = 'w-[min(36rem,var(--bits-popover-anchor-width))]';
export const NEW_CHAT_DRAFT_KEY = '__new_chat__';
/** Lines of text from which the main chat form expands into its large editor. */
export const CHAT_FORM_EXPAND_MIN_LINES = 4;
@@ -11,8 +11,6 @@ import FileIcon from '@lucide/svelte/icons/file';
// not a microphone: that one is for recording and dictation
import AudioIcon from '@lucide/svelte/icons/file-headphone';
import FileTextIcon from '@lucide/svelte/icons/file-text';
import CompactCommandIcon from '@lucide/svelte/icons/fold-vertical';
import CwdCommandIcon from '@lucide/svelte/icons/folder-open';
import ImageIcon from '@lucide/svelte/icons/image';
import LoadingIcon from '@lucide/svelte/icons/loader-2';
import ModelIcon from '@lucide/svelte/icons/package';
@@ -20,12 +18,10 @@ import PauseDownloadIcon from '@lucide/svelte/icons/pause';
import ResumeDownloadIcon from '@lucide/svelte/icons/play';
import LoadIcon from '@lucide/svelte/icons/power';
import RetryIcon from '@lucide/svelte/icons/rotate-cw';
import PromptCommandIcon from '@lucide/svelte/icons/sparkles';
import VideoIcon from '@lucide/svelte/icons/video';
import CancelLoadIcon from '@lucide/svelte/icons/x';
import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
import { FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
import type { ModelCapabilities } from '#lib/types/models.js';
import type { Component } from 'svelte';
export {
CAPABILITY_ICONS,
CAPABILITY_LABELS,
@@ -65,14 +61,6 @@ export const CAPABILITY_FLAG_KEYS: Record<ModelCapability, keyof ModelCapabiliti
[ModelCapability.TOOL_USE]: 'tools'
};
/** Icons of the slash-command picker, one per chat-form command. */
export const CHAT_FORM_COMMAND_ICONS: Record<ChatFormCommandAction, Component> = {
[ChatFormCommandAction.COMPACT]: CompactCommandIcon,
[ChatFormCommandAction.CWD]: CwdCommandIcon,
[ChatFormCommandAction.MODEL]: MODEL_ICON,
[ChatFormCommandAction.PROMPT]: PromptCommandIcon
};
/** Icons of the download control a manager row shows while it downloads. */
export const MODEL_DOWNLOAD_ICONS = {
pause: PauseDownloadIcon,
@@ -9,6 +9,9 @@
/** Label shown for the working-directory picker / `/cwd` slash command. */
export const SET_WORKING_DIRECTORY_LABEL = 'Set working directory';
/** Prefix of a hidden file or folder name (`.git`, `.config`). */
export const HIDDEN_NAME_PREFIX = '.';
export const GLOB = {
/** `C:`, the drive part of a Windows absolute path. */
DRIVE_PREFIX_REGEX: /^[A-Za-z]:/,
@@ -31,15 +34,28 @@ export const GLOB = {
export const SEARCH = {
// Search tuning for the picker's file_glob_search calls.
DEBOUNCE_MS: 180,
// A typo-tolerant search runs only when the exact one finds nothing. Past
// the shallow walk it goes less deep than the exact search, as it sends one
// glob per pair of neighbouring query characters.
FUZZY_MAX_DEPTH: 3,
// One wrong, missing, extra or swapped character still matches.
FUZZY_MAX_EDITS: 1,
// Longer queries would send too many globs for the typo-tolerant search.
FUZZY_MAX_QUERY_LENGTH: 16,
// Shorter queries are too loose to tell a typo from another name.
FUZZY_MIN_QUERY_LENGTH: 4,
LIMIT: 100,
// Home-relative globs descend deeper than path navigation, which only
// needs the direct children of the parent.
MAX_DEPTH: 6,
// A plain name is searched anywhere under home down to this depth; path
// navigation only needs the direct children of the parent.
MAX_DEPTH: 4,
MAX_RESULTS_SHOWN: 20,
NATIVE_LIMIT: 20,
// Native folder-picker resolution searches a shallow, bounded window.
NATIVE_MAX_DEPTH: 4,
PATH_NAV_MAX_DEPTH: 1
PATH_NAV_MAX_DEPTH: 1,
// A plain name is searched this deep first: the walk is fast, and the
// server's result cap cannot crowd the nearest folders out of it.
SHALLOW_DEPTH: 2
} as const;
export const FILE_GLOB_SEARCH_PICKERS = {
+2 -1
View File
@@ -84,7 +84,8 @@ export enum ChatFormCommandAction {
COMPACT = 'compact',
CWD = 'cwd',
MODEL = 'model',
PROMPT = 'prompt'
PROMPT = 'prompt',
SYSTEM_MESSAGE = 'system-message'
}
export enum FileMentionEntryType {
@@ -1,12 +1,19 @@
import { PROMPT_TRIGGER_PREFIX } from '#lib/constants/index.ts';
import { CWD_COMMAND_NAME } from '#lib/constants/index.ts';
import { ChatFormCommandAction, KeyboardKey } from '#lib/enums/index.ts';
import type { ChatFormCommand } from '#lib/types/index.ts';
import { getChatCommands } from '#lib/utils/index.ts';
import {
abbreviateHome,
type CommandDismissSnapshot,
type CommandToken,
findCommandToken,
findMentionToken,
getChatCommands,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
type MentionDismissSnapshot,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot,
takeMentionDismissSnapshot
} from '#lib/utils/index.ts';
@@ -22,6 +29,11 @@ export interface UseChatFormPickersOptions {
focusInput: () => void;
/** Whether typing `/` or `@` opens a picker at all. */
opensOnInput: () => boolean;
/**
* Whether the working directory is typed in the chat input, after a `/cwd` command
* wherever it is in the message, instead of in the picker's own search field.
*/
editsCwdInline: () => boolean;
/** Gates `/model`. */
getShowModelSelector: () => boolean;
/** Gates `/prompt`. */
@@ -32,6 +44,10 @@ export interface UseChatFormPickersOptions {
canCompact: () => boolean;
/** Runs `/compact`. */
onCompact: () => void;
/** Gates `/system-message`. */
canEditSystemMessage: () => boolean;
/** Runs `/system-message`: the form turns into the system message editor. */
onSystemMessage: () => void;
getCwd: () => string | null;
/** Mention search fallback scope. */
getServerHome: () => string | null;
@@ -54,11 +70,18 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
let mentionQuery = $state('');
let isWorkingDirectoryPickerOpen = $state(false);
let workingDirectoryQuery = $state('');
// The open picker searches the `/cwd` command in the chat input, not a field of its own.
// Set on every open and kept after a close, so the picker fades out the way it looked
let isWorkingDirectoryInline = $state(false);
// Last dismissed `@`-mention token; while intact, the picker does not
// reopen, so an escaped `@<query>` stays literal until edited.
let mentionDismissedSnapshot: MentionDismissSnapshot | null = null;
// Same dismissal contract for the `/`-command token.
let commandDismissedSnapshot: CommandDismissSnapshot | null = null;
// Where the open working directory picker's `/cwd` command is, its path as last typed,
// and the input's length then: an edit elsewhere in the message moves it by the
// change in length if it was made before it
let cwdCommand: { start: number; query: string; length: number } | null = null;
// Fall back to the server home so the picker still finds matches
// before a cwd is set.
@@ -66,55 +89,93 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
const availableCommands = $derived(
getChatCommands({
canCompact: opts.canCompact,
canEditSystemMessage: opts.canEditSystemMessage,
hasCwdTools: opts.hasCwdTools,
hasPrompts: opts.hasPrompts,
showModelSelector: opts.getShowModelSelector()
})
);
// only the commands that take an argument read the words after them
const commandNames = $derived(
availableCommands.filter((command) => command.takesArgument).map((command) => command.name)
);
const caretOf = (value: string) => opts.getCaretOffset() ?? value.length;
const commandAt = (value: string) => findCommandToken(value, caretOf(value), commandNames);
// Dispatch a slash command picked from the list: consume the token and
// open the target picker, seeding its search with `args`. Runs only on
// explicit selection (Enter/click), so the buffer is never cleared
// mid-typing.
function dispatchCommand(command: ChatFormCommand, args: string) {
/** The open picker's `/cwd` command where it now is, or null when it was edited away. */
function currentCwdCommand(value = opts.getValue()) {
if (!cwdCommand) return null;
const { length, query, start } = cwdCommand;
const shift = value.length - length;
const caret = opts.getCaretOffset();
// an edit made before the command leaves the caret before it too
const isEditBefore = caret === undefined || caret <= start + shift;
return locateCwdCommand(value, start, query, isEditBefore ? shift : 0);
}
function trackCwdCommand(start: number, query: string, value: string) {
cwdCommand = { length: value.length, query, start };
}
function setValueAndCaret(value: string, caret: number) {
if (opts.getValue() !== value) opts.setValue(value);
queueMicrotask(() => opts.setCaretOffset(caret));
}
/** Takes the command out of the message, leaving the words around it. */
function consumeCommand(token: { start: number; end: number }) {
const next = removeCommandToken(opts.getValue(), token);
setValueAndCaret(next.value, next.caret);
}
// Dispatch a slash command picked from the list, wherever it is in the message: take the
// token out and open the target picker, seeding its search with `args`. Runs only on
// explicit selection (Enter/click), so nothing is cleared mid-typing.
function dispatchCommand(command: ChatFormCommand, token: CommandToken) {
isCommandPickerOpen = false;
commandQuery = '';
if (command.action !== ChatFormCommandAction.CWD) {
isWorkingDirectoryPickerOpen = false;
cwdCommand = null;
consumeCommand(token);
}
switch (command.action) {
case ChatFormCommandAction.COMPACT:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
opts.onCompact();
break;
case ChatFormCommandAction.PROMPT:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
isPromptPickerOpen = true;
promptSearchQuery = args.trim();
promptSearchQuery = token.args.trim();
break;
case ChatFormCommandAction.CWD: {
// Keep `/cwd <args>` in the input so the search field and the
// token stay two-way bound; normalize partial tokens (`/cw foo`).
const trimmed = args.trim();
const newValue = `/cwd ${trimmed}`;
// `/cwd <path>` stays where it was typed, the path two-way bound to the picker's
// search; a partial token (`/cw foo`) is completed
const query = token.args.trim();
const next = replaceWithCwdCommand(opts.getValue(), token, query);
if (opts.getValue() !== newValue) {
opts.setValue(newValue);
queueMicrotask(() => opts.setCaretOffset(newValue.length));
}
workingDirectoryQuery = trimmed;
isWorkingDirectoryInline = opts.editsCwdInline();
trackCwdCommand(next.start, query, next.value);
setValueAndCaret(next.value, next.caret);
workingDirectoryQuery = query;
isWorkingDirectoryPickerOpen = true;
break;
}
case ChatFormCommandAction.MODEL:
isWorkingDirectoryPickerOpen = false;
opts.setValue('');
opts.openModelSelector();
break;
case ChatFormCommandAction.SYSTEM_MESSAGE:
opts.onSystemMessage();
break;
}
}
@@ -123,44 +184,43 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
if (!opts.opensOnInput()) return;
const value = opts.getValue();
const cursor = opts.getCaretOffset() ?? value.length;
const cursor = caretOf(value);
const command = commandAt(value);
if (value.startsWith(PROMPT_TRIGGER_PREFIX)) {
// While the `/cwd` picker is open the command doubles as its search field: keep the two
// in sync instead of re-dispatching. An edit elsewhere in the message leaves it open
if (isWorkingDirectoryPickerOpen && cwdCommand) {
isCommandPickerOpen = false;
commandQuery = '';
// the path as typed when the caret is in the command, not in another `/cwd` the
// message names
const tracked = currentCwdCommand(value);
const located =
tracked && command?.name === CWD_COMMAND_NAME && command.start === tracked.start
? { query: command.args, start: command.start }
: tracked;
if (located) {
trackCwdCommand(located.start, located.query, value);
workingDirectoryQuery = located.query.trim();
} else {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
cwdCommand = null;
}
return;
}
if (command) {
isMentionPickerOpen = false;
mentionQuery = '';
isPromptPickerOpen = false;
promptSearchQuery = '';
const token = findCommandToken(value);
if (!token) {
isCommandPickerOpen = false;
commandQuery = '';
return;
}
// While the `/cwd` picker is open the token doubles as its search
// field: keep the two in sync instead of re-dispatching.
if (isWorkingDirectoryPickerOpen) {
isCommandPickerOpen = false;
commandQuery = '';
if (token.name === 'cwd') {
workingDirectoryQuery = token.args.trim();
} else {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
}
return;
}
// Dismissed token stays literal until it changes.
const isDismissedSticky =
commandDismissedSnapshot !== null &&
commandDismissedSnapshot.name === token.name &&
commandDismissedSnapshot.args === token.args;
const isDismissedSticky = isCommandDismissed(commandDismissedSnapshot, command);
if (isDismissedSticky) {
isCommandPickerOpen = false;
@@ -174,7 +234,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
// picks the command from the list.
if (availableCommands.length > 0) {
isCommandPickerOpen = true;
commandQuery = token.name;
commandQuery = command.name;
} else {
isCommandPickerOpen = false;
commandQuery = '';
@@ -190,10 +250,6 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
commandDismissedSnapshot = null;
}
if (isWorkingDirectoryPickerOpen) {
isWorkingDirectoryPickerOpen = false;
}
const token = findMentionToken(value, cursor);
if (token) {
@@ -246,16 +302,20 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
function handleCommandSelect(command: ChatFormCommand) {
// Dispatch on the live token so typed args seed the target picker.
const token = findCommandToken(opts.getValue());
const value = opts.getValue();
const caret = caretOf(value);
const token = commandAt(value) ?? { args: '', end: caret, name: '', start: caret };
dispatchCommand(command, token?.args ?? '');
dispatchCommand(command, token);
}
// Picker dismissed: snapshot the live token so it stays literal until
// deleted or retyped.
function handleCommandPickerClose() {
if (isCommandPickerOpen) {
commandDismissedSnapshot = takeCommandDismissSnapshot(opts.getValue());
const value = opts.getValue();
commandDismissedSnapshot = takeCommandDismissSnapshot(value, caretOf(value), commandNames);
}
isCommandPickerOpen = false;
@@ -286,33 +346,77 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
opts.focusInput();
}
/** True while the caret is in the `/cwd` command, not in the message around it. */
function isCaretInCwdCommand(): boolean {
const located = currentCwdCommand();
const caret = opts.getCaretOffset();
return !located || caret === undefined || (caret >= located.start && caret <= located.end);
}
/** Takes the `/cwd` command out, leaving the message written around it. */
function consumeCwdCommand() {
const located = currentCwdCommand();
cwdCommand = null;
if (located) consumeCommand(located);
}
// Opened from the + menu or the chip. Inline, the current directory (or the path already
// after a `/cwd` command) goes on a `/cwd` command at the caret, to be edited there
function handleWorkingDirectoryOpen() {
workingDirectoryQuery = opts.getCwd() ?? '';
const cwd = opts.getCwd();
const seed = cwd ? abbreviateHome(cwd, opts.getServerHome()) : '';
isWorkingDirectoryInline = opts.editsCwdInline();
if (isWorkingDirectoryInline) {
const value = opts.getValue();
const located = currentCwdCommand(value);
if (located) {
trackCwdCommand(located.start, located.query, value);
workingDirectoryQuery = located.query.trim();
queueMicrotask(() => opts.setCaretOffset(located.end));
} else {
const next = insertCwdCommand(value, caretOf(value), seed);
trackCwdCommand(next.start, seed, next.value);
workingDirectoryQuery = seed;
setValueAndCaret(next.value, next.caret);
}
} else {
workingDirectoryQuery = seed;
}
isWorkingDirectoryPickerOpen = true;
}
// A closed picker leaves no `/cwd` command behind: committing a directory or dismissing
// the picker gives the message back as it was
function handleWorkingDirectoryClose() {
isWorkingDirectoryPickerOpen = false;
workingDirectoryQuery = '';
consumeCwdCommand();
opts.focusInput();
}
// Two-way bind the text after `/cwd ` and the picker search input; the
// reverse direction is handled by handleInput.
// Two-way bind the text after `/cwd ` and the picker's own search field; the reverse
// direction is handled by handleInput. Inline, the `/cwd` command is the only field
$effect(() => {
if (!isWorkingDirectoryPickerOpen) return;
const query = workingDirectoryQuery;
const value = opts.getValue();
const token = findCommandToken(value);
if (!isWorkingDirectoryPickerOpen || isWorkingDirectoryInline) return;
if (!token || token.name !== 'cwd') return;
const located = currentCwdCommand();
const newValue = `/cwd ${workingDirectoryQuery}`;
if (!located || located.query === query) return;
if (newValue === value) return;
const next = replaceWithCwdCommand(opts.getValue(), located, query);
opts.setValue(newValue);
queueMicrotask(() => opts.setCaretOffset(newValue.length));
trackCwdCommand(next.start, query, next.value);
opts.setValue(next.value);
});
return {
@@ -329,6 +433,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
set commandQuery(v: string) {
commandQuery = v;
},
consumeCwdCommand,
dispatchCommand,
handleCommandPickerClose,
handleCommandSelect,
@@ -339,6 +444,7 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
handlePromptPickerClose,
handleWorkingDirectoryClose,
handleWorkingDirectoryOpen,
isCaretInCwdCommand,
get isCommandPickerOpen() {
return isCommandPickerOpen;
},
@@ -357,6 +463,9 @@ export function useChatFormPickers(opts: UseChatFormPickersOptions) {
set isPromptPickerOpen(v: boolean) {
isPromptPickerOpen = v;
},
get isWorkingDirectoryInline() {
return isWorkingDirectoryInline;
},
get isWorkingDirectoryPickerOpen() {
return isWorkingDirectoryPickerOpen;
},
+28 -17
View File
@@ -48,6 +48,7 @@ class ToolsStore {
private _error = $state<string | null>(null);
private _loading = $state(false);
private _serverHome = $state<string | null | undefined>(undefined);
private _serverHomeRequest: Promise<string | null> | null = null;
private _serverTools = $state<OpenAIToolDefinition[]>([]);
private _toolsEndpointUnreachable = $state(false);
// server tools that resolve their paths against the working directory,
@@ -434,27 +435,18 @@ class ToolsStore {
* directory picker's search scope and the `~` abbreviation of cwd
* displays. Returns null when tools are unavailable.
*/
async resolveServerHome(): Promise<string | null> {
if (this._serverHome !== undefined) return this._serverHome;
resolveServerHome(): Promise<string | null> {
if (this._serverHome !== undefined) return Promise.resolve(this._serverHome);
// a plain chat never calls the server's tools
if (!agenticMode.enabled) return null;
if (!agenticMode.enabled) return Promise.resolve(null);
try {
const res = await ToolsService.executeToolRaw(BuiltInTool.SERVER_FILE_GLOB_SEARCH, {
limit: 1,
max_depth: 1,
path: HOME_TILDE,
type: GlobSearchType.DIR
});
// callers at the same time (a send, the pickers) share one request
this._serverHomeRequest ??= this.requestServerHome().finally(() => {
this._serverHomeRequest = null;
});
this._serverHome = typeof res.base === 'string' ? res.base : null;
} catch {
// searches still work via a literal `~`, only `~` abbreviation degrades
this._serverHome = null;
}
return this._serverHome;
return this._serverHomeRequest;
}
setCategoryEnabled(source: ToolSource, enabled: boolean): void {
@@ -707,6 +699,25 @@ class ToolsStore {
return buildReadMediaToolDefinition(vision, audio);
}
private async requestServerHome(): Promise<string | null> {
try {
const res = await ToolsService.executeToolRaw(BuiltInTool.SERVER_FILE_GLOB_SEARCH, {
limit: 1,
max_depth: 1,
path: HOME_TILDE,
type: GlobSearchType.DIR
});
this._serverHome = typeof res.base === 'string' ? res.base : null;
} catch {
// searches still work via a literal `~`, only `~` abbreviation degrades. Left
// unresolved, so the next caller asks again instead of keeping the failure
return null;
}
return this._serverHome;
}
private toolKey(source: ToolSource, name: string, serverId?: string): string {
switch (source) {
case ToolSource.MCP:
+4
View File
@@ -251,6 +251,8 @@ export interface ChatCommandsOptions {
hasPrompts: () => boolean;
/** Gates `/cwd`. */
hasCwdTools: () => boolean;
/** Gates `/system-message`. */
canEditSystemMessage: () => boolean;
}
/** Protocol-level verbs accepted by the realtime inference control endpoint. Mirrors `CONTROL_ACTION`. */
@@ -263,6 +265,8 @@ export interface ChatFormCommand {
keywords?: string[];
action: ChatFormCommandAction;
disabled: boolean;
/** Takes an argument after a space (`/cwd ~/git`); the others end at their name. */
takesArgument?: boolean;
}
/**
+13 -4
View File
@@ -1,4 +1,4 @@
import { SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts';
import { CWD_COMMAND_NAME, SET_WORKING_DIRECTORY_LABEL } from '#lib/constants/index.ts';
import { ChatFormCommandAction } from '#lib/enums/index.ts';
import type { ChatCommandsOptions, ChatFormCommand } from '#lib/types/index.ts';
@@ -16,14 +16,16 @@ export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[]
action: ChatFormCommandAction.PROMPT,
description: 'Insert an MCP prompt',
disabled: !options.hasPrompts(),
name: 'prompt'
name: 'prompt',
takesArgument: true
},
{
action: ChatFormCommandAction.CWD,
description: SET_WORKING_DIRECTORY_LABEL,
disabled: !options.hasCwdTools(),
keywords: ['current working directory'],
name: 'cwd'
name: CWD_COMMAND_NAME,
takesArgument: true
},
{
action: ChatFormCommandAction.MODEL,
@@ -33,10 +35,17 @@ export function getChatCommands(options: ChatCommandsOptions): ChatFormCommand[]
},
{
action: ChatFormCommandAction.COMPACT,
description: 'Summarize the conversation to free up context',
description: 'Summarize to free up context',
disabled: !options.canCompact(),
keywords: ['summarize', 'context'],
name: 'compact'
},
{
action: ChatFormCommandAction.SYSTEM_MESSAGE,
description: 'Edit the system message',
disabled: !options.canEditSystemMessage(),
keywords: ['system prompt', 'instructions'],
name: 'system-message'
}
];
}
+220 -12
View File
@@ -1,17 +1,118 @@
import {
COMMAND_NAME_REGEX,
CWD_COMMAND_PREFIX,
PROMPT_TRIGGER_PREFIX
} from '#lib/constants/index.ts';
const SPACE = ' ';
const WHITESPACE_REGEX = /\s/;
const COMMAND_NAME_PREFIX_REGEX = /^([\w-]+)/;
/** A slash command typed in the chat input: `/name`, and the argument after it. */
export interface CommandToken {
/** Offset of the `/`. */
start: number;
/** Offset just past the token. */
end: number;
name: string;
/** What follows the name and its space, e.g. the path of `/cwd ~/git`. */
args: string;
}
const isWhitespace = (char: string | undefined) => !!char && WHITESPACE_REGEX.test(char);
/** True when a command can start at `index`: the input's start, or right after whitespace. */
function startsCommand(value: string, index: number): boolean {
return value[index] === PROMPT_TRIGGER_PREFIX && (index === 0 || isWhitespace(value[index - 1]));
}
/** Where the text the caret is in begins: after a new line or two spaces in a row. */
function runStart(value: string, cursor: number): number {
let i = cursor;
while (i > 0) {
const char = value[i - 1];
if (isWhitespace(char) && char !== SPACE) break;
if (char === SPACE && value[i - 2] === SPACE) break;
i--;
}
return i;
}
/** Past the word the caret is in: the token never takes the text after it. */
function wordEnd(value: string, cursor: number): number {
let end = cursor;
while (end < value.length && !isWhitespace(value[end])) end++;
return end;
}
/**
* Slash-command token detection for the chat form. Valid only at offset 0.
* The slash command the caret is in, anywhere in the input: a `/` at the input's start or
* after whitespace, then the command's name, as in `fix this /cwd ~/git`.
*
* A command that takes an argument (one of `commands`, or the start of one's name) takes
* it after a space, single spaces included (`/cwd ~/My Documents`); like an `@` mention,
* two spaces or a new line end it. So a path in the argument (`/cwd /usr/lo`) is not taken
* for a command of its own, unless it names one. Any other command ends at its name: the
* words after `/model` are the message's. After the caret the token runs to the end of the
* word.
*/
export function findCommandToken(
value: string
): { name: string; args: string; end: number } | null {
if (!value.startsWith('/')) return null;
value: string,
cursor: number,
commands: readonly string[] = []
): CommandToken | null {
if (cursor < 0 || cursor > value.length) return null;
const rest = value.slice(1);
const spaceIdx = rest.search(/\s/);
const name = spaceIdx === -1 ? rest : rest.slice(0, spaceIdx);
const args = spaceIdx === -1 ? '' : rest.slice(spaceIdx + 1);
const end = wordEnd(value, cursor);
const from = runStart(value, cursor);
return { args, end: value.length, name };
// the word the caret is in, when it is a `/name`
let word: CommandToken | null = null;
for (let i = cursor - 1; i >= from && !isWhitespace(value[i]); i--) {
if (!startsCommand(value, i)) continue;
const name = value.slice(i + 1, end);
if (COMMAND_NAME_REGEX.test(name)) word = { args: '', end, name, start: i };
break;
}
// a command that takes an argument further back on the run, with the caret in it
let withArgs: CommandToken | null = null;
for (let i = cursor - 1; i >= from; i--) {
if (!startsCommand(value, i)) continue;
// a known command, or the start of one (`/cw docs` completes to `/cwd docs`)
const name = COMMAND_NAME_PREFIX_REGEX.exec(value.slice(i + PROMPT_TRIGGER_PREFIX.length))?.[1];
if (!name || value[i + PROMPT_TRIGGER_PREFIX.length + name.length] !== SPACE) continue;
if (!commands.some((command) => command.startsWith(name))) continue;
const argsStart = i + PROMPT_TRIGGER_PREFIX.length + name.length + SPACE.length;
if (argsStart > cursor) continue;
withArgs = { args: value.slice(argsStart, end), end, name, start: i };
break;
}
if (word && (!withArgs || commands.some((command) => command.startsWith(word.name)))) {
return word;
}
return withArgs ?? word;
}
/**
@@ -20,14 +121,121 @@ export function findCommandToken(
* the picker does not re-open on in-token edits.
*/
export interface CommandDismissSnapshot {
start: number;
name: string;
args: string;
}
export function takeCommandDismissSnapshot(value: string): CommandDismissSnapshot | null {
const token = findCommandToken(value);
export function takeCommandDismissSnapshot(
value: string,
cursor: number,
commands: readonly string[] = []
): CommandDismissSnapshot | null {
const token = findCommandToken(value, cursor, commands);
if (!token) return null;
return { args: token.args, name: token.name };
return { args: token.args, name: token.name, start: token.start };
}
export function isCommandDismissed(
snapshot: CommandDismissSnapshot | null,
token: CommandToken
): boolean {
return (
!!snapshot &&
snapshot.start === token.start &&
snapshot.name === token.name &&
snapshot.args === token.args
);
}
/** The input with `[start, end)` taken out, and where the caret goes: where it was. */
export function removeCommandToken(
value: string,
token: { start: number; end: number }
): { value: string; caret: number } {
let before = value.slice(0, token.start);
let after = value.slice(token.end);
// one space is left where the token was, none at the start or end of a line
if ((!before || isWhitespace(before.at(-1))) && after.startsWith(SPACE)) {
after = after.slice(SPACE.length);
} else if (before.endsWith(SPACE) && (!after || isWhitespace(after[0]))) {
before = before.slice(0, -SPACE.length);
}
return { caret: before.length, value: before + after };
}
/** The input with `/cwd <query>` in `[start, end)`, and the offset past the query. */
export function replaceWithCwdCommand(
value: string,
token: { start: number; end: number },
query: string
): { value: string; start: number; caret: number } {
const text = `${CWD_COMMAND_PREFIX}${query}`;
return {
caret: token.start + text.length,
start: token.start,
value: value.slice(0, token.start) + text + value.slice(token.end)
};
}
/**
* The input with `/cwd <query>` written at `caret`, set apart from the words around it by
* a space, and where the command starts and the query ends.
*/
export function insertCwdCommand(
value: string,
caret: number,
query: string
): { value: string; start: number; caret: number } {
const before = value.slice(0, caret);
const after = value.slice(caret);
const lead = before && !isWhitespace(before.at(-1)) ? SPACE : '';
const trail = after && !isWhitespace(after[0]) ? SPACE : '';
const start = before.length + lead.length;
return replaceWithCwdCommand(before + lead + trail + after, { end: start, start }, query);
}
/**
* Finds the `/cwd` command again after an edit somewhere else: at `start` if the edit was
* after it, or moved by `shift` (the change in the input's length) if it was before. Its
* argument is `query` when the text still reads so, or else runs to two spaces or the end
* of the line. Null when the command is gone, even if the message names `/cwd` elsewhere.
*/
export function locateCwdCommand(
value: string,
start: number,
query: string,
shift = 0
): { start: number; end: number; query: string } | null {
const isCwdAt = (index: number) =>
startsCommand(value, index) &&
value.startsWith(CWD_COMMAND_PREFIX.trimEnd(), index) &&
(index + CWD_COMMAND_PREFIX.length - 1 === value.length ||
isWhitespace(value[index + CWD_COMMAND_PREFIX.length - 1]));
const found = [start, start + shift].find(isCwdAt);
if (found === undefined) return null;
const argsStart = Math.min(found + CWD_COMMAND_PREFIX.length, value.length);
if (value.startsWith(query, argsStart)) {
return { end: argsStart + query.length, query, start: found };
}
let end = argsStart;
while (
end < value.length &&
(!isWhitespace(value[end]) || (value[end] === SPACE && value[end + 1] !== SPACE))
) {
end++;
}
return { end, query: value.slice(argsStart, end).trimEnd(), start: found };
}
+238 -24
View File
@@ -5,8 +5,24 @@
*/
import { lastPathSegment } from './path-display';
import { buildGlobSearchArgs, joinPath, rankEntries } from './working-directory';
import { GLOB, PATH_SEPARATOR, SEARCH } from '#lib/constants/index.ts';
import {
buildFuzzyGlobs,
buildGlobSearchArgs,
fuzzyDistance,
isHiddenPath,
joinPath,
rankEntries,
splitPathQuery,
toHomeRelativeQuery,
toScopeSeparators
} from './working-directory';
import {
GLOB,
HIDDEN_NAME_PREFIX,
HOME_TILDE,
PATH_SEPARATOR,
SEARCH
} from '#lib/constants/index.ts';
import { BuiltInTool, GlobSearchType } from '#lib/enums/index.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import type {
@@ -78,6 +94,57 @@ export async function runGlobSearchWithChildren(
limit: number,
signal: AbortSignal,
options: GlobSearchChildOptions = {}
): Promise<GlobSearchChildResult> {
const search = (q: string) =>
searchWithChildren(q, scopePath, searchDepth, limit, signal, options);
query = toScopeSeparators(query, scopePath);
const pathQuery = splitPathQuery(query);
if (pathQuery) {
const direct = await search(query);
const canLookDeeper = !!pathQuery.last && searchDepth > SEARCH.PATH_NAV_MAX_DEPTH;
if (direct.error || direct.entries.length > 0 || !canLookDeeper) return direct;
// no such name in that folder (`~/llama.cpp`): look for it further down (`~/git/llama.cpp`)
const deep = await runGlobSearch(
{ ...direct.args, maxDepth: searchDepth },
options.type ?? GlobSearchType.ALL,
limit,
signal
);
if (deep.error) return direct;
const ranked = rankEntries(deep.entries, direct.args.rankQuery);
return { ...direct, base: deep.base, entries: ranked.map((e) => toEntryResult(e, deep.base)) };
}
if (!query.includes(PATH_SEPARATOR)) return search(query);
// A relative path (`ui/lib/voi`) is also followed from the scope itself: the
// server's glob matches it only below some other folder, never at the top.
const [direct, deep] = await Promise.all([search(joinPath(scopePath, query)), search(query)]);
// nothing found directly: the deep search speaks, its error included
if (direct.error || (direct.entries.length === 0 && deep.error)) return deep;
const directPaths = new Set(direct.entries.map((entry) => entry.path));
const below = deep.entries.filter((entry) => !directPaths.has(entry.path));
return { ...direct, entries: [...direct.entries, ...below] };
}
async function searchWithChildren(
query: string,
scopePath: string,
searchDepth: number,
limit: number,
signal: AbortSignal,
options: GlobSearchChildOptions
): Promise<GlobSearchChildResult> {
const {
childMaxDepth = SEARCH.PATH_NAV_MAX_DEPTH,
@@ -90,35 +157,182 @@ export async function runGlobSearchWithChildren(
if (res.error) return { args, base: res.base, entries: [], error: res.error };
const ranked = rankEntries(res.entries, args.rankQuery);
const entries = ranked.map((e) => toEntryResult(e, res.base));
const last = args.last;
const result = { args, base: res.base, entries: ranked.map((e) => toEntryResult(e, res.base)) };
const wantsDescend = descendOnTrailingSeparator
? query.endsWith(PATH_SEPARATOR) || query.endsWith(GLOB.WINDOWS_SEPARATOR)
: true;
if (last) {
const wantsDescend = descendOnTrailingSeparator
? query.endsWith(PATH_SEPARATOR) || query.endsWith(GLOB.WINDOWS_SEPARATOR)
: true;
const exact = ranked.find(
(e) => e.type === 'dir' && lastPathSegment(e.path).toLowerCase() === last.toLowerCase()
if (!args.last || !wantsDescend) return result;
return withExactDirChildren(result, ranked, args.last, type, limit, childMaxDepth, signal);
}
/** Append the children of the directory named exactly `name`, when the results hold one. */
async function withExactDirChildren(
result: GlobSearchChildResult,
ranked: GlobEntry[],
name: string,
type: GlobSearchType,
limit: number,
childMaxDepth: number,
signal: AbortSignal
): Promise<GlobSearchChildResult> {
const exact = ranked.find(
(e) => e.type === 'dir' && lastPathSegment(e.path).toLowerCase() === name.toLowerCase()
);
if (!exact) return result;
const exactDir = joinPath(result.base, exact.path);
const childRes = await runGlobSearch(
{ include: GLOB.WILDCARD, maxDepth: childMaxDepth, path: exactDir, rankQuery: '' },
type,
limit,
signal
);
if (childRes.error) return result;
// alphabetical, with hidden entries after the regular ones
const children = childRes.entries
.map((e) => toEntryResult(e, childRes.base))
.sort(
(a, b) =>
Number(isHiddenPath(a.name)) - Number(isHiddenPath(b.name)) || a.path.localeCompare(b.path)
);
if (wantsDescend && exact) {
const exactDir = joinPath(res.base, exact.path);
const childRes = await runGlobSearch(
{ include: GLOB.WILDCARD, maxDepth: childMaxDepth, path: exactDir, rankQuery: '' },
type,
limit,
signal
);
return { ...result, entries: [...result.entries, ...children], exactDir };
}
if (!childRes.error) {
const children = childRes.entries
.map((e) => toEntryResult(e, childRes.base))
.sort((a, b) => a.path.localeCompare(b.path));
/**
* Folders within a typo of the query's name, for when the exact search finds
* nothing. The depths are walked in turn, nearest first, and the walk stops at
* the first one that finds something: every glob is a walk of its own on the
* server, and its result cap could crowd the nearest folders out of a deeper one.
*/
async function runFuzzyFolderSearch(
args: GlobSearchArgs,
depths: number[],
signal: AbortSignal
): Promise<GlobSearchChildResult> {
const globs = buildFuzzyGlobs(args.rankQuery);
const close = new Map<string, GlobEntry>();
return { args, base: res.base, entries: [...entries, ...children], exactDir };
let base = '';
let error: string | undefined;
for (const maxDepth of depths) {
const results = await Promise.all(
globs.map((include) =>
runGlobSearch({ ...args, include, maxDepth }, GlobSearchType.DIR, SEARCH.LIMIT, signal)
)
);
base = results.find((res) => !res.error)?.base ?? base;
// a walk whose every glob failed reports why, rather than finding nothing
error = results.every((res) => res.error) ? results[0]?.error : undefined;
if (error) break;
for (const entry of results.flatMap((res) => res.entries)) {
if (fuzzyDistance(lastPathSegment(entry.path), args.rankQuery) <= SEARCH.FUZZY_MAX_EDITS) {
close.set(entry.path, entry);
}
}
if (close.size > 0) break;
}
return { args, base: res.base, entries };
if (error && close.size === 0) return { args, base, entries: [], error };
const entries = rankEntries([...close.values()], args.rankQuery);
return { args, base, entries: entries.map((e) => toEntryResult(e, base)) };
}
/**
* The working-directory picker's search. A query with a path in it (`git/llama`,
* `~/git`, `/usr/lo`) navigates: it matches the last segment among the parent's
* children. A plain name (`llama`) is looked up anywhere under home, nearest
* folders first: `onPartial` gets the shallow results while the deeper walk
* runs. Either way a search that finds nothing is retried allowing for a typo.
*/
export async function runFolderSearch(
query: string,
home: string | null,
signal: AbortSignal,
onPartial?: (result: GlobSearchChildResult) => void
): Promise<GlobSearchChildResult> {
const scope = home ?? HOME_TILDE;
const type = GlobSearchType.DIR;
query = toScopeSeparators(query, scope);
if (splitPathQuery(query) || query.includes(PATH_SEPARATOR)) {
const res = await runGlobSearchWithChildren(
toHomeRelativeQuery(query, home),
scope,
SEARCH.MAX_DEPTH,
SEARCH.LIMIT,
signal,
{ type }
);
if (res.error || res.entries.length > 0) return res;
return runFuzzyFolderSearch(res.args, [SEARCH.PATH_NAV_MAX_DEPTH], signal);
}
const args = buildGlobSearchArgs(query, scope, SEARCH.SHALLOW_DEPTH);
// started alongside the shallow search and read after it: a failure here (the search
// being cancelled, say) must not go unhandled, and costs only the deeper results
const deepSearch = runGlobSearch(
{ ...args, maxDepth: SEARCH.MAX_DEPTH },
type,
SEARCH.LIMIT,
signal
).catch((): GlobSearchResult => ({ base: '', entries: [] }));
const shallow = await runGlobSearch(args, type, SEARCH.LIMIT, signal);
if (shallow.error) return { args, base: shallow.base, entries: [], error: shallow.error };
const near = rankEntries(shallow.entries, query);
// only a near folder is entered on an exact name: a deeper namesake is just a result
const collect = (ranked: GlobEntry[], base: string) => {
const result = { args, base, entries: ranked.map((e) => toEntryResult(e, base)) };
return withExactDirChildren(
result,
near,
query,
type,
SEARCH.LIMIT,
SEARCH.PATH_NAV_MAX_DEPTH,
signal
);
};
if (near.length > 0) onPartial?.(await collect(near, shallow.base));
const deep = await deepSearch;
const nearPaths = new Set(near.map((entry) => entry.path));
// deeper folders go below the near ones, so the list does not reshuffle when they arrive
const far = rankEntries(
deep.entries.filter((entry) => !nearPaths.has(entry.path)),
query
);
if (near.length + far.length === 0) {
return runFuzzyFolderSearch(args, [SEARCH.SHALLOW_DEPTH, SEARCH.FUZZY_MAX_DEPTH], signal);
}
// hidden folders go last, below even the deeper regular ones
const isRegular = (entry: GlobEntry) =>
query.startsWith(HIDDEN_NAME_PREFIX) || !isHiddenPath(entry.path);
const found = [...near, ...far];
return collect(
[...found.filter(isRegular), ...found.filter((entry) => !isRegular(entry))],
shallow.base
);
}
@@ -0,0 +1,7 @@
/**
* True for a mouse move the user made. A list that renders under a resting
* pointer fires hover events too, and those must not move a picker's highlight.
*/
export function hasPointerMoved(event: MouseEvent) {
return event.movementX !== 0 || event.movementY !== 0;
}
+12 -1
View File
@@ -125,6 +125,7 @@ export {
} from './formatters';
// IME utilities
export { hasPointerMoved } from './has-pointer-moved';
export { isIMEComposing } from './is-ime-composing';
export { shouldTypeToFocus } from './type-to-focus';
@@ -235,9 +236,13 @@ export {
export {
splitPathQuery,
toHomeRelativeQuery,
toScopeSeparators,
buildCaseInsensitiveGlob,
buildFuzzyGlobs,
fuzzyDistance,
buildGlobSearchArgs,
rankEntries,
isHiddenPath,
joinPath,
highlightMatch,
type PathQuery
@@ -246,7 +251,7 @@ export {
export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs';
// Shared `file_glob_search` runner with a short-lived result cache
export { runGlobSearch, runGlobSearchWithChildren } from './glob-search';
export { runFolderSearch, runGlobSearch, runGlobSearchWithChildren } from './glob-search';
// Mention-token detection (for the `@`-triggered file/folder mention picker)
export {
@@ -257,7 +262,13 @@ export {
// Slash-command token detection (for the `/`-triggered command picker)
export {
type CommandToken,
findCommandToken,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot,
type CommandDismissSnapshot
} from './command-token';
+11 -2
View File
@@ -9,6 +9,11 @@ import {
TRAILING_SLASHES_REGEX
} from '#lib/constants/index.ts';
/** `~` or a path under it, as typed or as a search from `~` returns it. */
function isTildePath(path: string): boolean {
return path === HOME_TILDE || path.startsWith(HOME_TILDE_PREFIX);
}
export function lastPathSegment(p: string): string {
const trimmed = p.replace(TRAILING_SLASHES_REGEX, '');
const idx = trimmed.lastIndexOf(PATH_SEPARATOR);
@@ -16,14 +21,16 @@ export function lastPathSegment(p: string): string {
return idx === -1 ? trimmed : trimmed.slice(idx + 1);
}
// `~/...` under `home`; falls back to the basename when home is unknown
// or the path is outside it.
// `~/...` under `home` (a path already written from `~` stays as it is); falls back to the
// basename when home is unknown or the path is outside it.
export function abbreviateWorkingDir(
path: string | null | undefined,
home: string | null | undefined
): string {
if (!path) return '';
if (isTildePath(path)) return path;
if (!home) return lastPathSegment(path);
if (path === home) return HOME_TILDE;
@@ -37,6 +44,8 @@ export function abbreviateWorkingDir(
// Unlike abbreviateWorkingDir, paths outside `home` are returned
// unchanged - used where the full path matters.
export function abbreviateHome(path: string, home: string | null | undefined): string {
if (isTildePath(path)) return path;
if (!home) return path;
if (path === home) return HOME_TILDE;
@@ -9,6 +9,7 @@
import { lastPathSegment } from './path-display';
import {
GLOB,
HIDDEN_NAME_PREFIX,
HOME_TILDE,
HOME_TILDE_PREFIX,
LEADING_SLASHES_REGEX,
@@ -34,6 +35,19 @@ function toPosixSeparators(query: string): string {
return query.split(GLOB.WINDOWS_SEPARATOR).join(PATH_SEPARATOR);
}
/**
* The query with `\\` rewritten into `/` when the scope it is searched in is a
* Windows path (`C:/Users/al`, `//host/share`), so `git\\llama` is a path there
* too. Under a POSIX scope the backslash stays: it is a legal filename character.
*/
export function toScopeSeparators(query: string, scope: string): string {
const isWindowsScope = GLOB.DRIVE_PREFIX_REGEX.test(scope) || GLOB.UNC_ROOT_REGEX.test(scope);
if (!isWindowsScope) return query;
return query.split(GLOB.WINDOWS_SEPARATOR).join(PATH_SEPARATOR);
}
export function rootPrefixLength(path: string): number {
const unc = path.match(GLOB.UNC_ROOT_REGEX);
@@ -86,10 +100,11 @@ export function toHomeRelativeQuery(query: string, home?: string | null): string
return home ? joinPath(home, query) : HOME_TILDE_PREFIX + query;
}
export function buildCaseInsensitiveGlob(query: string): string {
let out = GLOB.WILDCARD;
/** Glob fragment matching `text` in any letter case, with glob metacharacters taken literally. */
function toCaseInsensitiveFragment(text: string): string {
let out = '';
for (const c of query) {
for (const c of text) {
const lo = c.toLowerCase();
const up = c.toUpperCase();
@@ -100,7 +115,70 @@ export function buildCaseInsensitiveGlob(query: string): string {
else out += c;
}
return out + GLOB.WILDCARD;
return out;
}
export function buildCaseInsensitiveGlob(query: string): string {
return GLOB.WILDCARD + toCaseInsensitiveFragment(query) + GLOB.WILDCARD;
}
/**
* Globs that together match every name within one typo of `query`: each one
* swaps a pair of neighbouring characters for a wildcard, which covers a
* wrong, missing, extra or swapped character there. They match far more than
* that, so the results are filtered with `fuzzyDistance`.
*/
export function buildFuzzyGlobs(query: string): string[] {
const chars = [...query];
if (chars.length < SEARCH.FUZZY_MIN_QUERY_LENGTH || chars.length > SEARCH.FUZZY_MAX_QUERY_LENGTH)
return [];
const globs = new Set<string>();
for (let i = 0; i + 1 < chars.length; i++) {
const kept = [chars.slice(0, i), chars.slice(i + 2)]
.filter((part) => part.length > 0)
.map((part) => toCaseInsensitiveFragment(part.join('')));
globs.add(GLOB.WILDCARD + kept.join(GLOB.WILDCARD) + GLOB.WILDCARD);
}
return [...globs];
}
/**
* Fewest single-character edits (a wrong, missing, extra or swapped
* character) that turn `query` into some part of `text`, ignoring case.
*/
export function fuzzyDistance(text: string, query: string): number {
const t = [...text.toLowerCase()];
const q = [...query.toLowerCase()];
// a match may start anywhere in the text, so the first row costs nothing
let previous: number[] = new Array(t.length + 1).fill(0);
let beforePrevious: number[] = [];
for (let i = 1; i <= q.length; i++) {
const row = [i];
for (let j = 1; j <= t.length; j++) {
const substitution = previous[j - 1] + (q[i - 1] === t[j - 1] ? 0 : 1);
let best = Math.min(previous[j] + 1, row[j - 1] + 1, substitution);
if (i > 1 && j > 1 && q[i - 1] === t[j - 2] && q[i - 2] === t[j - 1]) {
best = Math.min(best, beforePrevious[j - 2] + 1);
}
row.push(best);
}
beforePrevious = previous;
previous = row;
}
return Math.min(...previous);
}
export function buildGlobSearchArgs(
@@ -138,9 +216,24 @@ function rankScore(path: string, query: string): number {
return RANK_OTHER;
}
/** True when the path is, or sits inside, a hidden folder (`.config/llama`, `git\\.cache`). */
export function isHiddenPath(path: string): boolean {
return toPosixSeparators(path)
.split(PATH_SEPARATOR)
.some((segment) => segment.startsWith(HIDDEN_NAME_PREFIX));
}
/**
* Regular entries come before hidden ones, unless the query itself asks for a
* hidden name (`.config`). Within each group the best name match wins.
*/
export function rankEntries(entries: GlobEntry[], query: string): GlobEntry[] {
const hiddenRank = (path: string) =>
!query.startsWith(HIDDEN_NAME_PREFIX) && isHiddenPath(path) ? 1 : 0;
return [...entries].sort(
(a, b) =>
hiddenRank(a.path) - hiddenRank(b.path) ||
rankScore(a.path, query) - rankScore(b.path, query) ||
a.path.length - b.path.length ||
a.path.localeCompare(b.path)
@@ -1,7 +1,8 @@
// Guards the slash-command dispatch contract: commands dispatch only on
// explicit selection (Enter/click in the picker), never mid-typing.
// Typing `/model is broken` is prose until the command is picked - the
// buffer must survive; only an actual selection consumes the token.
// Typing `/model is broken` is prose: `/model` takes no argument, so the
// words after it close the picker and the buffer survives; only an actual
// selection consumes the token.
import ChatFormPickersHarness from './components/ChatFormPickersHarness.svelte';
import { tick } from 'svelte';
@@ -22,8 +23,7 @@ describe('slash command dispatch', () => {
expect(screen.component.getValue()).toBe('/model is broken');
expect(screen.component.getCalls()).not.toContain('openModelSelector');
expect(screen.component.getCalls().some((c) => c.startsWith('setValue:'))).toBe(false);
expect(pickers.isCommandPickerOpen).toBe(true);
expect(pickers.commandQuery).toBe('model');
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('dispatches /model on explicit selection and consumes the token', async () => {
@@ -31,7 +31,7 @@ describe('slash command dispatch', () => {
await tick();
screen.component.type('/model is broken');
screen.component.type('/model');
await tick();
const pickers = screen.component.getPickers();
@@ -47,6 +47,27 @@ describe('slash command dispatch', () => {
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('opens the system message editor on /system-message and consumes the token', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.type('/system');
await tick();
const pickers = screen.component.getPickers();
const command = pickers.availableCommands.find((c) => c.name === 'system-message');
if (!command) throw new Error('system-message command missing');
pickers.handleCommandSelect(command);
await tick();
expect(screen.component.getValue()).toBe('');
expect(screen.component.getCalls()).toContain('onSystemMessage');
expect(pickers.isCommandPickerOpen).toBe(false);
});
it('seeds the prompt picker search from the token args on selection', async () => {
const screen = render(ChatFormPickersHarness);
@@ -137,3 +158,186 @@ describe('slash command dispatch', () => {
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
});
});
describe('commands anywhere in the message', () => {
it('opens the command picker for a command typed after other words', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build /mod|');
await tick();
const pickers = screen.component.getPickers();
expect(pickers.isCommandPickerOpen).toBe(true);
expect(pickers.commandQuery).toBe('mod');
});
it('takes only the command out of the message on selection', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix /model| the build');
await tick();
const pickers = screen.component.getPickers();
const model = pickers.availableCommands.find((c) => c.name === 'model');
if (!model) throw new Error('model command missing');
pickers.handleCommandSelect(model);
await tick();
await Promise.resolve();
expect(screen.component.getValue()).toBe('fix the build');
expect(screen.component.getCaretOffset()).toBe('fix '.length);
expect(screen.component.getCalls()).toContain('openModelSelector');
});
it('leaves a path in the message alone', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('look in src/lib|');
await tick();
expect(screen.component.getPickers().isCommandPickerOpen).toBe(false);
});
});
describe('/cwd command in the chat input', () => {
it('writes the current directory on a /cwd command at the caret', async () => {
const screen = render(ChatFormPickersHarness, {
cwd: '/home/me/projects/app',
serverHome: '/home/me'
});
await tick();
screen.component.typeAt('fix| the build');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
await Promise.resolve();
expect(screen.component.getValue()).toBe('fix /cwd ~/projects/app the build');
expect(screen.component.getCaretOffset()).toBe('fix /cwd ~/projects/app'.length);
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
expect(pickers.isWorkingDirectoryInline).toBe(true);
expect(pickers.workingDirectoryQuery).toBe('~/projects/app');
});
it('searches the path after /cwd, not the words around it', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build|');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
expect(screen.component.getValue()).toBe('fix the build /cwd ');
screen.component.typeAt('fix the build /cwd docs|');
await tick();
expect(pickers.workingDirectoryQuery).toBe('docs');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
// an edit elsewhere in the message keeps the picker and its path
screen.component.typeAt('so,| fix the build /cwd docs');
await tick();
expect(pickers.workingDirectoryQuery).toBe('docs');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(true);
});
it('gives the message back when the picker closes', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix| the build');
const pickers = screen.component.getPickers();
pickers.handleWorkingDirectoryOpen();
await tick();
screen.component.typeAt('fix /cwd docs| the build');
pickers.handleWorkingDirectoryClose();
await tick();
expect(screen.component.getValue()).toBe('fix the build');
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
});
it('closes when its command is deleted, whatever else the message says', async () => {
const screen = render(ChatFormPickersHarness, {
cwd: '/home/me/git',
serverHome: '/home/me'
});
await tick();
const pickers = screen.component.getPickers();
screen.component.typeAt('why does /cwd break|');
pickers.handleWorkingDirectoryOpen();
await tick();
expect(screen.component.getValue()).toBe('why does /cwd break /cwd ~/git');
// deleting ` /cwd ~/git` shifts the text by as much as the other `/cwd` is away
screen.component.typeAt('why does /cwd break|');
await tick();
expect(pickers.isWorkingDirectoryPickerOpen).toBe(false);
expect(screen.component.getValue()).toBe('why does /cwd break');
});
it('completes a typed /cw command where it is, on selection', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
screen.component.typeAt('fix the build /cw docs|');
await tick();
const pickers = screen.component.getPickers();
const cwd = pickers.availableCommands.find((c) => c.name === 'cwd');
if (!cwd) throw new Error('cwd command missing');
pickers.handleCommandSelect(cwd);
await tick();
expect(screen.component.getValue()).toBe('fix the build /cwd docs');
expect(pickers.workingDirectoryQuery).toBe('docs');
});
it('tells the /cwd command from the message around it by the caret', async () => {
const screen = render(ChatFormPickersHarness);
await tick();
const pickers = screen.component.getPickers();
screen.component.typeAt('fix the build|');
pickers.handleWorkingDirectoryOpen();
await tick();
screen.component.typeAt('fix the build /cwd docs|');
expect(pickers.isCaretInCwdCommand()).toBe(true);
screen.component.typeAt('fix| the build /cwd docs');
expect(pickers.isCaretInCwdCommand()).toBe(false);
});
});
@@ -4,17 +4,26 @@
type UseChatFormPickersReturn
} from '#lib/hooks/use-chat-form-pickers.svelte.ts';
interface Props {
cwd?: string | null;
serverHome?: string | null;
}
let { cwd = null, serverHome = null }: Props = $props();
let value = $state('');
let caretOffset = $state(0);
const calls: string[] = [];
const pickers = useChatFormPickers({
canCompact: () => true,
canEditSystemMessage: () => true,
editsCwdInline: () => true,
focusInput: () => {},
getCaretOffset: () => caretOffset,
getCwd: () => null,
getCwd: () => cwd,
getPickersRef: () => undefined,
getServerHome: () => null,
getServerHome: () => serverHome,
getShowModelSelector: () => true,
getValue: () => value,
hasCwdTools: () => true,
@@ -22,6 +31,9 @@
onCompact: () => {
calls.push('onCompact');
},
onSystemMessage: () => {
calls.push('onSystemMessage');
},
openModelSelector: () => {
calls.push('openModelSelector');
},
@@ -42,6 +54,17 @@
pickers.handleInput();
}
// The same, with the caret at `|` in `text`: an edit somewhere in the middle.
export function typeAt(text: string) {
value = text.replace('|', '');
caretOffset = text.indexOf('|');
pickers.handleInput();
}
export function getCaretOffset() {
return caretOffset;
}
export function getValue() {
return value;
}
@@ -168,7 +168,7 @@ export const chatCommands: ChatFormCommand[] = [
},
{
action: ChatFormCommandAction.COMPACT,
description: 'Summarize the conversation to free up context',
description: 'Summarize to free up context',
disabled: true,
keywords: ['summarize', 'context'],
name: 'compact'
+129 -29
View File
@@ -1,51 +1,151 @@
import { findCommandToken, takeCommandDismissSnapshot } from '#lib/utils/index.ts';
import {
findCommandToken,
insertCwdCommand,
isCommandDismissed,
locateCwdCommand,
removeCommandToken,
replaceWithCwdCommand,
takeCommandDismissSnapshot
} from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
// the commands that take an argument
const COMMANDS = ['prompt', 'cwd'];
/** The token with the caret at `|` in `text`. */
function tokenAt(text: string, commands: readonly string[] = COMMANDS) {
const cursor = text.indexOf('|');
return findCommandToken(text.replace('|', ''), cursor, commands);
}
describe('findCommandToken', () => {
it('returns null when the value does not start with a slash', () => {
expect(findCommandToken('hello /prompt')).toBeNull();
expect(findCommandToken('')).toBeNull();
expect(findCommandToken('prompt')).toBeNull();
it('returns null where no command is typed', () => {
expect(tokenAt('|')).toBeNull();
expect(tokenAt('prompt|')).toBeNull();
expect(tokenAt('and/or|')).toBeNull();
expect(tokenAt('see ~/git|')).toBeNull();
});
it('parses a bare slash', () => {
expect(findCommandToken('/')).toEqual({ args: '', end: 1, name: '' });
it('finds a command at the start of the input', () => {
expect(tokenAt('/|')).toEqual({ args: '', end: 1, name: '', start: 0 });
expect(tokenAt('/prompt|')).toEqual({ args: '', end: 7, name: 'prompt', start: 0 });
});
it('parses a command name with no args', () => {
expect(findCommandToken('/prompt')).toEqual({ args: '', end: 7, name: 'prompt' });
it('finds a command anywhere in the message', () => {
expect(tokenAt('fix the build /cw|')).toEqual({ args: '', end: 17, name: 'cw', start: 14 });
expect(tokenAt('first line\n/mod|')).toEqual({ args: '', end: 15, name: 'mod', start: 11 });
expect(tokenAt('fix /cw| the build')).toEqual({ args: '', end: 7, name: 'cw', start: 4 });
});
it('parses a command name followed by a space', () => {
expect(findCommandToken('/prompt ')).toEqual({ args: '', end: 8, name: 'prompt' });
it('runs to the end of the word the caret is in', () => {
expect(tokenAt('/pro|mpt and more')).toEqual({ args: '', end: 7, name: 'prompt', start: 0 });
});
it('parses args after the command name', () => {
expect(findCommandToken('/prompt rev')).toEqual({ args: 'rev', end: 11, name: 'prompt' });
});
it('parses multi-word args', () => {
expect(findCommandToken('/prompt review code ')).toEqual({
args: ' review code ',
end: 22,
name: 'prompt'
it('takes the argument of a known command, single spaces included', () => {
expect(tokenAt('/prompt rev|')).toEqual({ args: 'rev', end: 11, name: 'prompt', start: 0 });
expect(tokenAt('fix /cwd ~/My Docs|')).toEqual({
args: '~/My Docs',
end: 18,
name: 'cwd',
start: 4
});
});
it('treats the whole run as the name when there is no space', () => {
expect(findCommandToken('/promptx')).toEqual({ args: '', end: 8, name: 'promptx' });
it('reads a path in the argument as the argument, not a command of its own', () => {
expect(tokenAt('/cwd /usr/lo|')?.name).toBe('cwd');
expect(tokenAt('/cwd /usr|')?.name).toBe('cwd');
});
it('ends the argument at two spaces or a new line', () => {
expect(tokenAt('/cwd docs more|')).toBeNull();
expect(tokenAt('/cwd docs\nmore|')).toBeNull();
});
it('leaves the words after a command without an argument to the message', () => {
expect(tokenAt('/model is broken|')).toBeNull();
expect(tokenAt('please use /m the small one|')).toBeNull();
expect(tokenAt('please use /m|')).toEqual({ args: '', end: 13, name: 'm', start: 11 });
});
it('takes no argument for an unknown name', () => {
expect(tokenAt('/promptx|')).toEqual({ args: '', end: 8, name: 'promptx', start: 0 });
expect(tokenAt('/foo bar|')).toBeNull();
expect(tokenAt('/cw docs|')).toEqual({ args: 'docs', end: 8, name: 'cw', start: 0 });
});
});
describe('takeCommandDismissSnapshot', () => {
it('returns null when there is no command token', () => {
expect(takeCommandDismissSnapshot('hello')).toBeNull();
describe('command dismissal', () => {
it('holds for the same token only', () => {
const snapshot = takeCommandDismissSnapshot('hi /prompt rev', 14, COMMANDS);
expect(snapshot).toEqual({ args: 'rev', name: 'prompt', start: 3 });
expect(isCommandDismissed(snapshot, { args: 'rev', end: 14, name: 'prompt', start: 3 })).toBe(
true
);
expect(isCommandDismissed(snapshot, { args: 'revi', end: 15, name: 'prompt', start: 3 })).toBe(
false
);
expect(takeCommandDismissSnapshot('hello', 5, COMMANDS)).toBeNull();
});
});
describe('removeCommandToken', () => {
it('leaves one space between the words around it', () => {
expect(removeCommandToken('fix /model the build', { end: 10, start: 4 })).toEqual({
caret: 4,
value: 'fix the build'
});
expect(removeCommandToken('fix the build /model', { end: 20, start: 14 })).toEqual({
caret: 13,
value: 'fix the build'
});
expect(removeCommandToken('/model fix it', { end: 6, start: 0 })).toEqual({
caret: 0,
value: 'fix it'
});
expect(removeCommandToken('/model', { end: 6, start: 0 })).toEqual({ caret: 0, value: '' });
});
});
describe('the /cwd command', () => {
it('is written at the caret, set apart by spaces', () => {
expect(insertCwdCommand('fix the build', 3, '~/git')).toEqual({
caret: 14,
start: 4,
value: 'fix /cwd ~/git the build'
});
expect(insertCwdCommand('', 0, '')).toEqual({ caret: 5, start: 0, value: '/cwd ' });
});
it('captures the name and args', () => {
expect(takeCommandDismissSnapshot('/prompt rev')).toEqual({
args: 'rev',
name: 'prompt'
it('completes a partial token in place', () => {
expect(replaceWithCwdCommand('fix /cw docs now', { end: 12, start: 4 }, 'docs')).toEqual({
caret: 13,
start: 4,
value: 'fix /cwd docs now'
});
});
it('is found again after an edit elsewhere', () => {
expect(locateCwdCommand('so, fix /cwd docs now', 4, 'docs', 4)).toEqual({
end: 17,
query: 'docs',
start: 8
});
expect(locateCwdCommand('fix the build', 4, 'docs')).toBeNull();
});
it('is looked for only where it was or where the edit moved it', () => {
expect(locateCwdCommand('why does /cwd break', 20, '~/git', -6)).toBeNull();
});
it('reads its path to two spaces or the end of the line when it changed', () => {
expect(locateCwdCommand('/cwd ~/My Docs more', 0, 'x')).toEqual({
end: 14,
query: '~/My Docs',
start: 0
});
expect(locateCwdCommand('/cwd', 0, '')).toEqual({ end: 4, query: '', start: 0 });
});
});
@@ -0,0 +1,142 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('#lib/services/tools.service.ts', () => ({
ToolsService: { executeToolRaw: vi.fn() }
}));
import { SEARCH } from '#lib/constants/index.ts';
import { ToolsService } from '#lib/services/tools.service.ts';
import { runFolderSearch } from '#lib/utils/index.ts';
const mockExecute = vi.mocked(ToolsService.executeToolRaw);
interface Folders {
[depth: number]: string[];
}
/** Serve `folders[max_depth]` for the globs that carry `needle`, and nothing for the rest. */
function serve(home: string, needle: string, folders: Folders) {
mockExecute.mockImplementation(async (_tool, params) => {
const { include, max_depth: depth, path } = params as Record<string, string | number>;
const paths = path === home && String(include).includes(needle) ? (folders[+depth] ?? []) : [];
return { base: String(path), entries: paths.map((p) => ({ path: p, type: 'dir' })) };
});
}
const signal = () => new AbortController().signal;
// Distinct homes per test so the module-level search cache never serves a
// prior test's result under the same (type, path, glob, depth) key.
beforeEach(() => {
mockExecute.mockReset();
});
describe('runFolderSearch', () => {
it('finds a plain name below home, nearest folders first', async () => {
const home = '/Users/deep';
serve(home, '[lL][lL][aA][mM][aA]', {
[SEARCH.MAX_DEPTH]: ['git/llama.cpp', 'git/work/tools/llama-bench'],
[SEARCH.SHALLOW_DEPTH]: ['git/llama.cpp']
});
const partial = vi.fn();
const res = await runFolderSearch('llama', home, signal(), partial);
expect(partial.mock.calls[0][0].entries.map((e: { path: string }) => e.path)).toEqual([
`${home}/git/llama.cpp`
]);
expect(res.entries.map((e) => e.path)).toEqual([
`${home}/git/llama.cpp`,
`${home}/git/work/tools/llama-bench`
]);
});
it('navigates a query with a path in it', async () => {
const home = '/Users/nav';
mockExecute.mockResolvedValueOnce({
base: `${home}/git`,
entries: [{ path: 'llama-ui', type: 'dir' }]
});
const res = await runFolderSearch('git/llama', home, signal());
expect(mockExecute.mock.calls[0][1]).toMatchObject({
max_depth: SEARCH.PATH_NAV_MAX_DEPTH,
path: `${home}/git`
});
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama-ui`]);
});
it('allows for a typo when nothing matches exactly', async () => {
const home = '/Users/typo';
// only the looser typo globs carry this fragment
serve(home, '[lL][lL]*[aA]', {
[SEARCH.FUZZY_MAX_DEPTH]: ['git/llama.cpp', 'git/all-data']
});
const res = await runFolderSearch('llana', home, signal());
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('finds nothing for a name that is more than a typo away', async () => {
const home = '/Users/none';
serve(home, 'never', {});
const res = await runFolderSearch('zzzzz', home, signal());
expect(res.entries).toEqual([]);
expect(res.error).toBeUndefined();
});
});
describe('runFolderSearch across platforms', () => {
it('navigates a backslash path under a Windows home', async () => {
const home = 'C:/Users/win';
mockExecute.mockResolvedValueOnce({
base: `${home}/git`,
entries: [{ path: 'llama.cpp', type: 'dir' }]
});
const res = await runFolderSearch('git\\llama', home, signal());
expect(mockExecute.mock.calls[0][1]).toMatchObject({ path: `${home}/git` });
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('keeps the near results when the deeper search fails', async () => {
const home = '/Users/flaky';
mockExecute.mockImplementation(async (_tool, params) => {
const { max_depth: depth, path } = params as Record<string, string | number>;
if (depth === SEARCH.MAX_DEPTH) throw new Error('network');
return { base: String(path), entries: [{ path: 'git/llama.cpp', type: 'dir' }] };
});
const res = await runFolderSearch('llama', home, signal());
expect(res.entries.map((e) => e.path)).toEqual([`${home}/git/llama.cpp`]);
});
it('stops the typo search at the nearest depth that finds something', async () => {
const home = '/Users/near';
serve(home, '[lL][lL]*[aA]', { [SEARCH.SHALLOW_DEPTH]: ['git/llama.cpp'] });
await runFolderSearch('llana', home, signal());
const depths = mockExecute.mock.calls.map(
([, params]) => (params as { max_depth: number }).max_depth
);
expect(depths).not.toContain(SEARCH.FUZZY_MAX_DEPTH);
});
});
@@ -122,3 +122,149 @@ describe('runGlobSearchWithChildren', () => {
expect(mockExecute).toHaveBeenCalledTimes(1);
});
});
describe('runGlobSearchWithChildren with a relative path', () => {
it('lists the folder at the top of the scope before its deeper namesakes', async () => {
const scope = '/Users/rootF';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
// the direct lookup navigates to the parent; the glob only sees deeper copies
return path === `${scope}/ui/lib`
? { base: path, entries: [{ path: 'voice', type: 'dir' }] }
: { base: scope, entries: [{ path: '.worktrees/a/ui/lib/voice', type: 'dir' }] };
});
const res = await runGlobSearchWithChildren(
'ui/lib/voi',
scope,
3,
50,
new AbortController().signal,
{ descendOnTrailingSeparator: true, type: GlobSearchType.ALL }
);
expect(res.entries.map((e) => e.path)).toEqual([
`${scope}/ui/lib/voice`,
`${scope}/.worktrees/a/ui/lib/voice`
]);
});
it('keeps the deeper matches when the path does not exist at the top', async () => {
const scope = '/Users/rootG';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === scope
? { base: scope, entries: [{ path: 'apps/ui/lib/voice', type: 'dir' }] }
: { error: 'path does not exist or is not a directory' };
});
const res = await runGlobSearchWithChildren(
'ui/lib/voi',
scope,
3,
50,
new AbortController().signal
);
expect(res.error).toBeUndefined();
expect(res.entries.map((e) => e.path)).toEqual([`${scope}/apps/ui/lib/voice`]);
});
});
describe('runGlobSearchWithChildren with a rooted path', () => {
it('looks further down when the folder itself holds no such name', async () => {
mockExecute
.mockResolvedValueOnce({ base: '/Users/rootDeep', entries: [] })
.mockResolvedValueOnce({
base: '/Users/rootDeep',
entries: [
{ path: '.cache/llama.cpp', type: 'dir' },
{ path: 'git/llama.cpp', type: 'dir' }
]
});
const res = await runGlobSearchWithChildren(
'~/llama.cpp',
'/Users/rootDeep/Desktop',
3,
50,
new AbortController().signal
);
expect(mockExecute.mock.calls.map((call) => call[1])).toMatchObject([
{ max_depth: 1, path: '~' },
{ max_depth: 3, path: '~' }
]);
expect(res.entries.map((e) => e.path)).toEqual([
'/Users/rootDeep/git/llama.cpp',
'/Users/rootDeep/.cache/llama.cpp'
]);
});
it('stays in the folder when it holds a match', async () => {
mockExecute.mockResolvedValueOnce({
base: '/Users/rootNear',
entries: [{ path: 'whisper.cpp', type: 'dir' }]
});
const res = await runGlobSearchWithChildren(
'~/whisper.cpp',
'/Users/rootNear/Desktop',
3,
50,
new AbortController().signal,
{ descendOnTrailingSeparator: true }
);
expect(mockExecute).toHaveBeenCalledTimes(1);
expect(res.entries.map((e) => e.path)).toEqual(['/Users/rootNear/whisper.cpp']);
});
});
describe('runGlobSearchWithChildren edge cases', () => {
it('follows a backslash path from a Windows scope', async () => {
const scope = 'C:/rootH';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === `${scope}/ui/lib`
? { base: path, entries: [{ path: 'voice', type: 'dir' }] }
: { base: scope, entries: [] };
});
const res = await runGlobSearchWithChildren(
'ui\\lib\\voi',
scope,
3,
50,
new AbortController().signal
);
expect(res.entries.map((e) => e.path)).toEqual([`${scope}/ui/lib/voice`]);
});
it('surfaces the deep search error when the direct lookup finds nothing', async () => {
const scope = '/Users/rootI';
mockExecute.mockImplementation(async (_tool, params) => {
const { path } = params as { path: string };
return path === scope ? { error: 'boom' } : { base: path, entries: [] };
});
const res = await runGlobSearchWithChildren(
'ui/lib/zzz',
scope,
3,
50,
new AbortController().signal
);
expect(res.error).toBe('boom');
});
});
@@ -20,6 +20,7 @@ import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts';
import type { AgenticSection, WriteFileMeta } from '#lib/types/index.ts';
import {
abbreviateHome,
abbreviateWorkingDir,
formatCwdMessage,
lastPathSegment,
parseCwdMessage
@@ -88,6 +89,21 @@ describe('abbreviateHome', () => {
});
});
describe('abbreviateWorkingDir', () => {
it('shows a directory under home from ~/', () => {
expect(abbreviateWorkingDir('/Users/al/git/llama.cpp', '/Users/al')).toBe('~/git/llama.cpp');
});
it('keeps a directory already written from ~', () => {
expect(abbreviateWorkingDir('~/git/llama.cpp', '/Users/al')).toBe('~/git/llama.cpp');
expect(abbreviateWorkingDir('~/git/llama.cpp', null)).toBe('~/git/llama.cpp');
});
it('shows the last segment of a directory outside home', () => {
expect(abbreviateWorkingDir('/opt/project', '/Users/al')).toBe('project');
});
});
describe('formatCwdMessage / parseCwdMessage', () => {
it('formats a cwd change matching the UI text, with a file link', () => {
expect(formatCwdMessage('/Users/al/Documents', '/Users/al')).toBe(
@@ -1,12 +1,16 @@
import { GLOB, SEARCH } from '#lib/constants/index.ts';
import {
buildCaseInsensitiveGlob,
buildFuzzyGlobs,
buildGlobSearchArgs,
fuzzyDistance,
highlightMatch,
isHiddenPath,
joinPath,
rankEntries,
splitPathQuery,
toHomeRelativeQuery
toHomeRelativeQuery,
toScopeSeparators
} from '#lib/utils/index.ts';
import { describe, expect, it } from 'vitest';
@@ -211,3 +215,69 @@ describe('toHomeRelativeQuery', () => {
expect(args.last).toBe('proj');
});
});
describe('buildFuzzyGlobs', () => {
it('swaps each pair of neighbouring characters for a wildcard', () => {
expect(buildFuzzyGlobs('lama')).toEqual(['*[mM][aA]*', '*[lL]*[aA]*', '*[lL][aA]*']);
});
it('skips queries too short or too long to match loosely', () => {
expect(buildFuzzyGlobs('abc')).toEqual([]);
expect(buildFuzzyGlobs('a'.repeat(SEARCH.FUZZY_MAX_QUERY_LENGTH + 1))).toEqual([]);
});
});
describe('fuzzyDistance', () => {
it('is zero when the text holds the query, in any case', () => {
expect(fuzzyDistance('Llama.cpp', 'llama')).toBe(0);
});
it('counts a wrong, missing, extra or swapped character as one edit', () => {
expect(fuzzyDistance('llama.cpp', 'llana')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'lama.')).toBe(0);
expect(fuzzyDistance('llama.cpp', 'llma.')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'llamma')).toBe(1);
expect(fuzzyDistance('llama.cpp', 'lalma')).toBe(1);
});
it('grows with every further edit', () => {
expect(fuzzyDistance('documents', 'llama')).toBeGreaterThan(SEARCH.FUZZY_MAX_EDITS);
});
});
describe('rankEntries with hidden folders', () => {
const entries = [
{ path: '.config/llama', type: 'dir' },
{ path: '.llama-app', type: 'dir' },
{ path: 'git/llama.cpp', type: 'dir' }
];
it('ranks regular folders above hidden ones, even an exact hidden match', () => {
expect(rankEntries(entries, 'llama').map((e) => e.path)).toEqual([
'git/llama.cpp',
'.config/llama',
'.llama-app'
]);
});
it('ranks by name alone when the query asks for a hidden name', () => {
expect(rankEntries(entries, '.llama')[0].path).toBe('.llama-app');
});
it('tells a hidden path by any of its segments', () => {
expect(isHiddenPath('git/.cache/x')).toBe(true);
expect(isHiddenPath('git/llama.cpp')).toBe(false);
});
});
describe('toScopeSeparators', () => {
it('reads a backslash as a separator under a Windows scope', () => {
expect(toScopeSeparators('git\\llama', 'C:/Users/al')).toBe('git/llama');
expect(toScopeSeparators('git\\llama', '//host/share/al')).toBe('git/llama');
});
it('leaves the backslash alone under a POSIX scope, where it is a filename character', () => {
expect(toScopeSeparators('git\\llama', '/home/al')).toBe('git\\llama');
expect(toScopeSeparators('git\\llama', '~')).toBe('git\\llama');
});
});