Compare 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
21 changed files with 1876 additions and 200 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 &&
+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
+7
View File
@@ -15074,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 {