Compare commits

..
9 Commits
Author SHA1 Message Date
Aman Gupta 5b1ba66b59 CUDA : read K/V through kv_rows in the vec flash attention kernel (#32520)
* CUDA : read K/V through kv_rows in the vec flash attention kernel

Without a bias only the MMA kernel read K/V through kv_rows. With a quantized, BF16 or F8_E4M3 cache it converted the whole K/V view to F16 on every call, so decode in a unified cache slowed down with the cells of all sequences, idle ones included.

The vec kernel already reads K/V through kv_rows for the indexed bias. Its kv_rows variant is now also instantiated without a bias (one query per slice, no softcap), and the kv_rows dispatch takes it for non-F16 K/V with one query per slice. F16 K/V and slices of several queries keep the MMA kernel.

tests : kv_rows cases with one query per slice for f16/bf16/q8_0/q4_0

ref #32181

* CUDA : take the vec kv_rows path only for K/V pairs with a compiled vec kernel

Without a compiled vec kernel for the K/V pair (the default GGML_CUDA_FA_QUANTS has only same-type pairs), the vec kernel falls back to f16 and converts the whole cache, which is slower than the MMA kernel. Mixed pairs such as q8_0/q4_0 keep the MMA kernel as on master. The lookup also covers the head sizes of the vec kernel.
2026-12-01 12:40:27 +08:00
Aman Gupta 713fee7fb0 llama : budget graph nodes for KV cache rotation (#33382) 2026-12-01 11:01:37 +08:00
cwriterandcwriter e89795bf78 sycl: Add GDN Replay support (#32944)
* sycl : replay the pending gated delta net tokens in the kernel

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

* sycl : fuse the state and pending input cpys into the replay gated delta net kernel

Assisted-by: Claude Opus 5.5

* sycl : stage tensor reads through pinned memory

Port of the download half of 6511ba973 (prompt-cache-speed) to master: reads
of 64 KiB or more go through a pinned block, up to four workers each own a
1 MiB slot, queue the device copy, touch the destination pages while it is in
flight, then copy out. The original applied from 1 MiB; the recurrent-state
reads of a GDN checkpoint are 64 KiB to 3 MiB per tensor.

Assisted-by: Claude Opus 5.5

* sycl : gated delta net with separate q and k strides

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: cwriter <cwriter@localhost>
2026-11-30 18:48:27 -08:00
Xuan-Son Nguyen 1f1e6cb26a unicode : fix \p{Lu} and \p{Ll} (#33403) 2026-12-01 00:50:42 +01:00
Sigbjørn Skjæret db503b89fd server : fix build (#33410) 2026-12-01 00:27:09 +01:00
Luc PommeretandLuc Pommeret 78c9ca4b06 llama : allow prism.hadamard folded weights for LFM3 (#33387)
* llama : allow prism.hadamard folded weights for LFM3

Add LLM_ARCH_LFM3 to the architectures that may load Hadamard-folded
weights, and accept the LFM3 short-convolution projections
(shortconv.in_proj, shortconv.out_proj) as foldable. Both are built
through build_lora_mm in lfm-base.cpp, so the input transform is applied.
The Python converter filter is aligned with the loader.

Assisted-by: Claude Opus 5.5

* llama : accept shortconv projections as Hadamard-foldable kinds

Drop the LFM3-only condition: shortconv.in_proj and shortconv.out_proj
are built through build_lora_mm, so list them with the other foldable
kinds in the loader and the converter.

Assisted-by: Claude Opus 5.5

---------

Co-authored-by: Luc Pommeret <zlucpommeret@gmail.com>
2026-11-30 23:58:38 +01:00
lhez abeb9e7bd7 opencl: support scaled mm (#33240)
* opencl: support scaled mm

Assisted-by: Codex

* opencl: optimized a bit using grid strided kernel
2026-11-30 14:39:33 -08:00
Titania nastadeva c8476ae546 gguf-py : avoid alignment padding round-trip amplification (#33378)
* gguf-py: stop write amplification in gguf-new-metadata / GGUFWriter padding

**Summary**

While auditing the `gguf` package, I found a write-amplification issue in the
`gguf-new-metadata` converter. Two values taken from the input file itself — the
declared `general.alignment` and the number of tensors — multiply together to
determine the size of the output file, with no sanity check anywhere in the chain.
A crafted GGUF that occupies **8 KiB on disk** makes the converter write a
**68 MB** valid output file; scaling the same recipe produces a **553 MB** output;
and at the maximum alignment the reader accepts, a **137-byte** input drives the
writer into an allocation of ~2³¹ list elements (~17 GiB of address space) and
crashes with `MemoryError`. This PR fixes both halves of the chain (see
"Proposed fix" below).

I am reporting this as a bug fix per the project's current security policy. I
understand DoS issues are handled case-by-case; the mechanism, the amplification
ratio, and the fact that this tool exists specifically to process model files
supplied by other people are why I believe it is worth fixing rather than leaving
as-is. The write-up below includes a working PoC, as the policy requests.


**Changes in this PR**

1. `gguf-py/gguf/gguf_writer.py` — `GGUFWriter.write_padding` now streams the
   zero padding in bounded 8 MiB chunks instead of materializing the whole gap
   as `bytes([0] * pad)` (whose intermediate list costs ~8 bytes of address
   space per pad byte). The number of padding bytes written is unchanged.
2. `gguf-py/gguf/scripts/gguf_new_metadata.py` — before the declared
   `general.alignment` from the input file is copied into the writer, it is
   sanity-checked against the source file's effective size (the smaller of
   its logical size and its on-disk usage, so sparse files cannot slip past),
   and an implausible alignment is rejected with a clear `ValueError`.

Verified after the fix: the q1c input (137 B, alignment 2^31) and the q1 input
(alignment 2^20, 8 KiB on disk) are both rejected cleanly with no large
allocation; a large-padding case and a benign round-trip both produce output
byte-identical to the unpatched converter, and the outputs re-validate in
`GGUFReader`.

**Affected versions**

- `gguf` 0.19.0 (PyPI) — all evidence below executed against this version.
- `gguf` 0.18.0 — affected by code identity: `gguf/scripts/gguf_new_metadata.py`
  and `gguf/gguf_reader.py` are byte-identical between 0.18.0 and 0.19.0, and
  `GGUFWriter.write_padding` is character-identical (0.18.0 lines 398–401 vs
  0.19.0 lines 401–404). Earlier versions were not checked.

**Root cause**

Three links, none of which validates the product of the other two:

1. *The reader trusts the declared layout parameters.* `GGUFReader`
   (`gguf/gguf_reader.py`) validates `general.alignment` only for type (UINT32)
   and form (non-zero power of two); any value up to 2³¹ is accepted. It also
   accepts tensor infos whose data offsets alias — many tensors may all point at
   offset 0 — and never checks that the file's tensor layout is actually spaced
   according to the alignment it declares. A file can therefore *declare* a huge
   alignment while physically containing almost no data.
2. *The converter copies the declared alignment into the writer unchecked.*
   In `gguf/scripts/gguf_new_metadata.py` (lines 207–210):

   ```python
   alignment = get_field_data(reader, gguf.Keys.General.ALIGNMENT)
   if alignment is not None:
       writer.data_alignment = alignment
   ```

   The script then copies every tensor from the input into the writer.
3. *The writer materializes every alignment gap, per tensor.*
   `GGUFWriter.write_tensor_data` calls `write_padding` after each tensor.
   `GGUFWriter.write_padding` (`gguf/gguf_writer.py`, lines 401–404):

   ```python
   def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
       pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
       if pad != 0:
           fp.write(bytes([0] * pad))
   ```

   The intermediate list `[0] * pad` allocates roughly **8 bytes of address space
   per pad byte** (one pointer per element) before any byte reaches the disk.

Total output size is therefore approximately `n_tensors × alignment`, where both
factors are controlled by the input file and nothing caps their product. In the
non-crashing regime the converter *succeeds* and produces a fully valid GGUF —
just a gigantic one — so the disk exhaustion is silent.

**Proof of concept**

Test environment: Python 3.12.3, `gguf==0.19.0`, `numpy==2.5.5`, Linux. All
inputs are files I crafted myself; no third-party model files are involved. The
PoC builder script is included with this PR (see "PoC" below). It constructs
GGUF files with a chosen `general.alignment`, a chosen number of ordinary
F32 `[1]` tensors (value 1.5), and all tensor data offsets aliased to offset 0,
written sparsely so the inputs occupy only 8 KiB on disk.

| Case | Construction | Input size | Result of `gguf-new-metadata <in> <out>` |
|---|---|---|---|
| q1 | alignment 2²⁰, 64 aliased tensors | 1,048,580 B logical / 8,192 B on disk | exit 0; output exactly **68,157,440 B**, valid GGUF (re-opened with `GGUFReader`: 64 tensors, alignment preserved, all values round-trip to 1.5) |
| q1b | alignment 2²⁴, 32 aliased tensors | 16,777,220 B logical / 8,192 B on disk | exit 0; output exactly **553,648,128 B** — output size tracks `n_tensors × alignment` |
| q1c | alignment 2³¹, one zero-element tensor, no tensor data | **137 B** total | exit 1, `MemoryError` (traceback below) |

SHA-256 (inputs / outputs): q1 input `dca9ec5ef54e4ac1a8f5b2018caecf0306669ef5f7bc3aed1c2ad4a7343aa77c`,
q1 output `699d134a1587a3400e76df79bda3be220e4ae30019c65e81638a0c0e613f316f`;
q1b input `32d56217fe02c4b620390a09de591b0ed3187396b333c1e85f44aebd99e953b9`,
q1b output `2c7ba547e0632f588647e109006fe61570c3103c732e4a38a299f980e7640c10`;
q1c input `c37e16cb7ad36a07c02dfb254a7fea0a62696d48a689392fcc30ced2d3a2984f`.
All three runs were re-executed on 2026-11-30 and reproduced these measurements
exactly (the q1c run was performed under a 4,500 MiB address-space cap for lab
safety; the `MemoryError` is the expected outcome with or without the cap on any
machine without ~17 GiB to spare).

q1c traceback (verbatim, paths trimmed):

```
  File "gguf/scripts/gguf_new_metadata.py", line 212, in main
    copy_with_new_metadata(reader, writer, new_metadata, remove_metadata)
  File "gguf/scripts/gguf_new_metadata.py", line 97, in copy_with_new_metadata
    writer.write_tensor_data(tensor.data, tensor_endianess=reader.endianess)
  File "gguf/gguf_writer.py", line 432, in write_tensor_data
    self.write_padding(fout, fout.tell())
  File "gguf/gguf_writer.py", line 404, in write_padding
    fp.write(bytes([0] * pad))
MemoryError
```

Had the allocation succeeded, the writer would have gone on to write ~2 GiB of
zero padding for the first tensor gap alone.

**Impact (honestly bounded)**

- Who is affected: anyone who runs `gguf-new-metadata` (or a downstream
  converter built on `GGUFWriter` that takes `data_alignment` from the input
  file) on a GGUF file obtained from someone else. Converting/re-packing models
  from public model hubs is the tool's normal, intended use.
- What an attacker gains: a file of a few kilobytes — small enough to pass
  casual inspection and upload limits — that reliably exhausts the victim's
  disk (silent, valid output: q1/q1b regime) or memory (crash: q1c regime)
  when converted. On shared/CI machines this is a denial of service against
  the conversion pipeline; on a full disk it can cascade to other processes.
- Bounds: each single padding gap is < 2³¹ bytes (alignment is a
  reader-validated UINT32 power of two); the **total** is
  `n_tensors × alignment`, and the tensor count is bounded only by what
  parses — effectively unbounded at file-crafting time. The bug requires the
  victim to run the converter; merely storing or reading the file with
  `GGUFReader` does not trigger it. No data is read, leaked, or executed.
- Classification: CWE-400 (Uncontrolled Resource Consumption), with CWE-770
  for the `[0] * pad` intermediate list. For reference, my CVSS v3.1 estimate
  is **5.5 (Medium)** — `CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H`
  (availability only; no confidentiality or integrity impact). I include this
  only as a severity reference — per the project policy, whether this is
  treated as a vulnerability or as a regular bug fix is the maintainers' call.

**Distinctness**

Public reports against gguf-py to date cover four reader-side issues (an
unbounded flat ARRAY `alen` loop at parse time; an unchecked `kv_count` crash;
a zero-dimension shape spoof; an out-of-bounds `offset_tensor` crash). This
issue differs from each in component (writer/converter, not reader), mechanism
(the writer re-materializes the declared alignment once per tensor), and
resource (output size / write-time allocation). To my knowledge it has not been
publicly reported. (The same alignment-copy + writer pattern also appears in
the editor GUI's save path, `gguf/scripts/gguf_editor_gui.py` ~line 1511,
noted from code reading; the executed evidence above is for the CLI converter.)

**PoC**

The PoC builder script (`build_phase3.py`, with its GGUF-crafting helper
`ggufbuild.py`) is reproduced in full in the collapsible section at the end
of this description. It builds the three inputs above from scratch — no
pre-built binary model files are needed.

**Testing ethics**

All testing was local, on files I created, against a library installed in my
own virtual environment. No third-party systems or files were involved. This
report was written by me as the reporter, with AI assistance during the audit.

Reported by Titania Nastadeva (GitHub: deva1999).

## Requirements

- I have read and agree with the [contributing guidelines](https://github.com/ggml-org/llama.cpp/blob/master/CONTRIBUTING.md)
- AI usage disclosure: yes — an AI assistant was used during the audit and to help draft this report; all findings were reproduced by executed tests, and I reviewed and take responsibility for the submitted changes.

<details>
<summary>PoC builder script (build_phase3.py + ggufbuild.py)</summary>

`build_phase3.py`:

```python
"""Phase 3 PoC builders: secondary-consumer targets (gguf-new-metadata / gguf-dump /
gguf-set-metadata / gguf-convert-endian) fed by reader-accepted crafted files."""
import os
import struct
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ggufbuild import (  # noqa: E402
    UINT8, UINT32, FLOAT32, STRING, ARRAY, F32,
    gstr, header, kv_scalar, kv_string, kv_u32, kv_array, tensor_info, pad_to, u64, f32,
)

OUT = os.path.dirname(os.path.abspath(__file__))


def w(name, data):
    p = os.path.join(OUT, name)
    with open(p, 'wb') as fh:
        fh.write(data)
    print(f"{name}: {len(data)} bytes")
    return p


def w_sparse(name, prefix, data_offs, tail):
    """Write prefix, then `tail` at absolute offset data_offs (sparse gap between)."""
    p = os.path.join(OUT, name)
    with open(p, 'wb') as fh:
        fh.write(prefix)
        fh.seek(data_offs)
        fh.write(tail)
    print(f"{name}: logical {data_offs + len(tail)} bytes (sparse)")
    return p


# ---------------------------------------------------------------- q1: amplification
# general.alignment = 2^20, 64 aliased F32[1] tensors all at offset 0.
def build_q1(name, alignment, n_tensors):
    kv = kv_string('general.architecture', 'amplif')
    kv += kv_u32('general.alignment', alignment)
    infos = b''
    for i in range(n_tensors):
        infos += tensor_info(f't{i}', [1], F32, 0)
    prefix = header(n_tensors, 2) + kv + infos
    data_offs = (len(prefix) + alignment - 1) // alignment * alignment
    return w_sparse(name, prefix, data_offs, f32(1.5))


build_q1('q1_amplif.gguf', 2**20, 64)          # expect ~64 MiB output from new-metadata
build_q1('q1b_amplif_big.gguf', 2**24, 32)     # expect ~512 MiB output

# ------------------------------------------------------- q1c: alignment = 2^31, one
# zero-element tensor (reader accepts: 0 elements need no data at data_offset).
kv = kv_string('general.architecture', 'amplif')
kv += kv_u32('general.alignment', 2**31)
infos = tensor_info('tz', [0], F32, 0)
w('q1c_align_max.gguf', header(1, 2) + kv + infos)

# ------------------------------------------------- q2/q3/q4: architecture type confusion
w('q2_arch_u32.gguf',
  header(0, 2) + kv_scalar('general.architecture', UINT32, struct.pack('<I', 7))
  + kv_string('general.name', 'victim'))
arr = gstr('x')
w('q3_arch_array.gguf',
  header(0, 1) + kv_array('general.architecture', STRING, arr, 1))
w('q4_arch_badutf8.gguf',
  header(0, 1) + kv_scalar('general.architecture', STRING, u64(2) + b'\xff\xfe'))

# ------------------------------------------------- q5: tokenizer tokens type confusion
w('q5_tokens_string.gguf',
  header(0, 2) + kv_string('general.architecture', 'tokarch')
  + kv_string('tokenizer.ggml.tokens', 'abc'))
elems = bytes([97, 98, 99])
w('q5b_tokens_u8.gguf',
  header(0, 2) + kv_string('general.architecture', 'tokarch')
  + kv_array('tokenizer.ggml.tokens', UINT8, elems, 3))

# ------------------------------------------------- q6: legit large vocab (control)
toks = b''.join(gstr(f'tok{i}') for i in range(50000))
scores = b''.join(struct.pack('<f', -0.001 * i) for i in range(50000))
merges = b''.join(gstr(f'tok{i} tok{i + 1}') for i in range(1000))
kv = kv_string('general.architecture', 'bigvocab')
kv += kv_array('tokenizer.ggml.tokens', STRING, toks, 50000)
kv += kv_array('tokenizer.ggml.token_scores', FLOAT32, scores, 50000)
kv += kv_array('tokenizer.ggml.merges', STRING, merges, 1000)
w('q6_vocab_big.gguf', header(0, 4) + kv)

# ------------------------------------------------- q7: truncated UINT32 scalar at EOF
w('q7_setmeta_trunc.gguf',
  header(0, 2) + kv_string('general.architecture', 'truncarch')
  + gstr('custom.value') + struct.pack('<I', UINT32))  # type word, zero value bytes

# ------------------------------------------------- q9: STRING array, clipped last element
elems = gstr('aa') + gstr('bb') + u64(50) + b'cc'  # 3rd declares 50, only 2 present
w('q9_md_strarray_clip.gguf',
  header(0, 2) + kv_string('general.architecture', 'cliparch')
  + kv_array('tokenizer.ggml.tokens', STRING, elems, 3))

print('done')
```

`ggufbuild.py`:

```python
"""Hand-rolled GGUF byte builders for Phase 2 PoCs (LE and BE variants)."""
import struct

# GGUFValueType
UINT8, INT8, UINT16, INT16, UINT32, INT32, FLOAT32, BOOL, STRING, ARRAY, UINT64, INT64, FLOAT64 = range(13)
# GGMLQuantizationType
F32, F16, Q4_0 = 0, 1, 2


def _e(endian):
    return '<' if endian == 'le' else '>'


def u32(v, e='le'):
    return struct.pack(_e(e) + 'I', v)


def u64(v, e='le'):
    return struct.pack(_e(e) + 'Q', v)


def f32(v, e='le'):
    return struct.pack(_e(e) + 'f', v)


def gstr(s, e='le'):
    b = s if isinstance(s, bytes) else s.encode()
    return u64(len(b), e) + b


def header(tensor_count, kv_count, e='le', version=3):
    # magic is the 4 ASCII bytes regardless of endianness
    return b'GGUF' + u32(version, e) + u64(tensor_count, e) + u64(kv_count, e)


def kv_scalar(key, vtype, raw_value_bytes, e='le'):
    return gstr(key, e) + u32(vtype, e) + raw_value_bytes


def kv_string(key, s, e='le'):
    return kv_scalar(key, STRING, gstr(s, e), e)


def kv_u32(key, v, e='le'):
    return kv_scalar(key, UINT32, u32(v, e), e)


def kv_array(key, itype, elements_bytes, count, e='le'):
    return gstr(key, e) + u32(ARRAY, e) + u32(itype, e) + u64(count, e) + elements_bytes


def tensor_info(name, dims, dtype, offset, e='le', n_dims_override=None):
    nd = len(dims) if n_dims_override is None else n_dims_override
    out = gstr(name, e) + u32(nd, e)
    for d in dims:
        out += u64(d, e)
    out += u32(dtype, e) + u64(offset, e)
    return out


def pad_to(buf, alignment):
    while len(buf) % alignment != 0:
        buf += b'\x00'
    return buf
```

</details>

* gguf-py: move alignment validation into GGUFReader per review

Per @CISC's review: the declared-alignment sanity check does not belong in
gguf_new_metadata. It now lives in GGUFReader, right after the existing
power-of-two validation, so every reader consumer is covered. The check
rejects a declared alignment larger than the source file's effective size
(the smaller of its logical size and its on-disk usage, so sparse files
cannot slip past). The converter-side check is removed (file back to
upstream). The write_padding streaming change is unchanged.

Re-tested: q1c (137 B, alignment 2^31), q1 and q1b (sparse) are now
rejected at reader construction with a clear ValueError and no large
allocation; a benign file and a large-padding non-sparse file convert
byte-identically to the unpatched converter.

* gguf-py: simplify the reader alignment check per review

Per @CISC's review: use self.data.nbytes for the file size instead of
stat-ing the path, remove the comment, and keep the raise on a single
line. The check is now two lines in GGUFReader.

Re-tested: the 137-byte alignment 2^31 file is rejected at reader
construction; the sparse large-alignment cases now convert without
crashing at ~44 MB peak RSS thanks to the streaming write_padding;
benign and large-padding outputs remain byte-identical.

* gguf-py: address review feedback

Restore the executable bit on gguf_new_metadata.py (content unchanged).
In write_padding: drop the comment, simplify the chunk selection, and
shrink the zero buffer to 8 KiB.
2026-11-30 23:28:36 +01:00
Ruben Ortlam 779b413a67 vulkan: add fp8 and scaled matmul support (#29791)
* vulkan: add fp8 and scaled matmul support

* remove supports_op rejection, reject unaligned src, fix get_rows issue

* add f8 copy pipelines

* fix test issue

* handle strided scale-views

* fixes after review

* use get_rows, not quant, use fastdiv for scaling shader

* fix test issue

* fix missing initializer
2026-11-30 19:22:22 +01:00
40 changed files with 2309 additions and 228 deletions
+2
View File
@@ -1071,6 +1071,7 @@ class ModelBase:
gguf.MODEL_ARCH.QWEN35,
gguf.MODEL_ARCH.QWEN35MOE,
gguf.MODEL_ARCH.QWEN3NEXT,
gguf.MODEL_ARCH.LFM3,
}
if self.model_arch not in _HADAMARD_ARCHS:
raise ValueError(
@@ -1085,6 +1086,7 @@ class ModelBase:
r"|ffn_gate_exps|ffn_up_exps|ffn_down_exps|ffn_gate_up_exps"
r"|ffn_gate_shexp|ffn_up_shexp|ffn_down_shexp"
r"|ssm_out"
r"|shortconv\.in_proj|shortconv\.out_proj"
r")\.weight"
)
weight_names: list[str] = []
+2
View File
@@ -72,6 +72,8 @@ However, A6x GPUs in phones are likely not supported due to the outdated driver
| MXFP4 | Support |
| IQ4_NL | Support |
`MUL_MAT` supports F32 weight scales per tensor or per output channel. `MUL_MAT_ID` supports F32 weight scales per tensor, per expert, or per output channel of each expert.
`MUL_MAT_ID` accepts an expert id of `-1` and writes zeros to that slot. `ADD_ID` adds no bias for `-1`, including in fused MoE operations.
## Model Preparation
+8
View File
@@ -574,6 +574,11 @@ 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, false, false>;
if constexpr (cols_per_block == 1 && !use_logit_softcap) {
if (dst->src[5]) {
fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, true>;
}
}
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
@@ -594,6 +599,9 @@ void ggml_cuda_flash_attn_ext_vec_case(ggml_backend_cuda_context & ctx, ggml_ten
float logit_softcap;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
// the kv_rows variant exists for one query per sequence without softcap
GGML_ASSERT(!dst->src[5] || (Q->ne[1] == 1 && logit_softcap == 0.0f));
if (Q->ne[1] == 1) {
constexpr int cols_per_block = 1;
if (logit_softcap == 0.0f) {
+16 -3
View File
@@ -765,10 +765,23 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
}
}
// without a bias only the MMA kernel reads K/V through kv_rows
// without a bias only the MMA and vec kernels read 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;
if (!(GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask)) {
return BEST_FATTN_KERNEL_NONE;
}
float logit_softcap = 0.0f;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
// the vec kernel reads quantized/bf16/f8 K/V in place, the MMA kernel would convert the whole cache to f16
// only for K/V pairs with a compiled vec kernel, the f16 fallback of the vec kernel also converts the whole cache
const bool vec_rows = n_kv % FATTN_KQ_STRIDE == 0 &&
(K->type != GGML_TYPE_F16 || V->type != GGML_TYPE_F16) && K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 &&
Q->ne[1] == 1 && logit_softcap == 0.0f && ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr;
if (vec_rows) {
return BEST_FATTN_KERNEL_VEC;
}
return Q->ne[0] != 40 && Q->ne[0] != 72 ? BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
}
// For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes:
+76 -9
View File
@@ -865,6 +865,7 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_add, kernel_add_row, kernel_add_f16, kernel_add_row_f16;
cl_kernel kernel_mul, kernel_mul_row, kernel_mul_f16, kernel_mul_row_f16;
cl_kernel kernel_mul_mat_scale = nullptr;
cl_kernel kernel_div, kernel_div_row, kernel_div_f16, kernel_div_row_f16;
cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16;
cl_kernel kernel_add_id;
@@ -1573,6 +1574,7 @@ struct ggml_backend_opencl_context {
#endif
for (cl_kernel kernel : {
kernel_gemv_f32_f32_mcr,
kernel_mul_mat_scale,
kernel_xielu_f32,
kernel_xielu_f16,
kernel_mul_mm_f16_f32_kq_p8,
@@ -4584,6 +4586,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
CL_CHECK((backend_ctx->kernel_mul_row = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row", &err), err));
CL_CHECK((backend_ctx->kernel_mul_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_f16", &err), err));
CL_CHECK((backend_ctx->kernel_mul_row_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row_f16", &err), err));
CL_CHECK((backend_ctx->kernel_mul_mat_scale = clCreateKernel(backend_ctx->program_mul, "kernel_mul_mat_scale", &err), err));
GGML_LOG_CONT(".");
}
@@ -11380,7 +11383,7 @@ static void ggml_cl_moe_gemm_coopmat(
clReleaseMemObject(buf_dst_image);
}
static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
// Runs the gate and up matmuls unchanged, then one kernel in place of
// add_id(gate) + add_id(up) + swiglu_oai. See ggml_opencl_can_fuse_moe_bias_glu.
@@ -11388,8 +11391,8 @@ static void ggml_cl_moe_bias_glu_fused(ggml_backend_t backend, ggml_tensor * gat
ggml_tensor * up_mm, const ggml_tensor * up_add, const ggml_tensor * glu) {
ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context;
ggml_cl_mul_mat_id(backend, gate_mm->src[0], gate_mm->src[1], gate_mm);
ggml_cl_mul_mat_id(backend, up_mm->src[0], up_mm->src[1], up_mm);
ggml_cl_mul_mat_ext(backend, gate_mm->src[0], gate_mm->src[1], gate_mm);
ggml_cl_mul_mat_ext(backend, up_mm->src[0], up_mm->src[1], up_mm);
const ggml_tensor * gbias = gate_add->src[1];
const ggml_tensor * ubias = up_add->src[1];
@@ -11678,6 +11681,10 @@ static bool ggml_opencl_can_fuse(const ggml_backend_opencl_context * backend_ctx
const ggml_tensor *up = cgraph->nodes[node_idx+1];
const ggml_tensor *glu = cgraph->nodes[node_idx+2];
if (ggml_get_src_scale(gate, 0) || ggml_get_src_scale(up, 0)) {
return false;
}
// decode GEMV path only (single token); prefill GEMM is separate
if (gate->ne[1] != 1 || up->ne[1] != 1) {
return false;
@@ -12746,10 +12753,6 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
return false;
}
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
return true;
@@ -39795,6 +39798,70 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst);
}
static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
const ggml_tensor * ids = dst->op == GGML_OP_MUL_MAT_ID ? dst->src[2] : nullptr;
if (ids) {
ggml_cl_mul_mat_id(backend, src0, src1, dst);
} else {
ggml_cl_mul_mat(backend, src0, src1, dst);
}
const ggml_tensor * scale = ggml_get_src_scale(dst, 0);
if (!scale) {
return;
}
GGML_ASSERT(ggml_is_contiguous(dst) && dst->type == GGML_TYPE_F32 && scale->type == GGML_TYPE_F32);
cl_ulong channel_stride = 0;
cl_ulong expert_stride = 0;
if (!ggml_is_scalar(scale)) {
if (ids && ggml_is_vector(scale) && scale->ne[0] == src0->ne[2]) {
expert_stride = scale->nb[0];
} else {
channel_stride = scale->nb[0];
expert_stride = ids ? scale->nb[1] : 0;
}
}
auto * backend_ctx = (ggml_backend_opencl_context *) backend->context;
auto * ed = (ggml_tensor_extra_cl *) dst->extra;
auto * es = (ggml_tensor_extra_cl *) scale->extra;
auto * ei = ids ? (ggml_tensor_extra_cl *) ids->extra : nullptr;
const cl_ulong offsetd = ed->offset + dst->view_offs;
const cl_ulong offsets = es->offset + scale->view_offs;
const cl_mem ids_buf = ids ? ei->data_device : nullptr;
const cl_ulong offseti = ids ? ei->offset + ids->view_offs : 0;
const cl_ulong ids_nb0 = ids ? ids->nb[0] : 0;
const cl_ulong ids_nb1 = ids ? ids->nb[1] : 0;
const cl_long n_expert = src0->ne[2];
const int ne0 = dst->ne[0];
const int ne1 = dst->ne[1];
cl_kernel kernel = backend_ctx->kernel_mul_mat_scale;
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ed->data_device));
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &es->data_device));
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsets));
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &channel_stride));
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &expert_stride));
CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &ids_buf));
CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offseti));
CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &ids_nb0));
CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &ids_nb1));
CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &n_expert));
CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0));
CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1));
// few rows (decode): 1 element per work-item to keep enough work-items, else 8
const size_t nth = 128;
const size_t nrows = (size_t) ne1*dst->ne[2]*dst->ne[3];
const size_t elems_per_item = nrows < 32 ? 1 : 8;
const size_t nwg = CEIL_DIV((size_t) ne0, nth*elems_per_item);
size_t global_work_size[] = { nwg*nth, (size_t) ne1, (size_t) (dst->ne[2]*dst->ne[3]) };
size_t local_work_size[] = { nth, 1, 1 };
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst);
}
static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_ASSERT(src0);
GGML_ASSERT(src0->extra);
@@ -42049,13 +42116,13 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor
if (!any_on_device && !ggml_cl_can_mul_mat(tensor->src[0], tensor->src[1], tensor)) {
return false;
}
func = ggml_cl_mul_mat;
func = ggml_cl_mul_mat_ext;
break;
case GGML_OP_MUL_MAT_ID:
if (!any_on_device) {
return false;
}
func = ggml_cl_mul_mat_id;
func = ggml_cl_mul_mat_ext;
break;
case GGML_OP_SCALE:
if (!any_on_device) {
+38
View File
@@ -150,3 +150,41 @@ kernel void kernel_mul_row_f16(
uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
dst[gid] = src0[gid] * src1[idx1];
}
kernel void kernel_mul_mat_scale(
global char * dst,
ulong offsetd,
global const char * scale,
ulong offsets,
ulong channel_stride,
ulong expert_stride,
global const char * ids,
ulong offseti,
ulong ids_nb0,
ulong ids_nb1,
long n_expert,
int ne0,
int ne1
) {
const int slot = get_group_id(1);
const int batch = get_group_id(2);
int expert = 0;
if (ids) {
expert = *(global const int *)(ids + offseti + slot*ids_nb0 + batch*ids_nb1);
if (expert < 0 || expert >= n_expert) {
return;
}
}
global float * d = (global float *)(dst + offsetd) + (ulong)ne0*(slot + (ulong)ne1*batch);
global const char * s = scale + offsets + expert*expert_stride;
if (channel_stride == 0) {
const float v = *(global const float *) s;
for (int i = get_global_id(0); i < ne0; i += get_global_size(0)) {
d[i] *= v;
}
} else {
for (int i = get_global_id(0); i < ne0; i += get_global_size(0)) {
d[i] *= *(global const float *)(s + i*channel_stride);
}
}
}
+192 -26
View File
@@ -22,6 +22,9 @@ static void launch_gated_delta_net_esimd(const float * q,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -52,7 +55,7 @@ static void launch_gated_delta_net_esimd(const float * q,
for (int t = 0; t < n_tokens; ++t) {
const simd<float, S_v> q_t = block_load<float, S_v>(q + iq3 * sq3 + t * sq2 + iq1 * sq1);
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sq3 + t * sq2 + iq1 * sq1);
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sk3 + t * sk2 + iq1 * sk1);
const float v_val = v[sequence * sv3 + t * sv2 + h_idx * sv1 + col];
const int64_t gb = sequence * sb3 + t * sb2 + h_idx * sb1;
const float g_val = exp(g[gb]);
@@ -78,8 +81,26 @@ static constexpr int gdn_warps = 2;
// State columns per warp when there are enough heads, see launch_gated_delta_net.
static constexpr int gdn_cols_wide = 4;
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
struct gdn_replay_args {
const float * pk; // [S_v, H_k, n_pend, n_seqs]
const float * pv; // [S_v, H, n_pend, n_seqs]
const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
const int32_t * n_rep; // [n_seqs]
int64_t sk1, sk2, sk3; // head, token and seq strides in floats
int64_t sv1, sv2, sv3;
int64_t sg1, sg2, sg3;
int n_pend;
bool keep; // write the state after the replay, not the final one
// optional (not KDA): store the k, v, g, beta inputs of the new tokens as pending (fused cpys)
float * st[4];
int64_t st2[4]; // token stride in floats
int64_t st3[4]; // seq stride in floats
};
// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns.
template <int S_v, int C, bool KDA, bool keep_rs_t>
template <int S_v, int C, bool KDA, bool keep_rs_t, bool replay>
void gated_delta_net_sycl(const float * q,
const float * k,
const float * v,
@@ -93,6 +114,9 @@ void gated_delta_net_sycl(const float * q,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -103,7 +127,8 @@ void gated_delta_net_sycl(const float * q,
const sycl::uint3 rq3_magic,
float scale,
int64_t state_slot_stride,
int K) {
int K,
const gdn_replay_args rep) {
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
const uint32_t h_idx = item_ct1.get_group(2);
const uint32_t sequence = item_ct1.get_group(1);
@@ -140,11 +165,79 @@ void gated_delta_net_sycl(const float * q,
}
}
if constexpr (replay) {
// the same state update as the main loop below, without the attention output
const int n_r = rep.n_rep[sequence];
const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1 + lane;
const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1 + col0;
const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
for (int t = 0; t < n_r; t++) {
const float * g_t = pgb + t * rep.sg2;
const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
float k_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
k_reg[r] = pk[t * rep.sk2 + r * warp_size];
}
if constexpr (!KDA) {
const float g_val = sycl::native::exp(*g_t);
#pragma unroll
for (int c = 0; c < C; c++) {
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += s_shard[c][r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
const float delta_col = (pv[t * rep.sv2 + c] - g_val * kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col;
}
}
} else {
float g_reg[rows_per_lane];
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]);
}
#pragma unroll
for (int c = 0; c < C; c++) {
float kv_shard = 0.0f;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
kv_shard += g_reg[r] * s_shard[c][r] * k_reg[r];
}
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
const float delta_col = (pv[t * rep.sv2 + c] - kv_col) * beta_val;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col;
}
}
}
}
if (rep.keep) {
float * out_col = state + col0 * S_v + lane;
#pragma unroll
for (int c = 0; c < C; c++) {
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
out_col[c * S_v + r * warp_size] = s_shard[c][r];
}
}
}
}
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane;
const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane;
const float * kp = k + iq3 * sk3 + iq1 * sk1 + lane;
const float * vp = v + sequence * sv3 + h_idx * sv1 + col0;
const float * bp = beta + sequence * sb3 + h_idx * sb1;
const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1);
@@ -173,7 +266,7 @@ void gated_delta_net_sycl(const float * q,
}
if (t + 1 < n_tokens) {
qp += sq2;
kp += sq2;
kp += sk2;
}
// Load outside the branch: the last token reads its own row again.
// A guarded load is 20% slower at 32 heads on Arc Pro B70.
@@ -190,6 +283,31 @@ void gated_delta_net_sycl(const float * q,
}
vp += sv2;
if constexpr (replay && !KDA) {
if (rep.st[0] != nullptr) {
// keep the inputs of this token pending: one work-group per k head writes k, each warp its v columns
const bool first_wg = item_ct1.get_group(0) == 0 && item_ct1.get_local_id(1) == 0;
if (first_wg && h_idx < neqk1_magic.z()) {
float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v + lane;
#pragma unroll
for (int r = 0; r < rows_per_lane; r++) {
dk[r * warp_size] = k_reg[r];
}
}
if (lane == 0) {
float * dv = rep.st[1] + sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col0;
#pragma unroll
for (int c = 0; c < C; c++) {
dv[c] = v_reg[c];
}
if (first_wg) {
rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
}
}
}
}
// attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta
float kq_shard = 0.0f;
#pragma unroll
@@ -281,6 +399,9 @@ void gated_delta_net_sycl(const float * q,
}
if constexpr (!keep_rs_t) {
if (replay && rep.keep) {
return;
}
float * out_col = state + col0 * S_v + lane;
#pragma unroll
for (int c = 0; c < C; c++) {
@@ -292,7 +413,7 @@ void gated_delta_net_sycl(const float * q,
}
}
template <bool KDA, bool keep_rs_t>
template <bool KDA, bool keep_rs_t, bool replay>
static void launch_gated_delta_net(const float * q_d,
const float * k_d,
const float * v_d,
@@ -308,6 +429,9 @@ static void launch_gated_delta_net(const float * q_d,
int64_t sq1,
int64_t sq2,
int64_t sq3,
int64_t sk1,
int64_t sk2,
int64_t sk3,
int64_t sv1,
int64_t sv2,
int64_t sv3,
@@ -319,6 +443,7 @@ static void launch_gated_delta_net(const float * q_d,
float scale,
int64_t state_slot_stride,
int K,
const gdn_replay_args & rep,
dpct::queue_ptr stream) {
//TODO: Add chunked kernel for even faster pre-fill
const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size;
@@ -333,9 +458,9 @@ static void launch_gated_delta_net(const float * q_d,
dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1);
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
gated_delta_net_sycl<sv, C, KDA, keep_rs_t>(
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2,
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
gated_delta_net_sycl<sv, C, KDA, keep_rs_t, replay>(
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2,
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
});
};
// gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster.
@@ -400,7 +525,6 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
GGML_ASSERT(ggml_is_contiguous_rows(src_q));
GGML_ASSERT(ggml_is_contiguous_rows(src_k));
GGML_ASSERT(ggml_is_contiguous_rows(src_v));
GGML_ASSERT(ggml_are_same_stride(src_q, src_k));
GGML_ASSERT(src_g->ne[0] == 1 || kda);
GGML_ASSERT(ggml_is_contiguous(src_g));
GGML_ASSERT(ggml_is_contiguous(src_beta));
@@ -410,6 +534,10 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
const int64_t sq1 = nbq1 / sizeof(float);
const int64_t sq2 = nbq2 / sizeof(float);
const int64_t sq3 = nbq3 / sizeof(float);
// k can have its own layout (a permuted or padded view), only its rows must be contiguous
const int64_t sk1 = nbk1 / sizeof(float);
const int64_t sk2 = nbk2 / sizeof(float);
const int64_t sk3 = nbk3 / sizeof(float);
const int64_t sv1 = nbv1 / sizeof(float);
const int64_t sv2 = nbv2 / sizeof(float);
const int64_t sv3 = nbv3 / sizeof(float);
@@ -433,35 +561,73 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
state_slot_stride = cache->slot_stride;
}
const ggml_tensor * src_pk = dst->src[6];
gdn_replay_args rep = {};
if (src_pk != nullptr) {
const ggml_tensor * src_pv = dst->src[7];
const ggml_tensor * src_pgb = dst->src[8];
const ggml_tensor * src_nr = dst->src[9];
GGML_ASSERT(K == 1);
GGML_ASSERT(src_pv != nullptr && src_pgb != nullptr && src_nr != nullptr);
GGML_ASSERT(src_pk->type == GGML_TYPE_F32 && src_pv->type == GGML_TYPE_F32 && src_pgb->type == GGML_TYPE_F32);
GGML_ASSERT(src_nr->type == GGML_TYPE_I32 && ggml_is_contiguous(src_nr) && ggml_nelements(src_nr) == n_seqs);
GGML_ASSERT(src_pk->nb[0] == sizeof(float) && src_pv->nb[0] == sizeof(float) && src_pgb->nb[0] == sizeof(float));
rep.pk = (const float *) src_pk->data;
rep.pv = (const float *) src_pv->data;
rep.pgb = (const float *) src_pgb->data;
rep.n_rep = (const int32_t *) src_nr->data;
rep.sk1 = src_pk->nb[1] / sizeof(float);
rep.sk2 = src_pk->nb[2] / sizeof(float);
rep.sk3 = src_pk->nb[3] / sizeof(float);
rep.sv1 = src_pv->nb[1] / sizeof(float);
rep.sv2 = src_pv->nb[2] / sizeof(float);
rep.sv3 = src_pv->nb[3] / sizeof(float);
rep.sg1 = src_pgb->nb[1] / sizeof(float);
rep.sg2 = src_pgb->nb[2] / sizeof(float);
rep.sg3 = src_pgb->nb[3] / sizeof(float);
rep.n_pend = ggml_get_op_params_i32(dst, 1);
rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
for (int i = 0; i < 4; ++i) {
rep.st[i] = cache != nullptr ? cache->in_dst[i] : nullptr;
rep.st2[i] = cache != nullptr ? cache->in_nb2[i] : 0;
rep.st3[i] = cache != nullptr ? cache->in_nb3[i] : 0;
}
}
#ifdef GGML_SYCL_DMMV_HAS_ESIMD
if (!kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
if (src_pk == nullptr && !kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
launch_gated_delta_net_esimd(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3,
sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
return;
}
#endif
#define GDN_LAUNCH(KDA, KEEP, REPLAY) \
launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, \
n_seqs, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, \
scale, state_slot_stride, K, rep, stream)
if (kda) {
if (keep_rs) {
launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, true, false);
} else if (src_pk != nullptr) {
GDN_LAUNCH(true, false, true);
} else {
launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(true, false, false);
}
} else {
if (keep_rs) {
launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, true, false);
} else if (src_pk != nullptr) {
GDN_LAUNCH(false, false, true);
} else {
launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
GDN_LAUNCH(false, false, false);
}
}
#undef GDN_LAUNCH
}
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
@@ -469,12 +635,12 @@ void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor *
}
void ggml_sycl_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
ggml_sycl_op_gated_delta_net(ctx, dst);
}
void ggml_sycl_op_gated_delta_net_fused_cache(ggml_backend_sycl_context & ctx, ggml_tensor * dst,
ggml_sycl_gated_delta_net_fused_cache cache) {
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
ggml_sycl_op_gated_delta_net_impl(ctx, dst, &cache);
}
+5
View File
@@ -9,6 +9,11 @@
struct ggml_sycl_gated_delta_net_fused_cache {
float * data; // rollback slot 0
int64_t slot_stride; // between rollback slots (0 when K==1)
// replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
float * in_dst[4] = {};
int64_t in_nb2[4] = {}; // token stride in elements
int64_t in_nb3[4] = {}; // seq stride in elements
};
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst);
+116 -5
View File
@@ -14,6 +14,7 @@
#include <array>
#include <assert.h>
#include <atomic>
#include <thread>
#include <cctype>
#include <cinttypes>
#include <cstddef>
@@ -747,6 +748,8 @@ struct ggml_backend_sycl_buffer_context {
optimize_feature opt_feature;
std::vector<ggml_tensor_extra_gpu *> tensor_extras;
host_staging staging;
// pinned block for get_tensor, one slot per download worker
char * download_staging = nullptr;
bool is_usm_system;
ggml_backend_sycl_buffer_context(int device, void * dev_ptr, queue_ptr stream, bool is_usm_system) :
@@ -772,6 +775,10 @@ struct ggml_backend_sycl_buffer_context {
~ggml_backend_sycl_buffer_context() {
drop_host_staging();
if (download_staging != nullptr) {
sycl::free(download_staging, *stream);
download_staging = nullptr;
}
if (dev_ptr != nullptr) {
ggml_sycl_set_device(device);
if (is_usm_system)
@@ -980,6 +987,54 @@ catch (sycl::exception const &exc) {
std::exit(1);
}
// Reads go through a pinned block, as a copy into pageable memory is slow, and the caller often hands over fresh
// memory, where the first write to each 4 KiB page takes a page fault. Each worker owns one slot and loops over the
// chunks: queue the device copy, touch the destination pages while it is in flight, wait, copy out. So the faults
// overlap the transfer and run on several threads. Returns false when the pinned block is not available.
static bool ggml_sycl_buffer_download_staged(ggml_backend_sycl_buffer_context * ctx, char * dst, const char * src,
size_t size) {
constexpr size_t min_size = 64*1024;
constexpr size_t chunk = 1*1024*1024;
constexpr size_t n_max = 4;
constexpr size_t page = 4096;
if (size < min_size) {
return false;
}
sycl::queue & q = *ctx->stream;
if (ctx->download_staging == nullptr) {
ctx->download_staging = (char *) sycl::malloc_host(n_max * chunk, q);
if (ctx->download_staging == nullptr) {
return false;
}
}
const size_t n_chnk = (size + chunk - 1) / chunk;
const size_t n_work = std::min(n_max, n_chnk);
std::atomic<size_t> next{ 0 };
auto work = [&](size_t w) {
char * stage = ctx->download_staging + w * chunk;
for (size_t i = next++; i < n_chnk; i = next++) {
const size_t off = i * chunk;
const size_t n = std::min(chunk, size - off);
sycl::event ev = q.memcpy(stage, src + off, n);
for (size_t j = 0; j < n; j += page) {
((volatile char *) dst)[off + j] = 0;
}
ev.wait_and_throw();
memcpy(dst + off, stage, n);
}
};
std::vector<std::thread> workers;
for (size_t w = 1; w < n_work; ++w) {
workers.emplace_back(work, w);
}
work(0);
for (auto & t : workers) {
t.join();
}
return true;
}
static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
const ggml_tensor *tensor,
void *data, size_t offset,
@@ -992,9 +1047,11 @@ static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
ggml_sycl_set_device(ctx->device);
auto stream = dpct::dev_mgr::instance().get_device(ctx->device).default_queue();
SYCL_CHECK(CHECK_TRY_ERROR(
stream.memcpy(data, (const char *)tensor->data + offset, size)
.wait()));
if (!ggml_sycl_buffer_download_staged(ctx, (char *) data, (const char *) tensor->data + offset, size)) {
SYCL_CHECK(CHECK_TRY_ERROR(
stream.memcpy(data, (const char *)tensor->data + offset, size)
.wait()));
}
}
catch (sycl::exception const &exc) {
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
@@ -6657,8 +6714,62 @@ static int ggml_sycl_try_gdn_cache_fusion(const ggml_cgraph * cgraph, int node_i
return 0;
}
// replay: the kernel reads the pending inputs (src[6..8]) while it writes the cache, so they must not share memory
const auto overlaps = [](const ggml_tensor * x, const ggml_tensor * y) {
const char * x0 = (const char *) x->data;
const char * y0 = (const char *) y->data;
return x0 < y0 + ggml_nbytes(y) && y0 < x0 + ggml_nbytes(x);
};
for (int s = 6; s <= 8; ++s) {
if (gdn->src[s] != nullptr && overlaps(gdn->src[s], dst)) {
return 0;
}
}
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
// replay (not KDA): the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
float * in_dst[4];
int64_t in_nb2[4];
int64_t in_nb3[4];
int skip_in = skip;
int n_in = 0;
for (int j = node_idx + skip + 1; n_in < 4 && j < cgraph->n_nodes; ++j) {
const ggml_tensor * n = cgraph->nodes[j];
if (ggml_sycl_is_view_or_noop(n) || (n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
continue;
}
const ggml_tensor * in = gdn->src[1 + n_in];
const ggml_tensor * s0 = n->src[0];
const ggml_tensor * d = n->src[1];
// the cpy reads the whole input, directly or through a view of the same data
const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
ggml_are_same_stride(s0, in));
if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) ||
d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float) ||
overlaps(d, gdn->src[6]) || overlaps(d, gdn->src[7]) || overlaps(d, gdn->src[8])) {
break;
}
in_dst[n_in] = (float *) d->data;
in_nb2[n_in] = d->nb[2] / sizeof(float);
in_nb3[n_in] = d->nb[3] / sizeof(float);
skip_in = j - node_idx;
++n_in;
}
if (n_in == 4) {
for (int c = 0; c < 4; ++c) {
fused_state_cpy.in_dst[c] = in_dst[c];
fused_state_cpy.in_nb2[c] = in_nb2[c];
fused_state_cpy.in_nb3[c] = in_nb3[c];
}
skip = skip_in;
}
}
return skip;
}
@@ -7718,8 +7829,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
case GGML_OP_OPT_STEP_SGD:
return true;
case GGML_OP_GATED_DELTA_NET:
// replay of pending tokens (op param 1) is not implemented
return ggml_get_op_params_i32(op, 1) == 0;
// replay of pending tokens (src[6..9]) always has a single state slot
return op->src[6] == nullptr || ggml_get_op_params_i32(op, 0) == 1;
case GGML_OP_SSM_CONV:
return op->type == GGML_TYPE_F32 &&
op->src[0]->type == GGML_TYPE_F32 &&
+4 -3
View File
@@ -1019,9 +1019,11 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
ggml_flash_attn_ext_set_sinks(tensor_clone, src_clone[4]);
}
} else if (tensor->op == GGML_OP_MUL_MAT) {
tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
tensor_clone = src_clone[2] ? ggml_mul_mat_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], nullptr)
: ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
} else if (tensor->op == GGML_OP_MUL_MAT_ID) {
tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
tensor_clone = src_clone[3] ? ggml_mul_mat_id_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], nullptr)
: ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
} else if (tensor->op == GGML_OP_SUB) {
tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
} else if (tensor->op == GGML_OP_MUL) {
@@ -1612,4 +1614,3 @@ void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
}
#endif
@@ -45,6 +45,18 @@ struct vk_mat_mat_stream_k_fixup_push_constants {
static_assert(sizeof(vk_mat_mat_push_constants) <= 128);
struct vk_op_mul_mat_scale_push_constants {
uint32_t ne0; uint32_t ne1; uint32_t ne2; uint32_t ne3;
uint32_t sne0; uint32_t sne1; uint32_t sne2; uint32_t sne3;
uint32_t snb0; uint32_t snb1; uint32_t snb2; uint32_t snb3;
uint32_t per_expert;
uint32_t has_ids;
uint32_t ids_s0; uint32_t ids_s1; uint32_t ids_offset;
uint32_t ne_012mp; uint32_t ne_012L;
uint32_t ne_01mp; uint32_t ne_01L;
uint32_t ne_0mp; uint32_t ne_0L;
};
struct vk_mat_vec_push_constants {
uint32_t ncols;
uint32_t stride_a;
@@ -1255,4 +1267,3 @@ static vk_op_binary_push_constants ggml_vk_rms_norm_push_constants(
eps, 0.0f, (int32_t)num_partials,
};
}
+7 -2
View File
@@ -864,6 +864,7 @@ struct vk_device_struct {
vk_pipeline pipeline_matmul_split_k_reduce;
vk_pipeline pipeline_matmul_stream_k_fixup;
vk_pipeline pipeline_mul_mat_scale_f32;
vk_pipeline pipeline_quantize_q8_1_x4;
vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
@@ -921,8 +922,8 @@ struct vk_device_struct {
vk_pipeline pipeline_roll_f32;
vk_pipeline pipeline_repeat_i32, pipeline_repeat_back_f32;
vk_pipeline pipeline_repeat_i16;
vk_pipeline pipeline_cpy_32, pipeline_cpy_f32_f16, pipeline_cpy_16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_bf16_f32, pipeline_cpy_bf16_f16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
vk_pipeline pipeline_contig_cpy_32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_bf16_f32, pipeline_contig_cpy_bf16_f16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
vk_pipeline pipeline_cpy_32, pipeline_cpy_f32_f16, pipeline_cpy_16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_bf16_f32, pipeline_cpy_bf16_f16, pipeline_cpy_8, pipeline_cpy_f8_e4m3_f16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
vk_pipeline pipeline_contig_cpy_32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_bf16_f32, pipeline_contig_cpy_bf16_f16, pipeline_contig_cpy_8, pipeline_contig_cpy_f8_e4m3_f16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
@@ -1175,6 +1176,10 @@ typedef std::vector<vk_submission> vk_sequence;
#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE 0x10
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC 0x20
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D 0x40
struct vk_staging_memcpy {
vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
+155 -11
View File
@@ -2776,6 +2776,9 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
}
#undef X_CM2
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_f8_e4m3_f16_f16acc", matmul_f8_e4m3_f16_f16acc_cm2_len, matmul_f8_e4m3_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true);
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_f8_e4m3_f16", matmul_f8_e4m3_f16_cm2_len, matmul_f8_e4m3_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true);
GGML_ASSERT(device->subgroup_ballot);
create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm2_len, matmul_id_subgroup_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
@@ -2820,6 +2823,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
FOR_EACH_LUT_FP4_TYPE(X_CM2_ID)
}
#undef X_CM2_ID
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, true}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f16_f16acc", matmul_id_subgroup_f8_e4m3_f16_f16acc_cm2_len, matmul_id_subgroup_f8_e4m3_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f16", matmul_id_subgroup_f8_e4m3_f16_cm2_len, matmul_id_subgroup_f8_e4m3_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
} else
#endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
#if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
@@ -2943,6 +2948,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
cm1_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_q6_k_q8_1", matmul_q6_k_q8_1_cm1_len, matmul_q6_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
if (!rdna4) { cm1_create_mmq({GGML_TYPE_NVFP4, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_nvfp4_q8_1", matmul_nvfp4_q8_1_cm1_len, matmul_nvfp4_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); }
}
if (device->coopmat_acc_f16_support) {
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_f8_e4m3_f32_f16acc", matmul_f8_e4m3_f32_f16acc_cm1_len, matmul_f8_e4m3_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_f8_e4m3_f16_f16acc", matmul_f8_e4m3_f16_f16acc_cm1_len, matmul_f8_e4m3_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
}
if (device->coopmat_acc_f32_support) {
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", matmul_f8_e4m3_f32_cm1_len, matmul_f8_e4m3_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_f8_e4m3_f16", matmul_f8_e4m3_f16_cm1_len, matmul_f8_e4m3_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
}
GGML_ASSERT(device->subgroup_ballot);
@@ -3000,6 +3013,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
FOR_EACH_LUT_FP4_TYPE(X_CM1_ID)
}
#undef X_CM1_ID
if (device->coopmat_acc_f16_support) {
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f32_f16acc", matmul_id_subgroup_f8_e4m3_f32_f16acc_cm1_len, matmul_id_subgroup_f8_e4m3_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f16_f16acc", matmul_id_subgroup_f8_e4m3_f16_f16acc_cm1_len, matmul_id_subgroup_f8_e4m3_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
}
if (device->coopmat_acc_f32_support) {
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f32", matmul_id_subgroup_f8_e4m3_f32_cm1_len, matmul_id_subgroup_f8_e4m3_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f16", matmul_id_subgroup_f8_e4m3_f16_cm1_len, matmul_id_subgroup_f8_e4m3_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
}
if (device->coopmat_int_support && (rdna3 || rdna4)) {
cm1_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q4_0_q8_1", matmul_id_subgroup_q4_0_q8_1_cm1_len, matmul_id_subgroup_q4_0_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
@@ -3080,6 +3101,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", SPV_DOT2(matmul_##tstr##_f32), sizeof(vk_mat_mat_push_constants), 3);
FOR_EACH_LUT_TYPE(X_SG)
#undef X_SG
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_f8_e4m3_f32), sizeof(vk_mat_mat_push_constants), 3);
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", SPV_DOT2(matmul_f8_e4m3_f32), sizeof(vk_mat_mat_push_constants), 3);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
@@ -3119,6 +3142,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", SPV_DOT2(matmul_id_subgroup_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
FOR_EACH_LUT_TYPE(X_SG_ID_SUB)
#undef X_SG_ID_SUB
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32", SPV_DOT2(matmul_id_subgroup_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
std::vector<vk_tile_config> tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}};
@@ -3156,6 +3181,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", SPV_DOT2(matmul_id_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
FOR_EACH_LUT_TYPE(X_SG_ID)
#undef X_SG_ID
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_f8_e4m3_f32", SPV_DOT2(matmul_id_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
std::vector<vk_tile_config> tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}};
@@ -3194,6 +3221,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", matmul_##tstr##_f32_fp32_len, matmul_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3);
FOR_EACH_LUT_TYPE(X_SG_FP32)
#undef X_SG_FP32
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", matmul_f8_e4m3_f32_fp32_len, matmul_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
@@ -3227,6 +3255,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", matmul_id_subgroup_##tstr##_f32_fp32_len, matmul_id_subgroup_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
FOR_EACH_LUT_TYPE(X_SG_ID_SUB_FP32)
#undef X_SG_ID_SUB_FP32
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32", matmul_id_subgroup_f8_e4m3_f32_fp32_len, matmul_id_subgroup_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
} else {
sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f32_f32", matmul_id_f32_f32_fp32_len, matmul_id_f32_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_f16", matmul_id_f16_fp32_len, matmul_id_f16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
@@ -3239,6 +3268,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", matmul_id_##tstr##_f32_fp32_len, matmul_id_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
FOR_EACH_LUT_TYPE(X_SG_ID_FP32)
#undef X_SG_ID_FP32
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_f8_e4m3_f32", matmul_id_f8_e4m3_f32_fp32_len, matmul_id_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
}
}
}
@@ -3419,6 +3449,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F8_E4M3][i], "mul_mat_vec_f8_e4m3_f32_f32", arr_dmmv_f8_e4m3_f32_f32_len[reduc16], arr_dmmv_f8_e4m3_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
@@ -3448,6 +3479,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F8_E4M3][i], "mul_mat_vec_f8_e4m3_f16_f32", arr_dmmv_f8_e4m3_f16_f32_len[reduc16], arr_dmmv_f8_e4m3_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
@@ -3523,6 +3555,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_NVFP4], "mul_mat_vec_id_nvfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F8_E4M3], "mul_mat_vec_id_f8_e4m3_f32", arr_dmmv_id_f8_e4m3_f32_f32_len[reduc16], arr_dmmv_id_f8_e4m3_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (device->integer_dot_product) {
@@ -3590,6 +3623,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_NVFP4], "dequant_nvfp4", dequant_nvfp4_len, dequant_nvfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F8_E4M3], "dequant_f8_e4m3", dequant_f8_e4m3_len, dequant_f8_e4m3_data, "main", 2, 5 * sizeof(uint32_t), {256, 1, 1}, {}, 1);
// get_rows
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
@@ -3620,6 +3654,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_NVFP4], "get_rows_nvfp4", get_rows_nvfp4_len, get_rows_nvfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F8_E4M3], "get_rows_f8_e4m3", get_rows_f8_e4m3_len, get_rows_f8_e4m3_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_I32], "get_rows_i32", get_rows_i32_len, get_rows_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
@@ -3650,6 +3685,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_NVFP4], "get_rows_nvfp4_f32", get_rows_nvfp4_f32_len, get_rows_nvfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F8_E4M3], "get_rows_f8_e4m3_f32", get_rows_f8_e4m3_f32_len, get_rows_f8_e4m3_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_get_rows_back_f32, "get_rows_back_f32", get_rows_back_f32_len, get_rows_back_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {256, 1, 1}, {}, 1, true);
ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1);
@@ -3778,6 +3814,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f32,"cpy_bf16_f32",cpy_bf16_f32_len,cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f16,"cpy_bf16_f16",cpy_bf16_f16_len,cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_8, "cpy_8", cpy_8_len, cpy_8_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_f8_e4m3_f16, "cpy_f8_e4m3_f16", cpy_f8_e4m3_f16_len, cpy_f8_e4m3_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
@@ -3788,6 +3826,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f32,"contig_cpy_bf16_f32",contig_cpy_bf16_f32_len,contig_cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f16,"contig_cpy_bf16_f16",contig_cpy_bf16_f16_len,contig_cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_8, "contig_cpy_8", contig_cpy_8_len, contig_cpy_8_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f8_e4m3_f16, "contig_cpy_f8_e4m3_f16", contig_cpy_f8_e4m3_f16_len, contig_cpy_f8_e4m3_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
@@ -3902,6 +3942,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_antialias_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS}, 1);
ggml_vk_create_pipeline(device, device->pipeline_mul_mat_scale_f32, "mul_mat_scale_f32", mul_mat_scale_f32_len, mul_mat_scale_f32_data, "main", 3, sizeof(vk_op_mul_mat_scale_push_constants), {256, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
ggml_vk_create_pipeline(device, device->pipeline_pad_reflect_1d_f32, "pad_reflect_1d_f32", pad_reflect_1d_f32_len, pad_reflect_1d_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
@@ -6340,6 +6382,7 @@ vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
case GGML_TYPE_NVFP4:
case GGML_TYPE_TQ1_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_F8_E4M3:
break;
default:
return nullptr;
@@ -6405,6 +6448,7 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context *
case GGML_TYPE_NVFP4:
case GGML_TYPE_TQ1_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_F8_E4M3:
break;
default:
return nullptr;
@@ -6493,6 +6537,7 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context
case GGML_TYPE_NVFP4:
case GGML_TYPE_TQ1_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_F8_E4M3:
break;
default:
return nullptr;
@@ -7094,6 +7139,13 @@ vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_t
return ctx->device->pipeline_cpy_bf16_f16;
}
}
if (src->type == GGML_TYPE_F8_E4M3 && to == GGML_TYPE_F16) {
if (contig) {
return ctx->device->pipeline_contig_cpy_f8_e4m3_f16;
} else {
return ctx->device->pipeline_cpy_f8_e4m3_f16;
}
}
if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
if (contig) {
return ctx->device->pipeline_contig_cpy_f32_i32;
@@ -7140,6 +7192,9 @@ vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_t
}
}
if (src->type == to && !ggml_is_quantized(to) && ggml_type_size(to) == 1) {
return contig ? ctx->device->pipeline_contig_cpy_8 : ctx->device->pipeline_cpy_8;
}
if (src->type == to) {
// Copy two or four bytes at a time, depending on block size.
// For quantized types, we scale by block size/type size. But
@@ -7280,7 +7335,7 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub
std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
std::cerr << "))");
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
const uint64_t ne00 = src0->ne[0];
@@ -7657,6 +7712,10 @@ static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_
GGML_UNUSED(m);
}
static bool ggml_vk_mat_vec_folds_weight_scale(const ggml_tensor * scale, bool swap_inputs = false) {
return scale != nullptr && !swap_inputs && ggml_is_contiguous(scale);
}
static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool swap_inputs = false) {
ggml_tensor * dst = cgraph->nodes[node_idx];
const ggml_tensor * src0 = dst->src[swap_inputs ? 1 : 0];
@@ -7666,7 +7725,7 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context&
std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
std::cerr << ")),)");
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
const uint64_t ne00 = src0->ne[0];
@@ -7872,6 +7931,15 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context&
fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
}
// fold weight scale (src[2]) via the F0 slot, free since scaled matmuls don't fuse
if (ggml_vk_mat_vec_folds_weight_scale(dst->src[2], swap_inputs)) {
d_F0 = ggml_vk_tensor_subbuffer(ctx, dst->src[2]);
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE;
if (ggml_nelements(dst->src[2]) > 1) {
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC;
}
}
ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(ne12 * ne13, ctx->device->properties.limits.maxComputeWorkGroupCount[1]));
uint32_t base_work_group_y = 0;
@@ -8167,6 +8235,48 @@ static uint32_t ggml_vk_nb_elem(const ggml_tensor * t, int i) {
return (uint32_t)(t->nb[i] / ggml_type_size(t->type));
}
static void ggml_vk_mul_mat_scale(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
const bool is_id = dst->op == GGML_OP_MUL_MAT_ID;
const ggml_tensor * scale = is_id ? dst->src[3] : dst->src[2];
const ggml_tensor * ids = is_id ? dst->src[2] : nullptr;
GGML_ASSERT(scale != nullptr && scale->type == GGML_TYPE_F32);
GGML_ASSERT(dst->type == GGML_TYPE_F32 && ggml_is_contiguous(dst));
const bool per_channel_expert = is_id && scale->ne[0] == dst->ne[0] && scale->ne[1] == dst->src[0]->ne[2];
const bool per_expert = is_id && (ggml_nelements(scale) == dst->src[0]->ne[2] || per_channel_expert);
vk_pipeline pipeline = ctx->device->pipeline_mul_mat_scale_f32;
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
ggml_vk_sync_buffers(ctx, subctx);
vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, dst);
vk_subbuffer d_S = ggml_vk_tensor_subbuffer(ctx, scale);
vk_subbuffer d_I = is_id ? ggml_vk_tensor_subbuffer(ctx, ids, true) : d_S;
vk_op_mul_mat_scale_push_constants pc = {
(uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2], (uint32_t)dst->ne[3],
(uint32_t)scale->ne[0], (uint32_t)scale->ne[1], (uint32_t)scale->ne[2], (uint32_t)scale->ne[3],
ggml_vk_nb_elem(scale, 0), ggml_vk_nb_elem(scale, 1), ggml_vk_nb_elem(scale, 2), ggml_vk_nb_elem(scale, 3),
per_channel_expert ? 2u : per_expert ? 1u : 0u,
is_id ? 1u : 0u,
is_id ? (uint32_t)(ids->nb[0] / sizeof(int32_t)) : 0u,
is_id ? (uint32_t)(ids->nb[1] / sizeof(int32_t)) : 0u,
is_id ? get_misalign_bytes(ctx, ids) / (uint32_t)sizeof(int32_t) : 0u,
0, 0, 0, 0, 0, 0,
};
init_fastdiv_values(pc.ne0 * pc.ne1 * pc.ne2, pc.ne_012mp, pc.ne_012L);
init_fastdiv_values(pc.ne0 * pc.ne1, pc.ne_01mp, pc.ne_01L);
init_fastdiv_values(pc.ne0, pc.ne_0mp, pc.ne_0L);
const uint64_t total = (uint64_t)ggml_nelements(dst);
const uint64_t max_elems = (uint64_t)ctx->device->properties.limits.maxComputeWorkGroupCount[0] * 256;
const uint32_t elements0 = (uint32_t)std::min(total, max_elems);
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { d_D, d_S, d_I }, pc, { elements0, 1, 1 });
}
void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst) {
VK_LOG_DEBUG("ggml_vk_dsv4_hc_comb(" << mixes << ", " << scale << ", " << base << ", " << dst << ")");
@@ -8310,6 +8420,8 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st
ggml_tensor * src1 = dst->src[1];
VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
bool folded = false;
// Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
// where the M dimension is very large.
// Split_k doesn't work with M splitting.
@@ -8371,11 +8483,16 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st
// mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
// when ne12 and ne13 are one.
} else if ((dst->ne[1] == 1 || (dst->ne[1] <= ggml_vk_mul_mat_vec_max_cols(ctx->device) && src1->ne[2] * src1->ne[3] == 1)) &&
(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3 || ggml_is_quantized(src0->type))) {
ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
folded = ggml_vk_mat_vec_folds_weight_scale(dst->src[2]);
} else {
ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
}
if (dst->src[2] != nullptr && !folded) {
ggml_vk_mul_mat_scale(ctx, subctx, dst);
}
}
static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
@@ -8741,7 +8858,7 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
std::cerr << "))");
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
GGML_ASSERT(ids->type == GGML_TYPE_I32);
@@ -8940,6 +9057,18 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
}
// fold weight scale (src[3]) via the F0 slot, free since scaled matmuls don't fuse
if (ggml_vk_mat_vec_folds_weight_scale(dst->src[3])) {
d_F0 = ggml_vk_tensor_subbuffer(ctx, dst->src[3]);
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE;
if (ggml_nelements(dst->src[3]) > 1) {
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC;
}
if (dst->src[3]->ne[0] == dst->ne[0] && dst->src[3]->ne[1] == src0->ne[2]) {
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D;
}
}
// Loop over the batch dimension
for (uint32_t expert_i1 = 0; expert_i1 < nei1; ++expert_i1) {
const vk_mat_vec_id_push_constants pc = {
@@ -8971,7 +9100,7 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
static bool ggml_vk_use_mul_mat_vec_id(const ggml_tensor * dst) {
const ggml_tensor * src0 = dst->src[0];
const ggml_tensor * ids = dst->src[2];
return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F8_E4M3 || ggml_is_quantized(src0->type));
}
bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
@@ -8984,11 +9113,17 @@ void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const
ggml_tensor * src1 = dst->src[1];
ggml_tensor * src2 = dst->src[2];
VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
bool folded = false;
if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
folded = ggml_vk_mat_vec_folds_weight_scale(dst->src[3]);
} else {
ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
}
if (dst->src[3] != nullptr && !folded) {
ggml_vk_mul_mat_scale(ctx, subctx, dst);
}
}
bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type) {
@@ -15280,6 +15415,12 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr
return false;
}
const ggml_tensor * base = cgraph->nodes[node_idx];
if ((base->op == GGML_OP_MUL_MAT && base->src[2] != nullptr) ||
(base->op == GGML_OP_MUL_MAT_ID && base->src[3] != nullptr)) {
return false;
}
if ((ops.size() == 2 || ops.size() == 3 || ops.size() == 4) &&
ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
// additional constraints specific to this fusion
@@ -17158,10 +17299,6 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
const vk_device& device = ggml_vk_get_device(ctx->device);
if (ggml_get_src_scale(op, 0)) {
return false;
}
const bool uses_bda = (op->op == GGML_OP_IM2COL || op->op == GGML_OP_IM2COL_3D) &&
device->shader_int64 && device->buffer_device_address;
@@ -17235,6 +17372,12 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_OP_MUL_MAT_ID:
{
ggml_type src0_type = op->src[0]->type;
// matmul paths bind these at their raw offset
for (const ggml_tensor * t : std::initializer_list<const ggml_tensor *>{op->src[0], op->src[1], ggml_get_src_scale(op, 0)}) {
if (t && (vk_tensor_offset(t) + t->view_offs) % device->properties.limits.minStorageBufferOffsetAlignment != 0) {
return false;
}
}
if (op->op == GGML_OP_MUL_MAT_ID) {
if (!ggml_vk_use_mul_mat_vec_id(op)) {
const ggml_tensor * ids = op->src[2];
@@ -17280,6 +17423,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_TYPE_NVFP4:
case GGML_TYPE_TQ1_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_F8_E4M3:
break;
default:
return false;
@@ -17288,7 +17432,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
if (op->op == GGML_OP_MUL_MAT_ID && op->src[2]->ne[3] != op->src[1]->ne[3]) {
return false;
}
if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16 || op->src[0]->type == GGML_TYPE_F8_E4M3) ||
!(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
return false;
}
@@ -17393,6 +17537,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_TYPE_NVFP4:
case GGML_TYPE_TQ1_0:
case GGML_TYPE_TQ2_0:
case GGML_TYPE_F8_E4M3:
case GGML_TYPE_I32:
return true;
default:
@@ -18477,4 +18622,3 @@ void ggml_vk_debug_label::begin(vk_context & ctx, const std::string & name) {
subctx->debug_labels.push_back(name);
ggml_vk_cmd_label_begin(subctx->s->buffer->buf, subctx->debug_labels.back().c_str());
}
@@ -1,5 +1,7 @@
#version 450
#extension GL_EXT_shader_8bit_storage : require
#include "types.glsl"
#include "generic_unary_head.glsl"
@@ -19,7 +21,9 @@ void main() {
if (idx + (num_iter-1)*num_threads < p.ne) {
[[unroll]] for (uint i = 0; i < num_iter; ++i) {
#if defined(DATA_A_BF16)
#if defined(DATA_A_F8_E4M3)
data_d[get_doffset() + idx] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + idx]));
#elif defined(DATA_A_BF16)
data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));
#elif defined(DATA_D_BF16)
float f = float(data_a[get_aoffset() + idx]);
@@ -37,7 +41,9 @@ void main() {
continue;
}
#if defined(DATA_A_BF16)
#if defined(DATA_A_F8_E4M3)
data_d[get_doffset() + idx] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + idx]));
#elif defined(DATA_A_BF16)
data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));
#elif defined(DATA_D_BF16)
float f = float(data_a[get_aoffset() + idx]);
@@ -1,5 +1,7 @@
#version 450
#extension GL_EXT_shader_8bit_storage : require
#include "types.glsl"
#include "generic_unary_head.glsl"
@@ -12,7 +14,9 @@ void main() {
return;
}
#if defined(DATA_A_BF16)
#if defined(DATA_A_F8_E4M3)
data_d[get_doffset() + dst_idx(idx)] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + src0_idx(idx)]));
#elif defined(DATA_A_BF16)
data_d[get_doffset() + dst_idx(idx)] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + src0_idx(idx)])));
#elif defined(DATA_D_BF16)
float f = float(data_a[get_aoffset() + src0_idx(idx)]);
@@ -0,0 +1,18 @@
#version 450
#include "dequant_head.glsl"
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout (binding = 0) readonly buffer A {uint8_t data_a[];};
layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
void main() {
const uint i = gl_GlobalInvocationID.x;
if (i >= p.nel) {
return;
}
data_b[i] = D_TYPE(e4m3_to_fp32(data_a[i]));
}
@@ -544,12 +544,38 @@ vec4 dequantize4(uint ib, uint iqs, uint a_offset) {
}
#endif
#if defined(DATA_A_F8_E4M3)
FLOAT_TYPE dequantize1(uint ib, uint iqs, uint a_offset) {
return FLOAT_TYPE(e4m3_to_fp32(data_a[a_offset + ib + iqs]));
}
vec2 dequantize(uint ib, uint iqs, uint a_offset) {
const uint idx = a_offset + ib + iqs;
return vec2(e4m3_to_fp32(data_a[idx]), e4m3_to_fp32(data_a[idx + 1]));
}
vec4 dequantize4(uint ib, uint iqs, uint a_offset) {
const uint idx = a_offset + ib + iqs;
return vec4(e4m3_to_fp32(data_a[idx ]), e4m3_to_fp32(data_a[idx + 1]),
e4m3_to_fp32(data_a[idx + 2]), e4m3_to_fp32(data_a[idx + 3]));
}
vec4 dequantize4_2aligned(uint ib, uint iqs, uint a_offset) {
const uint idx = a_offset + ib + iqs;
return vec4(e4m3_to_fp32(data_a[idx ]), e4m3_to_fp32(data_a[idx + 1]),
e4m3_to_fp32(data_a[idx + 2]), e4m3_to_fp32(data_a[idx + 3]));
}
#endif
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
vec2 get_dm(uint ib, uint a_offset) {
return vec2(0, 0);
}
#endif
#if defined(DATA_A_F8_E4M3)
vec2 get_dm(uint ib, uint a_offset) {
return vec2(1.0, 0.0);
}
#endif
#if defined(DATA_A_IQ1_M)
vec2 get_dm(uint ib, uint a_offset) {
const uint16_t[4] scales = data_a[a_offset + ib].scales;
@@ -1412,6 +1412,17 @@ f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords
}
#endif
#if defined(DATA_A_F8_E4M3)
layout(buffer_reference, std430, buffer_reference_align = 1) buffer decodeBufF8_E4M3 {
uint8_t block;
};
float16_t dequantFuncF8_E4M3(const in decodeBufF8_E4M3 bl, const in uint blockCoords[2], const in uint coordInBlock[2])
{
return float16_t(e4m3_to_fp32(bl.block));
}
#endif
#if defined(DATA_A_Q1_0)
#define dequantFuncA dequantFuncQ1_0
#define dequantFuncA_v dequantFuncQ1_0_v
@@ -1492,4 +1503,6 @@ f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords
#define dequantFuncA_v dequantFuncNVFP4_v
#elif defined(DATA_A_F32)
#define dequantFuncA dequantFuncF32
#elif defined(DATA_A_F8_E4M3)
#define dequantFuncA dequantFuncF8_E4M3
#endif
@@ -27,6 +27,8 @@ void main() {
#if defined(DATA_A_BF16)
TEMP_TYPE v = TEMP_TYPE(bf16_to_fp32(data_a[a_offset + i00]));
#elif defined(DATA_A_F8_E4M3)
TEMP_TYPE v = TEMP_TYPE(e4m3_to_fp32(data_a[a_offset + i00]));
#else
TEMP_TYPE v = TEMP_TYPE(data_a[a_offset + i00]);
#endif
@@ -0,0 +1,57 @@
#version 450
#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
#include "utils.glsl"
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
layout(binding = 0) buffer D { float data_d[]; };
layout(binding = 1) readonly buffer S { float data_s[]; };
layout(binding = 2) readonly buffer I { int32_t data_ids[]; };
layout(push_constant) uniform parameter {
uint ne0; uint ne1; uint ne2; uint ne3;
uint sne0; uint sne1; uint sne2; uint sne3;
uint snb0; uint snb1; uint snb2; uint snb3;
uint per_expert;
uint has_ids;
uint ids_s0; uint ids_s1; uint ids_offset;
uint ne_012mp; uint ne_012L;
uint ne_01mp; uint ne_01L;
uint ne_0mp; uint ne_0L;
} p;
void main() {
const uint total = p.ne0 * p.ne1 * p.ne2 * p.ne3;
const uint stride = gl_NumWorkGroups.x * gl_WorkGroupSize.x;
for (uint i = gl_GlobalInvocationID.x; i < total; i += stride) {
const uint i3 = fastdiv(i, p.ne_012mp, p.ne_012L);
const uint r3 = i - i3 * p.ne0 * p.ne1 * p.ne2;
const uint i2 = fastdiv(r3, p.ne_01mp, p.ne_01L);
const uint r2 = r3 - i2 * p.ne0 * p.ne1;
const uint i1 = fastdiv(r2, p.ne_0mp, p.ne_0L);
const uint i0 = r2 - i1 * p.ne0;
int32_t expert = 0;
if (p.has_ids != 0) {
expert = data_ids[p.ids_offset + i1 * p.ids_s0 + i2 * p.ids_s1];
if (expert < 0) {
continue;
}
}
uint si;
if (p.per_expert != 0) {
si = (p.per_expert == 2) ? i0 * p.snb0 + uint(expert) * p.snb1 : uint(expert) * p.snb0;
} else {
si = (i0 % p.sne0) * p.snb0
+ (i1 % p.sne1) * p.snb1
+ (i2 % p.sne2) * p.snb2
+ (i3 % p.sne3) * p.snb3;
}
data_d[i] *= data_s[si];
}
}
@@ -7,7 +7,7 @@
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
#if !defined(DATA_A_F32) && !defined(DATA_A_F16) && !defined(DATA_A_BF16)
#if !defined(DATA_A_F32) && !defined(DATA_A_F16) && !defined(DATA_A_BF16) && !defined(DATA_A_F8_E4M3)
#define K_PER_ITER 8
#else
#define K_PER_ITER 4
@@ -114,7 +114,7 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const
}
}
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) || defined(DATA_A_F8_E4M3)
void iter_aligned_nonquant(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint tid, const uint i)
{
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
@@ -93,6 +93,16 @@ layout (constant_id = 0) const uint BLOCK_SIZE = 32;
layout (constant_id = 1) const uint NUM_ROWS = 1;
layout (constant_id = 2) const uint NUM_COLS = 1;
#ifdef MUL_MAT_ID
#define WEIGHT_SCALE_INDEX(row) (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D) != 0) ? (expert_id * p.stride_d + (row)) : (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC) != 0) ? expert_id : 0u))
#else
#define WEIGHT_SCALE_INDEX(row) (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC) != 0) ? (row) : 0u)
#endif
#define APPLY_WEIGHT_SCALE(acc, row) \
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE) != 0) { \
(acc) *= FLOAT_TYPE(data_fuse0[WEIGHT_SCALE_INDEX(row)]); \
}
#ifdef USE_SUBGROUP_ADD_NO_SHMEM
void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) {
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
@@ -104,6 +114,7 @@ void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t
if (tid == 0) {
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
APPLY_WEIGHT_SCALE(temp[j][n], first_row + n);
#ifdef MUL_MAT_ID
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
@@ -162,6 +173,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs
[[unroll]] for (uint s = 0; s < gl_NumSubgroups; ++s) {
temp[j][n] += tmpsh[j][n][s];
}
APPLY_WEIGHT_SCALE(temp[j][n], first_row + n);
#ifdef MUL_MAT_ID
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
@@ -210,6 +222,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs
if (tid == 0) {
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
APPLY_WEIGHT_SCALE(tmpsh[j][n][0], first_row + n);
#ifdef MUL_MAT_ID
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
tmpsh[j][n][0] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
@@ -4,6 +4,11 @@
#define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
#define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
// weight scale in data_fuse0; _VEC: per-output (dense) / per-expert (id), else scalar;
// _2D (id only): per-channel-per-expert [n_out, n_expert]
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE 0x10
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC 0x20
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D 0x40
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
#if defined(A_TYPEV4)
@@ -87,6 +87,8 @@ layout (binding = 0) readonly buffer A_SCALAR {float data_a_scalar[];};
layout (binding = 0) readonly buffer A_SCALAR {float16_t data_a_scalar[];};
#elif defined(DATA_A_BF16)
layout (binding = 0) readonly buffer A_SCALAR {uint16_t data_a_scalar[];};
#elif defined(DATA_A_F8_E4M3)
layout (binding = 0) readonly buffer A_SCALAR {uint8_t data_a_scalar[];};
#endif
#if defined(A_TYPE_PACKED16)
layout (binding = 0) readonly buffer A_PACKED16 {A_TYPE_PACKED16 data_a_packed16[];};
@@ -283,7 +285,7 @@ void main() {
const uint warp_r = warp_i % (BM / WM);
const uint warp_c = warp_i / (BM / WM);
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) || defined(DATA_A_F8_E4M3)
const uint LOAD_VEC_A_EFF = (ALIGNED != 0) ? LOAD_VEC_A : 1;
const uint LOAD_VEC_BATCH_A = (ALIGNED != 0) ? 1 : 2;
#elif !defined(MULMAT_QUANT)
@@ -124,7 +124,7 @@ layout (binding = 3) writeonly buffer S {D_TYPE data_s[];};
layout (binding = 1) readonly buffer B4 {B_TYPEV4 data_b_v4[];};
#endif
#if defined(MULMAT_QUANT) || QUANT_K > 1
#if defined(MULMAT_QUANT) || QUANT_K > 1 || defined(DATA_A_F8_E4M3)
#include "dequant_funcs_cm2.glsl"
#ifndef MULMAT_QUANT
// Per-type path: use the alias set by dequant_funcs_cm2.glsl
@@ -345,6 +345,26 @@ void load_a_to_shmem(const uint pos_a, const uint row, const uint col, const uin
store_a(col, eff_row + 4, FLOAT_TYPEV2(kvalues_mxfp4[vui >> 4] * d,
kvalues_mxfp4[vui2 >> 4] * d));
#endif
#elif defined(DATA_A_F8_E4M3)
#if LOAD_VEC_A == 4
if (ALIGNED != 0) {
const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row;
const uint k_pair = row * LOAD_VEC_A / 2;
FLOAT_TYPEV4 aa = FLOAT_TYPEV4(e4m3_to_fp32(data_a[idx]));
store_a(col, k_pair, aa.xy);
store_a(col, k_pair + 1, aa.zw);
return;
}
#endif
const uint idx = pos_a + col * p.stride_a + row * 2;
if (idx_m < p.M && block + row * 2 + 1 < end_k) {
store_a(col, row, FLOAT_TYPEV2(e4m3_to_fp32(data_a_scalar[idx]),
e4m3_to_fp32(data_a_scalar[idx + 1])));
} else if (idx_m < p.M && block + row * 2 < end_k) {
store_a(col, row, FLOAT_TYPEV2(e4m3_to_fp32(data_a_scalar[idx]), 0.0f));
} else {
store_a(col, row, FLOAT_TYPEV2(0.0f));
}
#else
if (MmTypeA == GGML_TYPE_Q4_0) {
const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row;
@@ -12,6 +12,10 @@
#extension GL_EXT_float_e4m3 : require
#endif
#if defined(DATA_A_F8_E4M3)
#extension GL_EXT_shader_8bit_storage : require
#endif
#if defined(DATA_A_F32)
#define QUANT_K 1
#define QUANT_R 1
@@ -54,6 +58,18 @@
#define A_TYPE_PACKED32 uint32_t
#endif
#if defined(DATA_A_F8_E4M3)
#define QUANT_K 1
#define QUANT_R 1
#if LOAD_VEC_A == 4
#define A_TYPE u8vec4
#else
#define A_TYPE uint8_t
#endif
#define A_TYPE_PACKED32 uint32_t
#endif
#define QUANT_K_Q4_0 32
#define QUANT_R_Q4_0 2
@@ -1971,6 +1987,33 @@ float bf16_to_fp32(uint32_t u)
return uintBitsToFloat(u << 16);
}
// OCP E4M3: 1 sign, 4 exponent (bias 7), 3 mantissa. No infinities; S.1111.111 is NaN.
float e4m3_to_fp32(uint x) {
const uint s = (x >> 7) & 1u;
const uint e = (x >> 3) & 0xFu;
const uint m = x & 0x7u;
float val;
if (e == 0xFu && m == 0x7u) {
return uintBitsToFloat(0x7FC00000u | (s << 31)); // NaN
} else if (e == 0u) {
val = float(m) * (1.0 / 512.0); // 2^-6 * m/8
} else {
val = uintBitsToFloat(((e + 120u) << 23) | (m << 20));
}
return s == 1u ? -val : val;
}
#if defined(DATA_A_F8_E4M3)
float e4m3_to_fp32(uint8_t x) {
return e4m3_to_fp32(uint(x));
}
vec4 e4m3_to_fp32(u8vec4 x) {
return vec4(e4m3_to_fp32(uint(x.x)), e4m3_to_fp32(uint(x.y)),
e4m3_to_fp32(uint(x.z)), e4m3_to_fp32(uint(x.w)));
}
#endif
vec4 bf16_to_fp32(uvec4 u)
{
return vec4(bf16_to_fp32(u.x), bf16_to_fp32(u.y), bf16_to_fp32(u.z), bf16_to_fp32(u.w));
@@ -75,6 +75,7 @@ const std::vector<std::string> type_names = {
"tq1_0",
"tq2_0",
"bf16",
"f8_e4m3",
};
enum MatMulIdType {
@@ -628,6 +629,15 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c
{"FLOAT_TYPEV8", FLOAT_TYPE(8, tname)},
};
if (tname == "f8_e4m3") {
const std::string load_vec_a = coopmat2 ? "1" : "4";
if (!coopmat2) {
string_to_spv(shader_name + "_f8_e4m3_f32" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc);
}
string_to_spv(shader_name + "_f8_e4m3_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc);
continue;
}
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
if (!f16acc && !coopmat && !coopmat2 && !dot2 && (is_legacy_quant(tname) || is_k_quant(tname) || tname == "mxfp4" || tname == "iq3_s" || tname == "iq4_xs")) {
string_to_spv(shader_name + "_" + tname + "_q8_1", "mul_mmq.comp", merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"D_TYPE", "float"},}), fp16, coopmat, coopmat2, f16acc);
@@ -850,7 +860,7 @@ void process_shaders() {
string_to_spv("dequant_" + tname + "_transpose", "dequant_" + tname + ".comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}, {"DEQUANT_TRANSPOSE", "1"}}));
}
shader = (tname == "f32" || tname == "f16" || tname == "bf16") ? "get_rows.comp" : "get_rows_quant.comp";
shader = (tname == "f32" || tname == "f16" || tname == "bf16" || tname == "f8_e4m3") ? "get_rows.comp" : "get_rows_quant.comp";
if (tname == "f16") {
string_to_spv("get_rows_" + tname, shader, merge_maps(base_dict, {{"TEMP_TYPE", "FLOAT_TYPE"}, {data_a_key, "1"}, {"B_TYPE", "int"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}}));
@@ -895,6 +905,8 @@ void process_shaders() {
string_to_spv("cpy_f32_bf16","copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "uint16_t"}, {"DATA_D_BF16", "1"}});
string_to_spv("cpy_bf16_f32","copy.comp", {{"A_TYPE", "uint16_t"}, {"D_TYPE", "float"}, {"DATA_A_BF16", "1"}});
string_to_spv("cpy_bf16_f16","copy.comp", {{"A_TYPE", "uint16_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_BF16", "1"}});
string_to_spv("cpy_8", "copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "uint8_t"}});
string_to_spv("cpy_f8_e4m3_f16", "copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_F8_E4M3", "1"}});
string_to_spv("contig_cpy_32", "contig_copy.comp", {{"A_TYPE", "uint"}, {"D_TYPE", "uint"}});
string_to_spv("contig_cpy_f32_i32", "contig_copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "int"}});
string_to_spv("contig_cpy_i32_f32", "contig_copy.comp", {{"A_TYPE", "int"}, {"D_TYPE", "float"}});
@@ -904,6 +916,8 @@ void process_shaders() {
string_to_spv("contig_cpy_f32_bf16","contig_copy.comp",{{"A_TYPE", "float"}, {"D_TYPE", "uint16_t"}, {"DATA_D_BF16", "1"}});
string_to_spv("contig_cpy_bf16_f32","contig_copy.comp",{{"A_TYPE", "uint16_t"}, {"D_TYPE", "float"}, {"DATA_A_BF16", "1"}});
string_to_spv("contig_cpy_bf16_f16","contig_copy.comp",{{"A_TYPE", "uint16_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_BF16", "1"}});
string_to_spv("contig_cpy_8", "contig_copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "uint8_t"}});
string_to_spv("contig_cpy_f8_e4m3_f16", "contig_copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_F8_E4M3", "1"}});
string_to_spv("cpy_f32_i32", "copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "int"}});
string_to_spv("cpy_i32_f32", "copy.comp", {{"A_TYPE", "int"}, {"D_TYPE", "float"}});
@@ -987,6 +1001,8 @@ void process_shaders() {
string_to_spv("repeat_i16", "repeat.comp", {{"A_TYPE", "int16_t"}, {"D_TYPE", "int16_t"}});
string_to_spv("mul_mat_scale_f32", "mul_mat_scale.comp", {});
string_to_spv("pad_f32", "pad.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
string_to_spv("pad_reflect_1d_f32", "pad_reflect_1d.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
+2
View File
@@ -187,6 +187,8 @@ class GGUFReader:
# Ensure alignment is a non-zero power of two
if self.alignment == 0 or (self.alignment & (self.alignment - 1)) != 0:
raise ValueError('Invalid alignment: must be a non-zero power of two')
if self.alignment > self.data.nbytes:
raise ValueError(f'Declared general.alignment ({self.alignment}) exceeds the size of the input file ({self.data.nbytes} bytes)')
padding = offs % self.alignment
if padding != 0:
offs += int(self.alignment - padding)
+5 -1
View File
@@ -412,7 +412,11 @@ class GGUFWriter:
def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
if pad != 0:
fp.write(bytes([0] * pad))
zeros = bytes(8 * 1024)
while pad > 0:
chunk = zeros[:pad]
fp.write(chunk)
pad -= len(chunk)
def write_tensor_data(self, tensor: np.ndarray[Any, Any], tensor_endianess: GGUFEndian | None = None) -> None:
if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
+6
View File
@@ -98,6 +98,8 @@ CODEPOINT_FLAG_MARK = 0x0010 # \p{M}
CODEPOINT_FLAG_PUNCTUATION = 0x0020 # \p{P}
CODEPOINT_FLAG_SYMBOL = 0x0040 # \p{S}
CODEPOINT_FLAG_CONTROL = 0x0080 # \p{C}
CODEPOINT_FLAG_LOWERCASE = 0x0200 # \p{Ll}
CODEPOINT_FLAG_UPPERCASE = 0x0400 # \p{Lu}
UNICODE_CATEGORY_TO_FLAG = {
"Cn": CODEPOINT_FLAG_UNDEFINED, # Undefined
@@ -146,6 +148,10 @@ for (cpt, cpt_lower, cpt_upper, categ, bidir) in unicode_data_iter():
# codepoint category flags
codepoint_flags[cpt] = UNICODE_CATEGORY_TO_FLAG[categ]
if categ == "Lu":
codepoint_flags[cpt] |= CODEPOINT_FLAG_UPPERCASE
elif categ == "Ll":
codepoint_flags[cpt] |= CODEPOINT_FLAG_LOWERCASE
# lowercase conversion
if cpt_lower:
+8
View File
@@ -345,6 +345,7 @@ llama_context::llama_context(
cparams.op_offload = params.op_offload;
cparams.kv_unified = params.kv_unified;
cparams.kv_quantized = ggml_is_quantized(params.type_k) || ggml_is_quantized(params.type_v);
// the Hy4 flash pools gather their members from a single KV stream
if (model.arch == LLM_ARCH_HY_V4_FLASH && !cparams.kv_unified && cparams.n_seq_max > 1) {
@@ -2886,6 +2887,13 @@ uint32_t llama_context::graph_max_nodes() const {
res += 32u*model.hparams.n_layer_all;
}
// a quantized KV cache may rotate Q and K (K cache) and V and the attention output (V cache) of each layer,
// 3 nodes per rotation plus the rotation matrices, which the per-tensor estimate above does not cover for
// models with few tensors per layer (e.g. fused QKV)
if (cparams.kv_quantized) {
res += 16u*model.hparams.n_layer_all;
}
// every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling
for (const auto & [seq_id, sampler] : sampling.samplers) {
res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq;
+1
View File
@@ -51,6 +51,7 @@ struct llama_cparams {
bool no_perf;
bool op_offload;
bool kv_unified;
bool kv_quantized; // quantized K or V cache: the cache may rotate Q/K/V and the attention output
bool pipeline_parallel;
bool training; // set by llama_opt_init()
bool moe_random_routing; // benchmark only: random expert ids in the MoE GEMMs
+2
View File
@@ -2249,6 +2249,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
// only build_lora_mm/build_lora_mm_id apply the transform: refuse archs and tensor kinds that can skip them
switch (arch) {
case LLM_ARCH_LFM3:
case LLM_ARCH_LLAMA:
case LLM_ARCH_QWEN3:
case LLM_ARCH_QWEN3MOE:
@@ -2271,6 +2272,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
"ffn_gate_exps", "ffn_up_exps", "ffn_down_exps", "ffn_gate_up_exps",
"ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp",
"ssm_out",
"shortconv.in_proj", "shortconv.out_proj",
};
if (name == "output.weight") {
return true; // the output head is built through build_lora_mm in every arch
+1336 -127
View File
File diff suppressed because it is too large Load Diff
+30 -25
View File
@@ -145,14 +145,6 @@ static std::vector<unicode_cpt_flags> unicode_cpt_flags_array() {
cpt_flags[cpt].is_whitespace = true;
}
for (auto p : unicode_map_lowercase) {
cpt_flags[p.second].is_lowercase = true;
}
for (auto p : unicode_map_uppercase) {
cpt_flags[p.second].is_uppercase = true;
}
for (auto &range : unicode_ranges_nfd) { // start, last, nfd
cpt_flags[range.nfd].is_nfd = true;
}
@@ -1653,31 +1645,41 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
return {};
}
// collapsed categories: LETTER alone means a letter that is not Lu or Ll
static constexpr int UCAT_LU = unicode_cpt_flags::LETTER | unicode_cpt_flags::UPPERCASE;
static constexpr int UCAT_LL = unicode_cpt_flags::LETTER | unicode_cpt_flags::LOWERCASE;
static constexpr int UCAT_LX = unicode_cpt_flags::LETTER;
// unicode categories
static const std::map<std::string, int> k_ucat_enum = {
{ "\\p{N}", unicode_cpt_flags::NUMBER },
{ "\\p{L}", unicode_cpt_flags::LETTER },
{ "\\p{P}", unicode_cpt_flags::PUNCTUATION },
{ "\\p{M}", unicode_cpt_flags::ACCENT_MARK },
{ "\\p{S}", unicode_cpt_flags::SYMBOL },
{ "\\p{Lu}", unicode_cpt_flags::LETTER }, // Uppercase letter
{ "\\p{Ll}", unicode_cpt_flags::LETTER }, // Lowercase letter
{ "\\p{Lt}", unicode_cpt_flags::LETTER }, // Titlecase letter
{ "\\p{Lm}", unicode_cpt_flags::LETTER }, // Modifier letter
{ "\\p{Lo}", unicode_cpt_flags::LETTER }, // Other letter
// Lt, Lm and Lo share one collapsed category, so \p{Lt} also matches Lm and Lo letters
static const std::map<std::string, std::vector<int>> k_ucat_enum = {
{ "\\p{N}", { unicode_cpt_flags::NUMBER } },
{ "\\p{L}", { UCAT_LU, UCAT_LL, UCAT_LX } },
{ "\\p{P}", { unicode_cpt_flags::PUNCTUATION } },
{ "\\p{M}", { unicode_cpt_flags::ACCENT_MARK } },
{ "\\p{S}", { unicode_cpt_flags::SYMBOL } },
{ "\\p{Lu}", { UCAT_LU } }, // Uppercase letter
{ "\\p{Ll}", { UCAT_LL } }, // Lowercase letter
{ "\\p{Lt}", { UCAT_LX } }, // Titlecase letter
{ "\\p{Lm}", { UCAT_LX } }, // Modifier letter
{ "\\p{Lo}", { UCAT_LX } }, // Other letter
};
static const std::map<int, int> k_ucat_cpt = {
{ unicode_cpt_flags::NUMBER, 0xD1 },
{ unicode_cpt_flags::LETTER, 0xD2 },
{ UCAT_LX, 0xD2 },
{ unicode_cpt_flags::PUNCTUATION, 0xD3 },
{ unicode_cpt_flags::ACCENT_MARK, 0xD4 },
{ unicode_cpt_flags::SYMBOL, 0xD5 },
{ UCAT_LU, 0xD6 },
{ UCAT_LL, 0xD7 },
};
static const std::map<int, std::string> k_ucat_map = {
{ unicode_cpt_flags::NUMBER, "\x30-\x39" }, // 0-9
{ unicode_cpt_flags::LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
{ UCAT_LX, "" }, // no sub-128 codepoints
{ UCAT_LU, "\x41-\x5A" }, // A-Z
{ UCAT_LL, "\x61-\x7A" }, // a-z
{ unicode_cpt_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
{ unicode_cpt_flags::ACCENT_MARK, "" }, // no sub-128 codepoints
{ unicode_cpt_flags::SYMBOL, "\\\x24\\\x2B\x3C-\x3E\x5E\x60\\\x7C\\\x7E" }, // $+<=>^`|~
@@ -1712,13 +1714,14 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
}
const auto flags = unicode_cpt_flags_from_cpt(cpts[i]);
const int ucat = flags.as_uint() & (unicode_cpt_flags::MASK_CATEGORIES | unicode_cpt_flags::UPPERCASE | unicode_cpt_flags::LOWERCASE);
if (flags.is_whitespace) {
//NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
//text_collapsed[i] = (char) 0x85; // <Next Line> as whitespace fallback
text_collapsed[i] = (char) 0x0B; // <vertical tab> as whitespace fallback
} else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
} else if (k_ucat_cpt.find(ucat) != k_ucat_cpt.end()) {
text_collapsed[i] = k_ucat_cpt.at(ucat);
} else {
text_collapsed[i] = (char) 0xD0; // fallback
}
@@ -1787,8 +1790,10 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
if (!inside) {
regex_expr_collapsed += '[';
}
regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
for (const int ucat : k_ucat_enum.at(pat)) {
regex_expr_collapsed += k_ucat_cpt.at(ucat);
regex_expr_collapsed += k_ucat_map.at(ucat);
}
if (!inside) {
regex_expr_collapsed += ']';
}
+4 -4
View File
@@ -17,8 +17,8 @@ struct unicode_cpt_flags {
CONTROL = 0x0080, // regex: \p{C}
MASK_CATEGORIES = 0x00FF,
WHITESPACE = 0x0100,
LOWERCASE = 0x0200,
UPPERCASE = 0x0400,
LOWERCASE = 0x0200, // regex: \p{Ll}
UPPERCASE = 0x0400, // regex: \p{Lu}
NFD = 0x0800,
};
@@ -33,8 +33,8 @@ struct unicode_cpt_flags {
uint16_t is_control : 1; // regex: \p{C}
// helper flags
uint16_t is_whitespace : 1; // regex: \s
uint16_t is_lowercase : 1;
uint16_t is_uppercase : 1;
uint16_t is_lowercase : 1; // regex: \p{Ll}
uint16_t is_uppercase : 1; // regex: \p{Lu}
uint16_t is_nfd : 1;
// decode from uint16
+29 -3
View File
@@ -6850,7 +6850,7 @@ struct test_mul_mat_id : public test_case {
const int64_t m_v; // rows of as in memory, the experts of as are strided for m_v > m, no view for m_v == 0
const bool ids_offset;
const bool skip; // set some ids to a negative value
const int scale_gran; // weight scale granularity: 0=default, 1=per-expert scalar, 2=per-channel-per-expert
const int scale_gran; // weight scale granularity: 0=default, 1=per-expert scalar, 2=per-channel-per-expert, 3=per-tensor +inf
const bool scale_view;
std::string vars() override {
@@ -6908,12 +6908,14 @@ struct test_mul_mat_id : public test_case {
ggml_set_name(b, "b");
ggml_tensor * s = nullptr;
if (scale_gran == 2) {
if (scale_gran == 3) {
s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
} else if (scale_gran == 2) {
s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, m, n_mats);
} else if (scale_gran == 1 || ggml_needs_scale(type_a)) {
s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_mats);
}
if (s && skip && !scale_view) {
if (s && skip && !scale_view && scale_gran != 3) {
const int64_t n_channels = scale_gran == 2 ? m : 1;
ggml_tensor * storage = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_channels, n_mats + 1);
ggml_set_name(storage, "scale_storage");
@@ -6942,6 +6944,14 @@ struct test_mul_mat_id : public test_case {
std::vector<float> prefix(storage->ne[0], NAN);
ggml_backend_tensor_set(storage, prefix.data(), 0, prefix.size()*sizeof(float));
}
if (scale_gran == 3) {
// skipped slots stay zero with an infinite scale, positive inputs keep the other slots at +inf
for (const char * name : {"as", "b"}) {
init_tensor_uniform(ggml_get_tensor(ctx, name), 0.1f, 1.0f);
}
const float inf = INFINITY;
ggml_backend_tensor_set(ggml_get_tensor(ctx, "s"), &inf, 0, sizeof(float));
}
}
void reinit_perf_iter(ggml_context * ctx) override {
@@ -13601,6 +13611,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
}
for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F8_E4M3}) {
for (int64_t n : {1, 9}) {
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, n, 32, 0, false, true, 3));
}
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 9, 32, 0, true, true, 3));
}
for (int scale_gran : {1, 2}) {
for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F8_E4M3}) {
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 1, 1, false, 32, 4, 32, 0, false, false, scale_gran));
@@ -13609,6 +13626,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
}
test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 32, 4, 32, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran, true));
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 4, 32, 0, false, false, scale_gran, true));
// misaligned ids view
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 9, 32, 0, true, true, scale_gran));
}
for (int64_t n : {1, 8}) {
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 32, n, 256, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran));
@@ -15055,6 +15074,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 8, 2, 4096, 1280, nb, n_slices));
}
}
// decode: one token per slice, non-f16 K/V take the vec kernel
for (ggml_type type_KV : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
for (int64_t n_slices : {1, 3, 8}) {
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 2, 12, 8192, 2304, 1, n_slices, type_KV));
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 4, 5000, 512, 2, n_slices, type_KV));
}
}
// flash attention with an indexed bias (Inkling 2 relative-position bias)
for (bool kv_rows : {false, true}) {
+18
View File
@@ -82,6 +82,24 @@ int main() {
success = false;
}
// \p{Lu} and \p{Ll} must split on case, expected output from HF tokenizers
const std::vector<std::string> regex_exprs_case = {
"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
};
const std::vector<std::string> expected_case = {
"get", "User", "By", "ID", " HTTPServer", " \xc3\x80" "bc", "D\xc3\x89" "f", " stra\xc3\x9f" "e", "\xc3\x96" "l",
};
const auto actual_case = unicode_regex_split("getUserByID HTTPServer \xc3\x80" "bcD\xc3\x89" "f stra\xc3\x9f" "e\xc3\x96" "l", regex_exprs_case, false);
if (actual_case != expected_case) {
fprintf(stderr, "unexpected case split:");
for (const auto & piece : actual_case) {
fprintf(stderr, " [%s]", piece.c_str());
}
fprintf(stderr, "\n");
success = false;
}
const std::vector<std::string> regex_exprs_bytes = { "\\p{L}+", "\\p{N}+", "\\s+" };
const std::string byte_encode_text = "\xc4\x80\xc4\xb1\xe0\xa4\x95\xf0\x9f\x98\x80";
const auto actual_byte_encode = unicode_regex_split(byte_encode_text, regex_exprs_bytes, true);
+2
View File
@@ -190,9 +190,11 @@ public:
const std::function<bool()> & should_stop = nullptr) const = 0;
};
#if defined(LLAMA_SUBPROCESS)
// time the output gets to close once the job is killed, and between two checks of exit, deadline and stop
static constexpr int SERVER_TOOL_SUBPROCESS_DRAIN_MS = 2000;
static constexpr int SERVER_TOOL_SUBPROCESS_POLL_MS = 100;
#endif
// output of a job, capped at max_output, handed to on_chunk as it arrives until on_chunk returns false
struct subprocess_output {