Compare commits

...
12 Commits
Author SHA1 Message Date
cwriter aee03fbe80 sycl: fuse recurrent convolution windows (#31355) 2026-11-25 21:12:07 -05:00
Aleksander Grygier 9c003a97ab ui: open settings, the + menu and the model picker as sheets on phones, and manage MCP from settings (#33036)
* ui: add inset lists, rounder bottom sheets and a native select to the design system

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

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

Assisted-by: Claude (Opus 5.5 Medium)

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

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

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

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

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

Assisted-by: Claude (Opus 5.5 Medium)

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

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

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

Assisted-by: Claude (Opus 5.5 Medium)

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

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

Assisted-by: Claude (Opus 5.5 Medium)

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

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

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

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

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

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

* cont : clean-up comment

---------

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

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

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

---------

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

* fix float2 indexing

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

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

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

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

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

* convert : add hy_v4_flash

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

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

* tests : add hy_v4_flash to test-llama-archs

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

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

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

* tests : add the hy_v4_flash Metal fusion baseline

* model, mtmd : add hy_v4_flash vision

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

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

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

* CUDA: lightning indexer for 16 heads

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

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

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

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

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

* llama : use a unified KV cache for Hy4 flash

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

* rm redundant code in mtmd

* clean up comments

---------

Co-authored-by: Xuan Son Nguyen <son@huggingface.co>
2026-11-25 18:39:50 +01:00
241 changed files with 10023 additions and 1826 deletions
+1 -14
View File
@@ -13,7 +13,6 @@
blas,
cudaPackages,
autoAddDriverRunpath,
darwin,
rocmPackages,
vulkan-headers,
vulkan-loader,
@@ -104,17 +103,6 @@ let
ln -s /usr/bin/xcrun $out/bin
'';
# apple_sdk is supposed to choose sane defaults, no need to handle isAarch64
# separately
darwinBuildInputs =
with darwin.apple_sdk.frameworks;
[
Accelerate
CoreVideo
CoreGraphics
]
++ optionals useMetalKit [ MetalKit ];
cudaBuildInputs = with cudaPackages; [
cuda_cudart
cuda_nvml_dev
@@ -244,8 +232,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
++ optionals syclAot [ oclocAot ];
buildInputs =
optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs
++ optionals useCuda cudaBuildInputs
optionals useCuda cudaBuildInputs
++ optionals useMpi [ mpi ]
++ optionals useRocm rocmBuildInputs
++ optionals useBlas [ blas ]
+4
View File
@@ -146,6 +146,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"HrmTextForCausalLM": "hrm_text",
"HYV3ForCausalLM": "hunyuan",
"HYV4ForCausalLM": "hy_v4",
"HYV4FlashForCausalLM": "hy_v4_flash",
"IQuestCoderForCausalLM": "llama",
"Inkling2ForCausalLM": "inkling2",
"Inkling2LoopForCausalLM": "inkling2",
@@ -307,6 +308,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
"RWForCausalLM": "falcon",
"RWKV6Qwen2ForCausalLM": "rwkv",
"RWKV7ForCausalLM": "rwkv",
"Raon1MiniForCausalLM": "raon1_mini",
"RobertaForSequenceClassification": "bert",
"RobertaModel": "bert",
"RuGPT3XLForCausalLM": "gpt2",
@@ -390,6 +392,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
"GraniteSpeechPlusForConditionalGeneration": "granite",
"HiggsAudio3Model": "higgs_audio",
"HunYuanVLForConditionalGeneration": "hunyuan",
"HYV4FlashForCausalLM": "hy_v4_flash",
"HYV4FlashForConditionalGeneration": "hy_v4_flash",
"Idefics3ForConditionalGeneration": "smolvlm",
"Inkling2ForConditionalGeneration": "inkling2",
"Inkling2LoopForConditionalGeneration": "inkling2",
+3
View File
@@ -2473,6 +2473,9 @@ class TextModel(ModelBase):
if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
res = "domyn-edge"
if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1":
# ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview
res = "raon"
if res is None:
logger.warning("\n")
+650
View File
@@ -0,0 +1,650 @@
from __future__ import annotations
import json
from pathlib import Path
from typing import Callable, Iterable, cast
import numpy as np
import torch
from .base import LazyTorchTensor, MmprojModel, ModelBase, gguf, logger
from .deepseek41 import _StreamedBytes
from .hy_v4 import HYV4Model
# the reference derives the hash multipliers from the Engram seed, the 1-based layer id and the compressed vocab size
ENGRAM_SEED_STRIDE = 10007
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
@ModelBase.example("tencent/Hy4-Flash")
class HYV4FlashModel(HYV4Model):
"""hy_v4 with sparse and sliding-window MLA layers, sandwich norms, latent routed experts, Engram and a k-pool indexer.
The MTP draft block is exported as one extra sparse layer. The vision tower and the dfly draft layers are not converted.
"""
model_arch = gguf.MODEL_ARCH.HY_V4_FLASH
# the draft block is exported under block ids past the trunk, which skip_mtp would drop
skip_mtp = False
# dropped subsystems, see the class docstring
DROP_PREFIXES = ("vit.", "model.dfly_layers.")
DROP_SUBSTRINGS = ()
# the released config renamed sparse_attention, both name the same layer type
SPARSE_TYPES = ("sparse_attention", "deepseek_sparse_attention")
# the released checkpoints ship the token map as a tensor instead of engram_vocab_map.npz
ENGRAM_LOOKUP_TABLE = "lookup_table"
# compressed_indexer tail -> the tensor the graph reads it as
INDEXER_MAP = {
"token_key_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_K,
"token_key_norm.weight": gguf.MODEL_TENSOR.INDEXER_K_NORM,
"key_value_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_VALUE,
"key_gate_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_GATE,
"intra_group_ape": gguf.MODEL_TENSOR.INDEXER_KPOOL_APE,
"key_norm.weight": gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_NORM,
"query_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B,
"head_weight_projection.weight": gguf.MODEL_TENSOR.INDEXER_PROJ,
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# the draft block is an extra block, the loader subtracts the nextn count from block_count
if not getattr(self, "no_mtp", False):
self.block_count += self._n_nextn()
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
# Engram weights arrive one at a time but are written fused, so they wait here
self._engram_buf: dict[int, dict[str, torch.Tensor]] = {}
self._engram_tables: dict[int, torch.Tensor] = {}
self._engram_done: set[str] = set()
@classmethod
def filter_tensors(cls, item):
name = item[0]
if name.startswith(cls.DROP_PREFIXES) or any(s in name for s in cls.DROP_SUBSTRINGS):
return None
if name.startswith("model.mtp_layers."):
# hy_v4 drops the draft block; this model exports it, so skip that filter
return super(HYV4Model, cls).filter_tensors(item)
return super().filter_tensors(item)
def _layer_types(self) -> list[str]:
cached = getattr(self, "_layer_types_cache", None)
if cached is not None:
return cached
layer_types = self.hparams.get("layer_types")
n_layer = self.hparams["num_hidden_layers"]
if not layer_types or len(layer_types) < n_layer:
raise ValueError("HY_V4_FLASH needs a layer_types entry per layer")
unknown = set(layer_types[:n_layer]) - set(self.SPARSE_TYPES) - {"sliding_attention"}
if unknown:
raise ValueError(f"HY_V4_FLASH unknown layer_types values: {sorted(unknown)}")
# the released config renamed the sparse layers, normalize so the rest reads one name
self._layer_types_cache = ["sparse_attention" if t in self.SPARSE_TYPES else t for t in layer_types[:n_layer]]
return self._layer_types_cache
# Engram: one n-gram hash module per Engram layer, all buckets in one table as in deepseek41
def _engram_enabled(self) -> bool:
# engram_enable is optional, a False turns Engram off
return bool(self.hparams.get("engram_enable", True)) and bool(self.hparams.get("engram_layer_ids"))
def _engram_ids(self) -> list[int]:
"""engram_layer_ids, 1-based and sorted."""
ids = sorted(int(i) for i in self.hparams["engram_layer_ids"])
n_layer = self.hparams["num_hidden_layers"]
for i in ids:
# 1-based: the tensors live at model.layers.{i-1}.engram_layer.*
if not 1 <= i <= n_layer:
raise ValueError(f"HY_V4_FLASH engram_layer_ids has {i}, outside 1..{n_layer}")
return ids
def _engram_primes(self) -> dict[int, list[int]]:
"""Per 1-based layer id, the flattened [ngram][head] bucket counts."""
raw = self.hparams.get("engram_layer_head_vocab_sizes") or {}
n_gram = self.hparams["engram_max_ngram_size"]
n_head = self.hparams["engram_n_head_per_ngram"]
out = {}
for i in self._engram_ids():
# the keys are strings in the config
groups = raw.get(str(i)) or raw.get(i)
if groups is None:
raise ValueError(f"HY_V4_FLASH engram_layer_head_vocab_sizes has no entry for layer {i}")
if len(groups) != n_gram - 1 or any(len(g) != n_head for g in groups):
raise ValueError(
f"HY_V4_FLASH engram layer {i}: expected {n_gram - 1} groups of {n_head} bucket "
f"counts, got {[len(g) for g in groups]}")
out[i] = [int(p) for g in groups for p in g]
return out
def _engram_lookup_names(self) -> list[str]:
"""The lookup_table tensor of every Engram layer, empty when the checkpoint carries the npz instead."""
names = [f"model.layers.{i - 1}.engram_layer.{self.ENGRAM_LOOKUP_TABLE}" for i in self._engram_ids()]
present = [n for n in names if n in self.model_tensors]
if present and len(present) != len(names):
raise ValueError(f"HY_V4_FLASH engram is missing the lookup table of {sorted(set(names) - set(present))}")
return present
def _engram_vocab_map(self) -> tuple[list[int], int]:
"""The token -> compressed id map, extended by identity as the reference does, and the compressed vocab size."""
names = self._engram_lookup_names()
if names:
table = LazyTorchTensor.to_eager(self.model_tensors[names[0]]()).numpy().astype(np.int64)
for other in names[1:]:
if not np.array_equal(LazyTorchTensor.to_eager(self.model_tensors[other]()).numpy().astype(np.int64), table):
raise ValueError(f"HY_V4_FLASH engram lookup table of {other} differs from {names[0]}")
# the map is onto a dense id range from 0, so its largest id gives the compressed vocab size
compressed = int(table.max()) + 1
if int(table.min()) != 0 or len(np.unique(table)) != compressed:
raise ValueError("HY_V4_FLASH engram lookup table is not a dense id range from 0, supply engram_vocab_map.npz")
else:
path = Path(self.dir_model) / "engram_vocab_map.npz"
if not path.is_file():
raise FileNotFoundError(f"HY_V4_FLASH engram needs a lookup_table tensor or {path}")
with np.load(path) as z:
table = z["lookup_table"].astype(np.int64)
meta = json.loads(bytes(z["metadata"]).decode("utf-8").rstrip("\x00"))
compressed = int(meta["compressed_vocab_size"])
if int(table.max()) + 1 > compressed:
raise ValueError("HY_V4_FLASH engram lookup table exceeds its compressed vocab size")
if int(meta["engram_seed"]) != int(self.hparams.get("engram_seed", 0)):
raise ValueError("HY_V4_FLASH engram seed disagrees between the config and the vocab map")
n_vocab = self.hparams["vocab_size"]
token_map = list(map(int, table))
token_map += list(range(len(token_map), n_vocab))
return token_map, compressed
def _engram_multipliers(self, layer_id: int, compressed: int) -> list[int]:
seed = int(self.hparams.get("engram_seed", 0))
n_gram = self.hparams["engram_max_ngram_size"]
bound = max(1, (np.iinfo(np.int64).max // compressed) // 2)
rng = np.random.default_rng(seed + ENGRAM_SEED_STRIDE * layer_id)
return [int(m) for m in rng.integers(0, bound, size=n_gram) * 2 + 1]
def _engram_set_gguf_parameters(self):
hparams = self.hparams
ids = self._engram_ids()
primes = self._engram_primes()
token_map, compressed = self._engram_vocab_map()
n_gram = hparams["engram_max_ngram_size"]
n_head = hparams["engram_n_head_per_ngram"]
head_dim, rem = divmod(hparams["engram_n_embed_per_ngram"], n_head)
if rem:
raise ValueError("HY_V4_FLASH engram_n_embed_per_ngram is not a multiple of the head count")
# rebase each module's buckets into the shared table, row ids are int32
offsets: list[int] = []
multipliers: list[int] = []
base = 0
for i in ids:
for p in primes[i]:
offsets.append(base)
base += p
multipliers += self._engram_multipliers(i, compressed)
if base > np.iinfo(np.int32).max:
raise ValueError(f"HY_V4_FLASH engram table needs {base} rows, past the int32 row id limit")
w = self.gguf_writer
w.add_ple_layers([i - 1 for i in ids])
w.add_ple_ngram_size(n_gram)
w.add_ple_heads_per_ngram(n_head)
w.add_embedding_length_per_layer_input(head_dim)
w.add_ple_layer_multipliers(multipliers)
w.add_ple_head_offsets(offsets)
w.add_ple_head_vocab_sizes([p for i in ids for p in primes[i]])
w.add_engram_pad_token_id(hparams["engram_pad_id"])
w.add_engram_token_map(token_map)
logger.info(
"HY_V4_FLASH engram: %d module(s) at 0-based layers %s, %d-gram x %d heads x %d dims, "
"%d table rows, compressed vocab %d",
len(ids), [i - 1 for i in ids], n_gram, n_head, head_dim, base, compressed)
def _n_nextn(self) -> int:
return int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
def _layer_type_of(self, bid: int) -> str:
"""Layer type of any block, draft blocks included. Only sparse draft blocks are supported."""
n_layer = self.hparams["num_hidden_layers"]
if bid < n_layer:
return self._layer_types()[bid]
types = self.hparams.get("mtp_layer_types") or []
if not types:
return "sparse_attention"
t = types[min(bid - n_layer, len(types) - 1)]
if t != "sparse_attention":
raise ValueError(
f"HY_V4_FLASH: mtp_layer_types gives {t!r} for draft block {bid}, "
"but only 'sparse_attention' draft blocks are supported")
return t
def _write_rope_sections(self, sparse_rope: dict, window_rope: dict):
"""Write the M-RoPE sections of the VL checkpoints. Text-only files keep the loader default."""
sections = sparse_rope.get("mrope_section")
if sections is None:
return
if window_rope.get("mrope_section") != sections:
raise ValueError(
f"HY_V4_FLASH needs one mrope_section for both layer types, but "
f"{window_rope.get('mrope_section')} != {sections}")
if not sparse_rope.get("mrope_interleaved", False):
raise NotImplementedError("HY_V4_FLASH expects mrope_interleaved = true")
rope_dim = self.hparams["qk_rope_head_dim"]
if len(sections) != 3 or 2 * sum(sections) != rope_dim:
raise ValueError(f"HY_V4_FLASH mrope_section {sections} must sum to qk_rope_head_dim / 2")
self.gguf_writer.add_rope_dimension_sections(list(sections) + [0])
def _rope_for(self, layer_type: str) -> dict:
params = self.hparams.get("rope_parameters")
names = self.SPARSE_TYPES if layer_type == "sparse_attention" else (layer_type,)
found = [params[n] for n in names if isinstance(params, dict) and n in params]
if not found:
raise ValueError(f"HY_V4_FLASH needs rope_parameters[{layer_type!r}]")
if any(f != found[0] for f in found[1:]):
raise ValueError(f"HY_V4_FLASH has conflicting rope_parameters for {names}")
return found[0]
def set_gguf_parameters(self):
hparams = self.hparams
layer_types = self._layer_types()
is_swa = [t == "sliding_attention" for t in layer_types]
if not any(is_swa) or all(is_swa):
raise ValueError("HY_V4_FLASH expects a mix of sparse and sliding attention layers")
# the graph always applies the sandwich post-norms
if not hparams.get("sandwich_norm", False):
raise ValueError("HY_V4_FLASH expects sandwich_norm, the graph always applies the post-norms")
if hparams.get("dsa_skip_attn_post_norm", False):
raise ValueError(
"HY_V4_FLASH: dsa_skip_attn_post_norm is not supported - the graph applies "
"attn_post_norm on the sparse layers too")
# the non-sliding rope entry is keyed "sparse_attention", not "full_attention" as the base expects
sparse_rope = self._rope_for("sparse_attention")
window_rope = self._rope_for("sliding_attention")
# hide the key from hy_v4, which warns that it drops the draft block
n_nextn = self.hparams.pop("num_nextn_predict_layers", None)
try:
super().set_gguf_parameters()
finally:
if n_nextn is not None:
self.hparams["num_nextn_predict_layers"] = n_nextn
self.gguf_writer.add_rope_freq_base(sparse_rope["rope_theta"])
# the graph reorders the rope rows itself, so the sections only say how to split them
self._write_rope_sections(sparse_rope, window_rope)
# per-layer head count: the window layers carry swa_num_attention_heads
n_head = hparams["num_attention_heads"]
n_head_swa = hparams["swa_num_attention_heads"]
self.gguf_writer.remove_key(
gguf.Keys.Attention.HEAD_COUNT.format(arch=self.gguf_writer.arch))
# the arrays cover n_layer_all, the draft block is a sparse layer
is_swa_all = is_swa + [False] * (0 if getattr(self, "no_mtp", False) else self._n_nextn())
self.gguf_writer.add_head_count(
[n_head_swa if swa else n_head for swa in is_swa_all])
# the base already derives rope.freq_base_swa from rope_parameters["sliding_attention"]
self.gguf_writer.add_sliding_window(hparams["sliding_window"])
self.gguf_writer.add_sliding_window_pattern(is_swa_all)
# routed experts run here, the router and the shared expert stay at hidden_size
latent = hparams.get("routed_expert_hidden_size")
if latent:
self.gguf_writer.add_expert_latent_length(latent)
if self._n_nextn() and not getattr(self, "no_mtp", False):
self.gguf_writer.add_nextn_predict_layers(self._n_nextn())
if self._indexer_enabled():
# the pool size is compress_ratio, and the current group is always kept
ratio = hparams["compressed_indexer_compress_ratio"]
self.gguf_writer.add_indexer_kpool(ratio)
self.gguf_writer.add_indexer_kpool_select_tail(True)
# same check as the reference
group_topk = hparams.get("compressed_indexer_group_topk")
candidate = hparams.get("compressed_indexer_candidate_topk")
if group_topk and candidate and group_topk * ratio != candidate:
raise ValueError(
f"HY_V4_FLASH indexer: candidate_topk {candidate} != "
f"group_topk {group_topk} x compress_ratio {ratio}")
if hparams["index_topk"] % ratio:
raise ValueError(
f"HY_V4_FLASH indexer: index_topk {hparams['index_topk']} is not a multiple "
f"of compress_ratio {ratio}")
is_full = self.indexer_is_full() or []
logger.info(
"HY_V4_FLASH indexer: %d pooled groups of %d, keeping the best %d plus the current group (index_topk %d)",
sum(is_full), ratio, hparams["index_topk"] // ratio, hparams["index_topk"])
if self._engram_enabled():
self._engram_set_gguf_parameters()
self._check_mla_geometry()
logger.info(
"HY_V4_FLASH: %d sparse (%d heads, rope_theta %g) + %d sliding "
"(%d heads, rope_theta %g, window %d) layers",
is_swa.count(False), n_head, sparse_rope["rope_theta"],
is_swa.count(True), n_head_swa, window_rope["rope_theta"],
hparams["sliding_window"],
)
if hparams.get("engram_layer_ids") and not self._engram_enabled():
logger.warning(
"HY_V4_FLASH: engram_enable is off, dropping %d Engram layer(s)",
len(hparams["engram_layer_ids"]))
if hparams.get("use_compressed_indexer") and not self._indexer_enabled():
logger.warning(
"HY_V4_FLASH: dropping the compressed indexer - the sparse layers will "
"attend their whole context instead of the top %s tokens",
hparams.get("index_topk"),
)
def _check_mla_geometry(self):
"""Both layer types must share one MLA geometry, only the head count may differ."""
hparams = self.hparams
for sparse_key, window_key in (
("qk_nope_head_dim", "swa_qk_nope_head_dim"),
("qk_rope_head_dim", "swa_qk_rope_head_dim"),
("v_head_dim", "swa_v_head_dim"),
("qk_head_dim", "swa_qk_head_dim"),
("kv_lora_rank", "swa_kv_lora_rank"),
):
if window_key not in hparams:
continue
if hparams[window_key] != hparams[sparse_key]:
raise NotImplementedError(
f"HY_V4_FLASH needs one MLA geometry for both layer types, but "
f"{window_key}={hparams[window_key]} != {sparse_key}={hparams[sparse_key]}"
)
def _indexer_enabled(self) -> bool:
return bool(self.hparams.get("use_dsa")) and bool(self.hparams.get("use_compressed_indexer"))
def indexer_is_full(self) -> list[bool] | None:
"""Which layers own a k-pool indexer: the sparse ones. The config indexer_types marks every layer."""
if not self._indexer_enabled():
return None
n_all = self.hparams["num_hidden_layers"] + self._n_nextn()
return [self._layer_type_of(i) == "sparse_attention" for i in range(n_all)]
def prepare_tensors(self):
"""Check the compressed_indexer tensors instead of hy_v4's self_attn.indexer ones."""
self.hparams["num_key_value_heads"] = self.hparams["num_attention_heads"]
is_full = self.indexer_is_full()
if is_full is not None:
want = set(self.INDEXER_MAP)
n_layer = self.hparams["num_hidden_layers"]
present: dict[int, set[str]] = {}
for name in self.model_tensors:
head, sep, tail = name.partition(".self_attn.compressed_indexer.")
if not sep:
continue
# the draft block carries its own indexer, under a different prefix
if head.startswith("model.layers."):
present.setdefault(int(head.split(".")[2]), set()).add(tail)
elif head.startswith("model.mtp_layers."):
present.setdefault(n_layer + int(head.split(".")[2]), set()).add(tail)
for il, expect in enumerate(is_full):
seen = present.get(il, set())
if expect and seen != want:
raise ValueError(
f"HY_V4_FLASH layer {il} owns an indexer but is missing "
f"{sorted(want - seen)}" + (f" and carries unexpected {sorted(seen - want)}"
if seen - want else ""))
if not expect and seen:
raise ValueError(
f"HY_V4_FLASH layer {il} owns no indexer but carries {sorted(seen)}")
# straight to the grandparent: hy_v4's own validation does not apply here
super(HYV4Model, self).prepare_tensors()
if self._engram_enabled():
T = gguf.MODEL_TENSOR
want = {self.format_tensor_name(T.PER_LAYER_TOKEN_EMBD)}
for i in self._engram_ids():
for t in (T.ENGRAM_KV, T.ENGRAM_KV_B, T.ENGRAM_GATE, T.ENGRAM_LOOKUP_NORM, T.ENGRAM_HC_SCALE, T.ENGRAM_PRE_GAMMA):
want.add(self.format_tensor_name(t, i - 1))
if want - self._engram_done:
raise ValueError(f"HY_V4_FLASH: incomplete Engram tensors {sorted(want - self._engram_done)}")
def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int):
# ggml_add / ggml_mul operands, kept f32 as deepseek41 does for engram_gate
if new_name.endswith((".engram_gate.weight", ".engram_kv_b.weight", ".engram_hc_scale.weight")):
return gguf.GGMLQuantizationType.F32
# the pooled-key position bias is a ggml_add operand too
if new_name.endswith(".indexer_compressor_ape.weight"):
return gguf.GGMLQuantizationType.F32
# the base rule misses the router of the renumbered draft block
if new_name.endswith((".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight")):
return gguf.GGMLQuantizationType.F32
return super().tensor_force_quant(name, new_name, bid, n_dims)
def _engram_modify(self, data_torch: torch.Tensor, name: str,
bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
"""Fuse a layer's Engram weights as deepseek41 does, once all parts of a group arrived."""
if bid is None:
raise ValueError(f"HY_V4_FLASH: engram tensor without a layer id: {name}")
hc = self.hparams["hc_mult"]
n_head = self.hparams["engram_n_head_per_ngram"] * (self.hparams["engram_max_ngram_size"] - 1)
tail = name.split(".engram_layer.", 1)[1]
if tail == self.ENGRAM_LOOKUP_TABLE:
# the token map, read through _engram_vocab_map() and written as GGUF metadata
return
buf = self._engram_buf.setdefault(bid, {})
buf[tail] = data_torch
tn = self.format_tensor_name
T = gguf.MODEL_TENSOR
def ready(*names) -> bool:
return all(n in buf for n in names)
def take(*names):
return [buf.pop(n) for n in names]
# hc key projections then the value projection, the order the graph views assume
kv_parts = [f"key_projs.{c}.weight" for c in range(hc)] + ["value_proj.weight"]
if ready(*kv_parts):
yield tn(T.ENGRAM_KV, bid), torch.cat(take(*kv_parts), dim=0)
kvb_parts = [f"key_projs.{c}.bias" for c in range(hc)] + ["value_proj.bias"]
if ready(*kvb_parts):
yield tn(T.ENGRAM_KV_B, bid), torch.stack(take(*kvb_parts), dim=0)
# engram_gate folds the key and query norms, as deepseek41 does
gate_parts = [f"norm_key.{c}.weight" for c in range(hc)] + [f"norm_query.{c}.weight" for c in range(hc)]
if ready(*gate_parts):
parts = take(*gate_parts)
yield tn(T.ENGRAM_GATE, bid), torch.stack(
[parts[c] * parts[hc + c] for c in range(hc)], dim=0)
norm_parts = [f"lookup_per_head_norms.{c}.weight" for c in range(n_head)]
if ready(*norm_parts):
yield tn(T.ENGRAM_LOOKUP_NORM, bid), torch.stack(take(*norm_parts), dim=0)
scale_parts = [f"unified_per_hc_scales.{c}" for c in range(hc)]
if ready(*scale_parts):
yield tn(T.ENGRAM_HC_SCALE, bid), torch.stack(take(*scale_parts), dim=0)
if ready("unified_pre_gamma"):
yield tn(T.ENGRAM_PRE_GAMMA, bid), take("unified_pre_gamma")[0]
# the tables of all modules are concatenated in layer order
if ready("multi_head_embedding.embedding.weight"):
self._engram_tables[bid] = take("multi_head_embedding.embedding.weight")[0]
want = [i - 1 for i in self._engram_ids()]
if all(i in self._engram_tables for i in want):
self._write_engram_tables([self._engram_tables.pop(i) for i in want])
def _write_engram_tables(self, tables: list[torch.Tensor]) -> None:
# the concatenated tables are ~127 GB in BF16, so they are streamed one table at a time as deepseek41 does
f32 = self.ftype == gguf.LlamaFileType.ALL_F32
dim = tables[0].shape[1]
if any(t.shape[1] != dim for t in tables):
raise ValueError("HY_V4_FLASH engram tables differ in width")
n_rows = sum(t.shape[0] for t in tables)
def chunks() -> Iterable[np.ndarray]:
while tables:
table = LazyTorchTensor.to_eager(tables.pop(0))
for r0 in range(0, table.shape[0], 1 << 18):
# a copy, so that no chunk still held by the writer keeps the whole table alive
rows = (table[r0:r0 + (1 << 18)].float() if f32 else table[r0:r0 + (1 << 18)].bfloat16()).clone()
yield rows.view(torch.uint8).numpy()
del table, rows
qt = gguf.GGMLQuantizationType.F32 if f32 else gguf.GGMLQuantizationType.BF16
data = cast(np.ndarray, _StreamedBytes((n_rows, dim * (4 if f32 else 2)), chunks))
name = self.format_tensor_name(gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD)
self.gguf_writer.add_tensor(name, data, raw_dtype=qt)
self._engram_done.add(name)
NEXTN_MAP = {
"eh_proj.weight": gguf.MODEL_TENSOR.NEXTN_EH_PROJ,
"enorm.weight": gguf.MODEL_TENSOR.NEXTN_ENORM,
"hnorm.weight": gguf.MODEL_TENSOR.NEXTN_HNORM,
"final_layernorm.weight": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
}
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
if name.startswith("model.mtp_layers."):
if not self._n_nextn() or getattr(self, "no_mtp", False):
return
parts = name.split(".", 3)
nbid = self.hparams["num_hidden_layers"] + int(parts[2])
tail = parts[3]
key = self.NEXTN_MAP.get(tail)
if key is not None:
yield self.format_tensor_name(key, nbid), data_torch
return
# the rest of the block is an ordinary sparse layer, so re-enter under its block index
yield from self.modify_tensors(data_torch, f"model.layers.{nbid}.{tail}", nbid)
return
if ".compressed_indexer." in name:
# dropped when the indexer is off, the sparse layers then attend their whole context
if not self._indexer_enabled():
return
tail = name.split(".compressed_indexer.", 1)[1]
key = self.INDEXER_MAP.get(tail)
if key is None:
raise ValueError(f"HY_V4_FLASH: unmapped compressed_indexer tensor {name}")
# intra_group_ape [kpool, head_dim] is already ne (head_dim, kpool)
yield self.format_tensor_name(key, bid), data_torch
return
if ".engram_layer." in name:
if not self._engram_enabled():
return
for new_name, t in self._engram_modify(data_torch, name, bid):
self._engram_done.add(new_name)
yield new_name, t
return
# split kv_b_proj with the head count of this layer, the base uses a global one
if name.endswith("kv_b_proj.weight") and bid is not None:
hparams = self.hparams
n_head = (hparams["swa_num_attention_heads"]
if self._layer_type_of(bid) == "sliding_attention"
else hparams["num_attention_heads"])
v_head_dim = hparams["v_head_dim"]
qk_nope_head_dim = hparams["qk_nope_head_dim"]
expected = n_head * (v_head_dim + qk_nope_head_dim)
if data_torch.shape[0] != expected:
raise ValueError(
f"HY_V4_FLASH layer {bid}: {name} has {data_torch.shape[0]} rows, "
f"expected {expected} = {n_head} heads x ({qk_nope_head_dim} + {v_head_dim})"
)
kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1])
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
k_b = k_b.transpose(1, 2)
tn = self.format_tensor_name
yield from ModelBase.modify_tensors(self, k_b, tn(gguf.MODEL_TENSOR.ATTN_K_B, bid), bid)
yield from ModelBase.modify_tensors(self, v_b, tn(gguf.MODEL_TENSOR.ATTN_V_B, bid), bid)
return
yield from super().modify_tensors(data_torch, name, bid)
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
class HYV4FlashVisionModel(MmprojModel):
"""Vision tower of HY_V4_FLASH: a SigLIP-shaped encoder with a rmsnorm_mlp_adapter projector.
Positions come from a learned grid, resampled to the patch grid. The projector merges 2x2 patches with a strided conv2d, runs a 1x1 conv2d and appends a newline embedding to every row.
"""
projector_type = gguf.VisionProjectorType.HY_V4_FLASH
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
assert self.hparams_vision is not None
# there is no image_size, the position-embedding grid is max_image_size / patch_size
self.hparams_vision["image_size"] = self.hparams_vision.get("max_image_size", 2048)
def set_gguf_parameters(self):
super().set_gguf_parameters()
assert self.hparams_vision is not None
vcfg = self.hparams_vision
projector_type = vcfg.get("projector_type")
if projector_type != "rmsnorm_mlp_adapter":
raise ValueError(f"unsupported projector_type {projector_type!r}")
# the graph implements the plain variant only
unsupported = {
"use_2d_rope": bool(vcfg.get("use_2d_rope", False)),
"cat_extra_token": bool(vcfg.get("cat_extra_token", False)),
"use_image_newline_token": not vcfg.get("use_image_newline_token", True),
"perceive_post_norm": bool(vcfg.get("perceive_post_norm", False)),
"hidden_act": vcfg.get("hidden_act", "gelu") != "gelu",
"interpolate_mode": vcfg.get("interpolate_mode", "bilinear") != "bilinear",
}
for key, bad in unsupported.items():
if bad:
raise NotImplementedError(f"HY_V4_FLASH vision config {key}={vcfg.get(key)!r} is not supported")
self.gguf_writer.add_clip_projector_type(self.projector_type)
self.gguf_writer.add_vision_use_gelu(True)
# rms_norm_eps is also the LayerNorm eps of the encoder blocks
self.gguf_writer.add_vision_attention_layernorm_eps(vcfg.get("rms_norm_eps", 1e-5))
self.gguf_writer.add_vision_spatial_merge_size(vcfg.get("spatial_merge_size", 2))
self.gguf_writer.add_vision_min_pixels(int(self.preprocessor_config["min_pixels"]))
self.gguf_writer.add_vision_max_pixels(int(self.preprocessor_config["max_pixels"]))
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], torch.Tensor]]) -> tuple[str, Callable[[], torch.Tensor]] | None:
if not item[0].startswith("vit."):
return None
return super().filter_tensors(item)
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
# row 0 of the position embedding is an unused CLS slot, the reference resamples rows 1:
if "position_embedding" in name:
data_torch = data_torch[1:]
yield from super().modify_tensors(data_torch, name, bid)
def tensor_force_quant(self, name, new_name, bid, n_dims):
# conv weights in F32 or F16, BF16 IM2COL is not supported on Metal
if ("mm.0." in new_name or "mm.2." in new_name) and new_name.endswith(".weight"):
return gguf.GGMLQuantizationType.F16 if self.ftype == gguf.LlamaFileType.MOSTLY_F16 else gguf.GGMLQuantizationType.F32
return super().tensor_force_quant(name, new_name, bid, n_dims)
+6
View File
@@ -248,6 +248,12 @@ class Inkling2Model(TextModel):
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
# PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention
# output gate (self_attn.o_proj.gate_proj.weight); neither is in the tensor map.
name = name.replace(".linear.", ".")
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
+206
View File
@@ -0,0 +1,206 @@
from __future__ import annotations
from typing import Any, Callable, Iterable
import torch
from torch import Tensor
from .base import ModelBase, TextModel, gguf
_REQUIRED = object()
def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any:
# the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error
values = [config[key] for key in (new, old) if config.get(key) is not None]
if len(values) == 2 and values[0] != values[1]:
raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}")
if values:
return values[0]
if default is _REQUIRED:
raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})")
return default
def _rda_config(hp: dict[str, Any]) -> dict[str, Any]:
# rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers
if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None:
raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config")
config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"]
result = {
"num_heads": config["num_heads"],
"head_dim": config["head_dim"],
"conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"),
"full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"),
"mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"),
"rda_layers": _renamed_key(config, "rda_layers", "kda_layers"),
}
# absent and null differ here (see set_gguf_parameters), so the key is copied only when present
if "gate_lower_bound" in config:
result["gate_lower_bound"] = config["gate_lower_bound"]
return result
@ModelBase.register("Raon1MiniForCausalLM")
@ModelBase.example("KRAFTON/Raon-1-mini-preview")
class Raon1MiniModel(TextModel):
model_arch = gguf.MODEL_ARCH.RAON1_MINI
# mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale
_MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN"))
_MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z",
"alpha_pre", "alpha_post", "res.alpha_z", "res.eta")
# Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0.
_KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda")
_KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._experts: dict[tuple[int, str], dict[int, Tensor]] = {}
self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {}
self._rda_layers = set(_rda_config(self.hparams)["rda_layers"])
def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
filtered = super().filter_tensors(item)
if filtered is None:
return None
name, _ = filtered
if name.startswith("model.layers."):
layer = name.split(".", 3)[2]
# MTP layers follow the main model layers.
if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]:
return None
return filtered
def set_gguf_parameters(self):
hp = self.hparams
rda_config = _rda_config(hp)
n_layer = hp["num_hidden_layers"]
# 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers)
rda = self._rda_layers
mla = set(rda_config["mla_layers"])
if rda & mla or rda | mla != set(range(1, n_layer + 1)):
raise ValueError("Raon-1 mini attention layer lists must partition all layers")
# the hybrid memory needs both layer kinds
if not rda or not mla:
raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer")
if hp.get("tie_word_embeddings"):
raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)")
if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"]
or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ"
or hp["moe_router_activation_func"] != "sigmoid"
or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size")
or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1):
raise ValueError("Unsupported Raon-1 mini architecture variant")
if rda_config["num_heads"] != hp["num_attention_heads"]:
raise ValueError("Raon-1 mini RDA and MLA head counts must match")
super().set_gguf_parameters()
self.gguf_writer.add_vocab_size(hp["vocab_size"])
self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)])
self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"])
# the .get() defaults below are the HF config defaults
self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128))
self.gguf_writer.add_kda_head_dim(rda_config["head_dim"])
# HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate
if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None:
self.gguf_writer.add_kda_gate_lower_bound(bound)
self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"])
self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"])
self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"])
self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length(hp["kv_lora_rank"])
self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"])
self.gguf_writer.add_value_length_mla(hp["v_head_dim"])
self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6))
self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"])
self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"])
self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"])
self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"])
self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"])
self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"])
self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"])
self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4))
self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5))
self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0))
def prepare_tensors(self):
super().prepare_tensors()
if self._experts or self._mhc:
raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}")
def tensor_force_quant(self, name, new_name, bid, n_dims):
if ".hc_" in new_name and not new_name.endswith("_fn.weight"):
return gguf.GGMLQuantizationType.F32
quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0)
if self.ftype in quantized and new_name.startswith("blk."):
keep = self._KEEP_UNQUANTIZED
if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0:
keep += self._KEEP_UNQUANTIZED_Q8_0
if new_name.split(".")[2] in keep:
return gguf.GGMLQuantizationType.F16
return super().tensor_force_quant(name, new_name, bid, n_dims)
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
for site, prefix in self._MHC_SITES:
marker = f".{site}."
if marker not in name:
continue
assert bid is not None
parts = self._mhc.setdefault((bid, site), {})
suffix = name.split(marker, 1)[1]
if suffix in parts:
raise ValueError(f"Duplicate tensor {name}")
parts[suffix] = data_torch
if len(parts) < len(self._MHC_PARTS):
return
fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")])
base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")])
scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")])
for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)):
yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid)
del self._mhc[(bid, site)]
return
# moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3}
if ".moe.experts." in name or ".block_sparse_moe.experts." in name:
assert bid is not None
tail = name.split(".experts.", 1)[1].split(".")
eid, wid = int(tail[0]), tail[1]
group = self._experts.setdefault((bid, wid), {})
if eid in group or not 0 <= eid < self.hparams["num_experts"]:
raise ValueError(f"Invalid expert tensor {name}")
group[eid] = data_torch
if len(group) == self.hparams["num_experts"]:
tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP,
"up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP,
"w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid]
yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid)
del self._experts[(bid, wid)]
return
if name.endswith("kv_b_proj.weight"):
n_head = self.hparams["num_attention_heads"]
qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"]
kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"])
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid)
yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid)
return
if name.endswith(".self_attn.g_proj.weight"):
assert bid is not None
rda = bid + 1 in self._rda_layers
tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE
yield self.format_tensor_name(tid, bid), data_torch
return
if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")):
data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1])
if name.endswith(".A_log"):
data_torch = -torch.exp(data_torch.float())
# dt_bias -> the name SSM_DT's mapping expects, as for qwen3next
if name.endswith(".dt_bias"):
name = name.removesuffix(".dt_bias") + ".dt_proj.bias"
yield from super().modify_tensors(data_torch, name, bid)
+1
View File
@@ -169,6 +169,7 @@ models = [
{"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", },
{"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", },
{"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", },
{"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", },
]
# some models are known to be broken upstream, so we will skip them as exceptions
+1
View File
@@ -318,6 +318,7 @@ ninja
## Known Issues
- Adreno E17 compiler workarounds are disabled by default. If you encounter Flash Attention compilation failures or incorrect MoE results, set `GGML_OPENCL_ADRENO_E17_QUIRKS=1` before starting llama.cpp.
- Flash attention does not always improve performance.
- Currently OpenCL backend works on A6xx GPUs with recent drivers and compilers (usually found in IoT platforms).
However, it does not work on A6xx GPUs found in phones with old drivers and compilers.
+1
View File
@@ -822,6 +822,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
| GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. |
| GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. |
| GGML_SYCL_ENABLE_FUSION | 0 or 1 (default) | Enable fused-kernel dispatch in graph compute. Unsupported types and layouts fall back to the standalone op kernels. See `ggml_sycl_can_fuse()`. |
| GGML_SYCL_FUSE_CONV_WINDOW | 0 or 1 (default) | Fuse four-tap recurrent convolution windows, rollback cache updates and SiLU into one kernel. Other shapes use the existing kernels. |
| GGML_SYCL_ENABLE_ESIMD | 0 or 1 (default)| Enable ESIMD kernels when available. |
| GGML_SYCL_ENABLE_XMX_ESIMD | 0 or 1 (default) | Use the XMX (DPAS) multi-column mat-vec kernels for reordered Q2_K to Q6_K and Q8_0 weights on Xe2 GPUs. Speeds up speculative decoding and short prompt batches. |
| GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. |
+8 -2
View File
@@ -56,8 +56,8 @@ function(ggml_get_system_arch)
endif()
endfunction()
# Determines which FlashAttention vector kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
# Determines which FlashAttention kernel template instances to compile, returns them in OUT_SRCS.
function(ggml_cuda_fattn_instances DIR OUT_SRCS)
set(FA_TYPES q4_0 q4_1 q5_0 q5_1 q8_0 bf16 f16 f8_e4m3)
string(TOLOWER "${GGML_CUDA_FA_QUANTS}" FA_QUANTS)
@@ -122,6 +122,12 @@ function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
message(FATAL_ERROR "FlashAttention template instance \"${SRC}\" does not exist")
endif()
list(APPEND SRCS "${SRC}")
file(GLOB TILE_SRCS "${DIR}/template-instances/fattn-tile-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${TILE_SRCS})
file(GLOB MMA_SRCS "${DIR}/template-instances/fattn-mma-f16-instance-${COMBINATION}-*.cu")
list(APPEND SRCS ${MMA_SRCS})
endforeach()
set(${OUT_SRCS} ${SRCS} PARENT_SCOPE)
+1 -5
View File
@@ -116,16 +116,12 @@ if (CUDAToolkit_FOUND)
list(APPEND GGML_HEADERS_CUDA "../../include/ggml-cuda.h")
file(GLOB GGML_SOURCES_CUDA "*.cu")
file(GLOB SRCS "template-instances/fattn-tile*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/fattn-mma*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmq*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
file(GLOB SRCS "template-instances/mmf*.cu")
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
list(APPEND GGML_SOURCES_CUDA ${SRCS})
ggml_add_backend_library(ggml-cuda
+2
View File
@@ -1,3 +1,5 @@
#pragma once
// Simplified API for asynchronous data loading.
#include "common.cuh"
+292 -25
View File
@@ -2,6 +2,8 @@
#include "common.cuh"
#include "convert.cuh"
#include "cp-async.cuh"
#include "mma.cuh"
#include "vecdotq.cuh"
#include <cstdint>
@@ -18,16 +20,16 @@
// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
typedef void (* fattn_kernel_t)(
const char * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const char * __restrict__ mask,
const char * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
using fattn_kernel_t = void (*)(
const float2 * __restrict__ Q,
const char * __restrict__ K,
const char * __restrict__ V,
const half * __restrict__ mask,
const float * __restrict__ sinks,
const int * __restrict__ KV_max,
const int * __restrict__ KV_rows,
float * __restrict__ dst,
float2 * __restrict__ dst_meta,
const float scale,
const float max_bias,
const float m0,
@@ -35,16 +37,21 @@ typedef void (* fattn_kernel_t)(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33);
const int32_t s31, const int64_t s32, const int64_t s33);
typedef float (*vec_dot_KQ_t)(
const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds);
template <typename T_src, typename T_dst>
using fattn_load_tile_t = void (*)(
const T_src * __restrict__ KV, T_dst * __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * __restrict__ indices);
struct ggml_cuda_flash_attn_ext_f16_extra_data {
uintptr_t K;
uintptr_t V;
@@ -669,6 +676,253 @@ static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict
}
}
template <int warp_size, int nwarps, int I, int J, int stride_tile,
bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle,
typename T_src, typename T_dst>
struct flash_attn_load_tile_impl;
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, true, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if constexpr (KV_indirection) {
// K/V rows given per mask column, negative rows are padding
i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
uint32_t offset = i*stride_tile*sizeof(half2) + k*cpy_nb;
if constexpr (use_swizzle) {
offset = ggml_cuda_mma::swizzle<stride_tile*sizeof(half2), char>(offset, i);
}
cp_async_cg_16<preload>(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / cpy_ne;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*cpy_ne : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*cpy_ne;
} else {
src = KV + int64_t(k_VKQ_0 + i)*stride_KV + k*cpy_ne;
}
} else {
src = zero;
}
half2 * dst;
if constexpr (use_swizzle) {
dst = ggml_cuda_mma::swizzle<stride_tile>(tile_KV, i*stride_tile + k*cpy_ne, i);
} else {
dst = tile_KV + i*stride_tile + k*cpy_ne;
}
ggml_cuda_memcpy_1<cpy_nb>(dst, src);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection>
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, false, half2, float> {
static __device__ __forceinline__ void load(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int h2_per_chunk = cpy_ne / 2;
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
GGML_UNUSED(indices);
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
const int chunks_per_row = D2 / h2_per_chunk;
const half2 * const __restrict__ KV_0 = use_sparse || (KV_indirection && indices) ? KV : KV + int64_t(k_VKQ_0)*stride_KV;
auto load_step = [&] __device__ (const int n) {
const int stride_k = warp_size >> n;
if (stride_k == 0) {
return;
}
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > I && i >= I) {
break;
}
const __align__(16) half2 zero[h2_per_chunk] = {{0.0f, 0.0f}};
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
if constexpr (KV_indirection) {
if (indices) {
const int64_t i_KV = max(indices[k_VKQ_0 + i], 0);
src = KV_0 + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = KV_0 + i*stride_KV + k*h2_per_chunk;
}
} else {
src = zero;
}
__align__(16) half2 tmp_h2[h2_per_chunk];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(tmp_h2, src);
__align__(16) float2 tmp_f2[h2_per_chunk];
#pragma unroll
for (int l = 0; l < h2_per_chunk; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2);
}
}
};
ggml_cuda_unroll<7>{}(load_step);
}
};
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle, typename T_src, typename T_dst>
static __device__ __forceinline__ void flash_attn_load_tile(
const T_src * const __restrict__ KV, T_dst * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, use_cp_async, oob_check, use_sparse, KV_indirection, use_swizzle, T_src, T_dst>::load(
KV, tile_KV, D2, stride_KV, k_VKQ_0, i_sup, indices);
}
// Helper function to get a C++ type for calculating pointer offsets from a ggml type:
template <ggml_type type>
static __host__ __device__ auto ggml_cuda_fattn_kv_dtype() {
if constexpr (type == GGML_TYPE_F16) {
return half2{};
} else {
static_assert(type == -1, "bad type");
}
}
template <ggml_type type_K, int D, int nthreads>
constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() {
if constexpr (type_K == GGML_TYPE_F16) {
@@ -1028,9 +1282,10 @@ static __global__ void flash_attn_combine_results(
dst[tid] = VKQ_numerator / VKQ_denominator;
}
template <int DV, int ncols1, int ncols2>
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
void launch_fattn(
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared,
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel,
const int nwarps, const size_t nbytes_shared,
const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse,
const int warp_size = WARP_SIZE, const bool async_kv_preload = false
) {
@@ -1148,6 +1403,14 @@ void launch_fattn(
}
}
GGML_ASSERT(nb11 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb12 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb13 % sizeof(T_K_stride) == 0);
GGML_ASSERT(nb21 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb22 % sizeof(T_V_stride) == 0);
GGML_ASSERT(nb23 % sizeof(T_V_stride) == 0);
const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1);
const int gqa_ratio = Q->ne[2] / K->ne[2];
const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2);
@@ -1311,20 +1574,24 @@ void launch_fattn(
ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream);
ggml_cuda_kernel_launch(fattn_kernel, launch_params,
(const char *) Q->data,
K_data,
V_data,
mask ? ((const char *) mask->data) : nullptr,
sinks ? ((const char *) sinks->data) : nullptr,
(const float2 *) Q->data,
(const char *) K_data,
(const char *) V_data,
mask ? ((const half *) mask->data) : nullptr,
sinks ? ((const float *) sinks->data) : nullptr,
KV_max.ptr,
kv_rows ? (const int *) kv_rows->data : nullptr,
!stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr,
scale, max_bias, m0, m1, n_head_log2, logit_softcap,
Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3],
K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13,
nb21, nb22, nb23,
Q->ne[0], ne01, Q->ne[2], Q->ne[3],
int32_t(Q->nb[1] / sizeof(float2)), int32_t(Q->nb[2] / sizeof(float2)), int32_t(Q->nb[3] / sizeof(float2)),
K->ne[0], n_kv, K->ne[2], K->ne[3],
int32_t(nb11 / sizeof(T_K_stride)), int32_t(nb12 / sizeof(T_K_stride)), int64_t(nb13 / sizeof(T_K_stride)),
int32_t(nb21 / sizeof(T_V_stride)), int32_t(nb22 / sizeof(T_V_stride)), int64_t(nb23 / sizeof(T_V_stride)),
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0
mask ? int32_t(mask->nb[1] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[2] / sizeof(half)) : 0,
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0
);
CUDA_CHECK(cudaGetLastError());
+147 -241
View File
@@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages(
// ------------------------------------------------------------------------------------------------------------------
template<int stride_tile, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
// The minimum granularity is 16 bytes.
constexpr int chunk_size = 16;
constexpr int h2_per_chunk = chunk_size / sizeof(half2);
const int chunks_per_row = D2 / h2_per_chunk;
if constexpr (use_cp_async) {
static_assert(warp_size == 32, "bad warp_size");
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
constexpr int preload = 64;
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
auto load = [&] __device__ (auto n) {
const int stride_k = warp_size >> n;
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
int64_t i_KV;
if constexpr (use_sparse) {
// padded slots gather row 0, the -inf mask removes their contribution
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
i_KV = index >= 0 ? index : 0;
} else if (indices) {
// K/V rows given per mask column, negative rows are padding
i_KV = max(indices[k_VKQ_0 + i], 0);
} else {
i_KV = k_VKQ_0 + i;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
cp_async_cg_16<preload>(tile_KV_32 + swizzle<stride_tile*sizeof(half2), char>(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
} else {
const half2 zero[4] = {{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}};
auto load = [&] __device__ (const int n) {
const int stride_k = 32 >> n;
const int k0_start = stride_k == 32 ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
const int stride_i = warp_size / stride_k;
if (k0_start == k0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
break;
}
#pragma unroll
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
const half2 * src;
if constexpr (use_sparse) {
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
} else if (!oob_check || i < i_sup) {
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
src = KV + i_KV*stride_KV + k*h2_per_chunk;
} else {
src = zero;
}
ggml_cuda_memcpy_1<16>(swizzle<stride_tile>(tile_KV, i*stride_tile + k*h2_per_chunk, i), src);
}
}
};
// 1: max 32*16=512 bytes, 256 half
// 2: max 16*16=256 bytes, 128 half
// 3: max 8*16=128 bytes, 64 half
// 4: max 4*16= 64 bytes, 32 half
// 5: max 2*16= 32 bytes, 16 half
// 6: max 1*16= 16 bytes, 8 half
ggml_cuda_unroll<6>{}(load);
}
}
template<int ncols1, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
const half * const __restrict__ mask_h, half * const __restrict__ tile_mask,
@@ -612,11 +502,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps,
bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, bool last_iter, bool oob_check,
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ>
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ,
typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
float2 * const __restrict__ dstk,
@@ -653,6 +544,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -676,7 +574,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
constexpr bool use_cp_async = true;
cp_async_wait_all();
__syncthreads();
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2, tile_V, min(nbatch_V2, DV/2), stride_V, k_VKQ_0, k_VKQ_sup, indices);
} else {
// the sparse mask values are gathered per element, always load them synchronously
@@ -696,7 +594,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
if constexpr (nstages <= 1) {
const int k0_diff = min(k0_stop, DKQ/2) - k0_start; // Only load the real head size from global memory.
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1033,7 +931,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0_next*nbatch_fa, k_VKQ_sup, indices);
}
}
@@ -1049,7 +947,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
const int i0_diff = min(i0_stop, DV) - i0_start; // Only load the real head size from global memory.
if (!V_is_K_view || i0_stop > 2*nbatch_K2) {
constexpr bool use_cp_async = nstages == 1;
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
(V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices);
if (use_cp_async) {
cp_async_wait_all();
@@ -1261,11 +1159,11 @@ template<int DKQ, int ncols> struct mma_tile_sizes {
};
#endif // defined(TURING_MMA_AVAILABLE)
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup>
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const float2 * const __restrict__ Q_f2,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask_h,
const int32_t * const __restrict__ indices,
const float * const __restrict__ sinks_f,
@@ -1310,6 +1208,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
// FIXME this is causing performance regressions on AMD/V100.
#ifdef TURING_MMA_AVAILABLE
constexpr bool KV_indirection = true;
#else
constexpr bool KV_indirection = use_sparse;
#endif // TURING_MMA_AVAILABLE
constexpr int DKQp = GGML_PAD(DKQ, 16);
constexpr int DVp = GGML_PAD(DV, 16);
@@ -1459,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
(mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
}
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0*nbatch_fa, k_VKQ_sup, indices);
}
@@ -1472,7 +1377,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0_next, k_VKQ_sup);
@@ -1482,7 +1387,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1493,7 +1398,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1502,7 +1407,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
const int k_VKQ_sup = ne11 - kb0*nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1513,7 +1418,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
@@ -1522,7 +1427,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
constexpr int k_VKQ_sup = nbatch_fa;
flash_attn_ext_f16_iter
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
@@ -1936,18 +1841,18 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u
(DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8);
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse>
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, ggml_type type_K, ggml_type type_V>
__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_ext_f16(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -1955,19 +1860,22 @@ static __global__ void flash_attn_ext_f16(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
ggml_cuda_pdl_sync(); // TODO optimize placement
#if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
// sparse: one index list per (sequence, query tile), the live count of each list follows the lists
const int * GGML_CUDA_RESTRICT sparse_indices = use_sparse ? KV_max_ptr : nullptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
@@ -2024,12 +1932,7 @@ static __global__ void flash_attn_ext_f16(
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const int stride_Q1 = nb01 / sizeof(float2);
const int stride_Q2 = nb02 / sizeof(float2);
const int stride_K = nb11 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_V = V_is_K_view ? stride_K : nb21 / sizeof(half2);
const int stride_V = V_is_K_view ? s11 : s21;
const int iter_k = (ne11 + (nbatch_fa - 1)) / nbatch_fa;
const int iter_j = (ne01.z + (ncols1 - 1)) / ncols1;
@@ -2072,14 +1975,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2096,14 +1999,14 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
if (kb0_start == 0) {
constexpr bool needs_fixup = false; // CUDA block is working on an entire tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
} else {
constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile.
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
}
kbc += iter_k;
@@ -2126,14 +2029,14 @@ static __global__ void flash_attn_ext_f16(
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
@@ -2149,27 +2052,30 @@ static __global__ void flash_attn_ext_f16(
constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
constexpr bool needs_fixup = false;
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
#else
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
}
bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2);
template <int DKQ, int DV, int ncols1, int ncols2>
template <int DKQ, int DV, int ncols1, int ncols2, ggml_type type_K = GGML_TYPE_F16, ggml_type type_V = GGML_TYPE_F16>
void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * KQV = dst;
const int id = ggml_cuda_get_device();
const int cc = ggml_cuda_info().devices[id].cc;
@@ -2223,7 +2129,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) {
if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) {
constexpr bool use_sparse_kernel = true;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
use_sparse = true;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
@@ -2233,7 +2139,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
} else {
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2245,7 +2151,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
#endif // !defined(GGML_USE_MUSA)
{
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2256,7 +2162,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
} else {
constexpr bool use_logit_softcap = true;
constexpr bool use_sparse_kernel = false;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
if (!shared_memory_limit_raised[id]) {
@@ -2266,83 +2172,83 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
}
const bool async_kv_preload = nstages == 2 && !use_sparse;
launch_fattn<DV, ncols1, ncols2>
launch_fattn<DV, ncols1, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload);
}
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_mma_f16_case \
<DKQ, DV, ncols1, ncols2, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16); \
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols, type_K, type_V) \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8, type_K, type_V); \
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16, type_K, type_V); \
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64, GGML_TYPE_F16, GGML_TYPE_F16)
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64, GGML_TYPE_F16, GGML_TYPE_F16)
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
// The number of viable configurations for Deepseek is very limited:
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
// Mistral Small 4 (DKQ=320, DV=256), GQA=32-only build:
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
// For GLM 4.7 Flash
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
+29 -13
View File
@@ -1,59 +1,75 @@
#include "common.cuh"
#include "fattn-tile.cuh"
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_tile_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
switch (K->ne[0]) {
case 40: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 40, 40, type_K, type_V>(ctx, dst);
} break;
case 64: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 64, 64, type_K, type_V>(ctx, dst);
} break;
case 72: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 72, 72, type_K, type_V>(ctx, dst);
} break;
case 80: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 80, 80, type_K, type_V>(ctx, dst);
} break;
case 96: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case< 96, 96, type_K, type_V>(ctx, dst);
} break;
case 112: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<112, 112, type_K, type_V>(ctx, dst);
} break;
case 128: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<128, 128, type_K, type_V>(ctx, dst);
} break;
case 192: {
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_tile_case<192, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<192, 128, type_K, type_V>(ctx, dst);
} break;
case 256: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<256, 256, type_K, type_V>(ctx, dst);
} break;
case 320: {
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_tile_case<320, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<320, 256, type_K, type_V>(ctx, dst);
} break;
case 512: {
GGML_ASSERT(V->ne[0] == K->ne[0]);
ggml_cuda_flash_attn_ext_tile_case<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<512, 512, type_K, type_V>(ctx, dst);
} break;
case 576: {
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_tile_case<576, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_tile_case<576, 512, type_K, type_V>(ctx, dst);
} break;
default:
GGML_ABORT("Unsupported head size");
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
+109 -201
View File
@@ -373,133 +373,28 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
return (ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols) >> 23) & ((1 << 9) - 1);
}
// TODO: deduplicate with mma-f16
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (2*stride_j);
const int j0_stop = ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne;
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
ggml_cuda_memcpy_1<cpy_nb>(
tile_KV + i*(J/2 + J_padding) + j,
!oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
}
}
}
};
// 1: max 64*16=512 bytes, 512 half
// 2: max 32*16=512 bytes, 256 half
// 3: max 16*16=256 bytes, 128 half
// 4: max 8*16=128 bytes, 64 half
// 5: max 4*16= 64 bytes, 32 half
// 6: max 2*16= 32 bytes, 16 half
// 7: max 1*16= 16 bytes, 8 half
static_assert(J % 8 == 0, "bad J");
static_assert((J/2) % cpy_ne == 0, "bad J");
ggml_cuda_unroll<7>{}(load);
}
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
static __device__ __forceinline__ void flash_attn_tile_load_tile(
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_ne = cpy_nb / 4;
auto load = [&] __device__ (const int n) {
const int stride_j = warp_size >> n;
if (stride_j == 0) {
return;
}
const int j0_start = stride_j == warp_size ? 0 : (J/cpy_ne) - (J/cpy_ne) % (2*stride_j);
const int j0_stop = (J/cpy_ne) - (J/cpy_ne) % (1*stride_j);
const int stride_i = warp_size / stride_j;
if (j0_start == j0_stop) {
return;
}
#pragma unroll
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
if (i0 + nwarps*stride_i <= I || i < I) {
#pragma unroll
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2);
const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}};
__align__(16) half2 tmp_h2[cpy_ne/2];
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(
tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
__align__(16) float2 tmp_f2[cpy_ne/2];
#pragma unroll
for (int l = 0; l < cpy_ne/2; ++l) {
tmp_f2[l] = __half22float2(tmp_h2[l]);
}
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*(J + J_padding) + 2*j, tmp_f2);
}
}
}
};
// 1: max 32*16=512 bytes, 128 float
// 2: max 16*16=256 bytes, 64 float
// 3: max 8*16=128 bytes, 32 float
// 4: max 4*16= 64 bytes, 16 float
// 5: max 2*16= 32 bytes, 8 float
static_assert(J % 8 == 0, "bad J");
static_assert(J % cpy_ne == 0, "bad J");
ggml_cuda_unroll<5>{}(load);
}
// Function that performs a single iteration in for the KQ matrix multiplication:
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot>
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_K>
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const T_K * const __restrict__ K_h2,
T_vec_dot * const KV_tmp,
const int stride_K2,
const int k_VKQ_0,
const int k_VKQ_sup,
const int k_KQ_0,
float * KQ_acc) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, cpy_ne, oob_check>
(K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup);
constexpr int stride_tile_K = std::is_same_v<T_vec_dot, half2> ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne;
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, false, false, T_K, T_vec_dot>
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, nullptr);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -556,11 +451,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
// Function that performs a single iteration of the main loop over up to nbatch_fa tokens.
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int DV, int nbatch_fa, int nbatch_K,
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc>
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
static __device__ __forceinline__ void flash_attn_tile_iter(
T_vec_dot * const Q_tmp,
const half2 * const __restrict__ K_h2,
const half2 * const __restrict__ V_h2,
const T_K * const __restrict__ K_h2,
const T_V * const __restrict__ V_h2,
const half * const __restrict__ mask,
const uint3 ne01,
const float logit_softcap,
@@ -576,7 +471,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
const int k_VKQ_0,
const int k_VKQ_max,
const int col_Q_0) {
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int ncols = ncols1*ncols2;
@@ -716,10 +611,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
constexpr int nbatch_V = (DV % nbatch_K == 0 ? nbatch_K : nbatch_K*2/3) * nbatch_fa / DV; // Number of V columns that fit in SRAM for K.
static_assert(nbatch_fa % nbatch_V == 0, "bad nbatch_V");
static_assert(nbatch_V % np == 0, "bad nbatch_V");
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
#pragma unroll
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_V, DV, 0, oob_check>
(V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0);
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, false, false, T_V, T_vec_dot>
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr);
__syncthreads();
#ifdef FAST_FP16_AVAILABLE
@@ -788,18 +684,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
}
}
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap> // D == head size
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V> // D == head size
__launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2))
static __global__ void flash_attn_tile(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -807,21 +703,24 @@ static __global__ void flash_attn_tile(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
// Skip unused kernel variants for faster compilation:
@@ -830,15 +729,22 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
#ifdef AMD_MFMA_AVAILABLE
if (ncols1 == 64 && ncols2 == 1) {
// The tile kernel is suffering from register spills for ncols1 == 64 && ncols2 == 1.
NO_DEVICE_CODE;
return;
}
#endif // AMD_MFMA_AVAILABLE
static_assert(ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols1*ncols2) != 0, "kernel config not defined");
@@ -855,19 +761,19 @@ static __global__ void flash_attn_tile(
const int sequence = blockIdx.z / (ne02/ncols2);
const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2)
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0);
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio));
const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape
const float2 * Q_f2 = Q + s03*sequence + s02* head0;
const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio);
const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr;
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
const int stride_K2 = nb11 / sizeof(half2);
const int stride_V2 = nb21 / sizeof(half2);
const int stride_mask = nb31 / sizeof(half);
const int stride_K2 = s11;
const int stride_V2 = s21;
const int stride_mask = s31;
const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, head0, n_head_log2, m0, m1) : 1.0f;
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
constexpr int cpy_nb = 16;
constexpr int cpy_ne = cpy_nb / 4;
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp.
@@ -919,8 +825,7 @@ static __global__ void flash_attn_tile(
if (i0 + np*warp_size*cpy_ne_D <= DKQ || i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D < DKQ) {
__align__(16) float tmp_f[cpy_ne_D] = {0.0f};
ggml_cuda_memcpy_1<sizeof(tmp_f)>
(tmp_f, &Q_f[c*(nb02/sizeof(float)) + fastmodulo(col_Q_0 + j, ne01)*(nb01/sizeof(float))
+ i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D]);
(tmp_f, Q_f2 + c*s02 + fastmodulo(col_Q_0 + j, ne01)*s01 + i0/2 + (threadIdx.y % np)*(warp_size*(cpy_ne_D/2)) + threadIdx.x*(cpy_ne_D/2));
#pragma unroll
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
@@ -1056,7 +961,7 @@ static __global__ void flash_attn_tile(
#pragma unroll
for (int jc0 = 0; jc0 < cpw; ++jc0) {
const int jc = jc0 + (threadIdx.y/np)*cpw;
const float sink = ((const float *) sinks)[head0 + jc % ncols2];
const float sink = sinks[head0 + jc % ncols2];
float KQ_max_new_j = fmaxf(KQ_max[jc0], sink);
const float KQ_max_scale = expf(KQ_max[jc0] - KQ_max_new_j);
@@ -1137,18 +1042,21 @@ static __global__ void flash_attn_tile(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
template <int DKQ, int DV, int ncols2, bool use_logit_softcap>
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
const ggml_tensor * Q = dst->src[0];
const int id = ggml_cuda_get_device();
@@ -1159,12 +1067,12 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
#ifdef GGML_USE_HIP
if constexpr (DKQ <= 128) {
if (Q->ne[1] > 32/ncols2) {
if (!(amd_mfma_available(cc) && ncols2 == 1) && Q->ne[1] > 32/ncols2) {
constexpr int cols_per_block = 64;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1179,8 +1087,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 32;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1191,8 +1099,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 16;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1203,8 +1111,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 8;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1215,8 +1123,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 4;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1226,8 +1134,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
constexpr int cols_per_block = 2;
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
launch_fattn<DV, cols_per_block/ncols2, ncols2>
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
return;
}
@@ -1235,7 +1143,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
GGML_ABORT("fatal error");
}
template <int DKQ, int DV, bool use_logit_softcap>
template <int DKQ, int DV, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -1262,12 +1170,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
// Therefore, use a GQA ratio of 16 with 16 columns / block to stay below 48 kiB of SRAM / block.
#ifdef GGML_USE_HIP
if (use_gqa_opt && gqa_ratio % 32 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
#else
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
#endif // GGML_USE_HIP
@@ -1276,11 +1184,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 576) {
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
}
@@ -1288,11 +1196,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ == 192) {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
if (use_gqa_opt && gqa_ratio % 16 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8");
@@ -1300,29 +1208,29 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DV <= 256) {
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V>(ctx, dst);
return;
}
}
GGML_ABORT("fatal error");
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * KQV = dst;
@@ -1331,28 +1239,28 @@ void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_te
if (logit_softcap == 0.0f) {
constexpr bool use_logit_softcap = false;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
} else {
constexpr bool use_logit_softcap = true;
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
}
}
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
#define DECL_FATTN_TILE_CASE(DKQ, DV) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \
template void ggml_cuda_flash_attn_ext_tile_case \
<DKQ, DV, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
extern DECL_FATTN_TILE_CASE( 40, 40);
extern DECL_FATTN_TILE_CASE( 64, 64);
extern DECL_FATTN_TILE_CASE( 72, 72);
extern DECL_FATTN_TILE_CASE( 80, 80);
extern DECL_FATTN_TILE_CASE( 96, 96);
extern DECL_FATTN_TILE_CASE(112, 112);
extern DECL_FATTN_TILE_CASE(128, 128);
extern DECL_FATTN_TILE_CASE(192, 128);
extern DECL_FATTN_TILE_CASE(256, 256);
extern DECL_FATTN_TILE_CASE(320, 256);
extern DECL_FATTN_TILE_CASE(512, 512);
extern DECL_FATTN_TILE_CASE(576, 512);
extern DECL_FATTN_TILE_CASE( 40, 40, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 64, 64, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 72, 72, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 80, 80, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE( 96, 96, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16);
extern DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16);
+46 -46
View File
@@ -19,15 +19,15 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap> // D == head size
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
static __global__ void flash_attn_ext_vec(
const char * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const char * mask_ptr,
const char * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float2 * Q_ptr,
const char * K_ptr,
const char * V_ptr,
const half * mask_ptr,
const float * sinks_ptr,
const int * KV_max_ptr,
const int * KV_rows_ptr,
float * dst_ptr,
float2 * dst_meta_ptr,
const float scale,
const float max_bias,
const float m0,
@@ -35,22 +35,22 @@ static __global__ void flash_attn_ext_vec(
const uint32_t n_head_log2,
const float logit_softcap,
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
const int32_t nb01, const int32_t nb02, const int32_t nb03,
const int32_t s01, const int32_t s02, const int32_t s03,
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
const int32_t nb11, const int32_t nb12, const int64_t nb13,
const int32_t nb21, const int32_t nb22, const int64_t nb23,
const int32_t s11, const int32_t s12, const int64_t s13,
const int32_t s21, const int32_t s22, const int64_t s23,
const int32_t ne31, const int32_t ne32, const int32_t ne33,
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
const int32_t s31, const int64_t s32, const int64_t s33) {
ggml_cuda_pdl_lc();
#ifdef FLASH_ATTN_AVAILABLE
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
const char * GGML_CUDA_RESTRICT K = K_ptr;
const char * GGML_CUDA_RESTRICT V = V_ptr;
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
float * GGML_CUDA_RESTRICT dst = dst_ptr;
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
GGML_UNUSED(KV_rows_ptr);
// Skip unused kernel variants for faster compilation:
@@ -58,12 +58,12 @@ static __global__ void flash_attn_ext_vec(
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
return;
}
@@ -108,11 +108,11 @@ static __global__ void flash_attn_ext_vec(
const int sequence = blockIdx.z / ne02;
const int head = blockIdx.z - sequence*ne02;
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
Q += nb03*sequence + nb02* head + nb01*ic0;
K += nb13*sequence + nb12*(head / gqa_ratio);
V += nb23*sequence + nb22*(head / gqa_ratio);
Q += s03*sequence + s02* head + s01*ic0;
K += s13*sequence + s12*(head / gqa_ratio);
V += s23*sequence + s22*(head / gqa_ratio);
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr;
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1);
@@ -176,7 +176,7 @@ static __global__ void flash_attn_ext_vec(
tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f);
}
} else {
const float * Q_f = (const float *) (Q + j*nb01);
const float * Q_f = (const float *) (Q + j*s01);
constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE;
#pragma unroll
for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) {
@@ -206,7 +206,7 @@ static __global__ void flash_attn_ext_vec(
} else if constexpr (type_K == GGML_TYPE_F8_E4M3) {
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float * Q_j = (const float *) (Q + j*nb01);
const float * Q_j = (const float *) (Q + j*s01);
#pragma unroll
for (int i0 = 0; i0 < D; i0 += nthreads_KQ*4) {
const int i = i0 + (threadIdx.x % nthreads_KQ)*4;
@@ -229,7 +229,7 @@ static __global__ void flash_attn_ext_vec(
const half2 scale_h2 = make_half2(scale, scale);
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -252,7 +252,7 @@ static __global__ void flash_attn_ext_vec(
#else
#pragma unroll
for (int j = 0; j < ncols; ++j) {
const float2 * Q_j = (const float2 *) (Q + j*nb01);
const float2 * Q_j = Q + j*s01;
#pragma unroll
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
@@ -271,12 +271,12 @@ static __global__ void flash_attn_ext_vec(
}
const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
K += blockIdx.y*nthreads * nb11;
V += blockIdx.y*nthreads * nb21;
K += blockIdx.y*nthreads * s11;
V += blockIdx.y*nthreads * s21;
maskh += blockIdx.y*nthreads;
for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads,
// Increment pointers after each loop:
K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) {
K += gridDim.y*nthreads*s11, V += gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
// Calculate KQ tile and keep track of new maximum KQ values:
float KQ_reg[ncols]; // KQ in registers.
@@ -293,7 +293,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int j = 0; j < ncols; ++j) {
float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]);
float sum = vec_dot_KQ(K + i_KQ*s11, Q_reg[j], Q_i32[j], Q_ds[j]);
sum = warp_reduce_sum<nthreads_KQ>(sum);
if (use_logit_softcap) {
@@ -357,14 +357,14 @@ static __global__ void flash_attn_ext_vec(
half2 tmp[V_rows_per_thread/2];
if constexpr (type_V == GGML_TYPE_BF16) {
float2 tmp_f[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp_f,
dequantize_V(V + k*s21, tmp_f,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]);
}
} else {
dequantize_V(V + k*nb21, tmp,
dequantize_V(V + k*s21, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
}
#pragma unroll
@@ -384,7 +384,7 @@ static __global__ void flash_attn_ext_vec(
#pragma unroll
for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) {
float2 tmp[V_rows_per_thread/2];
dequantize_V(V + k*nb21, tmp,
dequantize_V(V + k*s21, tmp,
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
#pragma unroll
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
@@ -402,7 +402,7 @@ static __global__ void flash_attn_ext_vec(
}
if (sinks && blockIdx.y == 0) {
const float sink = ((const float *) sinks)[head];
const float sink = sinks[head];
#pragma unroll
for (int j0 = 0; j0 < ncols; j0 += nwarps) {
@@ -540,12 +540,12 @@ static __global__ void flash_attn_ext_vec(
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
max_bias, m0, m1, n_head_log2, logit_softcap,
ne00, ne01, ne02, ne03,
nb01, nb02, nb03,
s01, s02, s03,
ne10, ne11, ne12, ne13,
nb11, nb12, nb13,
nb21, nb22, nb23,
s11, s12, s13,
s21, s22, s23,
ne31, ne32, ne33,
nb31, nb32, nb33);
s31, s32, s33);
NO_DEVICE_CODE;
#endif // FLASH_ATTN_AVAILABLE
}
@@ -563,7 +563,7 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
const bool need_f16_K = type_K == GGML_TYPE_F16;
const bool need_f16_V = type_V == GGML_TYPE_F16;
constexpr size_t nbytes_shared = 0;
launch_fattn<D, cols_per_block, 1>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
launch_fattn<D, cols_per_block, 1, char, char>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
}
template <int D, ggml_type type_K, ggml_type type_V>
+67 -50
View File
@@ -159,7 +159,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_
#endif // !defined(GGML_USE_MUSA)
}
template <int DKQ, int DV, int ncols2>
template <int DKQ, int DV, int ncols2, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * Q = dst->src[0];
@@ -169,7 +169,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
// a sparse variant at the full tile width gathers the union of its queries once, prefer it for large batches
constexpr bool has_wide_sparse = ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 64/ncols2, ncols2);
if (!(has_wide_sparse && Q->ne[1] > 32/ncols2) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, ncols2)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
@@ -177,38 +177,39 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
if constexpr (ncols2 <= 8) {
if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if constexpr (ncols2 <= 16) {
if (Q->ne[1] <= 16/ncols2) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
}
if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) ||
(GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) {
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2, type_K, type_V>(ctx, dst);
}
template <int DKQ, int DV>
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
const ggml_tensor * mask = dst->src[3];
const ggml_tensor * kv_rows = dst->src[5];
// with kv_rows the kernel iterates over the mask columns
const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1];
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
float max_bias = 0.0f;
memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
@@ -235,22 +236,22 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute:
if (cc == GGML_CUDA_CC_VOLTA) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
return;
} else {
GGML_ABORT("fatal error");
@@ -260,44 +261,45 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
// On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask.
if (amd_wmma_available(cc)) {
if (use_gqa_opt && gqa_ratio % 8 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 4 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio % 2 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
}
if (use_gqa_opt && gqa_ratio > 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 2) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
return;
}
if (use_gqa_opt && gqa_ratio > 1) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
return;
}
if constexpr (DKQ <= 256) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
} else {
GGML_ABORT("fatal error");
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
template <ggml_type type_K, ggml_type type_V>
static void ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const ggml_tensor * KQV = dst;
const ggml_tensor * Q = dst->src[0];
@@ -308,31 +310,31 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
switch (Q->ne[0]) {
case 40:
GGML_ASSERT(V->ne[0] == 40);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40, type_K, type_V>(ctx, dst);
break;
case 64:
GGML_ASSERT(V->ne[0] == 64);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64, type_K, type_V>(ctx, dst);
break;
case 72:
GGML_ASSERT(V->ne[0] == 72);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72, type_K, type_V>(ctx, dst);
break;
case 80:
GGML_ASSERT(V->ne[0] == 80);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80, type_K, type_V>(ctx, dst);
break;
case 96:
GGML_ASSERT(V->ne[0] == 96);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96, type_K, type_V>(ctx, dst);
break;
case 112:
GGML_ASSERT(V->ne[0] == 112);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112, type_K, type_V>(ctx, dst);
break;
case 128:
GGML_ASSERT(V->ne[0] == 128);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128, type_K, type_V>(ctx, dst);
break;
case 192: {
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
@@ -344,15 +346,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16, type_K, type_V>(ctx, dst);
} else {
GGML_ASSERT(gqa_ratio % 8 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8, type_K, type_V>(ctx, dst);
}
} break;
case 256:
GGML_ASSERT(V->ne[0] == 256);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256, type_K, type_V>(ctx, dst);
break;
case 320:
// For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build).
@@ -367,12 +369,12 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
const int gqa_ratio = Q->ne[2] / K->ne[2];
GGML_ASSERT(gqa_ratio % 32 == 0);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32, type_K, type_V>(ctx, dst);
}
break;
case 512:
GGML_ASSERT(V->ne[0] == 512);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512, type_K, type_V>(ctx, dst);
break;
case 576: {
// For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels.
@@ -386,50 +388,50 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
const int gqa_ratio = Q->ne[2] / K->ne[2];
if (amd_mfma_available(cc) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, 16)) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else if (gqa_ratio == 20 && GGML_CUDA_CC_IS_NVIDIA(cc)) { // GLM 4.7 Flash
if (cc >= GGML_CUDA_CC_GB10) {
if (Q->ne[1] <= 8) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_BLACKWELL) {
if (Q->ne[1] <= 4 && K->ne[1] >= 65536) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
if (Q->ne[1] <= 4) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
if (cc >= GGML_CUDA_CC_TURING) {
if (Q->ne[1] <= 4) {
if (K->ne[1] <= 16384) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32, type_K, type_V>(ctx, dst);
break;
}
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
break;
}
// Volta:
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
} else if (gqa_ratio % 16 == 0) {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
} else {
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
}
} break;
default:
@@ -437,6 +439,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
}
}
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * K = dst->src[1];
const ggml_tensor * V = dst->src[2];
if constexpr (GGML_CUDA_FA_F16_F16) {
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
return;
}
}
// Fallback: convert K and V to F16.
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
}
#define FATTN_VEC_CASE(D, type_K_case, type_V_case) \
if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) { \
if (head_size == (D) && type_K == GGML_TYPE_##type_K_case && type_V == GGML_TYPE_##type_V_case) { \
+37 -1
View File
@@ -622,6 +622,42 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor *
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 32, k, GGML_TYPE_F32)
GGML_ABORT("fatal error");
}
} else if (n_embd == 128 && n_head == 16) {
if ((turing_mma_available(cc) || amd_mfma_available(cc) || amd_wmma_available(cc)) && k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_BF16) {
constexpr int K_VECS_PER_BLOCK = 32;
constexpr int WARPS_PER_BLOCK = 4;
dim3 block(ggml_cuda_info().devices[device].warp_size, WARPS_PER_BLOCK);
int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK);
dim3 grid(num_kv_blocks, n_batch, n_stream);
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_F16)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q4_0)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q4_1)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q5_0)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q5_1)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q8_0)
GGML_ABORT("fatal error");
} else {
// use vector kernel
constexpr int K_VECS_PER_WARP = 8;
constexpr int WARPS_PER_BLOCK = 8;
constexpr int K_VECS_PER_BLOCK = K_VECS_PER_WARP * WARPS_PER_BLOCK;
dim3 block(32, WARPS_PER_BLOCK);
int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK);
dim3 grid(num_kv_blocks, n_batch, n_stream);
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F16)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_0)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_1)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_0)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_1)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q8_0)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_BF16)
LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F32)
GGML_ABORT("fatal error");
}
} else if (n_embd == 128 && n_head == 4 && n_batch >= LIGHTNING_INDEXER_TILE_TOKENS) {
// too few heads for a wmma tile, the tile kernel shares the keys across the tokens
constexpr int WARPS_PER_BLOCK = 8;
@@ -688,7 +724,7 @@ bool ggml_cuda_lightning_indexer_supported(int device, const ggml_tensor * dst)
return false;
}
if (neq1 != 64 && neq1 != 32 && neq1 != 4) {
if (neq1 != 64 && neq1 != 32 && neq1 != 16 && neq1 != 4) {
return false;
}
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,6 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,12 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,13 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,14 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
@@ -1,6 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1);
@@ -1,12 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1);
@@ -1,13 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
@@ -1,14 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-mma-f16.cuh"
DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8);
DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8);
DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8);
DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8);
DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8);
DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8);
DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8);
DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8);
DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8);
DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(320, 256);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(40, 40);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(512, 512);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(576, 512);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(64, 64);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(72, 72);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(80, 80);
@@ -1,5 +0,0 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(96, 96);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -2,4 +2,4 @@
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(112, 112);
DECL_FATTN_TILE_CASE(40, 40, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -2,4 +2,4 @@
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(128, 128);
DECL_FATTN_TILE_CASE(64, 64, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -2,4 +2,4 @@
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(192, 128);
DECL_FATTN_TILE_CASE(72, 72, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -2,4 +2,4 @@
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(256, 256);
DECL_FATTN_TILE_CASE(80, 80, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -0,0 +1,5 @@
// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE(96, 96, GGML_TYPE_F16, GGML_TYPE_F16);
@@ -10,11 +10,13 @@ HEAD_SIZES_V_OVERRIDE = {576: 512, 320: 256, 192: 128}
TYPES_KV = ["GGML_TYPE_F16", "GGML_TYPE_Q4_0", "GGML_TYPE_Q4_1", "GGML_TYPE_Q5_0", "GGML_TYPE_Q5_1", "GGML_TYPE_Q8_0", "GGML_TYPE_BF16", "GGML_TYPE_F8_E4M3"]
TYPES_KV_TILE_MMA = ["GGML_TYPE_F16"]
SOURCE_FATTN_TILE = """// This file has been autogenerated by generate_cu_files.py, do not edit manually.
#include "../fattn-tile.cuh"
DECL_FATTN_TILE_CASE({head_size_kq}, {head_size_v});
DECL_FATTN_TILE_CASE({head_size_kq}, {head_size_v}, {type_k}, {type_v});
"""
SOURCE_FATTN_VEC = """// This file has been autogenerated by generate_cu_files.py, do not edit manually.
@@ -32,7 +34,7 @@ SOURCE_FATTN_MMA_START = """// This file has been autogenerated by generate_cu_f
"""
SOURCE_FATTN_MMA_CASE = "DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2});\n"
SOURCE_FATTN_MMA_CASE = "DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2}, {type_k}, {type_v});\n"
TYPES_MMQ = [
"GGML_TYPE_Q1_0",
@@ -71,38 +73,45 @@ def get_short_name(long_quant_name):
for filename in glob("*.cu"):
os.remove(filename)
for head_size_kq in HEAD_SIZES_KQ:
head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq)
with open(f"fattn-tile-instance-dkq{head_size_kq}-dv{head_size_v}.cu", "w") as f:
f.write(SOURCE_FATTN_TILE.format(head_size_kq=head_size_kq, head_size_v=head_size_v))
for type_k in TYPES_KV_TILE_MMA:
for type_v in TYPES_KV_TILE_MMA:
for head_size_kq in HEAD_SIZES_KQ:
head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq)
with open(f"fattn-tile-instance-{get_short_name(type_k)}-{get_short_name(type_v)}-dkq{head_size_kq}-dv{head_size_v}.cu", "w") as f:
f.write(SOURCE_FATTN_TILE.format(
head_size_kq=head_size_kq, head_size_v=head_size_v, type_k=type_k, type_v=type_v))
for type_k in TYPES_KV:
for type_v in TYPES_KV:
with open(f"fattn-vec-instance-{get_short_name(type_k)}-{get_short_name(type_v)}.cu", "w") as f:
f.write(SOURCE_FATTN_VEC.format(type_k=type_k, type_v=type_v))
for ncols in [8, 16, 32, 64]:
for ncols2 in [1, 2, 4, 8, 16, 32]:
if ncols2 > ncols:
continue
ncols1 = ncols // ncols2
with open(f"fattn-mma-f16-instance-ncols1_{ncols1}-ncols2_{ncols2}.cu", "w") as f:
f.write(SOURCE_FATTN_MMA_START)
for type_k in TYPES_KV_TILE_MMA:
for type_v in TYPES_KV_TILE_MMA:
for ncols in [8, 16, 32, 64]:
for ncols2 in [1, 2, 4, 8, 16, 32]:
if ncols2 > ncols:
continue
ncols1 = ncols // ncols2
with open(f"fattn-mma-f16-instance-{get_short_name(type_k)}-{get_short_name(type_v)}-ncols1_{ncols1}-ncols2_{ncols2}.cu", "w") as f:
f.write(SOURCE_FATTN_MMA_START)
for head_size_kq in HEAD_SIZES_KQ:
# Skip compilation of unused ncols2 values for niche head sizes:
if head_size_kq == 192 and ncols2 not in (8, 16): # MiMo-V2.5
continue
if head_size_kq == 320 and ncols2 != 32: # Mistral Small 4
continue
if head_size_kq == 512 and ncols2 not in (2, 4, 8): # Gemma 4 (+ MTP)
continue
if head_size_kq == 576 and ncols2 not in (4, 16, 32): # Deepseek, GLM 4.7 Flash
continue
if head_size_kq not in (192, 320, 576) and ncols2 in (16, 32):
continue
head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq)
f.write(SOURCE_FATTN_MMA_CASE.format(ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v))
for head_size_kq in HEAD_SIZES_KQ:
# Skip compilation of unused ncols2 values for niche head sizes:
if head_size_kq == 192 and ncols2 not in (8, 16): # MiMo-V2.5
continue
if head_size_kq == 320 and ncols2 != 32: # Mistral Small 4
continue
if head_size_kq == 512 and ncols2 not in (2, 4, 8): # Gemma 4 (+ MTP)
continue
if head_size_kq == 576 and ncols2 not in (4, 16, 32): # Deepseek, GLM 4.7 Flash
continue
if head_size_kq not in (192, 320, 576) and ncols2 in (16, 32):
continue
head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq)
f.write(SOURCE_FATTN_MMA_CASE.format(
ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v,
type_k=type_k, type_v=type_v))
for type in TYPES_MMQ:
with open(f"mmq-instance-{get_short_name(type)}.cu", "w") as f:
+1 -5
View File
@@ -61,16 +61,12 @@ file(GLOB GGML_HEADERS_ROCM "../ggml-cuda/*.cuh")
list(APPEND GGML_HEADERS_ROCM "../../include/ggml-cuda.h")
file(GLOB GGML_SOURCES_ROCM "../ggml-cuda/*.cu")
file(GLOB SRCS "../ggml-cuda/template-instances/fattn-tile*.cu")
list(APPEND GGML_SOURCES_ROCM ${SRCS})
file(GLOB SRCS "../ggml-cuda/template-instances/fattn-mma*.cu")
list(APPEND GGML_SOURCES_ROCM ${SRCS})
file(GLOB SRCS "../ggml-cuda/template-instances/mmq*.cu")
list(APPEND GGML_SOURCES_ROCM ${SRCS})
file(GLOB SRCS "../ggml-cuda/template-instances/mmf*.cu")
list(APPEND GGML_SOURCES_ROCM ${SRCS})
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS)
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS)
list(APPEND GGML_SOURCES_ROCM ${SRCS})
ggml_add_backend_library(ggml-hip
+2 -2
View File
@@ -1067,8 +1067,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_meta
{
if (ne00 < 32) {
nsg = 1;
nr0 = 32;
nr1 = 1;
nr0 = std::min(ne01, 32);
nr1 = 32/nr0;
suffix = "_short";
} else {
nsg = std::min(4, (ne00 + 127) / 128);
+2 -11
View File
@@ -9,8 +9,6 @@
#include "ggml-metal-ops.h"
#include "ggml-metal-tuning.h"
#include <TargetConditionals.h>
#include <mutex>
#include <string>
@@ -655,13 +653,6 @@ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgrap
ggml_metal_graph_optimize(ctx, cgraph);
}
// iOS can stop a command buffer that runs for more than a few seconds, so split the graph into shorter ones there
#if TARGET_OS_IPHONE
#define GGML_METAL_DEFAULT_N_CB 8
#else
#define GGML_METAL_DEFAULT_N_CB 1
#endif // TARGET_OS_IPHONE
static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) {
GGML_ASSERT(ggml_backend_is_metal(backend));
@@ -713,7 +704,7 @@ ggml_backend_t ggml_backend_metal_init(void) {
/* .context = */ ctx,
};
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
ggml_backend_metal_set_n_cb(backend, 1);
return backend;
}
@@ -809,7 +800,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t
/* .context = */ ctx,
};
ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB);
ggml_backend_metal_set_n_cb(backend, 1);
return backend;
+6 -3
View File
@@ -1187,11 +1187,14 @@ void kernel_mul_mv_t_t_short_impl(
device char * dst,
uint3 tgpig,
ushort tiisg) {
const int r0 = tgpig.x*32 + tiisg;
const int r1 = tgpig.y;
const int n0 = args.nr0;
const int n1 = 32/n0;
const int r0 = tgpig.x*n0 + tiisg%n0;
const int r1 = tgpig.y*n1 + tiisg/n0;
const int im = tgpig.z;
if (r0 >= args.ne01) {
if (tiisg >= n0*n1 || r0 >= args.ne01 || r1 >= args.ne11) {
return;
}
+1 -5
View File
@@ -33,10 +33,6 @@ if (MUSAToolkit_FOUND)
list(APPEND GGML_HEADERS_MUSA "../ggml-musa/mudnn.cuh")
file(GLOB GGML_SOURCES_MUSA "../ggml-cuda/*.cu")
file(GLOB SRCS "../ggml-cuda/template-instances/fattn-tile*.cu")
list(APPEND GGML_SOURCES_MUSA ${SRCS})
file(GLOB SRCS "../ggml-cuda/template-instances/fattn-mma*.cu")
list(APPEND GGML_SOURCES_MUSA ${SRCS})
file(GLOB SRCS "../ggml-cuda/template-instances/mmq*.cu")
list(APPEND GGML_SOURCES_MUSA ${SRCS})
@@ -46,7 +42,7 @@ if (MUSAToolkit_FOUND)
add_compile_definitions(GGML_MUSA_MUDNN_COPY)
endif()
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS)
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS)
list(APPEND GGML_SOURCES_MUSA ${SRCS})
set_source_files_properties(${GGML_SOURCES_MUSA} PROPERTIES LANGUAGE CXX)
+7 -3
View File
@@ -11958,8 +11958,12 @@ static bool adreno_e17_compiler_quirks(const ggml_backend_opencl_context *backen
backend_ctx->adreno_cl_compiler_version.type != ADRENO_CL_COMPILER_TYPE::E17) {
return false;
}
const char * env = getenv("GGML_OPENCL_ADRENO_E17_QUIRKS");
return !(env && env[0] == '0');
static const bool enabled = []() {
const char * e = getenv("GGML_OPENCL_ADRENO_E17_QUIRKS");
return e && e[0] && e[0] != '0';
}();
return enabled;
}
static bool ggml_cl_q2_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) {
@@ -12989,7 +12993,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
return true;
}
#endif
// The E17 compilers segfault while building FA kernels, skip E17 for now
// Some E17 compilers crash while building FA kernels.
if (adreno_e17_compiler_quirks(backend_ctx)) {
return false;
}
+1
View File
@@ -71,6 +71,7 @@ void ggml_sycl_host_free(void* ptr);
extern int g_ggml_sycl_debug;
extern int g_ggml_sycl_enable_optimize;
extern int g_ggml_sycl_enable_fusion;
extern int g_ggml_sycl_fuse_conv_window;
extern int g_ggml_sycl_enable_esimd;
extern int g_ggml_sycl_mmid_esimd;
extern int g_ggml_sycl_mmvq_wide;
+39 -1
View File
@@ -110,6 +110,7 @@ int g_ggml_sycl_memtrace = 0;
int g_ggml_sycl_memtrace_step = 64;
int g_ggml_sycl_enable_vmm = 1;
int g_ggml_sycl_enable_fusion = 1;
int g_ggml_sycl_fuse_conv_window = 1;
int g_ggml_sycl_enable_esimd = 1;
int g_ggml_sycl_mmid_esimd = 1;
int g_ggml_sycl_mmvq_wide = 1;
@@ -444,6 +445,7 @@ static void ggml_check_sycl() try {
g_ggml_sycl_memtrace_step = ggml_sycl_get_env("GGML_SYCL_MEMTRACE_STEP", 64);
g_ggml_sycl_enable_vmm = ggml_sycl_get_env("GGML_SYCL_ENABLE_VMM", 1);
g_ggml_sycl_enable_fusion = ggml_sycl_get_env("GGML_SYCL_ENABLE_FUSION", 1);
g_ggml_sycl_fuse_conv_window = ggml_sycl_get_env("GGML_SYCL_FUSE_CONV_WINDOW", 1);
g_ggml_sycl_enable_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_ESIMD", 1);
g_ggml_sycl_mmid_esimd = ggml_sycl_get_env("GGML_SYCL_MMID_ESIMD", 1);
g_ggml_sycl_mmvq_wide = ggml_sycl_get_env("GGML_SYCL_MMVQ_WIDE", 1);
@@ -594,6 +596,7 @@ static void ggml_check_sycl() try {
#endif
GGML_LOG_INFO(" GGML_SYCL_ENABLE_FUSION: %d\n", g_ggml_sycl_enable_fusion);
GGML_LOG_INFO(" GGML_SYCL_FUSE_CONV_WINDOW: %d\n", g_ggml_sycl_fuse_conv_window);
GGML_LOG_INFO(" GGML_SYCL_UPLOAD_STAGING_SLOTS: %d\n", g_ggml_sycl_upload_staging_slots);
#if defined(__INTEL_LLVM_COMPILER)
@@ -6698,6 +6701,7 @@ static int ggml_sycl_try_gdn_cache_fusion(const ggml_cgraph * cgraph, int node_i
}
static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * sycl_ctx, ggml_cgraph * cgraph) {
ggml_sycl_conv_window_match conv_window;
for (int i = 0; i < cgraph->n_nodes; i++) {
ggml_tensor * node = cgraph->nodes[i];
if (ggml_sycl_is_view_or_noop(node)) {
@@ -6707,6 +6711,24 @@ static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * syc
continue;
}
// Run the window and cache updates at the convolution.
if (conv_window.concat == nullptr && node->op == GGML_OP_CONCAT &&
ggml_sycl_match_conv_window(cgraph, i, conv_window)) {
continue;
}
if (conv_window.concat != nullptr) {
if (std::find(conv_window.cont, conv_window.cont + conv_window.n_slots, node) != conv_window.cont + conv_window.n_slots ||
std::find(conv_window.cpy, conv_window.cpy + conv_window.n_slots, node) != conv_window.cpy + conv_window.n_slots) {
continue;
}
if (node == conv_window.conv) {
ggml_sycl_ssm_conv_window(*sycl_ctx, conv_window);
i = conv_window.last_idx;
conv_window = {};
continue;
}
}
const int nodes_to_skip = ggml_sycl_fuse(*sycl_ctx, cgraph, i);
if (nodes_to_skip != 0) {
i += nodes_to_skip;
@@ -7194,6 +7216,22 @@ static void ggml_backend_sycl_event_wait(ggml_backend_t backend, ggml_backend_ev
std::exit(1);
}
static void ggml_backend_sycl_graph_optimize(ggml_backend_t backend, ggml_cgraph * cgraph,
ggml_backend_graph_optimize_params * params) {
GGML_UNUSED(backend);
for (int i = 0; i < cgraph->n_nodes; ++i) {
ggml_sycl_conv_window_match match;
if (cgraph->nodes[i]->op != GGML_OP_CONCAT || !ggml_sycl_match_conv_window(cgraph, i, match)) {
continue;
}
// Inputs and delayed cache writes must stay allocated until the fused kernel.
for (ggml_tensor * t : { match.concat->src[0], match.concat->src[1], match.cpy[0]->src[1] }) {
params->add_alloc_dep(params->user_data, t->view_src ? t->view_src : t, match.silu);
}
i = match.last_idx;
}
}
static ggml_backend_i ggml_backend_sycl_interface = {
/* .get_name = */ ggml_backend_sycl_get_name,
/* .free = */ ggml_backend_sycl_free,
@@ -7212,7 +7250,7 @@ static ggml_backend_i ggml_backend_sycl_interface = {
/* .graph_compute = */ ggml_backend_sycl_graph_compute,
/* .event_record = */ ggml_backend_sycl_event_record,
/* .event_wait = */ ggml_backend_sycl_event_wait,
/* .graph_optimize = */ NULL,
/* .graph_optimize = */ ggml_backend_sycl_graph_optimize,
};
static ggml_guid_t ggml_backend_sycl_guid() {
+290
View File
@@ -1,7 +1,10 @@
#include "ssm_conv.hpp"
#include "common.hpp"
#include "element_wise.hpp"
#include "fusion.hpp"
#include <algorithm>
#include <climits>
#include <cstdio>
using namespace sycl;
@@ -359,3 +362,290 @@ void ggml_sycl_ssm_conv_fused(ggml_backend_sycl_context & ctx, ggml_tensor * dst
}
ggml_sycl_op_ssm_conv(ctx, dst, silu_dst, bias);
}
static const ggml_tensor * conv_window_base(const ggml_tensor * t) {
return t->view_src ? t->view_src : t;
}
static bool conv_window_f32_strides(const ggml_tensor * t) {
for (int d = 0; d < GGML_MAX_DIMS; ++d) {
if (t->nb[d] % sizeof(float) != 0) {
return false;
}
}
return true;
}
bool ggml_sycl_match_conv_window(const ggml_cgraph * cgraph, int node_idx, ggml_sycl_conv_window_match & m) {
if (!g_ggml_sycl_fuse_conv_window || !g_ggml_sycl_enable_fusion) {
return false;
}
const ggml_tensor * concat = cgraph->nodes[node_idx];
if (concat->op != GGML_OP_CONCAT || ggml_get_op_params_i32(concat, 0) != 0 || concat->type != GGML_TYPE_F32 ||
(concat->flags & GGML_TENSOR_FLAG_OUTPUT) || concat->ne[3] != 1 || !ggml_is_contiguous(concat)) {
return false;
}
const ggml_tensor * state = concat->src[0];
const ggml_tensor * xt = concat->src[1];
if (state->type != GGML_TYPE_F32 || xt->type != GGML_TYPE_F32 || !conv_window_f32_strides(state) ||
!conv_window_f32_strides(xt)) {
return false;
}
// the kernel is written for d_conv == 4: three state columns
const int64_t state_cols = state->ne[0];
const int64_t channels = concat->ne[1];
const int64_t n_seqs = concat->ne[2];
if (state_cols != 3 || channels <= 0 || channels > INT_MAX - 255 ||
xt->ne[0] <= 0 || xt->ne[0] > INT_MAX - 7 || n_seqs <= 0 || n_seqs > INT_MAX) {
return false;
}
ggml_sycl_conv_window_match r;
r.concat = concat;
const ggml_tensor * cache = nullptr;
const ggml_tensor * pending = nullptr; // a cont still waiting for its cpy
int n_views = 0;
// Check intervening nodes after the cache is known.
const int end = std::min(cgraph->n_nodes, node_idx + 64);
for (int j = node_idx + 1; j < end && r.conv == nullptr; ++j) {
ggml_tensor * n = cgraph->nodes[j];
if (n->op == GGML_OP_VIEW && n->src[0] == concat) {
if ((n->flags & GGML_TENSOR_FLAG_OUTPUT) || n->ne[0] != state_cols || n->ne[1] != channels || n->ne[2] != n_seqs || n->ne[3] != 1 ||
n->nb[1] != concat->nb[1] || n->nb[2] != concat->nb[2] || n->view_offs % sizeof(float) != 0 ||
ggml_node_get_use_count(cgraph, j) != 1) {
return false;
}
n_views++;
} else if (n->op == GGML_OP_CONT && n->src[0]->op == GGML_OP_VIEW && n->src[0]->src[0] == concat) {
if (pending != nullptr || r.n_slots == GGML_SYCL_CONV_WINDOW_MAX_SLOTS ||
!ggml_node_has_n_uses(cgraph, j, 1)) {
return false;
}
pending = n;
} else if (n->op == GGML_OP_CPY && ((pending != nullptr && n->src[0] == pending) ||
(pending == nullptr && n->src[0]->op == GGML_OP_VIEW && n->src[0]->src[0] == concat))) {
if (r.n_slots == GGML_SYCL_CONV_WINDOW_MAX_SLOTS) {
return false;
}
// dst is a [state_cols * channels, n_seqs] view of the cache rows
const ggml_tensor * dst = n->src[1];
if (dst->type != GGML_TYPE_F32 || dst->ne[0] != state_cols * channels || dst->ne[1] != n_seqs ||
dst->ne[2] != 1 || dst->ne[3] != 1 || dst->nb[0] != sizeof(float) || dst->nb[1] % sizeof(float) != 0 || dst->nb[1] < dst->ne[0] * sizeof(float)) {
return false;
}
if (cache == nullptr) {
cache = conv_window_base(dst);
}
// one seq stride for all slots, and the tail must stay inside one channel row
const ggml_tensor * tail = pending != nullptr ? pending->src[0] : n->src[0];
const int64_t s_idx = tail->view_offs / sizeof(float);
if (conv_window_base(dst) != cache || (r.n_slots > 0 && dst->nb[1] != r.cpy[0]->src[1]->nb[1]) ||
s_idx + state_cols > concat->ne[0]) {
return false;
}
for (int p = 0; p < r.n_slots; ++p) {
const ggml_tensor * prev = r.cpy[p]->src[1];
if (dst->view_offs >= prev->view_offs ? dst->view_offs - prev->view_offs < ggml_nbytes(prev) :
prev->view_offs - dst->view_offs < ggml_nbytes(dst)) {
return false;
}
}
r.cont[r.n_slots] = pending;
r.cpy[r.n_slots] = n;
r.n_slots++;
pending = nullptr;
} else if (n->op == GGML_OP_SSM_CONV && n->src[0] == concat) {
r.conv = n;
r.conv_idx = j;
}
}
if (r.conv == nullptr || r.n_slots == 0 || pending != nullptr || n_views != r.n_slots ||
ggml_node_get_use_count(cgraph, node_idx) != n_views + 1) {
return false;
}
const ggml_tensor * weights = r.conv->src[1];
if (weights->type != GGML_TYPE_F32 || weights->ne[0] != state_cols + 1 || !ggml_is_contiguous(weights) ||
r.conv->type != GGML_TYPE_F32 || conv_window_base(weights) == cache) {
return false;
}
// the window reads state and x, the kernel writes the cache: they must not overlap
const ggml_tensor * state_base = conv_window_base(state);
const ggml_tensor * x_base = conv_window_base(xt);
if (state_base == cache || x_base == cache) {
return false;
}
// Delayed cache copies must not cross a reader or an input write.
for (int j = node_idx + 1; j < r.conv_idx; ++j) {
const ggml_tensor * n = cgraph->nodes[j];
if ((n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || n->op == GGML_OP_VIEW || n->op == GGML_OP_RESHAPE ||
n->op == GGML_OP_TRANSPOSE || n->op == GGML_OP_PERMUTE || n->op == GGML_OP_NONE) {
continue;
}
if (std::find(r.cont, r.cont + r.n_slots, n) != r.cont + r.n_slots ||
std::find(r.cpy, r.cpy + r.n_slots, n) != r.cpy + r.n_slots) {
continue;
}
for (int s = 0; s < GGML_MAX_SRC; ++s) {
const ggml_tensor * src = n->src[s];
if (src == nullptr) {
continue;
}
const ggml_tensor * b = conv_window_base(src);
if (b == cache || b == concat || std::find(r.cont, r.cont + r.n_slots, b) != r.cont + r.n_slots) {
return false;
}
}
const ggml_tensor * b = conv_window_base(n);
if (b == cache || b == state_base || b == x_base) {
return false;
}
}
if (ggml_sycl_can_fuse(cgraph, r.conv_idx, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) {
r.add = cgraph->nodes[r.conv_idx + 1];
r.silu = cgraph->nodes[r.conv_idx + 2];
r.last_idx = r.conv_idx + 2;
} else if (ggml_sycl_can_fuse(cgraph, r.conv_idx, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) {
r.silu = cgraph->nodes[r.conv_idx + 1];
r.last_idx = r.conv_idx + 1;
} else {
return false;
}
if (r.silu->type != GGML_TYPE_F32 || !ggml_is_contiguous(r.silu)) {
return false;
}
if (r.add != nullptr) {
const ggml_tensor * bias = r.add->src[0] == r.conv ? r.add->src[1] : r.add->src[0];
if (conv_window_base(bias) == cache) {
return false;
}
}
m = r;
return true;
}
struct conv_window_slots {
float * dst[GGML_SYCL_CONV_WINDOW_MAX_SLOTS];
int s_idx[GGML_SYCL_CONV_WINDOW_MAX_SLOTS];
int n;
};
// Each work-item slides a four-value window over up to eight tokens.
// Token max(0, w - 3) writes cache column w, so each cache value has one writer.
static void kernel_ssm_conv_window(queue & q, const float * state, const float * x, const float * weights,
const float * bias, float * dst, conv_window_slots slots, int d_inner, int n_t,
int n_s, int64_t st_col, int64_t st_ch, int64_t st_seq, int64_t x_tok,
int64_t x_ch, int64_t x_seq, int64_t cache_seq) {
constexpr int DC = 4;
constexpr int NC = DC - 1;
constexpr int TT = 8;
// a 3D range: 64-bit div/mod of a flat index is emulated and costs a lot at the prefill shape
const int wg = 256;
const int c_pad = (d_inner + wg - 1) / wg * wg;
const int n_tb = (n_t + TT - 1) / TT;
q.parallel_for(nd_range<3>(range<3>(n_s, n_tb, c_pad), range<3>(1, 1, wg)), [=](nd_item<3> item) {
const int c = static_cast<int>(item.get_global_id(2));
const int t0 = static_cast<int>(item.get_global_id(1)) * TT;
const int s = static_cast<int>(item.get_global_id(0));
if (c >= d_inner) {
return;
}
const int t1 = sycl::min(t0 + TT, n_t);
const float * sp = state + s * st_seq + c * st_ch;
const float * xp = x + s * x_seq + c * x_ch;
float win[DC];
#pragma unroll
for (int k = 0; k < NC; ++k) {
const int w = t0 + k;
win[k + 1] = w < NC ? sp[w * st_col] : xp[(w - NC) * x_tok];
}
float cw[DC];
#pragma unroll
for (int k = 0; k < DC; ++k) {
cw[k] = weights[static_cast<size_t>(c) * DC + k];
}
const float b = bias != nullptr ? bias[c] : 0.0f;
for (int t = t0; t < t1; ++t) {
#pragma unroll
for (int k = 0; k < NC; ++k) {
win[k] = win[k + 1];
}
win[NC] = xp[t * x_tok];
float sumf = 0.0f;
#pragma unroll
for (int k = 0; k < DC; ++k) {
sumf += win[k] * cw[k];
}
if (bias != nullptr) {
sumf += b;
}
dst[(static_cast<size_t>(s) * n_t + t) * d_inner + c] = op_silu(sumf);
// constant win[] indices keep the window in registers
for (int p = 0; p < slots.n; ++p) {
float * cd = slots.dst[p] + s * cache_seq + static_cast<size_t>(c) * NC;
#pragma unroll
for (int k = 0; k < DC; ++k) {
const int w = t + k;
const int j = w - slots.s_idx[p];
if (j >= 0 && j < NC && sycl::max(w - NC, 0) == t) {
cd[j] = win[k];
}
}
}
}
});
}
void ggml_sycl_ssm_conv_window(ggml_backend_sycl_context & ctx, const ggml_sycl_conv_window_match & m) {
const ggml_tensor * state = m.concat->src[0];
const ggml_tensor * xt = m.concat->src[1];
const int d_inner = m.concat->ne[1];
const int n_t = xt->ne[0];
const int n_s = m.concat->ne[2];
GGML_ASSERT(m.conv->ne[0] == d_inner && m.conv->ne[1] == n_t && m.conv->ne[2] == n_s);
conv_window_slots slots = {};
slots.n = m.n_slots;
for (int p = 0; p < m.n_slots; ++p) {
const ggml_tensor * tail = m.cpy[p]->src[0];
if (tail->op == GGML_OP_CONT) {
tail = tail->src[0];
}
slots.dst[p] = static_cast<float *>(m.cpy[p]->src[1]->data);
slots.s_idx[p] = static_cast<int>(tail->view_offs / sizeof(float));
}
const float * bias = nullptr;
if (m.add != nullptr) {
const ggml_tensor * bias_t = (m.add->src[0] == m.conv) ? m.add->src[1] : m.add->src[0];
bias = static_cast<const float *>(bias_t->data);
}
constexpr int64_t fs = sizeof(float);
kernel_ssm_conv_window(*ctx.stream(), static_cast<const float *>(state->data),
static_cast<const float *>(xt->data), static_cast<const float *>(m.conv->src[1]->data),
bias, static_cast<float *>(m.silu->data), slots, d_inner, n_t, n_s, state->nb[0] / fs,
state->nb[1] / fs, state->nb[2] / fs, xt->nb[0] / fs, xt->nb[1] / fs, xt->nb[2] / fs,
m.cpy[0]->src[1]->nb[1] / fs);
}
+19
View File
@@ -4,3 +4,22 @@
void ggml_sycl_ssm_conv(ggml_backend_sycl_context & ctx, ggml_tensor * dst);
void ggml_sycl_ssm_conv_fused(ggml_backend_sycl_context & ctx, ggml_tensor * dst, ggml_tensor * add, ggml_tensor * silu_dst);
#define GGML_SYCL_CONV_WINDOW_MAX_SLOTS 8
// Match the recurrent window, rollback cache copies, convolution and SiLU.
struct ggml_sycl_conv_window_match {
const ggml_tensor * concat = nullptr;
ggml_tensor * conv = nullptr;
ggml_tensor * add = nullptr;
ggml_tensor * silu = nullptr;
int conv_idx = -1;
int last_idx = -1; // the silu node: the last node the kernel writes
int n_slots = 0;
const ggml_tensor * cont[GGML_SYCL_CONV_WINDOW_MAX_SLOTS] = {};
const ggml_tensor * cpy[GGML_SYCL_CONV_WINDOW_MAX_SLOTS] = {};
};
// Purely structural, so graph_optimize and the compute loop see the same answer.
bool ggml_sycl_match_conv_window(const ggml_cgraph * cgraph, int node_idx, ggml_sycl_conv_window_match & m);
void ggml_sycl_ssm_conv_window(ggml_backend_sycl_context & ctx, const ggml_sycl_conv_window_match & m);
+133
View File
@@ -199,6 +199,7 @@ class Keys:
VALUE_LENGTH = "{arch}.attention.value_length"
LAYERNORM_EPS = "{arch}.attention.layer_norm_epsilon"
LAYERNORM_RMS_EPS = "{arch}.attention.layer_norm_rms_epsilon"
LATENT_NORM_RMS_EPS = "{arch}.attention.latent_norm_rms_epsilon"
GROUPNORM_EPS = "{arch}.attention.group_norm_epsilon"
GROUPNORM_GROUPS = "{arch}.attention.group_norm_groups"
CAUSAL = "{arch}.attention.causal"
@@ -740,6 +741,7 @@ class MODEL_ARCH(IntEnum):
HUNYUAN_VL = auto()
HY_V3 = auto()
HY_V4 = auto()
HY_V4_FLASH = auto()
SMOLLM3 = auto()
GPT_OSS = auto()
LFM2 = auto()
@@ -774,6 +776,7 @@ class MODEL_ARCH(IntEnum):
KIMI_LINEAR = auto()
KIMI_K3 = auto()
KIMI_K31 = auto()
RAON1_MINI = auto()
TALKIE = auto()
MELLUM = auto()
NANBEIGE = auto()
@@ -977,6 +980,7 @@ class MODEL_TENSOR(IntEnum):
SSM_F_A = auto() # Kimi Linear
SSM_F_B = auto() # Kimi Linear
SSM_BETA = auto() # Kimi Linear qwen3.5
SSM_RDA = auto() # Raon-1 mini
SSM_G_A = auto() # Kimi Linear
SSM_G_B = auto() # Kimi Linear
SSM_G = auto() # Kimi K3 (full-rank KDA gate, replaces SSM_G_A/SSM_G_B)
@@ -1159,6 +1163,7 @@ class MODEL_TENSOR(IntEnum):
INDEXER_COMPRESSOR_NORM = auto()
INDEXER_KPOOL_GATE = auto()
INDEXER_KPOOL_APE = auto()
INDEXER_KPOOL_VALUE = auto()
ATTN_V_GATE = auto() # k2-horizon MoVA router
ATTN_V_EXP = auto() # k2-horizon MoVA value experts
# vision
@@ -1541,6 +1546,10 @@ class MODEL_TENSOR(IntEnum):
DSPARK_MARKOV_CTX_NORM = auto() # rnn markov head: target feature norm
ENGRAM_KV = auto()
ENGRAM_GATE = auto()
ENGRAM_KV_B = auto()
ENGRAM_LOOKUP_NORM = auto()
ENGRAM_PRE_GAMMA = auto()
ENGRAM_HC_SCALE = auto()
DFLASH_ATTN_CONV_BASE = auto()
DFLASH_ATTN_CONV_PROJ = auto()
DFLASH_FFN_CONV_BASE = auto()
@@ -1763,6 +1772,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.HUNYUAN_VL: "hunyuan_vl",
MODEL_ARCH.HY_V3: "hy_v3",
MODEL_ARCH.HY_V4: "hy_v4",
MODEL_ARCH.HY_V4_FLASH: "hy_v4_flash",
MODEL_ARCH.SMOLLM3: "smollm3",
MODEL_ARCH.GPT_OSS: "gpt-oss",
MODEL_ARCH.LFM2: "lfm2",
@@ -1797,6 +1807,7 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
MODEL_ARCH.KIMI_LINEAR: "kimi-linear",
MODEL_ARCH.KIMI_K3: "kimi-k3",
MODEL_ARCH.KIMI_K31: "kimi-k31",
MODEL_ARCH.RAON1_MINI: "raon1",
MODEL_ARCH.TALKIE: "talkie",
MODEL_ARCH.MELLUM: "mellum",
MODEL_ARCH.NANBEIGE: "nanbeige",
@@ -1998,6 +2009,7 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
MODEL_TENSOR.SSM_F_A: "blk.{bid}.ssm_f_a", # Kimi Linear
MODEL_TENSOR.SSM_F_B: "blk.{bid}.ssm_f_b", # Kimi Linear
MODEL_TENSOR.SSM_BETA: "blk.{bid}.ssm_beta", # Kimi Linear qwen3.5
MODEL_TENSOR.SSM_RDA: "blk.{bid}.ssm_rda", # Raon-1 mini
MODEL_TENSOR.SSM_G_A: "blk.{bid}.ssm_g_a", # Kimi Linear
MODEL_TENSOR.SSM_G_B: "blk.{bid}.ssm_g_b", # Kimi Linear
MODEL_TENSOR.SSM_G: "blk.{bid}.ssm_g", # Kimi K3
@@ -2180,6 +2192,7 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
MODEL_TENSOR.INDEXER_COMPRESSOR_NORM: "blk.{bid}.indexer_compressor_norm",
MODEL_TENSOR.INDEXER_KPOOL_GATE: "blk.{bid}.indexer_compressor_gate",
MODEL_TENSOR.INDEXER_KPOOL_APE: "blk.{bid}.indexer_compressor_ape",
MODEL_TENSOR.INDEXER_KPOOL_VALUE: "blk.{bid}.indexer_compressor_value",
# vision
MODEL_TENSOR.V_MMPROJ: "mm.{bid}",
MODEL_TENSOR.V_MMPROJ_FC: "mm.model.fc",
@@ -2602,6 +2615,10 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM: "markov_ctx_norm",
MODEL_TENSOR.ENGRAM_KV: "blk.{bid}.engram_kv",
MODEL_TENSOR.ENGRAM_GATE: "blk.{bid}.engram_gate",
MODEL_TENSOR.ENGRAM_KV_B: "blk.{bid}.engram_kv_b",
MODEL_TENSOR.ENGRAM_LOOKUP_NORM: "blk.{bid}.engram_lookup_norm",
MODEL_TENSOR.ENGRAM_PRE_GAMMA: "blk.{bid}.engram_pre_gamma",
MODEL_TENSOR.ENGRAM_HC_SCALE: "blk.{bid}.engram_hc_scale",
MODEL_TENSOR.DFLASH_ATTN_CONV_BASE: "blk.{bid}.attn_conv_base",
MODEL_TENSOR.DFLASH_ATTN_CONV_PROJ: "blk.{bid}.attn_conv_proj",
MODEL_TENSOR.DFLASH_FFN_CONV_BASE: "blk.{bid}.ffn_conv_base",
@@ -6102,6 +6119,67 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.FFN_DOWN_SHEXP,
MODEL_TENSOR.FFN_UP_SHEXP,
],
MODEL_ARCH.HY_V4_FLASH: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
MODEL_TENSOR.OUTPUT,
MODEL_TENSOR.ROPE_FREQS,
MODEL_TENSOR.HC_HEAD_FN,
MODEL_TENSOR.HC_HEAD_BASE,
MODEL_TENSOR.HC_HEAD_SCALE,
MODEL_TENSOR.ATTN_NORM,
MODEL_TENSOR.ATTN_SINKS,
MODEL_TENSOR.ATTN_Q_A,
MODEL_TENSOR.ATTN_Q_A_NORM,
MODEL_TENSOR.ATTN_Q_B,
MODEL_TENSOR.ATTN_KV_A_MQA,
MODEL_TENSOR.ATTN_KV_A_NORM,
MODEL_TENSOR.ATTN_K_B,
MODEL_TENSOR.ATTN_V_B,
MODEL_TENSOR.ATTN_OUT,
MODEL_TENSOR.ATTN_GATE,
MODEL_TENSOR.INDEXER_K_NORM,
MODEL_TENSOR.INDEXER_PROJ,
MODEL_TENSOR.INDEXER_ATTN_K,
MODEL_TENSOR.INDEXER_ATTN_Q_B,
MODEL_TENSOR.HC_ATTN_FN,
MODEL_TENSOR.HC_ATTN_BASE,
MODEL_TENSOR.HC_ATTN_SCALE,
MODEL_TENSOR.HC_FFN_FN,
MODEL_TENSOR.HC_FFN_BASE,
MODEL_TENSOR.HC_FFN_SCALE,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_EXP_PROBS_B,
MODEL_TENSOR.FFN_NORM,
MODEL_TENSOR.FFN_GATE,
MODEL_TENSOR.FFN_DOWN,
MODEL_TENSOR.FFN_UP,
MODEL_TENSOR.FFN_GATE_EXP,
MODEL_TENSOR.FFN_DOWN_EXP,
MODEL_TENSOR.FFN_UP_EXP,
MODEL_TENSOR.FFN_GATE_SHEXP,
MODEL_TENSOR.FFN_DOWN_SHEXP,
MODEL_TENSOR.FFN_UP_SHEXP,
MODEL_TENSOR.ATTN_POST_NORM,
MODEL_TENSOR.FFN_POST_NORM,
MODEL_TENSOR.FFN_ROUTED_DOWN,
MODEL_TENSOR.FFN_ROUTED_UP,
MODEL_TENSOR.PER_LAYER_TOKEN_EMBD,
MODEL_TENSOR.ENGRAM_KV,
MODEL_TENSOR.ENGRAM_GATE,
MODEL_TENSOR.ENGRAM_KV_B,
MODEL_TENSOR.ENGRAM_LOOKUP_NORM,
MODEL_TENSOR.ENGRAM_PRE_GAMMA,
MODEL_TENSOR.ENGRAM_HC_SCALE,
MODEL_TENSOR.INDEXER_KPOOL_GATE,
MODEL_TENSOR.INDEXER_KPOOL_APE,
MODEL_TENSOR.INDEXER_KPOOL_VALUE,
MODEL_TENSOR.INDEXER_COMPRESSOR_NORM,
MODEL_TENSOR.NEXTN_EH_PROJ,
MODEL_TENSOR.NEXTN_ENORM,
MODEL_TENSOR.NEXTN_HNORM,
MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
],
MODEL_ARCH.SMOLLM3: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
@@ -6903,6 +6981,56 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.FFN_ROUTED_UP,
MODEL_TENSOR.FFN_ROUTED_NORM,
],
MODEL_ARCH.RAON1_MINI: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT_NORM,
MODEL_TENSOR.OUTPUT,
MODEL_TENSOR.ATTN_NORM,
# MLA (full-attention layers)
MODEL_TENSOR.ATTN_Q,
MODEL_TENSOR.ATTN_K,
MODEL_TENSOR.ATTN_V,
MODEL_TENSOR.ATTN_OUT,
MODEL_TENSOR.ATTN_GATE,
MODEL_TENSOR.ATTN_Q_A,
MODEL_TENSOR.ATTN_Q_B,
MODEL_TENSOR.ATTN_KV_A_MQA,
MODEL_TENSOR.ATTN_K_B,
MODEL_TENSOR.ATTN_V_B,
MODEL_TENSOR.ATTN_Q_A_NORM,
MODEL_TENSOR.ATTN_KV_A_NORM,
# RDA (linear-attention layers)
MODEL_TENSOR.SSM_CONV1D_Q,
MODEL_TENSOR.SSM_CONV1D_K,
MODEL_TENSOR.SSM_CONV1D_V,
MODEL_TENSOR.SSM_F_A,
MODEL_TENSOR.SSM_F_B,
MODEL_TENSOR.SSM_BETA,
MODEL_TENSOR.SSM_RDA,
MODEL_TENSOR.SSM_A,
MODEL_TENSOR.SSM_G,
MODEL_TENSOR.SSM_DT,
MODEL_TENSOR.SSM_NORM,
MODEL_TENSOR.HC_ATTN_FN,
MODEL_TENSOR.HC_ATTN_BASE,
MODEL_TENSOR.HC_ATTN_SCALE,
MODEL_TENSOR.HC_FFN_FN,
MODEL_TENSOR.HC_FFN_BASE,
MODEL_TENSOR.HC_FFN_SCALE,
# FFN
MODEL_TENSOR.FFN_NORM,
MODEL_TENSOR.FFN_GATE,
MODEL_TENSOR.FFN_DOWN,
MODEL_TENSOR.FFN_UP,
MODEL_TENSOR.FFN_GATE_INP,
MODEL_TENSOR.FFN_EXP_PROBS_B,
MODEL_TENSOR.FFN_GATE_EXP,
MODEL_TENSOR.FFN_DOWN_EXP,
MODEL_TENSOR.FFN_UP_EXP,
MODEL_TENSOR.FFN_GATE_SHEXP,
MODEL_TENSOR.FFN_DOWN_SHEXP,
MODEL_TENSOR.FFN_UP_SHEXP,
],
MODEL_ARCH.TALKIE: [
MODEL_TENSOR.TOKEN_EMBD,
MODEL_TENSOR.OUTPUT,
@@ -7282,6 +7410,10 @@ MODEL_TENSOR_SKIP: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
MODEL_TENSOR.ROPE_FREQS,
MODEL_TENSOR.ATTN_ROT_EMBD,
],
MODEL_ARCH.HY_V4_FLASH: [
MODEL_TENSOR.ROPE_FREQS,
MODEL_TENSOR.ATTN_ROT_EMBD,
],
MODEL_ARCH.XING4_0: [
MODEL_TENSOR.ROPE_FREQS,
MODEL_TENSOR.ATTN_ROT_EMBD,
@@ -7570,6 +7702,7 @@ class VisionProjectorType:
KOKORO = "kokoro" # audio generation: StyleTTS2 prosody predictor + iSTFTNet decoder
TINY_VOCA = "tiny_voca" # audio generation: duration predictor, frame transformers, source-filter vocoder
HUNYUANVL = "hunyuanvl"
HY_V4_FLASH = "hy_v4_flash"
PARAKEET = "parakeet" # audio
MINIMAXM3 = "minimax_m3"
MINICPMV4_6 = "minicpmv4_6"
+3
View File
@@ -1053,6 +1053,9 @@ class GGUFWriter:
def add_layer_norm_rms_eps(self, value: float) -> None:
self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value)
def add_latent_norm_rms_eps(self, value: float) -> None:
self.add_float32(Keys.Attention.LATENT_NORM_RMS_EPS.format(arch=self.arch), value)
def add_group_norm_eps(self, value: float) -> None:
self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value)
+14
View File
@@ -442,6 +442,7 @@ class TensorNameMap:
"model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2
"model.layers.{bid}.post_operator_norm", # lfm3
"model.layers.{bid}.post_attention_norm", # domynedge
"model.layers.{bid}.self_attn.post_proj_norm", # hy-v4-flash
),
# Rotary embeddings
@@ -663,6 +664,8 @@ class TensorNameMap:
"model.layers.{bid}.post_mlp_layernorm", # glm-4-0414
"model.layers.{bid}.post_ffn_norm", # kolibri1
"model.layers.layers.{bid}.post_mlp_norm.weight", # plamo2
"model.layers.{bid}.mlp.combine_output_norm", # hy-v4-flash (MoE layers)
"model.layers.{bid}.mlp.post_fc2_norm", # hy-v4-flash (dense layers)
"model.layers.{bid}.feed_forward.up_proj",
"model.layers.{bid}.post_moe_norm", # grok-2
"model.layers.{bid}.post_ffn_norm", # lfm3
@@ -716,6 +719,7 @@ class TensorNameMap:
"backbone.layers.{bid}.mixer.gate.e_score_correction", # nemotron-h-moe
"model.layers.{bid}.mlp.e_score_correction", # exaone-moe
"model.layers.{bid}.block_sparse_moe.gate.e_score_correction", # kimi
"model.layers.{bid}.moe.gate.e_score_correction", # raon1_mini
"model.layers.{bid}.moe.router_bias", # step3.5 expert selection bias
"model.layers.{bid}.mlp.experts.e_score_correction", # laguna
),
@@ -789,6 +793,7 @@ class TensorNameMap:
"layers.{bid}.shared_experts.w3", # mistral-large
"backbone.layers.{bid}.mixer.shared_experts.up_proj", # nemotron-h-moe
"model.layers.{bid}.block_sparse_moe.shared_experts.up_proj", # kimi
"model.layers.{bid}.moe.shared_experts.up_proj", # raon1_mini
"model.layers.{bid}.share_expert.up_proj", # step3.5
),
@@ -842,6 +847,7 @@ class TensorNameMap:
"model.layers.{bid}.mlp.shared_mlp.gate_proj", # hunyuan
"layers.{bid}.shared_experts.w1", # mistral-large
"model.layers.{bid}.block_sparse_moe.shared_experts.gate_proj", # kimi
"model.layers.{bid}.moe.shared_experts.gate_proj", # raon1_mini
"model.layers.{bid}.share_expert.gate_proj", # step3.5
),
@@ -1024,6 +1030,7 @@ class TensorNameMap:
"layers.{bid}.shared_experts.w2", # mistral-large
"backbone.layers.{bid}.mixer.shared_experts.down_proj", # nemotron-h-moe
"model.layers.{bid}.block_sparse_moe.shared_experts.down_proj", # kimi
"model.layers.{bid}.moe.shared_experts.down_proj", # raon1_mini
"model.layers.{bid}.share_expert.down_proj", # step3.5
"layers.{bid}.moe.shared_expert.down", # metis16
),
@@ -1286,13 +1293,19 @@ class TensorNameMap:
"model.layers.{bid}.self_attn.b_proj", # Kimi Linear
"model.layers.{bid}.attention.b_proj", # bailingmoe3
),
# Raon-1 mini RDA: per-head write-gate offset
MODEL_TENSOR.SSM_RDA: (
"model.layers.{bid}.self_attn.rda_w_proj",
),
# Kimi K3 latent MoE: routed experts operate in a down-projected space
MODEL_TENSOR.FFN_ROUTED_DOWN: (
"model.layers.{bid}.block_sparse_moe.routed_expert_down_proj",
"model.layers.{bid}.mlp.routed_expert_down_proj", # hy-v4-flash
),
MODEL_TENSOR.FFN_ROUTED_UP: (
"model.layers.{bid}.block_sparse_moe.routed_expert_up_proj",
"model.layers.{bid}.mlp.routed_expert_up_proj", # hy-v4-flash
),
MODEL_TENSOR.FFN_ROUTED_NORM: (
@@ -2707,6 +2720,7 @@ class TensorNameMap:
MODEL_TENSOR.V_MM_PRE_NORM: (
"vit.perceive.before_rms", # HunyuanVL
"vit.perceive.norm", # hy-v4-flash
),
MODEL_TENSOR.V_TOK_IMG_BEGIN: (
@@ -0,0 +1,134 @@
{#- Text-only ChatML SFT protocol for raon-1-mini. -#}
{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else false %}
{%- macro render_content(content, is_system_content=false) %}
{%- if content is string %}
{{- content }}
{%- elif content is iterable and content is not mapping %}
{%- for item in content %}
{%- if 'text' in item %}
{{- item.text }}
{%- else %}
{{- raise_exception('raon-1-mini supports text content only.') }}
{%- endif %}
{%- endfor %}
{%- elif content is none or content is undefined %}
{{- '' }}
{%- else %}
{{- raise_exception('Unexpected content type.') }}
{%- endif %}
{%- endmacro %}
{%- macro render_assistant_body(message, content, reasoning_content, preserve_reasoning) %}
{%- if preserve_reasoning and reasoning_content|trim %}
{{- '<think>\n' + reasoning_content|trim + '\n</think>\n\n' }}
{%- else %}
{{- '<think></think>\n\n' }}
{%- endif %}
{{- content }}
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
{%- for tool_call in message.tool_calls %}
{%- if tool_call.function is defined %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{%- if loop.first %}
{%- if content|trim %}
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- else %}
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- else %}
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
{%- endif %}
{%- if tool_call.arguments is defined %}
{%- for args_name, args_value in tool_call.arguments|items %}
{{- '<parameter=' + args_name + '>\n' }}
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
{{- args_value }}
{{- '\n</parameter>\n' }}
{%- endfor %}
{%- endif %}
{{- '</function>\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>' }}
{%- endmacro %}
{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system\n' }}
{{- '# Tools\n\nYou have access to the following functions:\n\n<tools>' }}
{%- for tool in tools %}
{{- '\n' }}
{{- tool | tojson }}
{%- endfor %}
{{- '\n</tools>' }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
{%- if messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, true)|trim %}
{%- if content %}
{{- '\n\n' + content }}
{%- endif %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif messages[0].role == 'system' %}
{%- set content = render_content(messages[0].content, true)|trim %}
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- if ns.multi_step_tool and message.role == 'user' %}
{%- set content = render_content(message.content)|trim %}
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- for message in messages %}
{%- set content = render_content(message.content)|trim %}
{%- if message.role == 'system' %}
{%- if not loop.first %}
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
{%- endif %}
{%- elif message.role == 'user' %}
{{- '<|im_start|>user\n' + content + '<|im_end|>\n' }}
{%- elif message.role == 'assistant' %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- elif content.startswith('<think>') and '</think>' in content %}
{%- set thinking_parts = content.split('</think>', 1) %}
{%- set reasoning_content = thinking_parts[0][7:].strip('\n') %}
{%- set content = thinking_parts[1].lstrip('\n') %}
{%- endif %}
{{- '<|im_start|>assistant\n' }}
{%- set preserve_reasoning = (not truncate_history_thinking) or (loop.index0 > ns.last_query_index) %}
{%- if message.loss is defined and message.loss is false %}
{{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }}
{%- else %}
{%- generation %}
{{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }}
{%- endgeneration %}
{%- endif %}
{{- '\n' }}
{%- elif message.role == 'tool' %}
{%- if loop.previtem and loop.previtem.role != 'tool' %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' + content + '\n</tool_response>' }}
{%- if loop.last or loop.nextitem.role != 'tool' %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{{- raise_exception('Unexpected message role.') }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think></think>\n\n' }}
{%- else %}
{{- '<think>\n' }}
{%- endif %}
{%- endif %}
+22 -22
View File
@@ -75,28 +75,28 @@ def main():
log_file = sys.argv[1]
ignored = {
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
}
+19
View File
@@ -134,6 +134,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_HUNYUAN_VL, "hunyuan_vl" },
{ LLM_ARCH_HY_V3, "hy_v3" },
{ LLM_ARCH_HY_V4, "hy_v4" },
{ LLM_ARCH_HY_V4_FLASH, "hy_v4_flash" },
{ LLM_ARCH_SMOLLM3, "smollm3" },
{ LLM_ARCH_OPENAI_MOE, "gpt-oss" },
{ LLM_ARCH_LFM2, "lfm2" },
@@ -170,6 +171,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
{ LLM_ARCH_KIMI_LINEAR, "kimi-linear" },
{ LLM_ARCH_KIMI_K3, "kimi-k3" },
{ LLM_ARCH_KIMI_K31, "kimi-k31" },
{ LLM_ARCH_RAON1_MINI, "raon1" },
{ LLM_ARCH_GLM5_NEXT, "glm5-next" },
{ LLM_ARCH_TALKIE, "talkie" },
{ LLM_ARCH_MELLUM, "mellum" },
@@ -308,6 +310,7 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
{ LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
{ LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
{ LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
{ LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, "%s.attention.latent_norm_rms_epsilon" },
{ LLM_KV_ATTENTION_GROUPNORM_EPS, "%s.attention.group_norm_epsilon" },
{ LLM_KV_ATTENTION_GROUPNORM_GROUPS, "%s.attention.group_norm_groups" },
{ LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
@@ -702,6 +705,7 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
{ LLM_TENSOR_SSM_F_A, "blk.%d.ssm_f_a" },
{ LLM_TENSOR_SSM_F_B, "blk.%d.ssm_f_b" },
{ LLM_TENSOR_SSM_BETA, "blk.%d.ssm_beta" },
{ LLM_TENSOR_SSM_RDA, "blk.%d.ssm_rda" },
{ LLM_TENSOR_SSM_G_A, "blk.%d.ssm_g_a" },
{ LLM_TENSOR_SSM_G, "blk.%d.ssm_g" },
{ LLM_TENSOR_ATTN_RES_SCORE, "blk.%d.attn_res_score" },
@@ -904,6 +908,7 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
{ LLM_TENSOR_INDEXER_COMPRESSOR_NORM, "blk.%d.indexer_compressor_norm" },
{ LLM_TENSOR_INDEXER_KPOOL_GATE, "blk.%d.indexer_compressor_gate" },
{ LLM_TENSOR_INDEXER_KPOOL_APE, "blk.%d.indexer_compressor_ape" },
{ LLM_TENSOR_INDEXER_KPOOL_VALUE, "blk.%d.indexer_compressor_value" },
{ LLM_TENSOR_FFN_GATE_TID2EID, "blk.%d.ffn_gate_tid2eid" },
{ LLM_TENSOR_MASKED_EMBD_CENTROIDS, "masked_embd_centroids" },
{ LLM_TENSOR_MASKED_EMBD_ORDERING, "masked_embd_ordering" },
@@ -918,6 +923,10 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
{ LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, "markov_ctx_norm" },
{ LLM_TENSOR_ENGRAM_KV, "blk.%d.engram_kv" },
{ LLM_TENSOR_ENGRAM_GATE, "blk.%d.engram_gate" },
{ LLM_TENSOR_ENGRAM_KV_B, "blk.%d.engram_kv_b" },
{ LLM_TENSOR_ENGRAM_LOOKUP_NORM, "blk.%d.engram_lookup_norm" },
{ LLM_TENSOR_ENGRAM_PRE_GAMMA, "blk.%d.engram_pre_gamma" },
{ LLM_TENSOR_ENGRAM_HC_SCALE, "blk.%d.engram_hc_scale" },
{ LLM_TENSOR_DFLASH_ATTN_CONV_BASE, "blk.%d.attn_conv_base" },
{ LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, "blk.%d.attn_conv_proj" },
{ LLM_TENSOR_DFLASH_FFN_CONV_BASE, "blk.%d.ffn_conv_base" },
@@ -1140,6 +1149,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_SSM_F_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_F_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_BETA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_RDA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_G_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_SSM_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ATTN_RES_SCORE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
@@ -1269,6 +1279,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_INDEXER_COMPRESSOR_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_INDEXER_KPOOL_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_INDEXER_KPOOL_APE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
{LLM_TENSOR_INDEXER_KPOOL_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_FFN_GATE_TID2EID, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
{LLM_TENSOR_NEXTN_PROJ_PRE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_NEXTN_PROJ_POST, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}},
@@ -1352,6 +1363,10 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
{LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}},
{LLM_TENSOR_ENGRAM_KV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_ENGRAM_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_ENGRAM_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
{LLM_TENSOR_ENGRAM_LOOKUP_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_ENGRAM_PRE_GAMMA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_ENGRAM_HC_SCALE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
{LLM_TENSOR_DFLASH_ATTN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
{LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
{LLM_TENSOR_DFLASH_FFN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
@@ -1486,6 +1501,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) {
case LLM_ARCH_BAILINGMOE3:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_GLM5_NEXT:
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
@@ -1519,6 +1535,7 @@ bool llm_arch_supports_rs_rollback(const llm_arch & arch) {
switch (arch) {
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_QWEN35:
case LLM_ARCH_QWEN35MOE:
case LLM_ARCH_CLOVER_MOE:
@@ -1579,6 +1596,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
case LLM_ARCH_DEEPSEEK2:
case LLM_ARCH_DEEPSEEK32:
case LLM_ARCH_HY_V4:
case LLM_ARCH_HY_V4_FLASH:
case LLM_ARCH_DOTS3NOTE:
case LLM_ARCH_XING4_0:
case LLM_ARCH_GLM_DSA:
@@ -1599,6 +1617,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
case LLM_ARCH_BAILINGMOE3:
case LLM_ARCH_KIMI_K3:
case LLM_ARCH_KIMI_K31:
case LLM_ARCH_RAON1_MINI:
case LLM_ARCH_QWEN3TTS:
case LLM_ARCH_LIMITE:
return false;
+9
View File
@@ -138,6 +138,7 @@ enum llm_arch {
LLM_ARCH_HUNYUAN_VL,
LLM_ARCH_HY_V3,
LLM_ARCH_HY_V4,
LLM_ARCH_HY_V4_FLASH,
LLM_ARCH_SMOLLM3,
LLM_ARCH_OPENAI_MOE,
LLM_ARCH_LFM2,
@@ -168,6 +169,7 @@ enum llm_arch {
LLM_ARCH_KIMI_LINEAR,
LLM_ARCH_KIMI_K3,
LLM_ARCH_KIMI_K31,
LLM_ARCH_RAON1_MINI,
LLM_ARCH_GLM5_NEXT,
LLM_ARCH_TALKIE,
LLM_ARCH_MELLUM,
@@ -314,6 +316,7 @@ enum llm_kv {
LLM_KV_ATTENTION_VALUE_LENGTH,
LLM_KV_ATTENTION_LAYERNORM_EPS,
LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS,
LLM_KV_ATTENTION_GROUPNORM_EPS,
LLM_KV_ATTENTION_GROUPNORM_GROUPS,
LLM_KV_ATTENTION_CAUSAL,
@@ -709,6 +712,7 @@ enum llm_tensor {
LLM_TENSOR_SSM_F_A, // kimi: forget gate projection A
LLM_TENSOR_SSM_F_B, // kimi: forget gate projection B
LLM_TENSOR_SSM_BETA, // kimi: beta mixing coefficient and qwen3.5
LLM_TENSOR_SSM_RDA, // raon1_mini: write gate offset
LLM_TENSOR_SSM_G_A, // kimi: output gate projection A
LLM_TENSOR_SSM_G_B, // kimi: output gate projection B
LLM_TENSOR_SSM_G, // kimi-k3: full-rank KDA gate
@@ -897,6 +901,7 @@ enum llm_tensor {
LLM_TENSOR_INDEXER_COMPRESSOR_NORM,
LLM_TENSOR_INDEXER_KPOOL_GATE, // glm5-next: k-pool gate scores
LLM_TENSOR_INDEXER_KPOOL_APE, // glm5-next: k-pool position bias
LLM_TENSOR_INDEXER_KPOOL_VALUE, // hy_v4_flash: what the k-pool actually pools
LLM_TENSOR_FFN_GATE_TID2EID,
LLM_TENSOR_NEXTN_PROJ_PRE,
LLM_TENSOR_NEXTN_PROJ_POST,
@@ -923,6 +928,10 @@ enum llm_tensor {
LLM_TENSOR_DSPARK_MARKOV_CTX_NORM,
LLM_TENSOR_ENGRAM_KV,
LLM_TENSOR_ENGRAM_GATE,
LLM_TENSOR_ENGRAM_KV_B, // hy_v4_flash: bias on the fused key/value projections
LLM_TENSOR_ENGRAM_LOOKUP_NORM, // hy_v4_flash: per-head RMSNorm of the looked-up rows
LLM_TENSOR_ENGRAM_PRE_GAMMA, // hy_v4_flash: scales the normed value before the gate
LLM_TENSOR_ENGRAM_HC_SCALE, // hy_v4_flash: per-hc per-channel additive gate offset
LLM_TENSOR_DFLASH_ATTN_CONV_BASE,
LLM_TENSOR_DFLASH_ATTN_CONV_PROJ,
LLM_TENSOR_DFLASH_FFN_CONV_BASE,
+8 -1
View File
@@ -196,7 +196,7 @@ llama_context::llama_context(
model.arch == LLM_ARCH_CLOVER_MOE ||
// KDA
model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT ||
model.arch == LLM_ARCH_BAILINGMOE3);
model.arch == LLM_ARCH_BAILINGMOE3 || model.arch == LLM_ARCH_RAON1_MINI);
cparams.n_threads = params.n_threads;
cparams.n_threads_batch = params.n_threads_batch;
@@ -375,6 +375,13 @@ llama_context::llama_context(
cparams.op_offload = params.op_offload;
cparams.kv_unified = params.kv_unified;
// 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) {
LLAMA_LOG_WARN("%s: %s needs a unified KV cache, the sequences share n_ctx\n", __func__, llm_arch_name(model.arch));
cparams.kv_unified = true;
}
cparams.moe_cache_size = params.moe_cache_size;
cparams.moe_cache_cpu_share = params.moe_cache_cpu_share;

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