From c943331339fb503503b21cc490f08d986bfdb1cf Mon Sep 17 00:00:00 2001 From: Pascal Date: Wed, 25 Nov 2026 18:39:50 +0100 Subject: [PATCH 01/47] 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 --- conversion/__init__.py | 3 + conversion/hy_v4_flash.py | 650 ++++++++++++++ ggml/src/ggml-cuda/lightning-indexer.cu | 38 +- gguf-py/gguf/constants.py | 78 ++ gguf-py/gguf/tensor_mapping.py | 6 + src/llama-arch.cpp | 12 + src/llama-arch.h | 6 + src/llama-context.cpp | 7 + src/llama-graph.cpp | 2 +- src/llama-kv-cache-dsa.cpp | 7 + src/llama-kv-cache.cpp | 125 +++ src/llama-kv-cache.h | 11 + src/llama-model-saver.cpp | 15 +- src/llama-model.cpp | 9 +- src/llama-model.h | 9 + src/llama-quant.cpp | 7 + src/models/hy-v4-flash.cpp | 1081 +++++++++++++++++++++++ src/models/models.h | 94 ++ tests/fusion/MTL.csv | 3 + tests/test-backend-ops.cpp | 4 +- tests/test-llama-archs.cpp | 78 +- tools/mtmd/CMakeLists.txt | 1 + tools/mtmd/models/hy-v4.cpp | 43 + tools/mtmd/models/models.h | 5 + tools/mtmd/mtmd-graph.cpp | 4 + tools/mtmd/mtmd-impl.h | 2 + tools/mtmd/mtmd-model.cpp | 47 +- tools/mtmd/mtmd-subcontext.cpp | 7 +- tools/mtmd/mtmd.cpp | 9 + 29 files changed, 2343 insertions(+), 20 deletions(-) create mode 100644 conversion/hy_v4_flash.py create mode 100644 src/models/hy-v4-flash.cpp create mode 100644 tools/mtmd/models/hy-v4.cpp diff --git a/conversion/__init__.py b/conversion/__init__.py index 146c309e65a7..59ea8509415a 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -146,6 +146,7 @@ "HrmTextForCausalLM": "hrm_text", "HYV3ForCausalLM": "hunyuan", "HYV4ForCausalLM": "hy_v4", + "HYV4FlashForCausalLM": "hy_v4_flash", "IQuestCoderForCausalLM": "llama", "Inkling2ForCausalLM": "inkling2", "Inkling2LoopForCausalLM": "inkling2", @@ -390,6 +391,8 @@ "GraniteSpeechPlusForConditionalGeneration": "granite", "HiggsAudio3Model": "higgs_audio", "HunYuanVLForConditionalGeneration": "hunyuan", + "HYV4FlashForCausalLM": "hy_v4_flash", + "HYV4FlashForConditionalGeneration": "hy_v4_flash", "Idefics3ForConditionalGeneration": "smolvlm", "Inkling2ForConditionalGeneration": "inkling2", "Inkling2LoopForConditionalGeneration": "inkling2", diff --git a/conversion/hy_v4_flash.py b/conversion/hy_v4_flash.py new file mode 100644 index 000000000000..309b61b64e68 --- /dev/null +++ b/conversion/hy_v4_flash.py @@ -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) diff --git a/ggml/src/ggml-cuda/lightning-indexer.cu b/ggml/src/ggml-cuda/lightning-indexer.cu index b7939243b74b..ff6402e47540 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cu +++ b/ggml/src/ggml-cuda/lightning-indexer.cu @@ -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; } diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 57852fad6bcf..bebc8706775c 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -740,6 +740,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() @@ -1159,6 +1160,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 +1543,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 +1769,7 @@ class MODEL_TENSOR(IntEnum): 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", @@ -2180,6 +2187,7 @@ class MODEL_TENSOR(IntEnum): 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 +2610,10 @@ class MODEL_TENSOR(IntEnum): 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 +6114,67 @@ class MODEL_TENSOR(IntEnum): 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, @@ -7282,6 +7355,10 @@ class MODEL_TENSOR(IntEnum): 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 +7647,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" diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c0bbfde2298d..c6946d53c4ef 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -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 @@ -1289,10 +1292,12 @@ class TensorNameMap: # 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 +2712,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: ( diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 4b7e786fa771..e14f915570e8 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -134,6 +134,7 @@ static const std::map 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" }, @@ -904,6 +905,7 @@ static const std::map 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 +920,10 @@ static const std::map 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" }, @@ -1269,6 +1275,7 @@ static const std::map 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 +1359,10 @@ static const std::map 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}}, @@ -1579,6 +1590,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: diff --git a/src/llama-arch.h b/src/llama-arch.h index 74ca69fe7e9b..9d0ced590549 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -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, @@ -897,6 +898,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 +925,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, diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 89465d0cee91..38a37ae75879 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -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; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 5fef4c42168a..9213d2a0edf0 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2609,7 +2609,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( const float limit = hparams.swiglu_clamp_exp[il]; constexpr float eps = 1e-6f; if (limit > eps) { - if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4) { + if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { cur = ggml_swiglu_clamp(ctx0, cur, up, limit); } else { up = ggml_clamp(ctx0, up, -limit, limit); diff --git a/src/llama-kv-cache-dsa.cpp b/src/llama-kv-cache-dsa.cpp index 1221f7f2bfae..42d2ae2631af 100644 --- a/src/llama-kv-cache-dsa.cpp +++ b/src/llama-kv-cache-dsa.cpp @@ -45,6 +45,13 @@ llama_kv_cache_dsa::llama_kv_cache_dsa( std::fill(hparams_lid.n_head_kv_arr.begin(), hparams_lid.n_head_kv_arr.end(), 1); hparams_lid.n_embd_head_k_full = model.hparams.indexer_head_size; + // a pooled indexer (hy_v4_flash) caches the value and the gate of each token, the pooled key is built from them in the graph + // the cached rows carry no position, the pooled key is rotated in the graph, so a K-shift must leave them alone + if (model.hparams.indexer_kpool > 0) { + hparams_lid.n_embd_head_k_full *= 2; + std::fill(hparams_lid.rope_pattern.begin(), hparams_lid.rope_pattern.end(), 0); + } + // KV sharing applies to the MLA cache only, each indexer owns its keys std::iota(hparams_lid.kv_source_impl.begin(), hparams_lid.kv_source_impl.end(), 0); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index bb546f7cdec8..c7444319bcf5 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2002,6 +2002,126 @@ void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch } } +void llama_kv_cache::set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, const slot_info & sinfo, uint32_t kpool, uint32_t n_kv) const { + GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams"); + GGML_ASSERT(pool_idxs->ne[0] == kpool && tail_idxs->ne[0] == kpool); + GGML_ASSERT(pool_mask->type == GGML_TYPE_F16); + GGML_ASSERT(sinfo.idxs.size() == 1 && sinfo.idxs[0].size() == ubatch->n_tokens); + + const auto & cells = v_cells[0]; + + const int64_t n_tokens = ubatch->n_tokens; + const int64_t n_pool = pool_idxs->ne[1]; + const uint32_t n_planes = hparams.n_pos_per_embd(); + GGML_ASSERT(pool_mask->ne[0] == n_pool && pool_pos->ne[0] == n_pool*n_planes && n_kv <= cells.size()); + + // one pool per kpool consecutive tokens of each sequence of the ubatch, in sequence order + // the order is the position, then the cell: the tokens of an image share their position with M-RoPE + // sequences that share a prefix share its pools, a lone sequence has nothing to share + std::vector idxs; + std::vector first; + std::map, int32_t> pool_of; + const bool dedup = ubatch->n_seqs_unq > 1; + + // the pool of each group of each sequence + std::vector> seq_pools(ubatch->n_seqs_unq); + + // the cells of each sequence in order, and the rank of each cell in its sequence + std::vector> order(ubatch->n_seqs_unq); + std::vector> rank (ubatch->n_seqs_unq); + + std::vector> seq_cells; + std::vector members(kpool); + for (uint32_t s = 0; s < ubatch->n_seqs_unq; ++s) { + const llama_seq_id seq_id = ubatch->seq_id_unq[s]; + + seq_cells.clear(); + for (uint32_t j = 0; j < n_kv; ++j) { + if (!cells.is_empty(j) && cells.seq_has(j, seq_id)) { + seq_cells.emplace_back(cells.pos_get(j), (int32_t) j); + } + } + if (!std::is_sorted(seq_cells.begin(), seq_cells.end())) { + std::sort(seq_cells.begin(), seq_cells.end()); + } + + auto & ord = order[s]; + auto & rnk = rank[s]; + ord.resize(seq_cells.size()); + rnk.assign(n_kv, -1); + for (size_t r = 0; r < seq_cells.size(); ++r) { + ord[r] = seq_cells[r].second; + rnk[ord[r]] = (int32_t) r; + } + + for (int32_t g = 0; (size_t) (g + 1)*kpool <= ord.size(); ++g) { + const auto beg = ord.begin() + g*kpool; + const auto end = beg + kpool; + int32_t k = (int32_t) first.size(); + if (dedup) { + members.assign(beg, end); + k = pool_of.try_emplace(members, k).first->second; + } + if (k == (int32_t) first.size()) { + idxs.insert(idxs.end(), beg, end); + first.push_back(*beg); + } + seq_pools[s].push_back(k); + } + } + + if ((int64_t) first.size() > n_pool) { + GGML_ABORT("the ubatch has %zu pools, the graph has room for %lld", first.size(), (long long) n_pool); + } + + // an unused pool is never picked, its score is -inf, but its members are still gathered: any cell does + std::vector pool_idxs_data(kpool*n_pool, 0); + std::copy(idxs.begin(), idxs.end(), pool_idxs_data.begin()); + + // the pooled key is rotated at the position of its first member, the M-RoPE planes are t, y, x, t + std::vector pool_pos_data(n_pool*n_planes, 0); + for (size_t k = 0; k < first.size(); ++k) { + const llama_pos t = cells.pos_get(first[k]); + pool_pos_data[k] = t; + if (n_planes == 4) { + const auto & e = cells.ext_get(first[k]); + pool_pos_data[1*n_pool + k] = e.y; + pool_pos_data[2*n_pool + k] = e.x; + pool_pos_data[3*n_pool + k] = t; + } + } + + std::vector pool_mask_data(n_pool*n_tokens, ggml_fp32_to_fp16(-INFINITY)); + std::vector tail_idxs_data(kpool*n_tokens, 0); + + const ggml_fp16_t zero = ggml_fp32_to_fp16(0.0f); + for (int64_t i = 0; i < n_tokens; ++i) { + // a token shared by several sequences has the same history in each, so its first one stands for all + const llama_seq_id seq_id = ubatch->seq_id[i][0]; + const uint32_t s = ubatch->seq_idx[seq_id]; + const int32_t r = rank[s][sinfo.idxs[0][i]]; + GGML_ASSERT(r >= 0); + const int32_t group = r/kpool; + + // the token sees the full pools of its sequence before its own + for (int32_t g = 0; g < group; ++g) { + pool_mask_data[i*n_pool + seq_pools[s][g]] = zero; + } + + // the token's own pool, up to the token itself, the token's cell again for the members it does not have yet + for (int32_t m = 0; m < (int32_t) kpool; ++m) { + const int32_t rm = group*(int32_t) kpool + m; + tail_idxs_data[i*kpool + m] = rm <= r ? order[s][rm] : (int32_t) sinfo.idxs[0][i]; + } + } + + ggml_backend_tensor_set(pool_idxs, pool_idxs_data.data(), 0, ggml_nbytes(pool_idxs)); + ggml_backend_tensor_set(pool_pos, pool_pos_data.data(), 0, ggml_nbytes(pool_pos)); + ggml_backend_tensor_set(pool_mask, pool_mask_data.data(), 0, ggml_nbytes(pool_mask)); + ggml_backend_tensor_set(tail_idxs, tail_idxs_data.data(), 0, ggml_nbytes(tail_idxs)); +} + bool llama_kv_cache::has_cell_ext() const { // M-RoPE needs the 2D position, the PLE / Engram n-gram hashes need the token id return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0; @@ -3124,6 +3244,11 @@ void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama kv->set_input_pos_bucket(dst, ubatch); } +void llama_kv_cache_context::set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, uint32_t kpool) const { + kv->set_input_kpool(pool_idxs, pool_pos, pool_mask, tail_idxs, ubatch, sinfos[i_cur], kpool, n_kv); +} + void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { kv->set_input_relative_pos(dst, ubatch, extent); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc41d5..acff46e19c59 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -249,6 +249,15 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + + // pools of kpool consecutive tokens of a sequence, in the order of their positions, for a pooled indexer (hy_v4_flash) + // the pools are rebuilt from the cells for every ubatch, so no sequence edit can leave them stale + // pool_idxs [kpool, n_pool] I32: member cells of each complete pool, cell 0 for an unused one + // pool_pos [n_pool*n_pos_per_embd] I32: position of the first member, where the pooled key is rotated + // pool_mask [n_pool, n_tokens] F16: 0 for a pool of the token's sequence that ends before the token's own pool, else -inf + // tail_idxs [kpool, n_tokens] I32: cells of the token's own pool, the token's cell for the members it does not have yet + void set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, const slot_info & sinfo, uint32_t kpool, uint32_t n_kv) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // true if llama_kv_cell_ext holds information that has to survive a state save/restore @@ -454,6 +463,8 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + void set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, uint32_t kpool) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // see llama_kv_cache::get_prev_tokens() diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index 4a62064e7dc6..51315fb5cc7d 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -370,6 +370,11 @@ void llama_model_saver::add_kv_from_model() { } } + if (model->arch == LLM_ARCH_HY_V4_FLASH && hparams.ple_n_heads > 0) { + add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + add_kv(LLM_KV_ENGRAM_TOKEN_MAP, model->engram_token_map); + } + // the PLE group only means anything whole: write all of it or none if (hparams.ple_n_heads > 0) { std::vector ple_layers; @@ -384,9 +389,13 @@ void llama_model_saver::add_kv_from_model() { add_kv(LLM_KV_PLE_CONV_KERNEL, hparams.ple_conv_kernel); add_kv(LLM_KV_PLE_EOS_TOKEN_ID, hparams.ple_eos_token_id); add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.ple_head_dim); - add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector( - hparams.ple_layer_multipliers.begin(), - hparams.ple_layer_multipliers.begin() + hparams.ple_n_modules*hparams.ple_ngram_size)); + if (model->arch == LLM_ARCH_HY_V4_FLASH) { + add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, model->engram_multipliers); + } else { + add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector( + hparams.ple_layer_multipliers.begin(), + hparams.ple_layer_multipliers.begin() + hparams.ple_n_modules*hparams.ple_ngram_size)); + } add_kv(LLM_KV_PLE_HEAD_OFFSETS, std::vector( hparams.ple_head_offsets.begin(), hparams.ple_head_offsets.begin() + hparams.ple_n_modules*hparams.ple_n_heads)); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 74abd222de58..e451b244e219 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -321,6 +321,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_hy_v3(params); case LLM_ARCH_HY_V4: return new llama_model_hy_v4(params); + case LLM_ARCH_HY_V4_FLASH: + return new llama_model_hy_v4_flash(params); case LLM_ARCH_SMOLLM3: return new llama_model_smollm3(params); case LLM_ARCH_OPENAI_MOE: @@ -2901,7 +2903,8 @@ void llama_model::print_info() const { if (arch == LLM_ARCH_DEEPSEEK2 || arch == LLM_ARCH_DEEPSEEK2OCR || arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_MISTRAL4 || - arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 || + arch == LLM_ARCH_HY_V4_FLASH) { LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead); LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q); LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv); @@ -3347,6 +3350,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, } } break; case LLM_ARCH_DOTS3NOTE: + case LLM_ARCH_HY_V4_FLASH: { GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE); @@ -3953,6 +3957,9 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { // HY_V4 rotates consecutive pairs, matching the reference implementation case LLM_ARCH_HY_V4: return LLAMA_ROPE_TYPE_NORM; + // HY_V4_FLASH keeps the interleaved rope rows and reorders them in the graph for M-RoPE (see src/models/hy-v4-flash.cpp) + case LLM_ARCH_HY_V4_FLASH: + return model->hparams.use_mrope() ? LLAMA_ROPE_TYPE_IMROPE : LLAMA_ROPE_TYPE_NORM; // the pairs of head values are offset by n_rot/2 case LLM_ARCH_FALCON: diff --git a/src/llama-model.h b/src/llama-model.h index e0273d7d106b..72e5fd6cbd8a 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -642,10 +642,17 @@ struct llama_layer { // glm5-next k-pool indexer struct ggml_tensor * indexer_kpool_gate = nullptr; struct ggml_tensor * indexer_kpool_ape = nullptr; + // hy_v4_flash: what the k-pool pools + struct ggml_tensor * indexer_kpool_value = nullptr; // deepseek41 struct ggml_tensor * engram_kv = nullptr; struct ggml_tensor * engram_gate = nullptr; // q_weight*k_weight folded + // hy_v4_flash: engram_kv bias, per-head norm of the looked-up rows, scale and offset of the delta + struct ggml_tensor * engram_kv_b = nullptr; + struct ggml_tensor * engram_lookup_norm = nullptr; + struct ggml_tensor * engram_pre_gamma = nullptr; + struct ggml_tensor * engram_hc_scale = nullptr; // MSA struct ggml_tensor * index_q_proj = nullptr; @@ -855,6 +862,8 @@ struct llama_model { // deepseek41 Engram: token id -> id of its normalized form, hashed into the n-grams std::vector engram_token_map; + // hy_v4_flash Engram: n_modules*ngram_size hash multipliers, more than hparams.ple_layer_multipliers holds + std::vector engram_multipliers; struct ggml_tensor * tok_embd = nullptr; struct ggml_tensor * type_embd = nullptr; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index d1fc91b1024a..5381f672a3f7 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -310,6 +310,13 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param // Engram gate is an elementwise weight (ggml_mul), not a matmul operand quantize &= name.find("engram_gate.weight") == std::string::npos; + // hy_v4_flash: these are ggml_add operands + if (arch == LLM_ARCH_HY_V4_FLASH) { + quantize &= name.find("engram_kv_b.weight") == std::string::npos; + quantize &= name.find("engram_hc_scale.weight") == std::string::npos; + quantize &= name.find("indexer_compressor_ape.weight") == std::string::npos; + } + // these are very small (e.g. 4x4) quantize &= name.find("altup") == std::string::npos; quantize &= name.find("laurel") == std::string::npos; diff --git a/src/models/hy-v4-flash.cpp b/src/models/hy-v4-flash.cpp new file mode 100644 index 000000000000..7f5c39232ec6 --- /dev/null +++ b/src/models/hy-v4-flash.cpp @@ -0,0 +1,1081 @@ +#include "models.h" + +#include "llama-kv-cache.h" +#include "llama-kv-cache-dsa.h" +#include "llama-kv-cache-dsa-iswa.h" + +#include + +// hy_v4 iHC, gated MLA and sinks, plus: sparse and sliding-window layers over one MLA geometry, +// sandwich norms, and routed experts at n_expert_latent instead of n_embd + +// a token that cannot be hashed: outside the map, or an embedding (image) position +static constexpr int64_t HY_V4_FLASH_ENGRAM_DEAD = -1; + +// the reference Engram norms leave eps unset, so they use the fp32 machine epsilon, not rms_norm_eps +static constexpr float HY_V4_FLASH_ENGRAM_EPS = 1.1920929e-07f; + +// the weights keep the reference's interleaved rope pairs, the M-RoPE kernels need NeoX halves +// q and k get the same reorder, so their dot product does not change +static ggml_tensor * hy_v4_flash_rope_to_neox(ggml_context * ctx, ggml_tensor * x) { + const int64_t n_rot = x->ne[0]; + x = ggml_reshape_4d(ctx, ggml_cont(ctx, x), 2, n_rot/2, x->ne[1], x->ne[2]); + x = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3)); + return ggml_reshape_3d(ctx, x, n_rot, x->ne[2], x->ne[3]); +} + +// IMROPE rotates the last pairs with the 4th position, the reference uses t there +static ggml_tensor * hy_v4_flash_pos(ggml_context * ctx, ggml_tensor * pos, int64_t n_tokens) { + return ggml_concat(ctx, ggml_view_1d(ctx, pos, 3*n_tokens, 0), ggml_view_1d(ctx, pos, n_tokens, 0), 0); +} + +static size_t hy_v4_flash_elem_offset(const ggml_tensor * t, int64_t i) { + return ggml_row_size(t->type, i); +} + +static ggml_tensor * hy_v4_flash_view_1d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t i0) { + return ggml_view_1d(ctx, t, ne0, hy_v4_flash_elem_offset(t, i0)); +} + +static ggml_tensor * hy_v4_flash_view_2d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t ne1, int64_t i0) { + return ggml_view_2d(ctx, t, ne0, ne1, t->nb[1], hy_v4_flash_elem_offset(t, i0)); +} + +void llama_model_hy_v4_flash::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead, false); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm, false); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false); + ml.get_key(LLM_KV_EXPERT_LATENT_LENGTH, hparams.n_expert_latent, false); + + // routed experts only; the shared and dense FFNs are not clamped + ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_EXP, hparams.swiglu_clamp_exp, hparams.n_layer_all, false); + + ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult); + ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps); + ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude); + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa); + hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + + // the sections are only used by the VL path (M-RoPE), a text-only file runs the normal rope + ml.get_key_or_arr(LLM_KV_ROPE_DIMENSION_SECTIONS, hparams.rope_sections, 4, false); + if (hparams.use_mrope()) { + const auto & s = hparams.rope_sections; + if (s[0] < 0 || s[1] < 0 || s[2] < 0 || s[3] < 0 || 2 * ((int64_t) s[0] + s[1] + s[2] + s[3]) != (int64_t) hparams.n_rot()) { + throw std::runtime_error("hy_v4_flash: rope sections must sum to n_rot / 2"); + } + } + + // the sparse layers select their context with a pooled indexer + ml.get_key(LLM_KV_ATTENTION_INDEXER_TOP_K, hparams.indexer_top_k); + { + ml.get_key(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, hparams.indexer_n_head); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, hparams.indexer_head_size); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL, hparams.indexer_kpool); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, hparams.indexer_kpool_select_tail, false); + ml.get_key_or_arr(LLM_KV_ATTENTION_INDEXER_TYPES, hparams.is_indexer_full_impl, hparams.n_layer(), false); + + // indexer.types says which layers own an indexer, none means no indexer + bool any = false; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + any = any || hparams.is_indexer_full(il); + } + + if (!any) { + throw std::runtime_error("hy_v4_flash: no layer owns an indexer"); + } else { + if (hparams.indexer_kpool < 2 || hparams.indexer_top_k % hparams.indexer_kpool != 0) { + throw std::runtime_error(format( + "hy_v4_flash: indexer top_k %u must be a multiple of the pool size %u", + hparams.indexer_top_k, hparams.indexer_kpool)); + } + if (hparams.indexer_kpool_select_tail && hparams.indexer_top_k / hparams.indexer_kpool < 2) { + throw std::runtime_error("hy_v4_flash: indexer top_k must reserve at least one history group and one tail group"); + } + // the indexer cache mirrors the full-attention child, so a window layer cannot own one + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (!hparams.is_indexer_full(il)) { + continue; + } + if (hparams.is_swa(il)) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u is a sliding-window layer and cannot own an indexer", il)); + } + // the indexer splits each head into a nope front and a rope tail, so the tail must fit + if (hparams.n_rot(il) >= hparams.indexer_head_size) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u indexer key length %u must be larger than the rope dimension %u", + il, hparams.indexer_head_size, hparams.n_rot(il))); + } + } + } + } + + GGML_ASSERT(hparams.is_mla()); + + if (!hparams.is_swa_any()) { + throw std::runtime_error("hy_v4_flash: no sliding-window layer, expected a hybrid stack"); + } + + // both layer types share one MLA geometry, only the head count differs + uint32_t n_embd_head_k_mla_swa = 0; + uint32_t n_embd_head_v_mla_swa = 0; + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA_SWA, n_embd_head_k_mla_swa, false); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA_SWA, n_embd_head_v_mla_swa, false); + + if ((n_embd_head_k_mla_swa && n_embd_head_k_mla_swa != hparams.n_embd_head_k_mla()) || + (n_embd_head_v_mla_swa && n_embd_head_v_mla_swa != hparams.n_embd_head_v_mla())) { + throw std::runtime_error(format( + "hy_v4_flash: needs one MLA geometry for both layer types, but the " + "sliding-window layers declare key/value %u/%u against %u/%u", + n_embd_head_k_mla_swa, n_embd_head_v_mla_swa, + hparams.n_embd_head_k_mla(), hparams.n_embd_head_v_mla())); + } + + // MLA runs as MQA: one latent row per token + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (hparams.n_head_kv(il) != 1) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u has n_head_kv %u, expected 1 for MLA", + il, hparams.n_head_kv(il))); + } + } + + // Engram is optional: deepseek41 n-gram hash tables, one module per Engram layer + // multipliers, primes and offsets are flat [module][...] arrays, so their lengths give the module count + std::vector e_layers; + ml.get_arr(LLM_KV_PLE_LAYERS, e_layers, false); + if (!e_layers.empty()) { + std::vector mult; + std::vector offsets; + std::vector primes; + ml.get_key(LLM_KV_PLE_NGRAM_SIZE, hparams.ple_ngram_size); + ml.get_key(LLM_KV_PLE_HEADS_PER_NGRAM, hparams.ple_heads_per_ngram); + ml.get_key(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.ple_head_dim); + ml.get_arr(LLM_KV_PLE_LAYER_MULTIPLIERS, mult); + ml.get_arr(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ml.get_arr(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ml.get_key(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + ml.get_arr(LLM_KV_ENGRAM_TOKEN_MAP, engram_token_map); + + const size_t n_e = e_layers.size(); + const size_t n_gram = hparams.ple_ngram_size; + const size_t n_cols = n_gram >= 2 ? (n_gram - 1)*hparams.ple_heads_per_ngram : 0; + if (n_cols == 0 || hparams.ple_head_dim == 0 || + mult.size() != n_e*n_gram || primes.size() != n_e*n_cols || offsets.size() != n_e*n_cols || + primes.size() > LLAMA_MAX_PLE_HEADS || + hparams.engram_pad_id >= engram_token_map.size()) { + throw std::runtime_error("hy_v4_flash engram metadata is inconsistent"); + } + for (size_t e = 0; e < n_e; ++e) { + if (e_layers[e] >= hparams.n_layer() || (e > 0 && e_layers[e] <= e_layers[e - 1])) { + throw std::runtime_error(format("hy_v4_flash engram layer %u is out of range or out of order", e_layers[e])); + } + hparams.is_ple_impl.set(e_layers[e]); + } + for (size_t c = 0; c < n_e*n_cols; ++c) { + // a bucket count of 0 traps in the hash; row ids are int32 + if (primes[c] < 2 || offsets[c] > (uint64_t) INT32_MAX || primes[c] > (uint64_t) INT32_MAX - offsets[c]) { + throw std::runtime_error(format("hy_v4_flash engram head %zu: bucket range out of range", c)); + } + hparams.ple_head_offsets[c] = (uint32_t) offsets[c]; + hparams.ple_head_vocab_sizes[c] = (uint32_t) primes[c]; + } + engram_multipliers = std::move(mult); + hparams.ple_n_heads = (uint32_t) n_cols; + hparams.ple_n_modules = (uint32_t) n_e; + } + + type = LLM_TYPE_UNKNOWN; +} + +void llama_model_hy_v4_flash::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t n_embd_head_k_mla = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_v_mla = hparams.n_embd_head_v_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k_mla - n_embd_head_qk_rope; + GGML_ASSERT(n_embd_head_qk_nope >= 1); + + const int64_t q_lora_rank = hparams.n_lora_q; + const int64_t kv_lora_rank = hparams.n_lora_kv; + const int64_t n_ff_exp = hparams.n_ff_exp(); + const int64_t n_expert_shared = hparams.n_expert_shared; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t n_embd_latent = hparams.n_expert_latent ? hparams.n_expert_latent : n_embd; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0); + + hc_head_fn = create_tensor(tn(LLM_TENSOR_HC_HEAD_FN, "weight"), {hc * n_embd, hc}, 0); + hc_head_base = create_tensor(tn(LLM_TENSOR_HC_HEAD_BASE, "weight"), {hc}, 0); + hc_head_scale = create_tensor(tn(LLM_TENSOR_HC_HEAD_SCALE, "weight"), {1}, 0); + + const int64_t ple_n_heads = hparams.ple_n_heads; + const int64_t ple_head_dim = hparams.ple_head_dim; + if (ple_n_heads > 0) { + // all modules share one table, so the row count is the end of the last bucket + int64_t n_rows = 0; + for (size_t c = 0; c < (size_t) hparams.ple_n_modules*ple_n_heads; ++c) { + n_rows = std::max(n_rows, (int64_t) hparams.ple_head_offsets[c] + hparams.ple_head_vocab_sizes[c]); + } + // 118 GiB at the full size: read lazily, so only the rows a batch hashes to are faulted in + per_layer_tok_embd = create_tensor(tn(LLM_TENSOR_PER_LAYER_TOKEN_EMBD, "weight"), {ple_head_dim, n_rows}, TENSOR_READ_LAZY); + } + + // the MTP block is a sparse layer after the trunk, without hyper-connections + for (int i = 0; i < (int) hparams.n_layer_all; ++i) { + auto & layer = layers[i]; + const bool is_nextn = i >= n_layer; + + // the MTP block is not supported yet, its tensors are skipped + const int flags = is_nextn ? TENSOR_SKIP | TENSOR_NOT_REQUIRED : 0; + + // the sliding-window layers carry more heads over the same latent geometry + const int64_t n_head_l = hparams.n_head(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags); + layer.attn_sinks = create_tensor(tn(LLM_TENSOR_ATTN_SINKS, "weight", i), {n_head_l}, flags); + + layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, flags); + layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, flags); + layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head_l * n_embd_head_k_mla}, flags); + layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + n_embd_head_qk_rope}, flags); + layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, flags); + layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {n_embd_head_qk_nope, kv_lora_rank, n_head_l}, flags); + layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v_mla, n_head_l}, flags); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head_l * n_embd_head_v_mla, n_embd}, flags); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head_l * n_embd_head_v_mla}, flags); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, flags); + + if (!is_nextn) { + layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc * n_embd, 2 * hc}, flags); + layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {2 * hc}, flags); + layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {2}, flags); + layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc * n_embd, 2 * hc}, flags); + layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {2 * hc}, flags); + layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {2}, flags); + } else { + // the draft block folds the next token's embedding into the trunk's final hidden state + layer.nextn.enorm = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), {n_embd}, flags); + layer.nextn.hnorm = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), {n_embd}, flags); + layer.nextn.eh_proj = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), {2 * n_embd, n_embd}, flags); + layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), {n_embd}, flags); + } + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, flags); + + // is_indexer_full() only covers the trunk, and the draft block always owns an indexer + if (is_nextn || hparams.is_indexer_full(i)) { + const int64_t n_idx = hparams.indexer_head_size; + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t kpool = hparams.indexer_kpool; + + layer.indexer_attn_k = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_K, "weight", i), {n_embd, n_idx}, flags); + layer.indexer_k_norm = create_tensor(tn(LLM_TENSOR_INDEXER_K_NORM, "weight", i), {n_idx}, flags); + // the pool averages a projection of the normed key, weighted by another projection of it + layer.indexer_kpool_value = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_VALUE, "weight", i), {n_idx, n_idx}, flags); + layer.indexer_kpool_gate = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_GATE, "weight", i), {n_idx, n_idx}, flags); + layer.indexer_kpool_ape = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_APE, "weight", i), {n_idx, kpool}, flags); + layer.indexer_comp_norm = create_tensor(tn(LLM_TENSOR_INDEXER_COMPRESSOR_NORM, "weight", i), {n_idx}, flags); + layer.indexer_attn_q_b = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_Q_B, "weight", i), {q_lora_rank, n_idx*n_idx_head}, flags); + layer.indexer_proj = create_tensor(tn(LLM_TENSOR_INDEXER_PROJ, "weight", i), {n_embd, n_idx_head}, flags); + } + + if (!is_nextn && engram_index(i) >= 0) { + // hc key projections and the value projection fused into one matmul, as deepseek41, plus a bias + layer.engram_kv = create_tensor(tn(LLM_TENSOR_ENGRAM_KV, "weight", i), {ple_n_heads * ple_head_dim, n_embd * (hc + 1)}, flags); + layer.engram_kv_b = create_tensor(tn(LLM_TENSOR_ENGRAM_KV_B, "weight", i), {n_embd, hc + 1}, flags); + layer.engram_gate = create_tensor(tn(LLM_TENSOR_ENGRAM_GATE, "weight", i), {n_embd, hc}, flags); + layer.engram_lookup_norm = create_tensor(tn(LLM_TENSOR_ENGRAM_LOOKUP_NORM, "weight", i), {ple_head_dim, ple_n_heads}, flags); + layer.engram_pre_gamma = create_tensor(tn(LLM_TENSOR_ENGRAM_PRE_GAMMA, "weight", i), {n_embd}, flags); + layer.engram_hc_scale = create_tensor(tn(LLM_TENSOR_ENGRAM_HC_SCALE, "weight", i), {n_embd, hc}, flags); + } + + if (!is_nextn && i < (int) hparams.n_layer_dense_lead) { + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, flags); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, flags); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, flags); + } else { + if (n_expert == 0 || n_expert_used == 0) { + throw std::runtime_error("hy_v4_flash: n_expert and n_expert_used must be > 0"); + } + + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, flags); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED | flags); + + if (hparams.n_expert_latent) { + layer.ffn_routed_down = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_DOWN, "weight", i), {n_embd, n_embd_latent}, flags); + layer.ffn_routed_up = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_UP, "weight", i), {n_embd_latent, n_embd}, flags); + } + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, flags); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, flags); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd_latent, n_expert}, flags); + + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_exp * n_expert_shared, n_embd}, flags); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags); + } + } +} + +int llama_model_hy_v4_flash::engram_index(int il) const { + if (hparams.ple_n_heads == 0 || !hparams.is_ple(il)) { + return -1; + } + int e = 0; + for (int j = 0; j < il; ++j) { + e += hparams.is_ple(j); + } + return e; +} + +void llama_model_hy_v4_flash::engram_hash(int e, const llama_ubatch & ubatch, + const std::vector & prev, + std::vector & ids, std::vector & valid) const { + const int64_t n_gram = hparams.ple_ngram_size; + const int64_t n_prev = n_gram - 1; + const int64_t n_head = hparams.ple_heads_per_ngram; + const int64_t n_cols = hparams.ple_n_heads; + + const uint64_t * mult = engram_multipliers.data() + (size_t) e*n_gram; + const uint32_t * primes = hparams.ple_head_vocab_sizes.data() + (size_t) e*n_cols; + const uint32_t * offs = hparams.ple_head_offsets.data() + (size_t) e*n_cols; + const int64_t pad = engram_token_map[hparams.engram_pad_id]; + + const auto cid = [&](llama_token t) -> int64_t { + return t < 0 || t >= (llama_token) engram_token_map.size() ? HY_V4_FLASH_ENGRAM_DEAD : engram_token_map[t]; + }; + + ids.resize(ubatch.n_tokens*n_cols); + valid.resize(ubatch.n_tokens*n_cols); + + std::vector toks(n_gram); + + for (int64_t i = 0; i < ubatch.n_tokens; ++i) { + // a short history is padded with the pad id, only an embedding position is invalid + const bool is_embd = !ubatch.token || (ubatch.is_mixed() && ubatch.type[i]); + int64_t c = is_embd ? HY_V4_FLASH_ENGRAM_DEAD : cid(ubatch.token[i]); + const bool dead = c == HY_V4_FLASH_ENGRAM_DEAD; + toks[0] = dead ? pad : c; + for (int64_t s = 1; s < n_gram; ++s) { + c = ubatch.pos[i] - s < 0 ? HY_V4_FLASH_ENGRAM_DEAD : cid(prev[i*n_prev + (n_prev - s)]); + toks[s] = c == HY_V4_FLASH_ENGRAM_DEAD ? pad : c; + } + + uint64_t rolling = toks[0]*mult[0]; + for (int64_t o = 1; o < n_gram; ++o) { + rolling ^= toks[o]*mult[o]; + for (int64_t h = 0; h < n_head; ++h) { + const int64_t col = (o - 1)*n_head + h; + ids [i*n_cols + col] = (int32_t) (rolling % primes[col] + offs[col]); + valid[i*n_cols + col] = dead ? 0.0f : 1.0f; + } + } + } +} + +// the row ids and their validity are host-side, so they are graph inputs rather than computed +class llm_graph_input_hy_v4_flash : public llm_graph_input_i { +public: + llm_graph_input_hy_v4_flash(const llama_model_hy_v4_flash & model, + const llama_kv_cache_context * mctx) : model(model), mctx(mctx) {} + + void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + + std::vector engram_ids; + std::vector engram_valid; + + const llama_model_hy_v4_flash & model; + const llama_kv_cache_context * mctx; +}; + +void llm_graph_input_hy_v4_flash::set_input(const llama_ubatch * ubatch) { + if (engram_ids.empty()) { + return; + } + + // a token shared by several sequences has the same history in each, so its first one resolves it + std::vector prev; + mctx->get_prev_tokens(*ubatch, model.hparams.ple_ngram_size - 1, prev); + + // hash every module before the first gather, so a lazily read table gets one batched readahead + std::vector> ids(engram_ids.size()); + std::vector> valid(engram_ids.size()); + std::vector all; + for (size_t e = 0; e < engram_ids.size(); ++e) { + model.engram_hash((int) e, *ubatch, prev, ids[e], valid[e]); + all.insert(all.end(), ids[e].begin(), ids[e].end()); + } + if (model.can_prefetch.count(model.per_layer_tok_embd)) { + llama_prefetch_rows(model.per_layer_tok_embd, all.data(), all.size()); + } + for (size_t e = 0; e < engram_ids.size(); ++e) { + if (engram_ids[e]->buffer) { + ggml_backend_tensor_set(engram_ids[e], ids[e].data(), 0, ids[e].size()*sizeof(int32_t)); + } + if (engram_valid[e]->buffer) { + ggml_backend_tensor_set(engram_valid[e], valid[e].data(), 0, valid[e].size()*sizeof(float)); + } + } +} + +bool llm_graph_input_hy_v4_flash::can_reuse(const llm_graph_params & params) { + // the memory context is rebuilt for every batch, re-fetch it as deepseek41 does + mctx = static_cast(params.mctx)->get_dsa()->get_mla(); + + bool res = true; + for (auto * t : engram_ids) { + res &= t->ne[0] == (int64_t) (model.hparams.ple_n_heads*params.ubatch.n_tokens); + } + return res; +} + +std::unique_ptr llama_model_hy_v4_flash::build_arch_graph(const llm_graph_params & params) const { + if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) { + throw std::runtime_error("hy_v4_flash: the MTP block is not supported yet"); + } + return std::make_unique(*this, params); +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const { + const auto & layer = model.layers[il]; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + const int64_t n_cols = hparams.ple_n_heads; + const int64_t head_dim = hparams.ple_head_dim; + + GGML_ASSERT(rows->ne[0] == head_dim && rows->ne[1] == n_cols && rows->ne[2] == nt); + + // unlike deepseek41, each looked-up row is RMS-normed and scaled by its head weight + ggml_tensor * r = ggml_rms_norm(ctx0, rows, HY_V4_FLASH_ENGRAM_EPS); + r = ggml_mul(ctx0, r, layer.engram_lookup_norm); + r = ggml_mul(ctx0, r, ggml_reshape_3d(ctx0, valid, 1, n_cols, nt)); + r = ggml_reshape_2d(ctx0, r, head_dim*n_cols, nt); + cb(r, "engram_rows_normed", il); + + // the fused key/value projection has a bias + ggml_tensor * kv = build_lora_mm(layer.engram_kv, r); + kv = ggml_add(ctx0, ggml_reshape_3d(ctx0, kv, n_embd, hc + 1, nt), layer.engram_kv_b); + cb(kv, "engram_kv", il); + + ggml_tensor * key = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, hc, nt, kv->nb[1], kv->nb[2], 0)); + ggml_tensor * value = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, 1, nt, kv->nb[1], kv->nb[2], hc*kv->nb[1])); + + // the gate is deepseek41's: engram_gate folds norm_key.w * norm_query.w + ggml_tensor * egate = ggml_is_quantized(layer.engram_gate->type) ? ggml_cast(ctx0, layer.engram_gate, GGML_TYPE_F32) : layer.engram_gate; + ggml_tensor * dot = ggml_mul(ctx0, ggml_mul(ctx0, ggml_rms_norm(ctx0, x, HY_V4_FLASH_ENGRAM_EPS), ggml_rms_norm(ctx0, key, HY_V4_FLASH_ENGRAM_EPS)), egate); + dot = ggml_scale(ctx0, ggml_sum_rows(ctx0, dot), 1.0f/sqrtf((float) n_embd)); + cb(dot, "engram_dot", il); + + // sigmoid(copysign(sqrt(max(|dot|, 1e-6)), dot)); sign(0) = +1 as in copysign + ggml_tensor * mag = ggml_sqrt(ctx0, ggml_clamp(ctx0, ggml_abs(ctx0, dot), 1e-6f, INFINITY)); + ggml_tensor * sign = ggml_scale_bias(ctx0, ggml_step(ctx0, ggml_neg(ctx0, dot)), -2.0f, 1.0f); + ggml_tensor * gate = ggml_sigmoid(ctx0, ggml_mul(ctx0, mag, sign)); + cb(gate, "engram_gate", il); + + // the delta is the normed value scaled by a learned gamma + ggml_tensor * signal = ggml_mul(ctx0, ggml_rms_norm(ctx0, value, HY_V4_FLASH_ENGRAM_EPS), layer.engram_pre_gamma); + // the per-hc offset is additive and per channel + ggml_tensor * scale = ggml_add(ctx0, ggml_repeat_4d(ctx0, gate, n_embd, hc, nt, 1), layer.engram_hc_scale); + cb(scale, "engram_scale", il); + + ggml_tensor * delta = ggml_mul(ctx0, ggml_repeat_4d(ctx0, signal, n_embd, hc, nt, 1), scale); + + // mask the whole delta of a token without a valid n-gram, as the bias still reaches the value path + ggml_tensor * any = ggml_sum_rows(ctx0, ggml_reshape_2d(ctx0, valid, n_cols, nt)); + any = ggml_step(ctx0, any); + delta = ggml_mul(ctx0, delta, ggml_reshape_3d(ctx0, any, 1, 1, nt)); + cb(delta, "engram_delta", il); + + return ggml_add(ctx0, x, delta); +} + +// reduce hc streams x[:,i,:] weighted by w[i,:] -> [n_embd, n_tokens] +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(x->ne[1] == hc); + + // the fused node is registered per layer, so the head reduce (il < 0) keeps the loop + if (cparams.fused_dsv4_hc_pre && il >= 0) { + ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, weights); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il}); + return result; + } + + ggml_tensor * result = nullptr; + for (int64_t ih = 0; ih < hc; ++ih) { + ggml_tensor * xh = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], ih * x->nb[1]); + ggml_tensor * wh = ggml_view_2d(ctx0, weights, 1, nt, weights->nb[1], ih * weights->nb[0]); + ggml_tensor * cur = ggml_mul(ctx0, xh, wh); + result = result ? ggml_add(ctx0, result, cur) : cur; + } + return result; +} + +llama_model_hy_v4_flash::graph::hc_pre +llama_model_hy_v4_flash::graph::build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd && x->ne[1] == hc); + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_mixes", il); + + ggml_tensor * scale_pre = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 0); + ggml_tensor * scale_post = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 1); + ggml_tensor * base_pre = hy_v4_flash_view_1d(ctx0, hc_base, hc, 0); + ggml_tensor * base_post = hy_v4_flash_view_1d(ctx0, hc_base, hc, hc); + + ggml_tensor * pre = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, 0); + pre = ggml_mul(ctx0, pre, scale_pre); + pre = ggml_add(ctx0, pre, base_pre); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_pre", il); + + ggml_tensor * post = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, hc); + post = ggml_mul(ctx0, post, scale_post); + post = ggml_add(ctx0, post, base_post); + post = ggml_sigmoid(ctx0, post); + post = ggml_scale(ctx0, post, hparams.hc_magnitude); + post = ggml_scale_bias(ctx0, post, 1.0f, hparams.dsv4_hc_eps); + cb(post, "hc_post_gate", il); + + return { build_hc_reduce(x, pre, il), post }; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[1]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(residual->ne[1] == hc); + + // comb is the identity here: each stream keeps its own residual, hy_v4 has no cross-stream mix + if (cparams.fused_dsv4_hc_post) { + ggml_tensor * result = ggml_dsv4_hc_post(ctx0, x, residual, post, nullptr); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il}); + return result; + } + + ggml_tensor * out = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * res_i = ggml_view_2d(ctx0, residual, n_embd, nt, residual->nb[2], i * residual->nb[1]); + ggml_tensor * post_i = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], i * post->nb[0]); + ggml_tensor * cur = ggml_add(ctx0, res_i, ggml_mul(ctx0, x, post_i)); + cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, nt); + out = out ? ggml_concat(ctx0, out, cur, 1) : cur; + } + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_head_mixes", -1); + + ggml_tensor * pre = ggml_mul(ctx0, mixes, hc_scale); + pre = ggml_add(ctx0, pre, hc_base); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_head_pre", -1); + + return build_hc_reduce(x, pre, -1); +} + +// the pools of the indexer, rebuilt from the cells of the indexer cache for every ubatch +class llama_model_hy_v4_flash::llm_graph_input_pool : public llm_graph_input_i { +public: + llm_graph_input_pool(const llama_kv_cache_context * mctx, uint32_t kpool) : mctx(mctx), kpool(kpool) {} + virtual ~llm_graph_input_pool() = default; + + void set_input(const llama_ubatch * ubatch) override { + mctx->set_input_kpool(pool_idxs, pool_pos, pool_mask, tail_idxs, ubatch, kpool); + } + + bool can_reuse(const llm_graph_params & params) override { + mctx = static_cast(params.mctx)->get_dsa()->get_lid(); + + bool res = true; + res &= pool_idxs->ne[1] == n_pool(mctx, params.cparams.n_seq_max, kpool); + res &= tail_idxs->ne[1] == params.ubatch.n_tokens; + return res; + } + + // every cell can start a pool, plus one misaligned pool per sequence + static int64_t n_pool(const llama_kv_cache_context * mctx, uint32_t n_seq_max, uint32_t kpool) { + return mctx->get_n_kv()/kpool + n_seq_max; + } + + ggml_tensor * pool_idxs = nullptr; // I32 [kpool, n_pool] + ggml_tensor * pool_pos = nullptr; // I32 [n_pool*n_pos_per_embd] + ggml_tensor * pool_mask = nullptr; // F16 [n_pool, n_tokens] + ggml_tensor * tail_idxs = nullptr; // I32 [kpool, n_tokens] + + const llama_kv_cache_context * mctx; + const uint32_t kpool; +}; + +llama_model_hy_v4_flash::llm_graph_input_pool * llama_model_hy_v4_flash::graph::build_inp_pool( + llm_graph_input_attn_k_dsa_iswa * inp_attn) { + const auto * mctx_lid = inp_attn->get_dsa()->mctx->get_lid(); + + const uint32_t kpool = hparams.indexer_kpool; + const int64_t n_pool = llm_graph_input_pool::n_pool(mctx_lid, cparams.n_seq_max, kpool); + + auto inp = std::make_unique(mctx_lid, kpool); + + inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); + inp->pool_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool*hparams.n_pos_per_embd()); + inp->pool_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F16, n_pool, n_tokens); + inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_tokens); + + ggml_set_input(inp->pool_idxs); + ggml_set_input(inp->pool_pos); + ggml_set_input(inp->pool_mask); + ggml_set_input(inp->tail_idxs); + + return (llm_graph_input_pool *) res->add_input(std::move(inp)); +} + +// rotate only the trailing n_rot of each indexer head, leaving the head's front half untouched +ggml_tensor * llama_model_hy_v4_flash::graph::build_indexer_rope( + ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, float freq_base, int il) const { + const int64_t n_nope = n_idx - n_rot; + GGML_ASSERT(n_nope > 0); + + ggml_tensor * front = ggml_view_3d(ctx0, x, n_nope, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], 0); + ggml_tensor * back = ggml_view_3d(ctx0, x, n_rot, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], ggml_row_size(x->type, n_nope)); + + // the same base the layer's own attention uses, so a cparams override reaches the indexer too + if (hparams.use_mrope()) { + int sections[GGML_MROPE_SECTIONS]; + std::copy(hparams.rope_sections.begin(), hparams.rope_sections.end(), sections); + + back = ggml_rope_multi(ctx0, hy_v4_flash_rope_to_neox(ctx0, back), pos, nullptr, n_rot, sections, rope_type, n_ctx_orig, + freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow); + } else { + back = ggml_rope_ext(ctx0, ggml_cont(ctx0, back), pos, nullptr, n_rot, rope_type, n_ctx_orig, + freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow); + } + cb(back, "indexer_rope", il); + + return ggml_concat(ctx0, ggml_cont(ctx0, front), back, 0); +} + +// the cells a token attends to: the best scored pools of its sequence plus its own pool +ggml_tensor * llama_model_hy_v4_flash::graph::build_pool_select( + ggml_tensor * cur, ggml_tensor * qr, ggml_tensor * inp_pos, float freq_base, + const llama_layer & layer, + llm_graph_input_attn_k_dsa_iswa * inp_attn, llm_graph_input_pool * inp_pool, + ggml_tensor * kq_mask, int il) { + const auto * inp_dsa = inp_attn->get_dsa(); + const auto * mctx_lid = inp_dsa->mctx->get_lid(); + + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t n_idx = hparams.indexer_head_size; + const int64_t kpool = hparams.indexer_kpool; + const int64_t n_pool = inp_pool->pool_idxs->ne[1]; + const int64_t n_kv = mctx_lid->get_n_kv(); + + // the query comes from the q lora residual of the main attention + ggml_tensor * iq = build_lora_mm(layer.indexer_attn_q_b, qr); + iq = ggml_reshape_3d(ctx0, iq, n_idx, n_idx_head, n_tokens); + iq = build_indexer_rope(iq, inp_pos, n_idx, freq_base, il); + cb(iq, "indexer_q", il); + + // key side: weight-only RMSNorm, unlike glm5-next's LayerNorm with a bias this model lacks + ggml_tensor * ik = build_lora_mm(layer.indexer_attn_k, cur); + ik = build_norm(ik, layer.indexer_k_norm, nullptr, LLM_NORM_RMS, il); + cb(ik, "indexer_k", il); + + // the value and the gate are linear in the token's key, so the cache holds them and the pools are built from them + ggml_tensor * iv = build_lora_mm(layer.indexer_kpool_value, ik); + ggml_tensor * ig = build_lora_mm(layer.indexer_kpool_gate, ik); + cb(ig, "indexer_gate", il); + + ggml_tensor * packed = ggml_reshape_3d(ctx0, ggml_concat(ctx0, iv, ig, 0), 2*n_idx, 1, n_tokens); + ggml_build_forward_expand(gf, mctx_lid->cpy_k(ctx0, packed, inp_dsa->get_k_idxs_lid(), il)); + + // the members of every pool, from the cache this ubatch just wrote to + ggml_tensor * k_lid = mctx_lid->get_k(ctx0, il); + GGML_ASSERT(k_lid->ne[0] == 2*n_idx && k_lid->ne[1] == 1 && k_lid->ne[2] == n_kv && k_lid->ne[3] == 1); + k_lid = ggml_view_2d(ctx0, k_lid, 2*n_idx, n_kv, k_lid->nb[2], 0); + + ggml_tensor * rows = ggml_get_rows(ctx0, k_lid, ggml_reshape_1d(ctx0, inp_pool->pool_idxs, kpool*n_pool)); + rows = ggml_reshape_3d(ctx0, rows, 2*n_idx, kpool, n_pool); + + ggml_tensor * pv = ggml_view_3d(ctx0, rows, n_idx, kpool, n_pool, rows->nb[1], rows->nb[2], 0); + ggml_tensor * pg = ggml_view_3d(ctx0, rows, n_idx, kpool, n_pool, rows->nb[1], rows->nb[2], + ggml_row_size(rows->type, n_idx)); + + // per channel softmax over the members of the gate plus the member's position bias, then the weighted sum of the values + ggml_tensor * logits = ggml_add(ctx0, pg, layer.indexer_kpool_ape); + logits = ggml_cont(ctx0, ggml_permute(ctx0, logits, 1, 0, 2, 3)); // [kpool, n_idx, n_pool] + // fold the pool axis into rows: soft_max maps ne[2] to a CUDA gridDim.y that caps at 65535 + ggml_tensor * probs = ggml_soft_max(ctx0, ggml_reshape_2d(ctx0, logits, kpool, n_idx*n_pool)); + probs = ggml_reshape_3d(ctx0, probs, kpool, n_idx, n_pool); + + pv = ggml_cont(ctx0, ggml_permute(ctx0, pv, 1, 0, 2, 3)); + ggml_tensor * pooled = ggml_sum_rows(ctx0, ggml_mul(ctx0, probs, pv)); // [1, n_idx, n_pool] + pooled = ggml_reshape_2d(ctx0, pooled, n_idx, n_pool); + + // the pooled key is normed, then rotated at the position of its first member + pooled = build_norm(pooled, layer.indexer_comp_norm, nullptr, LLM_NORM_RMS, il); + pooled = build_indexer_rope(ggml_reshape_3d(ctx0, pooled, n_idx, 1, n_pool), inp_pool->pool_pos, n_idx, freq_base, il); + cb(pooled, "indexer_pool_k", il); + + ggml_tensor * weights = build_lora_mm(layer.indexer_proj, cur); + weights = ggml_scale(ctx0, weights, 1.0f / sqrtf(float(n_idx * n_idx_head))); + cb(weights, "indexer_weights", il); + + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_pool->pool_mask); + cb(score, "indexer_score", il); + + // the token's own pool is always kept, so it does not take a pick + const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool - hparams.indexer_kpool_select_tail); + ggml_tensor * top_k = ggml_top_k(ctx0, score, n_top_pool); // [n_top_pool, n_tokens], unordered + + ggml_tensor * tail = hparams.indexer_kpool_select_tail ? inp_pool->tail_idxs : nullptr; + + if (cparams.fused_top_k_mask) { + // a pick scored -inf (another sequence, a later or unused pool) is dropped + ggml_tensor * sel = ggml_top_k_mask(ctx0, kq_mask, top_k, score, inp_pool->pool_idxs, tail); + res->add_fused_node({LLM_FUSED_OP_TOP_K_MASK, sel, il}); + cb(sel, "indexer_sel", il); + + return sel; + } + + // without the fused op, the picks are expanded to their cells + // a pick scored -inf is only taken once every visible pool is, so its cells are either hidden by the kq_mask or already kept + ggml_tensor * cells = ggml_get_rows(ctx0, inp_pool->pool_idxs, + ggml_reshape_1d(ctx0, ggml_cont(ctx0, top_k), n_top_pool*n_tokens)); // [kpool, n_top_pool*n_tokens] + cells = ggml_reshape_2d(ctx0, cells, kpool*n_top_pool, n_tokens); + if (tail) { + cells = ggml_concat(ctx0, cells, tail, 0); + } + + ggml_tensor * sel = build_top_k_mask(kq_mask, cells, il); + cb(sel, "indexer_sel", il); + + return sel; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_attention( + const llama_model & model, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * cur, + ggml_tensor * inp_pos, + int il) { + const auto & layer = model.layers[il]; + + const int64_t n_head_l = hparams.n_head(il); + const int64_t n_embd_head_k = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k - n_embd_head_qk_rope; + const uint32_t kv_lora_rank = hparams.n_lora_kv; + + const float kq_scale = 1.0f / sqrtf(float(n_embd_head_k)); + const float freq_base_l = model.get_rope_freq_base(cparams, il); + + ggml_tensor * qr = build_lora_mm(layer.wq_a, cur); + qr = build_norm(qr, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il); + cb(qr, "q_resid", il); + + ggml_tensor * q = build_lora_mm(layer.wq_b, qr); + + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, 0); + ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, + ggml_row_size(q->type, n_embd_head_qk_nope)); + + ggml_tensor * kv_cmpr_pe = build_lora_mm(layer.wkv_a_mqa, cur); + ggml_tensor * kv_cmpr = ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), 0); + ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_cmpr_pe, n_embd_head_qk_rope, 1, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank)); + + if (hparams.use_mrope()) { + q_pe = hy_v4_flash_rope_to_neox(ctx0, q_pe); + k_pe = hy_v4_flash_rope_to_neox(ctx0, k_pe); + } + q_pe = build_rope(q_pe, inp_pos, il); + cb(q_pe, "q_pe", il); + k_pe = build_rope(k_pe, inp_pos, il); + cb(k_pe, "k_pe", il); + + kv_cmpr = build_norm(kv_cmpr, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il); + cb(kv_cmpr, "kv_cmpr", il); + + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope); + q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3); + + // rope goes last so build_rope_shift() can shift the cache in place + ggml_tensor * Qcur = ggml_concat(ctx0, q_nope_absorbed, q_pe, 0); + + kv_cmpr = ggml_reshape_3d(ctx0, kv_cmpr, kv_lora_rank, 1, n_tokens); + ggml_tensor * Kcur = ggml_concat(ctx0, kv_cmpr, k_pe, 0); + ggml_tensor * Vcur = kv_cmpr; + + ggml_tensor * attn; + + if (hparams.is_swa(il)) { + attn = build_attn(inp_attn->get_swa(), + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, layer.wv_b, kq_scale, il); + } else { + // as build_attn of the DSA input, with the cells of the picked pools instead of a top-k of cells + auto * inp_dsa = inp_attn->get_dsa(); + const auto * mctx_mla = inp_dsa->mctx->get_mla(); + + ggml_build_forward_expand(gf, Qcur); + ggml_build_forward_expand(gf, Vcur); + ggml_build_forward_expand(gf, Kcur); + ggml_build_forward_expand(gf, mctx_mla->cpy_k(ctx0, Kcur, inp_dsa->get_k_idxs_mla(), il)); + + ggml_tensor * sel = build_pool_select(cur, qr, inp_pos, freq_base_l, layer, + inp_attn, inp_pool, inp_dsa->self_attn_mask_mla.raw, il); + + const int64_t n_sel = hparams.indexer_top_k; + + ggml_tensor * k = mctx_mla->get_k(ctx0, il); + ggml_tensor * v = ggml_view_4d(ctx0, k, kv_lora_rank, k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); + + attn = build_attn_mha(Qcur, k, v, nullptr, sel, nullptr, layer.attn_sinks, layer.wv_b, n_sel, kq_scale, il); + } + cb(attn, "attn_kqv", il); + + ggml_tensor * gate = build_lora_mm(layer.wqkv_gate, cur); + gate = ggml_sigmoid(ctx0, gate); + attn = ggml_mul(ctx0, attn, gate); + cb(attn, "attn_gated", il); + + ggml_tensor * out = build_lora_mm(layer.wo, attn); + out = build_norm(out, layer.attn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(out, "attn_out", il); + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const { + const auto & layer = model.layers[il]; + + // the router scores the full-width input, the experts take the latent one + ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, cur); + cb(logits, "ffn_moe_logits", il); + + ggml_tensor * routed_in = layer.ffn_routed_down + ? build_lora_mm(layer.ffn_routed_down, cur) + : cur; + + ggml_tensor * moe_out = build_moe_ffn(routed_in, + nullptr, + layer.ffn_up_exps, + layer.ffn_gate_exps, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + n_expert, n_expert_used, + LLM_FFN_SILU, hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il, + logits); + cb(moe_out, "ffn_moe_out", il); + + if (layer.ffn_routed_up) { + moe_out = build_lora_mm(layer.ffn_routed_up, moe_out); + cb(moe_out, "ffn_moe_up", il); + } + + ggml_tensor * shexp = build_ffn(cur, + layer.ffn_up_shexp, NULL, NULL, + layer.ffn_gate_shexp, NULL, NULL, + layer.ffn_down_shexp, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(shexp, "ffn_shexp", il); + + return ggml_add(ctx0, moe_out, shexp); +} + +llama_model_hy_v4_flash::graph::graph(const llama_model & model, const llm_graph_params & params) : + llm_graph_context(params) { + const int64_t hc = hparams.dsv4_hc_mult; + + ggml_tensor * cur; + + ggml_tensor * inp_pos = build_inp_pos(); + if (hparams.use_mrope()) { + inp_pos = hy_v4_flash_pos(ctx0, inp_pos, n_tokens); + } + + // the sparse layers are in the DSA cache with their indexer, the sliding-window layers in the SWA cache + llm_graph_input_attn_k_dsa_iswa * inp_attn = build_attn_inp_k_dsa_iswa(); + + llm_graph_input_pool * inp_pool = build_inp_pool(inp_attn); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + // Engram gathers go before the token embeddings, so the mixed embd copies after them land on the GPU + // and the host split keeps only small single threaded lookups + auto inp_eng = std::make_unique( + static_cast(model), inp_attn->get_dsa()->mctx->get_mla()); + std::vector engram_rows; + std::vector engram_valid; + for (int il = 0; ubatch.token && hparams.ple_n_heads > 0 && il < n_layer; ++il) { + if (!hparams.is_ple(il)) { + continue; + } + const int64_t n_cols = hparams.ple_n_heads; + + ggml_tensor * ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_cols*n_tokens); + ggml_set_input(ids); + ggml_set_name(ids, ("engram_ids-" + std::to_string(il)).c_str()); + inp_eng->engram_ids.push_back(ids); + + ggml_tensor * valid = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_cols*n_tokens); + ggml_set_input(valid); + ggml_set_name(valid, ("engram_valid-" + std::to_string(il)).c_str()); + inp_eng->engram_valid.push_back(valid); + engram_valid.push_back(valid); + + ggml_tensor * rows = ggml_get_rows(ctx0, model.per_layer_tok_embd, ids); + rows = ggml_reshape_3d(ctx0, rows, hparams.ple_head_dim, n_cols, n_tokens); + cb(rows, "engram_rows", il); + ggml_build_forward_expand(gf, rows); + engram_rows.push_back(rows); + } + res->add_input(std::move(inp_eng)); + + ggml_tensor * inp = build_inp_embd(model.tok_embd); + + // one embedding feeds hc parallel residual streams + ggml_tensor * inpL = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens); + inpL = ggml_repeat_4d(ctx0, inpL, n_embd, hc, n_tokens, 1); + cb(inpL, "hc_init", -1); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + + // Engram writes into the streams before the attention pre-mix reads them + const int e = static_cast(model).engram_index(il); + if (e >= 0 && !engram_rows.empty()) { + inpL = build_engram(model, inpL, engram_rows[e], engram_valid[e], il); + cb(inpL, "engram_out", il); + } + + ggml_tensor * residual = inpL; + hc_pre attn_hc = build_hc_pre(inpL, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, il); + cur = build_norm(attn_hc.cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + cur = build_attention(model, inp_attn, inp_pool, cur, inp_pos, il); + + inpL = build_hc_post(cur, residual, attn_hc.post, il); + cb(inpL, "hc_attn_out", il); + + residual = inpL; + hc_pre ffn_hc = build_hc_pre(inpL, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, il); + cur = build_norm(ffn_hc.cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + if ((uint32_t) il < hparams.n_layer_dense_lead) { + cur = build_ffn(cur, + layer.ffn_up, NULL, NULL, + layer.ffn_gate, NULL, NULL, + layer.ffn_down, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + } else { + cur = build_latent_moe(model, cur, il); + } + + cur = build_norm(cur, layer.ffn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_out", il); + + inpL = build_hc_post(cur, residual, ffn_hc.post, il); + cb(inpL, "l_out", il); + } + + // prune the output rows after all streams, or after the nextn state when it needs every row + if (crop_before_nextn(inp_out_ids)) { + ggml_tensor * flat = ggml_reshape_2d(ctx0, inpL, n_embd * hc, n_tokens); + flat = ggml_get_rows(ctx0, flat, inp_out_ids); + inpL = ggml_reshape_3d(ctx0, flat, n_embd, hc, n_outputs); + } + + cur = build_hc_head(inpL, model.hc_head_fn, model.hc_head_scale, model.hc_head_base); + cb(cur, "hc_head", -1); + + cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + + // the draft block reads this state through its hnorm + cb(cur, "h_nextn", -1); + res->t_h_nextn = cur; + + if (crop_after_nextn(inp_out_ids)) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + diff --git a/src/models/models.h b/src/models/models.h index d61469120f42..9f8e7cdcb65c 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2469,6 +2469,100 @@ struct llama_model_hy_v4 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +// hy_v4 iHC, gated MLA and sinks, with sparse and sliding-window layers, sandwich norms and latent routed experts +struct llama_model_hy_v4_flash : public llama_model_base { + llama_model_hy_v4_flash(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } + + // -1 when the layer has no Engram module, else its index among the Engram layers + int engram_index(int il) const; + + // n-gram hash of module e: one row id and one validity per (token, column) + void engram_hash(int e, const llama_ubatch & ubatch, const std::vector & prev, + std::vector & ids, std::vector & valid) const; + + class llm_graph_input_pool; + + struct graph : public llm_graph_context { + graph(const llama_model & model, const llm_graph_params & params); + + // iHC, same layout as hy_v4 + struct hc_pre { + ggml_tensor * cur; + ggml_tensor * post; + }; + + // reduce the hc streams to one, weighted by the pre gates + ggml_tensor * build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const; + + hc_pre build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const; + + ggml_tensor * build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const; + + ggml_tensor * build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const; + + ggml_tensor * build_attention( + const llama_model & model, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * cur, + ggml_tensor * inp_pos, + int il); + + llm_graph_input_pool * build_inp_pool(llm_graph_input_attn_k_dsa_iswa * inp_attn); + + // rotate only the trailing n_rot of each indexer head + ggml_tensor * build_indexer_rope(ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, + float freq_base, int il) const; + + // the kq_mask of the sparse layer, opened on the best scored pools plus the token's own pool + ggml_tensor * build_pool_select( + ggml_tensor * cur, + ggml_tensor * qr, + ggml_tensor * inp_pos, + float freq_base, + const llama_layer & layer, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * kq_mask, + int il); + + // routed experts run at n_expert_latent, the router and the shared expert at n_embd + ggml_tensor * build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const; + + // Engram adds its delta to the hc streams before the attention + ggml_tensor * build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const; + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + struct llama_model_hunyuan_vl : public llama_model_base { llama_model_hunyuan_vl(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 2a4f4b36192c..5b7ea18685c4 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -157,6 +157,9 @@ hy_v4 ,0 ,any ,MUL+ADD , 2 hy_v4 ,0 ,any ,NORM+MUL+ADD , 1 hy_v4 ,0 ,any ,RMS_NORM+MUL , 9 hy_v4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 +hy_v4_flash ,0 ,any ,MUL+ADD , 6 +hy_v4_flash ,0 ,any ,RMS_NORM+MUL , 32 +hy_v4_flash ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3 inkling2 ,0 ,any ,MUL+ADD , 6 inkling2 ,0 ,any ,RMS_NORM+MUL , 10 inkling2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index d0deb9109b68..098350f9f5a7 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14283,7 +14283,7 @@ static std::vector> make_test_cases_eval() { // lightning_indexer for (int kv : { 256 }) { for (int bs : { 1, 512 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (auto [ns, nm] : { std::pair{1, 1}, std::pair{4, 4}, std::pair{4, 1} }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, nm, type_K)); @@ -14962,7 +14962,7 @@ static std::vector> make_test_cases_perf() { // lightning_indexer for (int kv : { 256, 4096, 65536 }) { for (int bs : { 1, 512, 2048 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (int ns : { 1, 4 }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, ns, type_K)); diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 6faa8843decd..a7deed9f73d8 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -303,6 +303,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_XING4_0) { n_embd = 128; n_head = 1; @@ -310,6 +311,9 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (arch == LLM_ARCH_MISTRAL_LARGE4) { n_layer = 4; // cover NoPE, shared indexer and KV sharing layers } + if (arch == LLM_ARCH_HY_V4_FLASH) { + n_layer = 4; // dense + MoE across both sparse and sliding attention layers + } } else if (arch == LLM_ARCH_GLM5_NEXT) { // several heads so that -sm tensor can split them and the MLA flash attention has GQA > 1 n_embd = 128; @@ -382,13 +386,16 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE || arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 || arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 || - arch == LLM_ARCH_GLM5_NEXT + arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH ) { GGML_ASSERT(n_layer >= 2); std::vector n_head_per_layer; n_head_per_layer.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { - n_head_per_layer.push_back(il == 1 ? 0 : n_head); + // hy_v4_flash: the odd layers are sliding-window, with twice the heads + n_head_per_layer.push_back(arch == LLM_ARCH_HY_V4_FLASH + ? (il % 2 ? 2*n_head : n_head) + : (il == 1 ? 0 : n_head)); } // GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer. if (arch == LLM_ARCH_GLM5_NEXT) { @@ -400,7 +407,12 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const } else { ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head_per_layer); } - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); + if (arch == LLM_ARCH_HY_V4_FLASH) { + // MLA-as-MQA: one latent KV head on every layer, whatever the query head count + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, uint32_t(1)); + } else { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); + } } else if (arch == LLM_ARCH_METIS16) { // the layer types repeat in every pass std::vector n_head_kv_per_layer; @@ -430,6 +442,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_KIMI_K31 || arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_XING4_0) { @@ -496,7 +509,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE) { + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE || + arch == LLM_ARCH_HY_V4_FLASH) { std::vector pattern; pattern.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { @@ -586,6 +600,9 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const // summing to n_rot / 2 (n_rot is 64 in this fixture) if (arch == LLM_ARCH_BAILINGMOE3) { ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({8, 12, 12, 0})); + } else if (arch == LLM_ARCH_HY_V4_FLASH) { + // the published files carry the VL sections, so the text model runs the M-RoPE path + ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({12, 10, 10, 0})); } else { ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({n_embd_head/4, n_embd_head/4, n_embd_head/4, n_embd_head/4})); } @@ -606,6 +623,53 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); } + if (arch == LLM_ARCH_HY_V4_FLASH) { + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + // the indexer lives on the non-SWA layers, the even ones here + { + std::vector indexer_types; + indexer_types.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + indexer_types.push_back(il % 2 ? 0 : 1); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, uint32_t(96)); + + // one Engram module on layer 1, the head offsets are the running sum of the bucket counts + { + // the loader reads the bucket ranges as u64 arrays + const std::vector primes = {7, 11, 13, 17}; + std::vector offsets; + uint64_t base = 0; + for (uint64_t p : primes) { + offsets.push_back(base); + base += p; + } + ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({1})); + ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, uint32_t(3)); + ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, uint32_t(2)); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, uint32_t(32)); + // n_modules * ngram_size multipliers, odd as the reference derives them + ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({3, 5, 7})); + ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ms.add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, uint32_t(1)); + std::vector token_map(n_vocab); + for (uint32_t t = 0; t < n_vocab; t++) { + token_map[t] = (int32_t) t; + } + ms.add_kv(LLM_KV_ENGRAM_TOKEN_MAP, token_map); + } + } + if (arch == LLM_ARCH_MISTRAL_LARGE4) { // layer 3 reads the KV cache of layer 2, both are NoPE ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, std::vector({1, 1, 0, 0})); @@ -756,7 +820,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (moe) { ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, n_ff); ms.add_kv(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, n_ff / 2); // distinct from n_ff so a saver key-clobber surfaces on reload - ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, n_ff); + // a latent width distinct from n_ff_exp catches a transposed routed_down / routed_up + ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, arch == LLM_ARCH_HY_V4_FLASH ? uint32_t(64) : n_ff); ms.add_kv(LLM_KV_INTERLEAVE_MOE_LAYER_STEP, uint32_t(2)); // with more experts than a ubatch uses, the copy of the used experts in host memory skips some of them ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(host_experts_test(arch) ? 64 : arch == LLM_ARCH_CLOVER_MOE ? 4 : 2)); @@ -1129,6 +1194,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_HUNYUAN_MOE: case LLM_ARCH_HY_V3: case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: case LLM_ARCH_OPENAI_MOE: case LLM_ARCH_LFM2MOE: case LLM_ARCH_SMALLTHINKER: @@ -1219,7 +1285,7 @@ static bool arch_supported(const llm_arch arch) { // FIXME: these hit scheduler/view-backed-output issues with WebGPU on CI. #ifdef GGML_USE_WEBGPU if (arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_QWEN4EXP || - arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { return false; } #endif // GGML_USE_WEBGPU diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index cd9810e6d714..273c5148f418 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -54,6 +54,7 @@ add_library(mtmd models/granite-speech.cpp models/granite4-vision.cpp models/hunyuanvl.cpp + models/hy-v4.cpp models/inkling2v.cpp models/internvl.cpp models/kimivl.cpp diff --git a/tools/mtmd/models/hy-v4.cpp b/tools/mtmd/models/hy-v4.cpp new file mode 100644 index 000000000000..aa8ee8555796 --- /dev/null +++ b/tools/mtmd/models/hy-v4.cpp @@ -0,0 +1,43 @@ +#include "models.h" + +ggml_cgraph * mtmd_graph_hy_v4::build() { + const int merge = hparams.n_merge; + const int pw = n_patches_x; + const int ph = n_patches_y; + + // filled on CPU by mtmd_subcontext::encode(), same as hunyuanvl + ggml_tensor * pos_embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, ph * pw); + ggml_set_name(pos_embd, "hunyuanvl_pos_embd"); + ggml_set_input(pos_embd); + + ggml_tensor * inp = build_inp(); + ggml_tensor * cur = build_vit(inp, n_patches, NORM_TYPE_NORMAL, hparams.ffn_op, pos_embd, nullptr); + + cur = build_norm(cur, model.mm_pre_norm_w, nullptr, NORM_TYPE_RMS, eps, -1); + + // [C, W*H] -> [W, H, C] for conv2d + cur = ggml_reshape_3d(ctx0, cur, n_embd, pw, ph); + cur = ggml_permute(ctx0, cur, 2, 0, 1, 3); + cur = ggml_cont(ctx0, cur); + + cur = ggml_conv_2d(ctx0, model.mm_0_w, cur, merge, merge, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_0_b, 1, 1, model.mm_0_b->ne[0])); + cur = ggml_gelu_erf(ctx0, cur); + cur = ggml_conv_2d(ctx0, model.mm_1_w, cur, 1, 1, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_1_b, 1, 1, model.mm_1_b->ne[0])); + + const int ow = pw / merge; + const int oh = ph / merge; + const int idim = (int)cur->ne[2]; + + ggml_tensor * nl = ggml_reshape_4d(ctx0, model.image_newline, 1, 1, idim, 1); + nl = ggml_repeat_4d(ctx0, nl, 1, oh, idim, 1); + cur = ggml_concat(ctx0, cur, nl, 0); + + // [OW+1, OH, OC] -> [OC, (OW+1)*OH] + cur = ggml_permute(ctx0, cur, 1, 2, 0, 3); + cur = ggml_cont_2d(ctx0, cur, idim, (ow + 1) * oh); + + ggml_build_forward_expand(gf, cur); + return gf; +} diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index c1feef493aab..b47574157090 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -351,6 +351,11 @@ struct mtmd_graph_hunyuanvl : mtmd_graph { ggml_cgraph * build() override; }; +struct mtmd_graph_hy_v4 : mtmd_graph { + mtmd_graph_hy_v4(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} + ggml_cgraph * build() override; +}; + struct mtmd_graph_mobilenetv5 : mtmd_graph { mtmd_graph_mobilenetv5(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} ggml_cgraph * build() override; diff --git a/tools/mtmd/mtmd-graph.cpp b/tools/mtmd/mtmd-graph.cpp index a22f41d372da..576f27b836a0 100644 --- a/tools/mtmd/mtmd-graph.cpp +++ b/tools/mtmd/mtmd-graph.cpp @@ -911,6 +911,10 @@ std::unique_ptr mtmd_get_graph_builder(mtmd_subcontext * ctx, const { builder = std::make_unique(ctx, img); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + builder = std::make_unique(ctx, img); + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_LDP: diff --git a/tools/mtmd/mtmd-impl.h b/tools/mtmd/mtmd-impl.h index 12bc9728da53..d6b32fae4f8b 100644 --- a/tools/mtmd/mtmd-impl.h +++ b/tools/mtmd/mtmd-impl.h @@ -598,6 +598,7 @@ enum projector_type { PROJECTOR_TYPE_NEMOTRON_V2_VL, PROJECTOR_TYPE_NEMOTRON_OMNI, PROJECTOR_TYPE_HUNYUANVL, + PROJECTOR_TYPE_HY_V4_FLASH, PROJECTOR_TYPE_PARAKEET, PROJECTOR_TYPE_EXAONE4_5, PROJECTOR_TYPE_MINICPMV4_6, @@ -701,6 +702,7 @@ static std::map PROJECTOR_TYPE_NAMES = { { PROJECTOR_TYPE_NEMOTRON_OMNI, "nemotron_omni"}, { PROJECTOR_TYPE_EXAONE4_5, "exaone4_5"}, { PROJECTOR_TYPE_HUNYUANVL, "hunyuanvl"}, + { PROJECTOR_TYPE_HY_V4_FLASH, "hy_v4_flash"}, { PROJECTOR_TYPE_MINICPMV4_6, "minicpmv4_6"}, { PROJECTOR_TYPE_MINICPMV4_7, "minicpmv4_7"}, { PROJECTOR_TYPE_MINICPM_OCR_1_0, "minicpm_ocr_1_0"}, diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 97dc47598ccc..508dfbe94d81 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1263,6 +1263,23 @@ struct mtmd_model_loader { get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); hparams.set_warmup_n_tokens(32*32); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + hparams.n_merge = 2; + hparams.set_image_resize_algo(RESIZE_ALGO_BICUBIC, true); // HF processor replaces lanczos with bicubic + hparams.image_round_half_even = true; + hparams.image_resize_pad = PAD_NONE; + hparams.ffn_op = FFN_GELU; // tanh gelu (bias_activation_fusion) + log_ffn_op = "gelu"; + get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false); + if (hparams.n_merge == 0) { + throw std::runtime_error(mtmd_format("%s: spatial_merge_size must be > 0\n", __func__)); + } + hparams.set_limit_image_tokens(4, 4096); + get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels, false); + get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); + hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup + } break; case PROJECTOR_TYPE_LFM2A: case PROJECTOR_TYPE_D1OMNI_A: { @@ -3885,8 +3902,21 @@ struct mtmd_model_loader { model.image_newline = get_tensor(TN_IMAGE_NEWLINE); model.view_seperator = get_tensor(TN_IMAGE_SEPERATOR, false); // the position embedding is resampled on the host as F32 - if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32) { - throw std::runtime_error(mtmd_format("%s: HunyuanVL requires an F32 %s\n", __func__, mtmd_format(TN_POS_EMBD, prefix).c_str())); + if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32 || !ggml_is_matrix(model.position_embeddings) || model.position_embeddings->ne[0] != hparams.n_embd) { + throw std::runtime_error(mtmd_format("%s: HunyuanVL requires a 2D F32 %s\n", __func__, mtmd_format(TN_POS_EMBD, prefix).c_str())); + } + } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + model.mm_0_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "weight")); + model.mm_0_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "bias")); + model.mm_1_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "weight")); + model.mm_1_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "bias")); + model.mm_pre_norm_w = get_tensor(mtmd_format(TN_MM_PRE_NORM, "weight")); + model.image_newline = get_tensor(TN_IMAGE_NEWLINE); + if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32 || !ggml_is_matrix(model.position_embeddings) || model.position_embeddings->ne[0] != hparams.n_embd) { + throw std::runtime_error(mtmd_format("%s: %s requires a 2D F32 %s\n", __func__, + PROJECTOR_TYPE_NAMES[model.proj_type].c_str(), mtmd_format(TN_POS_EMBD, prefix).c_str())); } } break; case PROJECTOR_TYPE_JANUS_PRO: @@ -4690,6 +4720,8 @@ int mtmd_model::n_output_tokens_x(const mtmd_image_f32 * img) const { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->nx() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + return (img->nx() / params.patch_size) / params.n_merge + 1; // +1 for newline case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4725,6 +4757,8 @@ int mtmd_model::n_output_tokens_y(const mtmd_image_f32 * img) const { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->ny() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + return (img->ny() / params.patch_size) / params.n_merge; case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4998,6 +5032,13 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { int oh = (img->ny() / patch_size) / merge; n_patches = (ow + 1) * oh + 2; } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + int merge = hparams.n_merge; + int ow = (img->nx() / patch_size) / merge; + int oh = (img->ny() / patch_size) / merge; + n_patches = (ow + 1) * oh; + } break; case PROJECTOR_TYPE_DEEPSEEKOCR2: { // 1024 global view -> 256 query tokens + 1 view separator = 257; @@ -5245,6 +5286,8 @@ int mtmd_model::n_mmproj_embd() const { return mm_2_w->ne[1]; case PROJECTOR_TYPE_HUNYUANVL: return mm_model_proj->ne[1]; + case PROJECTOR_TYPE_HY_V4_FLASH: + return mm_1_w->ne[3]; case PROJECTOR_TYPE_COGVLM: return mm_4h_to_h_w->ne[1]; case PROJECTOR_TYPE_DEEPSEEKOCR: diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp index 078f154c7939..640950c5c832 100644 --- a/tools/mtmd/mtmd-subcontext.cpp +++ b/tools/mtmd/mtmd-subcontext.cpp @@ -2111,13 +2111,12 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } } break; case PROJECTOR_TYPE_HUNYUANVL: + case PROJECTOR_TYPE_HY_V4_FLASH: { - // Compute the HunyuanVL 2D position embedding on CPU (with the - // custom sf=(target+0.1)/n_grid bilinear sampling that the - // reference implementation uses) and upload it to the graph - // input declared in mtmd_graph_hunyuanvl::build(). + // resize position embedding on CPU, using bilinear with sf=(target+0.1)/n_grid GGML_ASSERT(model.position_embeddings != nullptr); ggml_tensor * src_t = model.position_embeddings; + GGML_ASSERT(ggml_is_matrix(src_t) && src_t->type == GGML_TYPE_F32); const int64_t n_embd = src_t->ne[0]; const int64_t n_pos = src_t->ne[1]; // = n_grid * n_grid const int n_grid = (int)std::lround(std::sqrt((double)n_pos)); diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index fdac762ac98c..e99d25792acc 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -1392,6 +1392,15 @@ struct mtmd_context { img_end = "<|hy_place▁holder▁no▁101|>"; image_preproc = std::make_unique(models.v.get()); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + if (text_model && pos_type != MTMD_POS_TYPE_MROPE) { + throw std::runtime_error("the hy_v4_flash projector needs a text model with M-RoPE rope sections"); + } + img_beg = "<|hy_image▁start:opensource|>"; + img_end = "<|hy_image▁end:opensource|>"; + image_preproc = std::make_unique(models.v.get()); + } break; case PROJECTOR_TYPE_EXAONE4_5: { // ... (image embeddings) ... From 94a1e4b722d4bff82a0319230682cb54e29ea4e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20G=C3=A4=C3=9Fler?= Date: Wed, 25 Nov 2026 18:47:26 +0100 Subject: [PATCH 02/47] CUDA: refactor & deduplicate FA data loading (#32901) * CUDA: refactor & deduplicate FA data loading * fix float2 indexing * fix hip quality check --- ggml/cmake/common.cmake | 10 +- ggml/src/ggml-cuda/CMakeLists.txt | 6 +- ggml/src/ggml-cuda/cp-async.cuh | 2 + ggml/src/ggml-cuda/fattn-common.cuh | 317 ++++++++++++-- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 400 +++++++----------- ggml/src/ggml-cuda/fattn-tile.cu | 42 +- ggml/src/ggml-cuda/fattn-tile.cuh | 312 +++++--------- ggml/src/ggml-cuda/fattn-vec.cuh | 92 ++-- ggml/src/ggml-cuda/fattn.cu | 117 ++--- ...f16-instance-f16-f16-ncols1_1-ncols2_16.cu | 6 + ...f16-instance-f16-f16-ncols1_1-ncols2_32.cu | 6 + ...-f16-instance-f16-f16-ncols1_1-ncols2_8.cu | 14 + ...f16-instance-f16-f16-ncols1_16-ncols2_1.cu | 12 + ...f16-instance-f16-f16-ncols1_16-ncols2_2.cu | 13 + ...f16-instance-f16-f16-ncols1_16-ncols2_4.cu | 14 + ...f16-instance-f16-f16-ncols1_2-ncols2_16.cu | 6 + ...f16-instance-f16-f16-ncols1_2-ncols2_32.cu | 6 + ...-f16-instance-f16-f16-ncols1_2-ncols2_4.cu | 14 + ...-f16-instance-f16-f16-ncols1_2-ncols2_8.cu | 14 + ...f16-instance-f16-f16-ncols1_32-ncols2_1.cu | 12 + ...f16-instance-f16-f16-ncols1_32-ncols2_2.cu | 13 + ...f16-instance-f16-f16-ncols1_4-ncols2_16.cu | 6 + ...-f16-instance-f16-f16-ncols1_4-ncols2_2.cu | 13 + ...-f16-instance-f16-f16-ncols1_4-ncols2_4.cu | 14 + ...-f16-instance-f16-f16-ncols1_4-ncols2_8.cu | 14 + ...f16-instance-f16-f16-ncols1_64-ncols2_1.cu | 12 + ...-f16-instance-f16-f16-ncols1_8-ncols2_1.cu | 12 + ...-f16-instance-f16-f16-ncols1_8-ncols2_2.cu | 13 + ...-f16-instance-f16-f16-ncols1_8-ncols2_4.cu | 14 + ...-f16-instance-f16-f16-ncols1_8-ncols2_8.cu | 14 + ...ttn-mma-f16-instance-ncols1_1-ncols2_16.cu | 6 - ...ttn-mma-f16-instance-ncols1_1-ncols2_32.cu | 6 - ...attn-mma-f16-instance-ncols1_1-ncols2_8.cu | 14 - ...ttn-mma-f16-instance-ncols1_16-ncols2_1.cu | 12 - ...ttn-mma-f16-instance-ncols1_16-ncols2_2.cu | 13 - ...ttn-mma-f16-instance-ncols1_16-ncols2_4.cu | 14 - ...ttn-mma-f16-instance-ncols1_2-ncols2_16.cu | 6 - ...ttn-mma-f16-instance-ncols1_2-ncols2_32.cu | 6 - ...attn-mma-f16-instance-ncols1_2-ncols2_4.cu | 14 - ...attn-mma-f16-instance-ncols1_2-ncols2_8.cu | 14 - ...ttn-mma-f16-instance-ncols1_32-ncols2_1.cu | 12 - ...ttn-mma-f16-instance-ncols1_32-ncols2_2.cu | 13 - ...ttn-mma-f16-instance-ncols1_4-ncols2_16.cu | 6 - ...attn-mma-f16-instance-ncols1_4-ncols2_2.cu | 13 - ...attn-mma-f16-instance-ncols1_4-ncols2_4.cu | 14 - ...attn-mma-f16-instance-ncols1_4-ncols2_8.cu | 14 - ...ttn-mma-f16-instance-ncols1_64-ncols2_1.cu | 12 - ...attn-mma-f16-instance-ncols1_8-ncols2_1.cu | 12 - ...attn-mma-f16-instance-ncols1_8-ncols2_2.cu | 13 - ...attn-mma-f16-instance-ncols1_8-ncols2_4.cu | 14 - ...attn-mma-f16-instance-ncols1_8-ncols2_8.cu | 14 - .../fattn-tile-instance-dkq320-dv256.cu | 5 - .../fattn-tile-instance-dkq40-dv40.cu | 5 - .../fattn-tile-instance-dkq512-dv512.cu | 5 - .../fattn-tile-instance-dkq576-dv512.cu | 5 - .../fattn-tile-instance-dkq64-dv64.cu | 5 - .../fattn-tile-instance-dkq72-dv72.cu | 5 - .../fattn-tile-instance-dkq80-dv80.cu | 5 - .../fattn-tile-instance-dkq96-dv96.cu | 5 - ...attn-tile-instance-f16-f16-dkq112-dv112.cu | 5 + ...attn-tile-instance-f16-f16-dkq128-dv128.cu | 5 + ...attn-tile-instance-f16-f16-dkq192-dv128.cu | 5 + ...attn-tile-instance-f16-f16-dkq256-dv256.cu | 5 + ...attn-tile-instance-f16-f16-dkq320-dv256.cu | 5 + ...fattn-tile-instance-f16-f16-dkq40-dv40.cu} | 2 +- ...attn-tile-instance-f16-f16-dkq512-dv512.cu | 5 + ...attn-tile-instance-f16-f16-dkq576-dv512.cu | 5 + ...fattn-tile-instance-f16-f16-dkq64-dv64.cu} | 2 +- ...fattn-tile-instance-f16-f16-dkq72-dv72.cu} | 2 +- ...fattn-tile-instance-f16-f16-dkq80-dv80.cu} | 2 +- .../fattn-tile-instance-f16-f16-dkq96-dv96.cu | 5 + .../template-instances/generate_cu_files.py | 63 +-- ggml/src/ggml-hip/CMakeLists.txt | 6 +- ggml/src/ggml-musa/CMakeLists.txt | 6 +- scripts/hip/gcn-cdna-vgpr-check.py | 44 +- 75 files changed, 1054 insertions(+), 935 deletions(-) create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu delete mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu rename ggml/src/ggml-cuda/template-instances/{fattn-tile-instance-dkq112-dv112.cu => fattn-tile-instance-f16-f16-dkq40-dv40.cu} (65%) create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu rename ggml/src/ggml-cuda/template-instances/{fattn-tile-instance-dkq128-dv128.cu => fattn-tile-instance-f16-f16-dkq64-dv64.cu} (65%) rename ggml/src/ggml-cuda/template-instances/{fattn-tile-instance-dkq192-dv128.cu => fattn-tile-instance-f16-f16-dkq72-dv72.cu} (65%) rename ggml/src/ggml-cuda/template-instances/{fattn-tile-instance-dkq256-dv256.cu => fattn-tile-instance-f16-f16-dkq80-dv80.cu} (65%) create mode 100644 ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu diff --git a/ggml/cmake/common.cmake b/ggml/cmake/common.cmake index c8d232294740..39c1fbb48982 100644 --- a/ggml/cmake/common.cmake +++ b/ggml/cmake/common.cmake @@ -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) diff --git a/ggml/src/ggml-cuda/CMakeLists.txt b/ggml/src/ggml-cuda/CMakeLists.txt index dcb380535336..00d1156196c5 100644 --- a/ggml/src/ggml-cuda/CMakeLists.txt +++ b/ggml/src/ggml-cuda/CMakeLists.txt @@ -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 diff --git a/ggml/src/ggml-cuda/cp-async.cuh b/ggml/src/ggml-cuda/cp-async.cuh index 1071352e7b94..bbef1c7d303d 100644 --- a/ggml/src/ggml-cuda/cp-async.cuh +++ b/ggml/src/ggml-cuda/cp-async.cuh @@ -1,3 +1,5 @@ +#pragma once + // Simplified API for asynchronous data loading. #include "common.cuh" diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index fc0cc7403910..59fd16abdf36 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -2,6 +2,8 @@ #include "common.cuh" #include "convert.cuh" +#include "cp-async.cuh" +#include "mma.cuh" #include "vecdotq.cuh" #include @@ -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 +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 +struct flash_attn_load_tile_impl; + +template +struct flash_attn_load_tile_impl { + 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(offset, i); + } + + cp_async_cg_16(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +struct flash_attn_load_tile_impl { + 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(tile_KV, i*stride_tile + k*cpy_ne, i); + } else { + dst = tile_KV + i*stride_tile + k*cpy_ne; + } + + ggml_cuda_memcpy_1(dst, src); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +struct flash_attn_load_tile_impl { + 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(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(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +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::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 +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 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 +template 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()); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index dea8d2ad35ec..5c7a37fb8f0e 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages( // ------------------------------------------------------------------------------------------------------------------ -template -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(tile_KV_32 + swizzle(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(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 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 + 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 + flash_attn_load_tile (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 + flash_attn_load_tile (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 (mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); } - flash_attn_ext_f16_load_tile + flash_attn_load_tile (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 + flash_attn_load_tile (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 struct mma_tile_sizes { }; #endif // defined(TURING_MMA_AVAILABLE) -template +template 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 (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); } - flash_attn_ext_f16_load_tile + flash_attn_load_tile (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 + 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 + 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 + 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 + 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 + 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 + 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 +template __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()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + + 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 + flash_attn_ext_f16_process_tile (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 + flash_attn_ext_f16_process_tile (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 + flash_attn_ext_f16_process_tile (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 +template 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()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + 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; + fattn_kernel = flash_attn_ext_f16; 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; + fattn_kernel = flash_attn_ext_f16; 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; + fattn_kernel = flash_attn_ext_f16; 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; + fattn_kernel = flash_attn_ext_f16; 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 + launch_fattn (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 \ - (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); \ - -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, 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, 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, 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) - -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); +#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \ + template void ggml_cuda_flash_attn_ext_mma_f16_case \ + (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ + +#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, 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, 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, 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, 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, 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); diff --git a/ggml/src/ggml-cuda/fattn-tile.cu b/ggml/src/ggml-cuda/fattn-tile.cu index accef6315a1b..42b488aca0e7 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cu +++ b/ggml/src/ggml-cuda/fattn-tile.cu @@ -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 +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(ctx, dst); + return; + } + } + + // Fallback: convert K and V to F16. + ggml_cuda_flash_attn_ext_tile_switch_head_size(ctx, dst); +} diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 177b2f0653bf..d15c6c884d8f 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -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 -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( - 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 -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( - 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(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 + 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 - (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 ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne; + flash_attn_load_tile + (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 + 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 ? DV/2 : DV; #pragma unroll for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { - flash_attn_tile_load_tile - (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); + flash_attn_load_tile + (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 // D == head size +template // 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()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + + 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 - (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 +template static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + using T_K = decltype(ggml_cuda_fattn_kv_dtype()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + 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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (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 +template 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(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } #else if (use_gqa_opt && gqa_ratio % 16 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(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(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(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(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 8 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(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(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 2 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if constexpr (DV <= 256) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } } GGML_ABORT("fatal error"); } -template +template 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(ctx, dst); + launch_fattn_tile_switch_ncols2(ctx, dst); } else { constexpr bool use_logit_softcap = true; - launch_fattn_tile_switch_ncols2(ctx, dst); + launch_fattn_tile_switch_ncols2(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 \ - (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); +#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \ + template void ggml_cuda_flash_attn_ext_tile_case \ + (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ + +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); diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 09a46187d105..978a2a038e32 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -19,15 +19,15 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { template // 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(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(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false); + launch_fattn(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false); } template diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index b37065c31dfb..d1cdcd856beb 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -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 +template 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(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(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(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } } if constexpr (ncols2 <= 16) { if (Q->ne[1] <= 16/ncols2) { - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(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(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); } -template +template 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(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if constexpr (DKQ <= 256) { if (use_gqa_opt && gqa_ratio % 2 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(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(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 2 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } } if (use_gqa_opt && gqa_ratio > 4) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio > 2) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio > 1) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if constexpr (DKQ <= 256) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(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 +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(ctx, dst); + return; + } + } + + // Fallback: convert K and V to F16. + ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(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) { \ diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu new file mode 100644 index 000000000000..fcf4114149c6 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu new file mode 100644 index 000000000000..083f5d1b8342 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu new file mode 100644 index 000000000000..6adcac083f40 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu new file mode 100644 index 000000000000..a7ed494a8cb7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu new file mode 100644 index 000000000000..e8b55046a23f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu new file mode 100644 index 000000000000..53cf952b1108 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu new file mode 100644 index 000000000000..23f4a9a5be25 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu new file mode 100644 index 000000000000..040a3224e434 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu new file mode 100644 index 000000000000..ffb774fe866f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu new file mode 100644 index 000000000000..02e48cc4043e --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu new file mode 100644 index 000000000000..68e71304d060 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu new file mode 100644 index 000000000000..857ccd4207b2 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu new file mode 100644 index 000000000000..c7125f78aad1 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu new file mode 100644 index 000000000000..d88c45377e48 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu new file mode 100644 index 000000000000..bbd1dd361aad --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu new file mode 100644 index 000000000000..8c233b5f12e7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu new file mode 100644 index 000000000000..daf4ca890257 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu new file mode 100644 index 000000000000..1459810148c9 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu new file mode 100644 index 000000000000..4ec32c1347a5 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu new file mode 100644 index 000000000000..415ecfa9fc6c --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu new file mode 100644 index 000000000000..ed37e9d38e80 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu deleted file mode 100644 index b2661b931624..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu deleted file mode 100644 index 8fc3b17976e7..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu deleted file mode 100644 index 3c861c2c0912..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu deleted file mode 100644 index 86501536489e..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu deleted file mode 100644 index 8cf304825901..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu deleted file mode 100644 index 51c91c2044b6..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu deleted file mode 100644 index fd41e71b1421..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu deleted file mode 100644 index abd2b21ce044..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu deleted file mode 100644 index b6f99eb72e52..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu deleted file mode 100644 index 14c120243035..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu deleted file mode 100644 index dbc58be55e54..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu deleted file mode 100644 index 784a1f919506..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu deleted file mode 100644 index cc41fa52f135..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu deleted file mode 100644 index 7ace51905334..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu deleted file mode 100644 index f27640e84efc..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu deleted file mode 100644 index 28a961b6b9b9..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu deleted file mode 100644 index 1ad67c0d8f3f..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu deleted file mode 100644 index 695782ca4be0..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu deleted file mode 100644 index de265981544e..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu deleted file mode 100644 index 9d9c748aef71..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu deleted file mode 100644 index 50f17f2f8d0d..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu deleted file mode 100644 index c91f508079d5..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu deleted file mode 100644 index 10b330fa6c03..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu deleted file mode 100644 index 7c61d8d2ecdb..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu deleted file mode 100644 index 254b7d2e1dc2..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu deleted file mode 100644 index 5caffac0467d..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu deleted file mode 100644 index 8f9d5315f2ac..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu deleted file mode 100644 index 90abb3b18626..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu deleted file mode 100644 index 7292c0aab8f9..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu +++ /dev/null @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu new file mode 100644 index 000000000000..ba680fa3c1ec --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu new file mode 100644 index 000000000000..640f4b034cf4 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu new file mode 100644 index 000000000000..425987914cee --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu new file mode 100644 index 000000000000..a828dc7e37ce --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu new file mode 100644 index 000000000000..138f7808468f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu index a8b15ad72a91..1346495d84f9 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu new file mode 100644 index 000000000000..79d63707614a --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu new file mode 100644 index 000000000000..2fa684e1d2bd --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu index 1da18105508a..f070f7b578a8 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu index b571cca0df23..881236ecd564 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu index bc65c723eca9..0a21116421e3 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu new file mode 100644 index 000000000000..05d4bd1712f7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu @@ -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); diff --git a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py index f49a015ae1f5..eeabf416328d 100755 --- a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py +++ b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py @@ -10,11 +10,13 @@ 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_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 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): +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 - 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)) + 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, + 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: diff --git a/ggml/src/ggml-hip/CMakeLists.txt b/ggml/src/ggml-hip/CMakeLists.txt index 35a898e23091..7d9b71d1cb1c 100644 --- a/ggml/src/ggml-hip/CMakeLists.txt +++ b/ggml/src/ggml-hip/CMakeLists.txt @@ -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 diff --git a/ggml/src/ggml-musa/CMakeLists.txt b/ggml/src/ggml-musa/CMakeLists.txt index 721621a1d815..c48fb8106a81 100644 --- a/ggml/src/ggml-musa/CMakeLists.txt +++ b/ggml/src/ggml-musa/CMakeLists.txt @@ -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) diff --git a/scripts/hip/gcn-cdna-vgpr-check.py b/scripts/hip/gcn-cdna-vgpr-check.py index d6a7fc45009d..fab76967baff 100644 --- a/scripts/hip/gcn-cdna-vgpr-check.py +++ b/scripts/hip/gcn-cdna-vgpr-check.py @@ -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', } From 2d5b3ddde360cbcefc641cc46cd9e00d700f277a Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Wed, 25 Nov 2026 19:01:27 +0100 Subject: [PATCH 03/47] model: use the indexed bias in the Inkling 2 graph (#33053) * use the indexed bias in the Inkling 2 graph * Remove RPC check --- src/llama-graph.cpp | 60 ++++++++++++++++++++++++++++------------- src/llama-graph.h | 7 ++--- src/models/inkling2.cpp | 15 +---------- src/models/models.h | 1 - 4 files changed, 46 insertions(+), 37 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 9213d2a0edf0..a96577f11cef 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3148,7 +3148,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + ggml_tensor * bias_table, + ggml_tensor * bias_indices) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3163,12 +3165,28 @@ ggml_tensor * llm_graph_context::build_attn_mha( k = ggml_permute(ctx0, k, 0, 2, 1, 3); v = ggml_permute(ctx0, v, 0, 2, 1, 3); + auto dense_bias_mask = [&]() { + ggml_tensor * table = ggml_cont(ctx0, ggml_permute(ctx0, bias_table, 1, 0, 2, 3)); + ggml_tensor * bias = ggml_get_rows(ctx0, table, bias_indices); + bias = ggml_reshape_4d(ctx0, bias, q->ne[2], bias_indices->ne[0], q->ne[1], n_stream); + bias = ggml_cont(ctx0, ggml_permute(ctx0, bias, 2, 0, 1, 3)); + cb(bias, "kq_b", il); + + ggml_tensor * mask = kq_mask->type == GGML_TYPE_F32 ? kq_mask : ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + mask = ggml_add(ctx0, bias, mask); + if (cparams.flash_attn) { + mask = ggml_cast(ctx0, mask, GGML_TYPE_F16); + } + cb(mask, "kq_mask_rel_pos", il); + return mask; + }; + ggml_tensor * cur; const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; GGML_ASSERT(use_flash_attn || kv_rows == nullptr); if (use_flash_attn) { - GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); + GGML_ASSERT(kq_b == nullptr && "Flash attention does not support dense KQ bias"); if (v_trans) { v = ggml_transpose(ctx0, v); @@ -3197,6 +3215,16 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); + if (bias_table) { + ggml_flash_attn_ext_add_indexed_bias(cur, bias_table, bias_indices); + auto * dev = model.dev_layer(il); + if ((!cparams.offload_kqv && ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_CPU) || !ggml_backend_dev_supports_op(dev, cur)) { + // Keep ordinary flash attention on the layer device. + ggml_flash_attn_ext_add_indexed_bias(cur, nullptr, nullptr); + cur->src[3] = dense_bias_mask(); + } + } + if (v_mla) { #if 0 // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. @@ -3216,6 +3244,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); } else { + if (bias_table) { + kq_mask = dense_bias_mask(); + } ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); cb(kq, "kq", il); @@ -3725,7 +3756,9 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il) { + int il, + ggml_tensor * bias_table = nullptr, + ggml_tensor * bias_indices = nullptr) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3791,7 +3824,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4454,7 +4487,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * q_cur, ggml_tensor * k_cur, ggml_tensor * v_cur, - ggml_tensor * kq_b, + ggml_tensor * bias_table, ggml_tensor * sinks, float kq_scale, int il) const { @@ -4464,22 +4497,11 @@ ggml_tensor * llm_graph_context::build_attn( const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; - // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, - // needs a kv_rows flash attention with a per-head mask (CUDA has none) GGML_ASSERT(attn_mask.rows == nullptr); + ggml_tensor * indices = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 - ggml_tensor * kq_mask = attn_mask.raw; - if (kq_mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); - } - kq_mask = ggml_add(ctx0, kq_b, kq_mask); - if (cparams.flash_attn) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); - } - cb(kq_mask, "kq_mask_rel_pos", il); - - return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, nullptr, + sinks, nullptr, kq_scale, il, bias_table, indices); } void llm_graph_context::build_dense_out( diff --git a/src/llama-graph.h b/src/llama-graph.h index ff155f14d2f6..508d05531531 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1349,7 +1349,9 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + ggml_tensor * bias_table = nullptr, // [n_bins, n_head_q, n_tokens] + ggml_tensor * bias_indices = nullptr) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1547,7 +1549,6 @@ struct llm_graph_context { uint32_t extent, uint32_t extent_swa) const; - // kq_b is added to the KQ mask, after the KQ scale ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, @@ -1556,7 +1557,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * bias_table, // [n_bins, n_head_q, n_tokens] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index bdd1f18d67ed..d5834717bf33 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -266,7 +266,6 @@ ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tenso ggml_tensor * llama_model_inkling2::graph::build_inputs() { inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); - attn = inp->get_attn(); recr = inp->get_recr(); ggml_tensor * inp_pos = build_inp_pos(); @@ -363,24 +362,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - - const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; - const int64_t n_kv = rel_pos->ne[0]; - ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - - ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); - cb(kq_b, "kq_b", il); // one zero tensor per head count for the whole graph ggml_tensor *& zero = zero_sinks[n_head]; @@ -391,7 +378,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cur = build_attn(inp, nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + Qcur, Kcur, Vcur, table, sinks, 1.0f/sqrtf(n_embd_head), il); cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); diff --git a/src/models/models.h b/src/models/models.h index 9f8e7cdcb65c..dbf5f977acb4 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2668,7 +2668,6 @@ struct llama_model_inkling2 : public llama_model_base { void build_output(ggml_tensor * cur, const std::vector & blocks); llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; - llm_graph_input_attn_kv_iswa * attn = nullptr; llm_graph_input_rs * recr = nullptr; ggml_tensor * inp_out_ids = nullptr; From 5a09582d80600fb5b0a8966e870061bddc8a3732 Mon Sep 17 00:00:00 2001 From: Seohyun Choi Date: Thu, 26 Nov 2026 03:38:12 +0900 Subject: [PATCH 04/47] model : add RAON-1-mini-preview support (#32176) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 (김형환) Co-authored-by: Seohyun Choi Co-authored-by: Piotr Wilkin --- conversion/__init__.py | 1 + conversion/base.py | 3 + conversion/raon1_mini.py | 206 ++++++++ convert_hf_to_gguf_update.py | 1 + gguf-py/gguf/constants.py | 55 ++ gguf-py/gguf/gguf_writer.py | 3 + gguf-py/gguf/tensor_mapping.py | 8 + .../KRAFTON-Raon-1-mini-preview.jinja | 134 +++++ src/llama-arch.cpp | 7 + src/llama-arch.h | 3 + src/llama-context.cpp | 2 +- src/llama-hparams.h | 1 + src/llama-model-saver.cpp | 1 + src/llama-model.cpp | 4 + src/llama-model.h | 2 + src/llama-quant.cpp | 51 +- src/llama-vocab.cpp | 17 + src/llama-vocab.h | 1 + src/models/delta-net-base.cpp | 44 ++ src/models/kimi-k3.cpp | 45 +- src/models/models.h | 52 +- src/models/raon1-mini.cpp | 484 ++++++++++++++++++ src/unicode.cpp | 175 +++++++ tests/fusion/MTL.csv | 5 + tests/test-chat.cpp | 390 ++++++++++++++ tests/test-llama-archs.cpp | 16 +- 26 files changed, 1663 insertions(+), 48 deletions(-) create mode 100644 conversion/raon1_mini.py create mode 100644 models/templates/KRAFTON-Raon-1-mini-preview.jinja create mode 100644 src/models/raon1-mini.cpp diff --git a/conversion/__init__.py b/conversion/__init__.py index 59ea8509415a..6796820109a9 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -308,6 +308,7 @@ "RWForCausalLM": "falcon", "RWKV6Qwen2ForCausalLM": "rwkv", "RWKV7ForCausalLM": "rwkv", + "Raon1MiniForCausalLM": "raon1_mini", "RobertaForSequenceClassification": "bert", "RobertaModel": "bert", "RuGPT3XLForCausalLM": "gpt2", diff --git a/conversion/base.py b/conversion/base.py index 540a66ba5098..f55d8560077d 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -2473,6 +2473,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: 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") diff --git a/conversion/raon1_mini.py b/conversion/raon1_mini.py new file mode 100644 index 000000000000..6a195766b84c --- /dev/null +++ b/conversion/raon1_mini.py @@ -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) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index 91fb418a5f2d..0b623a7b0d26 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -169,6 +169,7 @@ class TOKENIZER_TYPE(IntEnum): {"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 diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index bebc8706775c..15163565d2a4 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -199,6 +199,7 @@ class Attention: 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" @@ -775,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() @@ -978,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) @@ -1804,6 +1807,7 @@ class MODEL_TENSOR(IntEnum): 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", @@ -2005,6 +2009,7 @@ class MODEL_TENSOR(IntEnum): 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 @@ -6976,6 +6981,56 @@ class MODEL_TENSOR(IntEnum): 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, diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index 900aef6141a3..28b481e6526d 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -1053,6 +1053,9 @@ def add_layer_norm_eps(self, value: float) -> None: 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) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c6946d53c4ef..a8e7367c396b 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -719,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 ), @@ -792,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 ), @@ -845,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 ), @@ -1027,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 ), @@ -1289,6 +1293,10 @@ 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", diff --git a/models/templates/KRAFTON-Raon-1-mini-preview.jinja b/models/templates/KRAFTON-Raon-1-mini-preview.jinja new file mode 100644 index 000000000000..eff7831afcc4 --- /dev/null +++ b/models/templates/KRAFTON-Raon-1-mini-preview.jinja @@ -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 %} + {{- '\n' + reasoning_content|trim + '\n\n\n' }} + {%- else %} + {{- '\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\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- 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' }} + {%- for tool in tools %} + {{- '\n' }} + {{- tool | tojson }} + {%- endfor %} + {{- '\n' }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within 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' }} + {%- 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('') and content.endswith('')) %} + {%- 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('') and '' in content %} + {%- set thinking_parts = content.split('', 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\n' + content + '\n' }} + {%- 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 %} + {{- '\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index e14f915570e8..53889e037f9d 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -171,6 +171,7 @@ static const std::map 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" }, @@ -309,6 +310,7 @@ static const std::map 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" }, @@ -703,6 +705,7 @@ static const std::map 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" }, @@ -1146,6 +1149,7 @@ static const std::map 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}}, @@ -1497,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: @@ -1530,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: @@ -1611,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; diff --git a/src/llama-arch.h b/src/llama-arch.h index 9d0ced590549..fedc879bfb9a 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -169,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, @@ -315,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, @@ -710,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 diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 38a37ae75879..aa0b93045b91 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -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; diff --git a/src/llama-hparams.h b/src/llama-hparams.h index b6a373bfe5cf..e87667a7dcbb 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -146,6 +146,7 @@ struct llama_hparams { float f_norm_eps; float f_norm_rms_eps; float f_norm_group_eps; + float f_norm_rms_eps_latent = 0.0f; // RMS norm of the MLA q/kv latents (Raon-1 mini) // post norms use their own epsilon float f_post_norm_eps = 0.0f; diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index 51315fb5cc7d..00b169ef641c 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -268,6 +268,7 @@ void llama_model_saver::add_kv_from_model() { add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps); add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); add_kv(LLM_KV_POST_NORM_EPS, hparams.f_post_norm_eps); + add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent); add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, hparams.f_norm_group_eps); add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, hparams.n_norm_groups); add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_COUNT, hparams.n_value_expert); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index e451b244e219..72ad1b0e3718 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -391,6 +391,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_kimi_k3(params); case LLM_ARCH_KIMI_K31: return new llama_model_kimi_k31(params); + case LLM_ARCH_RAON1_MINI: + return new llama_model_raon1_mini(params); case LLM_ARCH_GLM5_NEXT: return new llama_model_glm5_next(params); case LLM_ARCH_STEP35: @@ -1195,6 +1197,7 @@ const char * llm_type_name(llm_type type) { case LLM_TYPE_21B_A3B: return "21B.A3B"; case LLM_TYPE_24B_A2B: return "24B.A2B"; case LLM_TYPE_26B_A4B: return "26B.A4B"; + case LLM_TYPE_29B_A4B: return "29B.A4B"; case LLM_TYPE_30B_A3B: return "30B.A3B"; case LLM_TYPE_31B_A3_5B: return "31B.A3.5B"; case LLM_TYPE_32B_A9B: return "32B.A9B"; @@ -3892,6 +3895,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_KIMI_LINEAR: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STARCODER: case LLM_ARCH_INKLING2: diff --git a/src/llama-model.h b/src/llama-model.h index 72e5fd6cbd8a..62fbda68ae0b 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -130,6 +130,7 @@ enum llm_type { LLM_TYPE_21B_A3B, // Ernie MoE small LLM_TYPE_24B_A2B, // lfm2moe LLM_TYPE_26B_A4B, // Gemma4 + LLM_TYPE_29B_A4B, // Raon-1 mini LLM_TYPE_30B_A3B, LLM_TYPE_31B_A3_5B, LLM_TYPE_32B_A9B, // Granite4 Hybrid @@ -612,6 +613,7 @@ struct llama_layer { struct ggml_tensor * ssm_f_a = nullptr; struct ggml_tensor * ssm_f_b = nullptr; struct ggml_tensor * ssm_beta = nullptr; + struct ggml_tensor * ssm_rda = nullptr; struct ggml_tensor * ssm_g_a = nullptr; struct ggml_tensor * ssm_g_b = nullptr; struct ggml_tensor * ssm_o_norm = nullptr; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 5381f672a3f7..c1fab892fa1a 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -407,6 +407,15 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name.find("hc_") == std::string::npos; } + // raon1_mini: mHC selectors and small RDA gate projections + if (arch == LLM_ARCH_RAON1_MINI) { + quantize &= name.find("hc_") == std::string::npos; + quantize &= name.find("ssm_f_a.weight") == std::string::npos; + quantize &= name.find("ssm_f_b.weight") == std::string::npos; + quantize &= name.find("ssm_beta.weight") == std::string::npos; + quantize &= name.find("ssm_rda.weight") == std::string::npos; + } + // the decision head of vllm-decision2 is small and computed in F32 if (arch == LLM_ARCH_VLLM_DECISION2) { quantize &= name.compare(0, 9, "decision.") != 0; @@ -500,6 +509,10 @@ static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tenso return fallback_type; } +static double bits_per_weight(ggml_type t) { + return 8.0 * ggml_type_size(t) / ggml_blck_size(t); +} + // select the target tensor type based on tensor category, ftype, and model arch static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype, tensor_category category) { const std::string name = ggml_get_name(tensor); @@ -538,11 +551,19 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } } + // raon1_mini: at Q6_K and Q8_0, where the floors below do not apply, keep the MLA latent projections at source precision: + // quantizing them costs +5.8% mean KL in Q8_0 for 44 MB. --pure and --tensor-type bypass this, as for the floors + if (arch == LLM_ARCH_RAON1_MINI && (ftype == LLAMA_FTYPE_MOSTLY_Q6_K || ftype == LLAMA_FTYPE_MOSTLY_Q8_0) && ( + name.find("attn_kv_a_mqa.weight") != std::string::npos || + name.find("attn_k_b.weight") != std::string::npos || + name.find("attn_v_b.weight") != std::string::npos)) { + return tensor->type; + } + // bumping to q8_0 is preferred since these tensors are not really big // TODO: nemotron 3 super shares ffn_latent and afmoe, bailingmoe3, dots3note, hy-v4, kimi-k3 and laguna share attn_gate. // Widening the guard is likely a win there too, but it changes their files, so it wants a perplexity comparison per architecture first. if (arch == LLM_ARCH_MUSE_SPARK && (category == TENSOR_CATEGORY_FFN_LATENT || category == TENSOR_CATEGORY_ATTENTION_GATE)) { - auto bits_per_weight = [](ggml_type t) { return 8.0 * ggml_type_size(t) / ggml_blck_size(t); }; if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { new_type = GGML_TYPE_Q8_0; } } @@ -724,6 +745,34 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type ++qs.i_ffn_up; } + // raon1_mini: the dense attention projections and the shared expert carry most of the low-bit loss, attn_output and attn_gate most of all + // only raise to a floor, after the counters above are updated, so the rest of the mixture does not change + if (arch == LLM_ARCH_RAON1_MINI && ggml_is_quantized(new_type)) { + const bool k_4_5 = ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || + ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M; + // IQ4_XS/NL and the 1-3 bit K and IQ mixtures (not Q2_0, TQ1_0, TQ2_0 or Q1_0) + const bool low = ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || + ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || + ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M; + ggml_type floor_type = GGML_TYPE_COUNT; + if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT || category == TENSOR_CATEGORY_ATTENTION_GATE) { + floor_type = k_4_5 ? GGML_TYPE_Q8_0 : low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } else if (name.find("attn_q_a.weight") != std::string::npos || name.find("attn_q_b.weight") != std::string::npos || + name.find("attn_k_b.weight") != std::string::npos || name.find("attn_kv_a_mqa.weight") != std::string::npos || + name.find("attn_v_b.weight") != std::string::npos || name.find("_shexp.weight") != std::string::npos) { + floor_type = k_4_5 || low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } else if (category == TENSOR_CATEGORY_ATTENTION_Q || category == TENSOR_CATEGORY_ATTENTION_K || + category == TENSOR_CATEGORY_ATTENTION_V || name.find("ssm_g.weight") != std::string::npos) { + floor_type = k_4_5 ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } + if (floor_type != GGML_TYPE_COUNT && bits_per_weight(new_type) < bits_per_weight(floor_type)) { + new_type = floor_type; + } + } + return new_type; } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 9e83a983ef6a..674daaa23fd7 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -401,6 +401,12 @@ struct llm_tokenizer_bpe : llm_tokenizer { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; + case LLAMA_VOCAB_PRE_TYPE_RAON: + regex_exprs = { + // regex from tokenizer.json (the CJK ranges are literal characters there), matched byte for byte in unicode_regex_split_custom() + " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + }; + break; case LLAMA_VOCAB_PRE_TYPE_QWEN35: regex_exprs = { // original regex from tokenizer.json @@ -685,6 +691,14 @@ struct llm_tokenizer_bpe_session { } } word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode); + } else if (tok_pre == LLAMA_VOCAB_PRE_TYPE_RAON) { + // Raon-1 mini's HF tokenizer applies an NFC normalizer before pre-tokenization. + // TODO: the converter also writes tokenizer.ggml.normalizer.nfc (read for UGM only); gate BPE on that flag once #30708 lands + std::string normalized_text; + for (const uint32_t cpt : unicode_cpts_normalize_nfc(unicode_cpts_from_utf8(text))) { + normalized_text += unicode_cpt_to_utf8(cpt); + } + word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode); } else { word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode); } @@ -2561,6 +2575,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "domyn-edge") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; + } else if (tokenizer_pre == "raon") { + pre_type = LLAMA_VOCAB_PRE_TYPE_RAON; + clean_spaces = false; } else if ( tokenizer_pre == "qwen35") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 425a3236c879..b3e8cd7e18b6 100644 --- a/src/llama-vocab.h +++ b/src/llama-vocab.h @@ -77,6 +77,7 @@ enum llama_vocab_pre_type { LLAMA_VOCAB_PRE_TYPE_SOPRANO = 65, LLAMA_VOCAB_PRE_TYPE_TEKKEN_NUM3 = 66, LLAMA_VOCAB_PRE_TYPE_ZONOS3 = 67, + LLAMA_VOCAB_PRE_TYPE_RAON = 68, }; // HF Metaspace pre-tokenizer prepend_scheme diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index f05bd8c0a2ba..f71e7fddda37 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -80,6 +80,50 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( return conv_input; } +// qkv selects one third of the shared convolution state row: Q, K or V. +ggml_tensor * llm_build_delta_net_base::build_kda_conv1d( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * conv_states_seq, + int64_t qkv, + ggml_tensor * x_proj, + ggml_tensor * conv_w, + int64_t d_conv, + int64_t head_dim, + int64_t n_heads, + int64_t n_seq_tokens, + int64_t n_seqs, + int il) { + const int64_t d_inner = head_dim * n_heads; + const int64_t conv_state_size = (d_conv - 1) * d_inner; + const int64_t n_embd_r_total = 3 * conv_state_size; + + ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); + + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_states_seq, qkv); + } else { + ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_states_seq, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_states_seq), + n_embd_r_total * ggml_element_size(conv_states_seq), + qkv * conv_state_size * ggml_element_size(conv_states_seq)); + + conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } + + ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); + ggml_tensor * conv_out = ggml_ssm_conv(ctx0, conv_x, conv_weight); + conv_out = ggml_reshape_2d(ctx0, conv_out, d_inner, n_tokens); + conv_out = ggml_silu(ctx0, conv_out); + + return ggml_reshape_4d(ctx0, conv_out, head_dim, n_heads, n_seq_tokens, n_seqs); +} + // [TAG_RECURRENT_REPLAY] // rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled // back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp index e0ef7b6cd40a..846a4886618e 100644 --- a/src/models/kimi-k3.cpp +++ b/src/models/kimi-k3.cpp @@ -351,42 +351,6 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) : // KDA layer // -// causal conv1d over one of Q/K/V. `qkv` selects which third of the conv state to use -ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d( - llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, - int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { - const int64_t d_inner = head_dim * n_head_kda; - const int64_t conv_state_size = (d_conv - 1) * d_inner; - const int64_t n_embd_r_total = 3 * conv_state_size; - - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); - ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - - ggml_tensor * conv_x = nullptr; - if (cparams.rs_replay) { - // the row holds the q, k and v conv histories one after the other - conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); - } else { - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - - conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); - } - - ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); - ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); - Xcur = ggml_reshape_2d(ctx0, Xcur, d_inner, n_tokens); - Xcur = ggml_silu(ctx0, Xcur); - - return ggml_reshape_4d(ctx0, Xcur, head_dim, n_head_kda, n_seq_tokens, n_seqs); -} - ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, int64_t d_conv, int64_t head_dim, int64_t n_head_kda, @@ -397,9 +361,12 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, ggml_mul_mat(ctx0, layer.wq, cur), + layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, ggml_mul_mat(ctx0, layer.wk, cur), + layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, ggml_mul_mat(ctx0, layer.wv, cur), + layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/models.h b/src/models/models.h index dbf5f977acb4..85b97dda0963 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -55,6 +55,20 @@ struct llm_build_delta_net_base : public llm_graph_context { int64_t conv_channels, int il); + ggml_tensor * build_kda_conv1d( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * conv_states_seq, + int64_t qkv, + ggml_tensor * x_proj, + ggml_tensor * conv_w, + int64_t d_conv, + int64_t head_dim, + int64_t n_heads, + int64_t n_seq_tokens, + int64_t n_seqs, + int il); + // run delta-net attention and write the new recurrent state(s) back to ssm_states_all // s: (head_v_dim, head_v_dim, num_v_heads, n_seqs); returns output: (head_v_dim, num_v_heads, n_seq_tokens, n_seqs) ggml_tensor * build_recurrent_attn( @@ -3296,11 +3310,6 @@ struct llama_model_kimi_k3 : public llama_model_base { int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t d_inner, int64_t n_seq_tokens, int64_t n_seqs, int il); - // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used - ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, - int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il); - ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, llm_graph_input_attn_kv * inp_attn_kv, @@ -3363,6 +3372,39 @@ struct llama_model_kimi_k31 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +struct llama_model_raon1_mini : public llama_model_base { + llama_model_raon1_mini(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; + + struct graph : public llm_build_delta_net_base { + graph(const llm_graph_params & params); + + ggml_tensor * helmert = nullptr; + ggml_tensor * identity = nullptr; + ggml_tensor * chart_base = nullptr; + + ggml_tensor * build_hc_pre(ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale, + ggml_tensor * base, ggml_tensor ** post, ggml_tensor ** comb, int il); + + ggml_tensor * build_hc_post(ggml_tensor * x, ggml_tensor * branch, + ggml_tensor * post, ggml_tensor * comb, int il); + + ggml_tensor * build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a); + + ggml_tensor * build_rda_layer(ggml_tensor * cur, const llama_layer & layer, + llm_graph_input_rs * inp_rs, int il); + + ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, + llm_graph_input_attn_k * inp_attn_k, int il); + + ggml_tensor * build_situ_ffn(ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate, + ggml_tensor * down, int il); + }; +}; + struct llama_model_glm5_next : public llama_model_base { llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/src/models/raon1-mini.cpp b/src/models/raon1-mini.cpp new file mode 100644 index 000000000000..e5b1671ecdd4 --- /dev/null +++ b/src/models/raon1-mini.cpp @@ -0,0 +1,484 @@ +#include "models.h" + +#include "llama-impl.h" + +#include "llama-memory-recurrent.h" + +void llama_model_raon1_mini::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv); + ml.get_key(LLM_KV_KDA_HEAD_DIM, hparams.n_embd_head_kda); + ml.get_key(LLM_KV_KDA_GATE_LOWER_BOUND, hparams.kda_gate_lower_bound, false); + + uint32_t n_rda = 0; + for (uint32_t i = 0; i < hparams.n_layer(); ++i) { + hparams.is_recr_impl[i] = hparams.n_head_kv(i) == 0; + n_rda += hparams.is_recr_impl[i]; + if (!hparams.is_recr_impl[i] && hparams.n_head_kv(i) != 1) { + throw std::runtime_error(format("Raon-1 mini MLA layers must have one KV head, layer %u has %u", i, hparams.n_head_kv(i))); + } + } + // the hybrid memory needs both kinds: RDA layers (head_count_kv 0) and MLA layers (head_count_kv 1) + if (n_rda == 0 || n_rda == hparams.n_layer()) { + throw std::runtime_error(format("Raon-1 mini needs both RDA and MLA layers, got %u RDA of %u layers", n_rda, hparams.n_layer())); + } + + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func); + + ml.get_key(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent); + ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank); + ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult); + ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps); + ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude); + ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); + ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta); + + // The Raon router normalizes selected scores by sum(scores) + 1e-20. + hparams.expert_weights_norm_eps = 1e-20f; + + auto require = [](bool ok, const std::string & what) { + if (!ok) { + throw std::runtime_error("invalid Raon-1 mini hyperparameters: " + what); + } + }; + // accepted ranges; only 2-4 mHC streams and a conv width of 4 have been run (the released model uses 4 streams) + require(hparams.dsv4_hc_mult >= 2 && hparams.dsv4_hc_mult <= 8, format("hyper_connection.count %u is not in [2, 8]", hparams.dsv4_hc_mult)); + require(hparams.ssm_d_conv == 4, format("ssm.conv_kernel %u is not 4", hparams.ssm_d_conv)); + require(hparams.ssm_dt_rank > 0, "ssm.time_step_rank is 0"); + require(hparams.n_lora_q > 0 && hparams.n_lora_kv > 0, "q_lora_rank or kv_lora_rank is 0"); + // the absorbed MLA attends over the latent: V is the kv_lora_rank-wide latent + require(hparams.n_embd_head_v_full == hparams.n_lora_kv, format("the MLA value length %u is not kv_lora_rank %u", hparams.n_embd_head_v_full, hparams.n_lora_kv)); + require(hparams.n_embd_head_k_mla() > hparams.n_rot(), format("the MLA key length %u is not larger than the RoPE dimension %u", hparams.n_embd_head_k_mla(), hparams.n_rot())); + require(hparams.f_norm_rms_eps_latent > 0 && hparams.dsv4_hc_eps > 0, "a normalization epsilon is not positive"); + require(hparams.hc_magnitude > 0, "hyper_connection.magnitude is not positive"); + require(hparams.situ_beta > 0 && hparams.situ_linear_beta > 0, "a SiTU beta is not positive"); + require(hparams.n_layer_dense_lead <= hparams.n_layer(), format("leading_dense_block_count %u is larger than block_count %u", hparams.n_layer_dense_lead, hparams.n_layer())); + const auto head_dim = hparams.n_embd_head_kda; + require(head_dim == 16 || head_dim == 32 || head_dim == 64 || head_dim == 128, + format("RDA head dimension %u is not 16, 32, 64 or 128", head_dim)); + + switch (hparams.n_layer()) { + case 25: type = LLM_TYPE_29B_A4B; break; + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_raon1_mini::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t hc = hparams.dsv4_hc_mult; + // selector width per mHC site: pre (hc) + post (hc) + combination ((hc-1)^2, Helmert coordinates) + const int64_t hc_mix_dim = 2*hc + (hc - 1)*(hc - 1); + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0); + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + + layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0); + layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {hc_mix_dim}, 0); + // scale: alpha_pre, alpha_post, alpha_z, eta + layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {4}, 0); + layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0); + layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {hc_mix_dim}, 0); + layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {4}, 0); + + const int64_t head_dim = hparams.n_embd_head_kda; + const int64_t d_conv = hparams.ssm_d_conv; + const int64_t d_inner = head_dim * n_head; + + if (hparams.is_recr(i)) { + layer.ssm_q_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_Q, "weight", i), {d_conv, 1, d_inner, 1}, 0); + layer.ssm_k_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_K, "weight", i), {d_conv, 1, d_inner, 1}, 0); + layer.ssm_v_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_V, "weight", i), {d_conv, 1, d_inner, 1}, 0); + + create_tensor_qkv(layer, i, n_embd, d_inner, d_inner, d_inner, 0); + + layer.ssm_f_a = create_tensor(tn(LLM_TENSOR_SSM_F_A, "weight", i), {n_embd, hparams.ssm_dt_rank}, 0); + layer.ssm_f_b = create_tensor(tn(LLM_TENSOR_SSM_F_B, "weight", i), {hparams.ssm_dt_rank, d_inner}, 0); + layer.ssm_beta = create_tensor(tn(LLM_TENSOR_SSM_BETA, "weight", i), {n_embd, n_head}, 0); + layer.ssm_rda = create_tensor(tn(LLM_TENSOR_SSM_RDA, "weight", i), {n_embd, n_head}, 0); + + layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A_NOSCAN, i), {n_head}, 0); + layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0); + + layer.ssm_g = create_tensor(tn(LLM_TENSOR_SSM_G, "weight", i), {n_embd, d_inner}, 0); + layer.ssm_o_norm = create_tensor(tn(LLM_TENSOR_SSM_NORM, "weight", i), {head_dim}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {d_inner, n_embd}, 0); + } else { + const int64_t q_lora_rank = hparams.n_lora_q; + const int64_t kv_lora_rank = hparams.n_lora_kv; + const int64_t n_embd_head_k = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_v = hparams.n_embd_head_v_mla(); + const int64_t qk_rope_head_dim = hparams.n_rot(); + const int64_t qk_nope_head_dim = n_embd_head_k - qk_rope_head_dim; + + layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0); + layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0); + layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0); + layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head*n_embd_head_k}, 0); + layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + qk_rope_head_dim}, 0); + layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {qk_nope_head_dim, kv_lora_rank, n_head}, 0); + layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v, n_head}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head*n_embd_head_v}, 0); + + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * n_embd_head_v, n_embd}, 0); + } + + if (i < (int) hparams.n_layer_dense_lead) { + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + } else { + const int64_t n_ff_exp = hparams.n_ff_exp(); + + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + + if (hparams.n_expert_shared > 0) { + const int64_t n_ff_shexp = n_ff_exp * hparams.n_expert_shared; + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + } + } + } +} + +std::unique_ptr llama_model_raon1_mini::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +// decay gate from x = f_b(f_a(cur)) + dt_bias; ssm_a holds -exp(A_log) +// with gate_lower_bound: g = lower_bound * sigmoid(exp(A_log) * x), else g = -softplus(exp(A_log) * x) +ggml_tensor * llama_model_raon1_mini::graph::build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a) { + const int64_t head_dim = hparams.n_embd_head_kda; + + ggml_tensor * A = ggml_reshape_3d(ctx0, ssm_a, 1, n_head, 1); + + x = ggml_reshape_3d(ctx0, x, head_dim, n_head, n_tokens); + x = ggml_mul(ctx0, x, A); + + // gate_lower_bound is not a clamp - when set, it swaps the decay gate activation + if (hparams.kda_gate_lower_bound > -INFINITY) { + x = ggml_sigmoid(ctx0, ggml_scale(ctx0, x, -1.0f)); + return ggml_scale(ctx0, x, hparams.kda_gate_lower_bound); + } + + return ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, x))); +} + +// Raon delta attention: a gated delta-rule layer whose write gate differs from its erase gate +ggml_tensor * llama_model_raon1_mini::graph::build_rda_layer( + ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, int il) { + const int64_t head_dim = hparams.n_embd_head_kda; + const int64_t d_conv = hparams.ssm_d_conv; + const int64_t d_inner = head_dim * n_head; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + ggml_tensor * conv_states_all = inp_rs->mctx->get_r_l(il); + ggml_tensor * conv_states_seq = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); + + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 0, build_lora_mm(layer.wq, cur), + layer.ssm_q_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 1, build_lora_mm(layer.wk, cur), + layer.ssm_k_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 2, build_lora_mm(layer.wv, cur), + layer.ssm_v_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + cb(Qcur, "rda_q_conv", il); + cb(Kcur, "rda_k_conv", il); + cb(Vcur, "rda_v_conv", il); + + ggml_tensor * f_a = build_lora_mm(layer.ssm_f_a, cur); + ggml_tensor * g1 = build_lora_mm(layer.ssm_f_b, f_a); + g1 = ggml_add(ctx0, g1, layer.ssm_dt_b); + g1 = build_rda_gate(g1, layer.ssm_a); + cb(g1, "rda_g1", il); + + g1 = ggml_reshape_4d(ctx0, g1, head_dim, n_head, n_seq_tokens, n_seqs); + + // erase gate sigmoid(beta), write gate sigmoid(beta + delta); the write/erase ratio is folded into V + ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur); + beta = ggml_reshape_4d(ctx0, beta, 1, n_head, n_seq_tokens, n_seqs); + ggml_tensor * delta = build_lora_mm(layer.ssm_rda, cur); + delta = ggml_reshape_4d(ctx0, delta, 1, n_head, n_seq_tokens, n_seqs); + ggml_tensor * erase = ggml_softplus(ctx0, ggml_neg(ctx0, beta)); + ggml_tensor * write = ggml_softplus(ctx0, ggml_neg(ctx0, ggml_add(ctx0, beta, delta))); + Vcur = ggml_mul(ctx0, Vcur, ggml_exp(ctx0, ggml_sub(ctx0, erase, write))); + cb(Vcur, "rda_v_scaled", il); + beta = ggml_sigmoid(ctx0, beta); + cb(beta, "rda_beta", il); + + // same as HF F.normalize(eps=1e-6): x / max(||x||, eps) + const float eps_norm = 1e-6f; + Qcur = ggml_l2_norm(ctx0, Qcur, eps_norm); + Kcur = ggml_l2_norm(ctx0, Kcur, eps_norm); + + ggml_tensor * g2 = build_lora_mm(layer.ssm_g, cur); + + // scan and state update + ggml_tensor * ssm_states_all = inp_rs->mctx->get_s_l(il); + ggml_tensor * state = build_rs(inp_rs, ssm_states_all, hparams.n_embd_s(), n_seqs); + state = ggml_reshape_4d(ctx0, state, head_dim, head_dim, n_head, n_seqs); + + ggml_tensor * output = build_recurrent_attn(inp_rs, ssm_states_all, Qcur, Kcur, Vcur, g1, beta, state, il); + output = ggml_cont(ctx0, output); + cb(output, "rda_scan_out", il); + + // output gate, then RMSNorm(o) * sigmoid(g2) + g2 = ggml_reshape_3d(ctx0, g2, head_dim, n_head, n_tokens); + + ggml_tensor * o = ggml_reshape_3d(ctx0, output, head_dim, n_head, n_tokens); + ggml_tensor * normed = build_norm(o, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il); + cb(g2, "rda_g2", il); + cb(normed, "rda_normed", il); + ggml_tensor * gated = ggml_mul(ctx0, normed, ggml_sigmoid(ctx0, g2)); + + gated = ggml_cont_2d(ctx0, gated, d_inner, n_tokens); + cur = build_lora_mm(layer.wo, gated); + cb(cur, "rda_out", il); + + return cur; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_hc_pre( + ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale, ggml_tensor * base, + ggml_tensor ** post, ggml_tensor ** comb, int il) { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nm = hc - 1; + const int64_t nt = x->ne[2]; + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, n_embd*hc, nt); + ggml_tensor * rms = ggml_sqrt(ctx0, ggml_scale_bias(ctx0, ggml_mean(ctx0, ggml_sqr(ctx0, flat)), 1.0f, hparams.dsv4_hc_eps)); + ggml_tensor * mixes = ggml_div(ctx0, build_lora_mm(fn, flat), rms); + cb(mixes, "hc_mixes", il); + + auto affine = [&](int64_t offset, int64_t width, int64_t si) { + ggml_tensor * z = ggml_view_2d(ctx0, mixes, width, nt, mixes->nb[1], offset*mixes->nb[0]); + ggml_tensor * a = ggml_view_1d(ctx0, scale, 1, si*scale->nb[0]); + ggml_tensor * b = ggml_view_1d(ctx0, base, width, offset*base->nb[0]); + return ggml_add(ctx0, ggml_mul(ctx0, z, a), b); + }; + ggml_tensor * pre = ggml_sigmoid(ctx0, affine(0, hc, 0)); + *post = ggml_scale(ctx0, ggml_sigmoid(ctx0, affine(hc, hc, 1)), hparams.hc_magnitude); + // combination: z ((hc-1)^2 Helmert coordinates) -> e = H z H^T, rho = 1 + max(0, max(-e / chart_base)), + // phi = chart_base + e / rho (doubly stochastic), comb = I + sigmoid(eta) * (phi - I) + ggml_tensor * z = ggml_cont_3d(ctx0, affine(2*hc, nm*nm, 2), nm, nm, nt); + ggml_tensor * e = ggml_mul_mat(ctx0, helmert, z); + e = ggml_mul_mat(ctx0, helmert, ggml_cont(ctx0, ggml_transpose(ctx0, e))); + ggml_tensor * ratio = ggml_neg(ctx0, ggml_div(ctx0, e, chart_base)); + ratio = ggml_reshape_2d(ctx0, ratio, hc*hc, nt); + ggml_tensor * rho = ggml_pool_1d(ctx0, ratio, GGML_OP_POOL_MAX, hc*hc, hc*hc, 0); + rho = ggml_scale_bias(ctx0, ggml_clamp(ctx0, rho, 0.0f, INFINITY), 1.0f, 1.0f); + rho = ggml_reshape_3d(ctx0, rho, 1, 1, nt); + ggml_tensor * phi = ggml_add(ctx0, ggml_div(ctx0, e, rho), chart_base); + ggml_tensor * gamma = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, scale, 1, 3*scale->nb[0])); + *comb = ggml_add(ctx0, ggml_mul(ctx0, ggml_sub(ctx0, phi, identity), gamma), identity); + cb(*comb, "hc_comb", il); + cb(pre, "hc_pre", il); + cb(*post, "hc_post", il); + + if (cparams.fused_dsv4_hc_pre) { + ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, pre); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il}); + return result; + } + + ggml_tensor * result = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], i*x->nb[1]); + ggml_tensor * wi = ggml_view_2d(ctx0, pre, 1, nt, pre->nb[1], i*pre->nb[0]); + ggml_tensor * term = ggml_mul(ctx0, xi, wi); + result = result ? ggml_add(ctx0, result, term) : term; + } + return result; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_hc_post( + ggml_tensor * x, ggml_tensor * branch, ggml_tensor * post, ggml_tensor * comb, int il) { + if (cparams.fused_dsv4_hc_post) { + ggml_tensor * result = ggml_dsv4_hc_post(ctx0, branch, x, post, comb); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il}); + return result; + } + + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + ggml_tensor * result = nullptr; + for (int64_t dst = 0; dst < hc; ++dst) { + ggml_tensor * sum = nullptr; + for (int64_t src = 0; src < hc; ++src) { + ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], src*x->nb[1]); + ggml_tensor * wi = ggml_view_2d(ctx0, comb, 1, nt, comb->nb[2], dst*comb->nb[0] + src*comb->nb[1]); + ggml_tensor * term = ggml_mul(ctx0, xi, wi); + sum = sum ? ggml_add(ctx0, sum, term) : term; + } + ggml_tensor * wi = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], dst*post->nb[0]); + sum = ggml_add(ctx0, sum, ggml_mul(ctx0, branch, wi)); + sum = ggml_reshape_3d(ctx0, sum, n_embd, 1, nt); + result = result ? ggml_concat(ctx0, result, sum, 1) : sum; + } + return result; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_mla_layer( + ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, int il) { + const int64_t nr = hparams.n_rot(); + const int64_t nk = hparams.n_embd_head_k_mla(); + const int64_t nn = nk - nr; + const int64_t rank = hparams.n_lora_kv; + // Raon defines a separate RMSNorm epsilon for its Q and KV latent projections. + const float eps = hparams.f_norm_rms_eps_latent; + ggml_tensor * q = build_lora_mm(layer.wq_a, cur); + q = ggml_mul(ctx0, ggml_rms_norm(ctx0, q, eps), layer.attn_q_a_norm); + cb(q, "mla_q_norm", il); + q = build_lora_mm(layer.wq_b, q); + ggml_tensor * kv = build_lora_mm(layer.wkv_a_mqa, cur); + ggml_tensor * latent = ggml_view_2d(ctx0, kv, rank, n_tokens, kv->nb[1], 0); + latent = ggml_mul(ctx0, ggml_rms_norm(ctx0, latent, eps), layer.attn_kv_a_norm); + cb(latent, "mla_kv_norm", il); + // NoPE: the "rope" dims of q and k are concatenated as they are, without rotation + ggml_tensor * extra = ggml_view_3d(ctx0, kv, nr, 1, n_tokens, kv->nb[1], kv->nb[1], rank*kv->nb[0]); + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, nn, n_head, n_tokens, nk*q->nb[0], q->nb[1], 0); + ggml_tensor * q_extra = ggml_view_3d(ctx0, q, nr, n_head, n_tokens, nk*q->nb[0], q->nb[1], nn*q->nb[0]); + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + q_nope = build_lora_mm(layer.wk_b, q_nope); + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + q = ggml_concat(ctx0, q_nope, q_extra, 0); + latent = ggml_reshape_3d(ctx0, latent, rank, 1, n_tokens); + ggml_tensor * k = ggml_concat(ctx0, latent, extra, 0); + ggml_tensor * out = build_attn(inp_attn_k, nullptr, nullptr, nullptr, q, k, latent, + nullptr, nullptr, layer.wv_b, 1.0f/sqrtf(nk), il); + out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, cur))); + cb(out, "mla_gated", il); + return build_lora_mm(layer.wo, out); +} + +// dense SiTU-GLU feed-forward for the lead layers and the shared expert: +// situ(gate, up) = beta*tanh(gate/beta)*sigmoid(gate) * lb*tanh(up/lb) +// build_ffn has no SiTU case; the routed experts go through build_moe_ffn, which has one +ggml_tensor * llama_model_raon1_mini::graph::build_situ_ffn( + ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate, ggml_tensor * down, int il) { + const float beta = hparams.situ_beta; + const float lb = hparams.situ_linear_beta; + + ggml_tensor * u = build_lora_mm(up, cur); + cb(u, "ffn_up", il); + ggml_tensor * g = build_lora_mm(gate, cur); + cb(g, "ffn_gate", il); + + ggml_tensor * act = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, g, 1.0f/beta)), beta); + act = ggml_mul(ctx0, act, ggml_sigmoid(ctx0, g)); + u = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, u, 1.0f/lb)), lb); + cur = ggml_mul(ctx0, act, u); + cb(cur, "ffn_situ", il); + + cur = build_lora_mm(down, cur); + cb(cur, "ffn_out", il); + return cur; +} + +llama_model_raon1_mini::graph::graph(const llm_graph_params & params) : llm_build_delta_net_base(params) { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nm = hc - 1; + helmert = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * row = nullptr; + for (int64_t j = 0; j < nm; ++j) { + const float v = (i <= j ? 1.0f : i == j + 1 ? -(float) (j + 1) : 0.0f)/sqrtf((j + 1)*(j + 2)); + ggml_tensor * c = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1), v); + row = row ? ggml_concat(ctx0, row, c, 0) : c; + } + row = ggml_reshape_2d(ctx0, row, nm, 1); + helmert = helmert ? ggml_concat(ctx0, helmert, row, 1) : row; + } + identity = ggml_diag(ctx0, ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, hc), 1.0f)); + chart_base = ggml_scale_bias(ctx0, identity, 0.5f, 0.5f/hc); + + ggml_tensor * inp = build_inp_embd(model.tok_embd); + inp = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens); + inp = ggml_repeat_4d(ctx0, inp, n_embd, hc, n_tokens, 1); + auto * inputs = build_inp_mem_hybrid_k(); + auto * inp_rs = inputs->get_recr(); + auto * inp_attn = inputs->get_attn(); + auto * out_ids = build_inp_out_ids(); + GGML_ASSERT(ubatch.n_seqs != 0 && ubatch.equal_seqs()); + GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens*ubatch.n_seqs); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + ggml_tensor * post; + ggml_tensor * comb; + ggml_tensor * cur = build_hc_pre(inp, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, &post, &comb, il); + cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + if (hparams.is_recr(il)) { + cur = build_rda_layer(cur, layer, inp_rs, il); + } else { + cur = build_mla_layer(cur, layer, inp_attn, il); + } + inp = build_hc_post(inp, cur, post, comb, il); + cb(inp, "hc_attn_out", il); + cur = build_hc_pre(inp, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, &post, &comb, il); + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + if (il < (int) hparams.n_layer_dense_lead) { + cur = build_situ_ffn(cur, layer.ffn_up, layer.ffn_gate, layer.ffn_down, il); + } else { + ggml_tensor * moe = build_moe_ffn(cur, + layer.ffn_gate_inp, + layer.ffn_up_exps, + layer.ffn_gate_exps, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, hparams.n_expert_used(), + LLM_FFN_SITU, hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il); + if (layer.ffn_gate_shexp) { + ggml_tensor * shared = build_situ_ffn(cur, layer.ffn_up_shexp, layer.ffn_gate_shexp, + layer.ffn_down_shexp, il); + moe = ggml_add(ctx0, moe, shared); + } + cur = moe; + } + inp = build_hc_post(inp, cur, post, comb, il); + inp = build_cvec(inp, il); + cb(inp, "l_out", il); + } + ggml_tensor * cur = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * x = ggml_view_2d(ctx0, inp, n_embd, n_tokens, inp->nb[2], i*inp->nb[1]); + cur = cur ? ggml_add(ctx0, cur, x) : x; + } + cur = ggml_scale(ctx0, cur, 1.0f/hc); + if (out_ids) { + cur = ggml_get_rows(ctx0, cur, out_ids); + } + cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; +} diff --git a/src/unicode.cpp b/src/unicode.cpp index 9226c73db66e..ea5957514bdd 100644 --- a/src/unicode.cpp +++ b/src/unicode.cpp @@ -1221,6 +1221,178 @@ static std::vector unicode_regex_split_custom_newlines(const std::string return bpe_offsets; } +// regex: ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+)*|\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+ +// Raon-1 mini: CJK runs are split from other letters, letter runs keep marks and can span one space, digits are grouped by 3 from the right +static std::vector unicode_regex_split_custom_raon(const std::string & text, const std::vector & offsets) { + std::vector bpe_offsets; + bpe_offsets.reserve(offsets.size()); + + const auto cpts = unicode_cpts_from_utf8(text); + + size_t start = 0; + for (auto offset : offsets) { + const size_t offset_ini = start; + const size_t offset_end = start + offset; + assert(offset_end <= cpts.size()); + start = offset_end; + + static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF; + auto _get_cpt = [&] (const size_t pos) -> uint32_t { + return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE; + }; + + auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags { + return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{}; + }; + + // [\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff] + auto _is_cjk = [&] (const size_t pos) -> bool { + const uint32_t cpt = _get_cpt(pos); + return (0x4e00 <= cpt && cpt <= 0x9fa5) || (0x3040 <= cpt && cpt <= 0x30ff); + }; + + // (?![CJK])\p{L} + auto _is_letter = [&] (const size_t pos) -> bool { + return _get_flags(pos).is_letter && !_is_cjk(pos); + }; + + // [^\s\p{L}\p{N}] + auto _is_punct = [&] (const size_t pos) -> bool { + if (pos < offset_ini || offset_end <= pos) { + return false; + } + const auto flags = _get_flags(pos); + return !flags.is_whitespace && !flags.is_letter && !flags.is_number; + }; + + size_t _prev_end = offset_ini; + auto _add_token = [&] (const size_t end) -> size_t { + assert(_prev_end <= end && end <= offset_end); + size_t len = end - _prev_end; + if (len > 0) { + bpe_offsets.push_back(len); + } + _prev_end = end; + return len; + }; + + for (size_t pos = offset_ini; pos < offset_end; ) { + const uint32_t cpt = _get_cpt(pos); + const auto flags = _get_flags(pos); + + // the CJK, letter and punctuation alternatives accept one optional leading space + size_t pos2 = pos + (cpt == ' '); + + // regex: ' ?[CJK]+' + if (_is_cjk(pos2)) { + do { + pos2++; + } while (_is_cjk(pos2)); + pos += _add_token(pos2); + continue; + } + + // regex: ' ?(?:(?:(?![CJK])\p{L})\p{M}*)+(?: (?:(?:(?![CJK])\p{L})\p{M}*)+)*' + if (_is_letter(pos2)) { + while (true) { + pos2++; + while (_get_flags(pos2).is_accent_mark) { + pos2++; + } + if (_is_letter(pos2)) { + continue; + } + // a single space joins two letter runs + if (_get_cpt(pos2) == ' ' && _is_letter(pos2 + 1)) { + pos2++; + continue; + } + break; + } + pos += _add_token(pos2); + continue; + } + + // regex: '\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))' - groups of three from the right + if (flags.is_number) { + size_t digit_start = pos; + size_t digit_count = 0; + + // Count consecutive digits + while (_get_flags(pos).is_number && pos < offset_end) { + digit_count++; + pos++; + } + + // Split based on total length modulo 3 + size_t remainder = digit_count % 3; + size_t current = digit_start; + + // Emit leading 1-2 digits if needed + if (remainder > 0) { + _add_token(current + remainder); + current += remainder; + } + + // Emit groups of 3 + while (current < digit_start + digit_count) { + _add_token(current + 3); + current += 3; + } + continue; + } + + // regex: ' ?[^\s\p{L}\p{N}]+[\r\n/]*' + if (_is_punct(pos2)) { + do { + pos2++; + } while (_is_punct(pos2)); + uint32_t cpt2 = _get_cpt(pos2); + while (cpt2 == '\r' || cpt2 == '\n' || cpt2 == '/') { + cpt2 = _get_cpt(++pos2); + } + pos += _add_token(pos2); + continue; + } + + // regex: '\s*[\r\n]+' + size_t num_whitespaces = 0; + size_t last_end_r_or_n = 0; + while (_get_flags(pos + num_whitespaces).is_whitespace) { + const uint32_t cpt2 = _get_cpt(pos + num_whitespaces); + if (cpt2 == '\r' || cpt2 == '\n') { + last_end_r_or_n = pos + num_whitespaces + 1; + } + num_whitespaces++; + } + if (last_end_r_or_n > 0) { + pos = last_end_r_or_n; + _add_token(pos); + continue; + } + + // regex: '\s+(?!\S)' + if (num_whitespaces > 1 && _get_cpt(pos + num_whitespaces) != OUT_OF_RANGE) { + pos += num_whitespaces - 1; + _add_token(pos); + continue; + } + + // regex: '\s+' + if (num_whitespaces > 0) { + pos += num_whitespaces; + _add_token(pos); + continue; + } + + // no matches + _add_token(++pos); + } + } + + return bpe_offsets; +} + static std::vector unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector & offsets) { std::vector bpe_offsets; @@ -1255,6 +1427,9 @@ static std::vector unicode_regex_split_custom(const std::string & text, // Splits digits into groups of 3 from the right (e.g., 1234567 -> 1, 234, 567) // TODO: Revisit this regex, in case there are any subtle tokenization differences with the original regex. bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets); + } else if (regex_expr == " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") { + // Raon-1 mini: must match the LLAMA_VOCAB_PRE_TYPE_RAON regex in llama-vocab.cpp byte for byte + bpe_offsets = unicode_regex_split_custom_raon(text, offsets); } return bpe_offsets; diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 5b7ea18685c4..ccb222e93f63 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -334,6 +334,11 @@ qwen4exp ,0 ,any ,RMS_NORM+MUL , 13 qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2 qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1 +raon1 ,0 ,any ,ADD+ADD+ADD , 1 +raon1 ,0 ,any ,GATED_DELTA_NET+CPY , 1 +raon1 ,0 ,any ,MUL+ADD , 2 +raon1 ,0 ,any ,RMS_NORM+MUL , 8 +raon1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1 refact ,0 ,any ,RMS_NORM+MUL , 5 refact ,0 ,any ,RMS_NORM+MUL , 5 ricursive ,0 ,any ,RMS_NORM+MUL , 9 diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 20a3cc6a0747..83c11cc2d4ac 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -4255,6 +4255,215 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect_content("Hello, world!\nWhat's up?") .run(); } + { + // Raon-1 mini: ChatML turns, an explicit envelope on every assistant turn and Qwen3-Coder style XML tool calls + auto tst = peg_tester("models/templates/KRAFTON-Raon-1-mini-preview.jinja", detailed_debug); + + // reasoning on: the generation prompt opens "\n" + tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .expect(message_assist_thoughts) + .run(); + + tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_NONE) + .enable_thinking(true) + .expect_content("\nI'm\nthinking\n\n\nHello, world!\nWhat's up?") + .run(); + + // reasoning off: the generation prompt already closes the envelope + tst.test("Hello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .expect(message_assist) + .run(); + + // typed arguments: integer + tst.test( + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_rules({ "tool-0", "tool-0-arg-0" }) + .run(); + + tst.test( + "I'm\nthinking\n\n\n" + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .tools({ special_function_tool }) + .expect(message_assist_call_thoughts) + .run(); + + // typed arguments: string and integer, optional arguments out of order + tst.test( + "\n" + "\n" + "\nhello\n\n" + "\n42\n\n" + "\n100\n\n" + "\nworld\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ tool_2req_4opt }) + .expect_tool_calls({ + { "tool_2req_4opt", R"({"req1": "hello", "req2": 42, "opt4": 100, "opt1": "world"})", {} }, + }) + .run(); + + // typed arguments: boolean, object and array values stay JSON + tst.test( + "\n" + "\n" + "\ntrue\n\n" + "\n" + "\n" + "\n" + "\n" + "\n{\"mode\": \"fast\", \"level\": 2}\n\n" + "\n" + "\n" + "\n" + "\n" + "\n[{\"item\": \"Check stuff\", \"selected\": false}]\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .parallel_tool_calls(true) + .tools({ toggle_tool, config_tool, todo_list }) + .expect_tool_calls({ + { "toggle", R"({"enabled": true})", {} }, + { "set_config", R"({"config": {"mode": "fast", "level": 2}})", {} }, + { "todo_list", R"({"todos": [{"item": "Check stuff", "selected": false}]})", {} }, + }) + .run(); + + // a string argument that looks like a number stays a string + tst.test( + "\n" + "\n" + "\n2024.c\n\n" + "\n1\n\n" + "\n2\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ edit_tool }) + .expect_tool_calls({ + { "edit", R"({"filename": "2024.c", "oldString": "1", "newString": "2"})", {} }, + }) + .run(); + + // nullable arguments + tst.test( + "\n" + "\n" + "\nnull\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_string_tool }) + .expect_tool_calls({ + { "set_nullable_str", R"({"name": null})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\nhello world\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_string_tool }) + .expect_tool_calls({ + { "set_nullable_str", R"({"name": "hello world"})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\nnull\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_int_tool }) + .expect_tool_calls({ + { "set_nullable_int", R"({"count": null})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\n42\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_int_tool }) + .expect_tool_calls({ + { "set_nullable_int", R"({"count": 42})", {} }, + }) + .run(); + + // content before the call, then reasoning + parallel calls + tst.test( + "I'm\nthinking\n\n\n" + "Hello, world!\nWhat's up?\n\n" + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .tools({ special_function_tool }) + .expect(message_assist_call_thoughts_content) + .run(); + + tst.test( + "\n" + "\n" + "\n1\n\n" + "\n" + "\n" + "\n" + "\n" + "\n1\n\n" + "\n2\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .parallel_tool_calls(true) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect_tool_calls({ + { "special_function", R"({"arg1": 1})", {} }, + { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} }, + }) + .run(); + } + { auto tst = peg_tester("models/templates/deepseek-ai-DeepSeek-V3.1.jinja", detailed_debug); tst.test( @@ -8188,6 +8397,13 @@ static void test_template_generation_prompt() { check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n\nI'm"); } + { + auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja"); + check(tmpls, basic(), "<|im_start|>assistant\n\n"); + check(tmpls, continuation_content(), "<|im_start|>assistant\n\nI'm thinking\n\n\nHello, "); + check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n\nI'm"); + } + { auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja"); check(tmpls, basic(), "<|start|>assistant"); @@ -8698,6 +8914,179 @@ static void test_deepseek_v4_1_message_fields() { } } +// Raon-1 mini template (models/templates/KRAFTON-Raon-1-mini-preview.jinja) prompt rendering +static void test_raon_prompt() { + LOG_DBG("%s\n", __func__); + + auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja"); + + common_chat_msg developer_msg; + developer_msg.role = "developer"; + developer_msg.content = "You are RAON."; + + common_chat_msg system_msg = developer_msg; + system_msg.role = "system"; + + auto render = [&](const std::vector & messages, bool with_tools, bool enable_thinking = true) { + common_chat_templates_inputs inputs; + inputs.messages = messages; + inputs.enable_thinking = enable_thinking; + if (with_tools) { + inputs.tools = { special_function_tool }; + } + return common_chat_templates_apply(tmpls.get(), inputs); + }; + + // a leading developer message is rendered as the system turn (the template itself rejects "developer") + { + const auto prompt = render({ developer_msg, message_user }, false).prompt.str(); + assert_equals(std::string( + "<|im_start|>system\nYou are RAON.<|im_end|>\n" + "<|im_start|>user\nHey there!<|im_end|>\n" + "<|im_start|>assistant\n\n"), prompt); + assert_equals(render({ system_msg, message_user }, false).prompt.str(), prompt); + } + + // with tools the system text follows the tool block in the same system turn + { + const auto prompt = render({ developer_msg, message_user }, true).prompt.str(); + assert_equals(true, string_starts_with(prompt, "<|im_start|>system\n# Tools\n\n")); + assert_contains(prompt, "\"name\": \"special_function\""); + assert_contains(prompt, "\n\nYou are RAON.<|im_end|>\n<|im_start|>user\nHey there!<|im_end|>\n"); + assert_not_contains(prompt, "developer"); + assert_equals(render({ system_msg, message_user }, true).prompt.str(), prompt); + } + + // reasoning off closes the think envelope in the generation prompt + { + const auto params = render({ message_user }, false, /* enable_thinking = */ false); + assert_equals(std::string("<|im_start|>assistant\n\n\n"), params.generation_prompt); + assert_ends_with(params.prompt.str(), params.generation_prompt); + } + + // assistant history as HF apply_chat_template renders it: kept reasoning and tool calls after the last query, an earlier turn's reasoning kept by default and dropped with truncate_history_thinking=true + { + common_chat_msg calls; + calls.role = "assistant"; + calls.reasoning_content = "Two calls."; + calls.tool_calls.push_back({ "special_function", "{\"arg1\": 1}", "call_1" }); + calls.tool_calls.push_back({ "special_function", "{\"arg1\": 2}", "call_2" }); + common_chat_msg r1; r1.role = "tool"; r1.tool_call_id = "call_1"; r1.content = "one"; + common_chat_msg r2; r2.role = "tool"; r2.tool_call_id = "call_2"; r2.content = "two"; + common_chat_msg user_q; user_q.role = "user"; user_q.content = "Call it twice."; + assert_ends_with(render({ user_q, calls, r1, r2 }, true).prompt.str(), std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "Two calls.\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "1\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "2\n" + "\n" + "\n" + "<|im_end|>\n" + "<|im_start|>user\n" + "\n" + "one\n" + "\n" + "\n" + "two\n" + "<|im_end|>\n" + "<|im_start|>assistant\n" + "\n")); + + common_chat_msg old; old.role = "assistant"; old.content = "Old thought.\n\n\nAnswer."; + common_chat_msg again; again.role = "user"; again.content = "Again."; + // with truncate_history_thinking = true the earlier turn's reasoning is dropped + { + common_chat_templates_inputs inputs; + inputs.messages = { user_q, old, again }; + inputs.chat_template_kwargs["truncate_history_thinking"] = "true"; + assert_equals(std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "\n" + "Answer.<|im_end|>\n" + "<|im_start|>user\n" + "Again.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n"), common_chat_templates_apply(tmpls.get(), inputs).prompt.str()); + } + + // by default (the template defaults truncate_history_thinking to false) the earlier turn keeps the reasoning split out of its content + { + assert_equals(std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "Old thought.\n" + "\n" + "\n" + "Answer.<|im_end|>\n" + "<|im_start|>user\n" + "Again.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n"), render({ user_q, old, again }, false).prompt.str()); + } + } + + // continuing an assistant message without reasoning: the shared Qwen3-Coder handler writes "\n\n\n\n", the template "\n\n"; this pins the handler's behaviour + { + common_chat_templates_inputs inputs; + inputs.messages = { message_user, simple_assist_msg("Hello, ") }; + inputs.add_generation_prompt = false; + inputs.continue_final_message = COMMON_CHAT_CONTINUATION_CONTENT; + assert_ends_with(common_chat_templates_apply(tmpls.get(), inputs).prompt.str(), + std::string("<|im_start|>assistant\n\n\n\n\nHello, ")); + } + + // Keep system instructions in order, including instructions sent as developer messages. + { + common_chat_msg second_system = system_msg; + second_system.content = "Keep it short."; + + const std::string system_turn = "<|im_start|>system\nYou are RAON.<|im_end|>\n"; + const std::string second_system_turn = "<|im_start|>system\nKeep it short.<|im_end|>\n"; + const std::string user_turn = "<|im_start|>user\nHey there!<|im_end|>\n"; + const std::string generation_prompt = "<|im_start|>assistant\n\n"; + + assert_equals(system_turn + second_system_turn + user_turn + generation_prompt, + render({ system_msg, second_system, message_user }, false).prompt.str()); + assert_equals(system_turn + user_turn + second_system_turn + generation_prompt, + render({ system_msg, message_user, second_system }, false).prompt.str()); + assert_equals(user_turn + system_turn + generation_prompt, + render({ message_user, developer_msg }, false).prompt.str()); + + // A system instruction can start a conversation without a user message. + assert_equals(system_turn + generation_prompt, render({ system_msg }, false).prompt.str()); + } + + // A closing tag in the answer is literal, even after an initial reasoning block. + { + const auto literal = simple_assist_msg("The answer quotes ."); + assert_contains(render({ message_user, literal, message_user }, false).prompt.str(), + "<|im_start|>assistant\n\n\nThe answer quotes .<|im_end|>\n"); + + const auto with_reasoning = simple_assist_msg("Reasoning.\n\nThe answer quotes ."); + assert_contains(render({ message_user, with_reasoning, message_user }, false).prompt.str(), + "<|im_start|>assistant\n\nReasoning.\n\n\nThe answer quotes .<|im_end|>\n"); + } +} + static void test_prompt_parts() { LOG_DBG("%s\n", __func__); const std::string tmpl_src = @@ -9132,6 +9521,7 @@ int main(int argc, char ** argv) { test_deepseek_v4_tool_result_ordering(); test_deepseek_v4_1_message_fields(); test_inkling2_media_blocks(); + test_raon_prompt(); test_template_generation_prompt(); test_reasoning_effort_caps(); test_prompt_parts(); diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index a7deed9f73d8..e9e7a6cbf137 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -300,6 +300,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 + || arch == LLM_ARCH_RAON1_MINI || arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 @@ -386,7 +387,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE || arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 || arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 || - arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH + arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_RAON1_MINI ) { GGML_ASSERT(n_layer >= 2); std::vector n_head_per_layer; @@ -398,7 +399,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const : (il == 1 ? 0 : n_head)); } // GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer. - if (arch == LLM_ARCH_GLM5_NEXT) { + if (arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_RAON1_MINI) { ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); // the MLA cache holds one latent head for (uint32_t & n : n_head_per_layer) { @@ -440,6 +441,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 + || arch == LLM_ARCH_RAON1_MINI || arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH @@ -485,6 +487,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_CLAMP_KQV, 1.0f); ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, 1e-5f); ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); + ms.add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, 1e-6f); ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, 1e-5f); ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, uint32_t(8)); ms.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(64) : uint32_t(512)); @@ -546,6 +549,14 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, false); } + if (arch == LLM_ARCH_RAON1_MINI) { + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1e-5f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + } + // MSA requires one indexer head per GQA (KV) head, unlike the DSA archs where the // indexer head count is independent of the main attention head count. if (arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_GLM5_NEXT) { @@ -1209,6 +1220,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_KIMI_LINEAR: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STEP35: case LLM_ARCH_MISTRAL4: From eb56575095e023a50f6d529a0397fec94a659f21 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Wed, 25 Nov 2026 20:02:31 +0100 Subject: [PATCH 05/47] ui: stop the streaming reply with Escape (#33051) Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/README.md | 2 +- .../app/chat/ChatForm/ChatForm.svelte | 24 ++- .../models/ModelsManager/ModelsManager.svelte | 11 +- .../chat/src/lib/constants/ui.constants.ts | 12 ++ .../src/lib/stores/sidebar-drag.svelte.ts | 5 +- .../client/chat-form-escape.svelte.test.ts | 144 ++++++++++++++++++ .../client/chat-form-voice.svelte.test.ts | 16 +- .../components/ChatFormTestWrapper.svelte | 25 ++- .../ChatFormVoiceTestWrapper.svelte | 5 +- 9 files changed, 222 insertions(+), 22 deletions(-) create mode 100644 ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index ec4b38b5796b..7838e7878777 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -55,7 +55,7 @@ The app reaches the llama-server on its own origin by default (llama-server serv - **Rendering** - Markdown (GFM), code highlighting, KaTeX math and Mermaid diagrams - **Models** - in ROUTER mode, a selector and a models manager: load and unload, downloads, Discover from the Hugging Face Hub, favorites and hidden models - **Tools** - built-in browser tools, llama-server's tools and MCP servers, each behind a permission prompt -- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar) +- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar, `Esc` stop the reply) ## Development diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 82ffb3f6aec0..ca2c651da467 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -22,6 +22,7 @@ CLIPBOARD_CONTENT_QUOTE_PREFIX, ICON_CLASS_DEFAULT, INITIAL_FILE_SIZE, + OPEN_OVERLAY_SELECTOR, PROMPT_CONTENT_SEPARATOR, SETTING_CONFIG_DEFAULT, SYSTEM_MESSAGE_PLACEHOLDER, @@ -700,16 +701,29 @@ await submit(); } - // Escape drops a recording, wherever the focus is - function handleWindowKeydown(event: KeyboardEvent) { - if (event.key !== KeyboardKey.ESCAPE || !voice.isActive || event.defaultPrevented) return; + // Escape drops a recording, or else stops the reply, wherever the focus is. On the body, so it + // runs before the overlays' document listeners: a tooltip closing on Escape does not take the key + function handleBodyKeydown(event: KeyboardEvent) { + if (event.key !== KeyboardKey.ESCAPE || event.defaultPrevented) return; + + if (document.querySelector(OPEN_OVERLAY_SELECTOR)) return; + + if (voice.isActive) { + event.preventDefault(); + voice.cancel(); + + return; + } + + // the system message editor and a message edit take Escape in their own window listeners + if (!isLoading || systemMode || chatStore.isEditing() || isIMEComposing(event)) return; event.preventDefault(); - voice.cancel(); + onStop?.(); } - + {#snippet systemMessageLeading()} {#if systemMessageAttachment} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte index 4cdf3112bf7c..32156e4b4170 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsManager/ModelsManager.svelte @@ -13,7 +13,8 @@ import { LOCAL_BACKEND_ID, type ModalityKey, - MODELS_TABLE_GROUP_LABELS + MODELS_TABLE_GROUP_LABELS, + OPEN_OVERLAY_SELECTOR } from '#lib/constants/index.ts'; import { ModelCapability, ModelsTableGroupKind } from '#lib/enums/index.ts'; import { modelsStore, uiStore } from '#lib/stores/index.ts'; @@ -169,14 +170,6 @@ void uiStore.closeModelsManager(); } - /** Overlays that handle their own Escape, so the page leaves them alone. */ - const OPEN_OVERLAY_SELECTOR = [ - '[role="dialog"][data-state="open"]', - '[role="alertdialog"][data-state="open"]', - '[role="menu"][data-state="open"]', - '[role="listbox"][data-state="open"]' - ].join(', '); - // Escape steps back the way the dialog's did: the pane's drawer closes itself, then // the next Escape leaves the page function handleKeydown(event: KeyboardEvent): void { diff --git a/ui/apps/chat/src/lib/constants/ui.constants.ts b/ui/apps/chat/src/lib/constants/ui.constants.ts index a371aec8d59a..8253af8c8338 100644 --- a/ui/apps/chat/src/lib/constants/ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/ui.constants.ts @@ -25,6 +25,18 @@ export const COPY_FEEDBACK_RESET_MS = 1500; export const NATIVE_CONTEXT_MENU_SELECTOR = 'a, img, video, audio, pre, code, input, textarea, [contenteditable="true"]'; +/** + * Open overlays that take Escape themselves, so what is under them leaves the key alone. + * Not tooltips and hover cards, which only close on it. + */ +export const OPEN_OVERLAY_SELECTOR = [ + '[role="dialog"][data-state="open"]', + '[role="alertdialog"][data-state="open"]', + '[role="menu"][data-state="open"]', + '[role="listbox"][data-state="open"]', + '[data-slot="popover-content"][data-state="open"]' +].join(', '); + /** * A sidebar section under a dragged chat, or one being moved: the faint tint * of the sidebar's resize handle, edged like the handle while it is dragged. diff --git a/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts b/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts index 73a0edefeb53..9e9f0b891001 100644 --- a/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts +++ b/ui/apps/chat/src/lib/stores/sidebar-drag.svelte.ts @@ -216,7 +216,7 @@ class SidebarDragStore { window.removeEventListener('pointermove', this.#handleMove); window.removeEventListener('pointerup', this.#handleUp); window.removeEventListener('pointercancel', this.#handleCancel); - window.removeEventListener('keydown', this.#handleKeydown); + window.removeEventListener('keydown', this.#handleKeydown, { capture: true }); if (!gesture?.active) return; @@ -257,7 +257,8 @@ class SidebarDragStore { window.addEventListener('pointermove', this.#handleMove); window.addEventListener('pointerup', this.#handleUp); window.addEventListener('pointercancel', this.#handleCancel); - window.addEventListener('keydown', this.#handleKeydown); + // capture: a drag takes Escape before the listeners that would act on it too + window.addEventListener('keydown', this.#handleKeydown, { capture: true }); } #scrollDelta(gesture: Gesture): number { diff --git a/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts new file mode 100644 index 000000000000..6d6d85cdd35f --- /dev/null +++ b/ui/apps/chat/tests/client/chat-form-escape.svelte.test.ts @@ -0,0 +1,144 @@ +// Guards the Escape contract of the chat form: while a reply streams Escape stops it, as the +// stop button does, unless something else takes the key first - an open menu or drawer, a +// picker, a selection in the editor, the system message editor or a message edit. A tooltip +// does not take it. + +import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte'; +import { EditorView } from '@codemirror/view'; +import { OPEN_OVERLAY_SELECTOR } from '#lib/constants/index.ts'; +import { chatStore } from '#lib/stores/index.ts'; +import { tick } from 'svelte'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const PHONE = { height: 844, width: 390 }; +const DESKTOP = { height: 900, width: 1280 }; +const ADD_MENU_TRIGGER_SELECTOR = '.file-upload-button'; +const TOOLTIP_SELECTOR = '[data-slot="tooltip-content"]'; +// a tooltip opens after its hover delay +const TOOLTIP_TIMEOUT_MS = 5000; +const MENTION_PICKER_TEXT = 'File search is unavailable'; + +async function renderForm({ isLoading = true, systemMode = false } = {}) { + const onStop = vi.fn(); + const { container } = render(ChatFormTestWrapper, { isLoading, onStop, systemMode }); + + await tick(); + + const content = container.querySelector('.cm-content'); + const editor = content && EditorView.findFromDOM(content); + + if (!editor) throw new Error('editor not rendered'); + + await userEvent.click(editor.contentDOM); + + return { container, editor, onStop }; +} + +describe('ChatForm Escape', () => { + afterEach(async () => { + chatStore.clearEditMode(); + await page.viewport(DESKTOP.width, DESKTOP.height); + }); + + it('stops the reply from the editor', async () => { + const { onStop } = await renderForm(); + + await userEvent.keyboard('{Escape}'); + + expect(onStop).toHaveBeenCalledOnce(); + }); + + it('stops the reply with the focus outside the form', async () => { + const { editor, onStop } = await renderForm(); + + editor.contentDOM.blur(); + await userEvent.keyboard('{Escape}'); + + expect(onStop).toHaveBeenCalledOnce(); + }); + + it('does nothing with no reply streaming', async () => { + const { onStop } = await renderForm({ isLoading: false }); + + await userEvent.keyboard('{Escape}'); + + expect(onStop).not.toHaveBeenCalled(); + }); + + // the add menu is a dropdown on a desktop and a drawer on a phone + it.each([ + { overlay: 'menu', viewport: DESKTOP }, + { overlay: 'drawer', viewport: PHONE } + ])('closes the open add $overlay first', async ({ viewport }) => { + await page.viewport(viewport.width, viewport.height); + + const { container, onStop } = await renderForm(); + const overlay = () => document.querySelector(OPEN_OVERLAY_SELECTOR); + + await userEvent.click(container.querySelector(ADD_MENU_TRIGGER_SELECTOR)!); + await expect.poll(overlay).toBeTruthy(); + + await userEvent.keyboard('{Escape}'); + await expect.poll(overlay).toBeNull(); + expect(onStop).not.toHaveBeenCalled(); + + await userEvent.keyboard('{Escape}'); + expect(onStop).toHaveBeenCalledOnce(); + }); + + it('stops the reply with a tooltip showing', async () => { + const { container, onStop } = await renderForm(); + + await userEvent.hover(container.querySelector(ADD_MENU_TRIGGER_SELECTOR)!); + await expect + .poll(() => document.querySelector(TOOLTIP_SELECTOR), { timeout: TOOLTIP_TIMEOUT_MS }) + .toBeTruthy(); + + await userEvent.keyboard('{Escape}'); + expect(onStop).toHaveBeenCalledOnce(); + }); + + it('closes the mention picker first', async () => { + const { onStop } = await renderForm(); + + await userEvent.keyboard('@m'); + await expect.poll(() => document.body.textContent).toContain(MENTION_PICKER_TEXT); + + await userEvent.keyboard('{Escape}'); + await expect.poll(() => document.body.textContent).not.toContain(MENTION_PICKER_TEXT); + expect(onStop).not.toHaveBeenCalled(); + }); + + it('drops a selection in the editor first', async () => { + const { editor, onStop } = await renderForm(); + + await userEvent.keyboard('hello'); + editor.dispatch({ selection: { anchor: 0, head: editor.state.doc.length } }); + + await userEvent.keyboard('{Escape}'); + expect(editor.state.selection.main.empty).toBe(true); + expect(onStop).not.toHaveBeenCalled(); + + await userEvent.keyboard('{Escape}'); + expect(onStop).toHaveBeenCalledOnce(); + }); + + it('leaves the key to the system message editor', async () => { + const { onStop } = await renderForm({ systemMode: true }); + + await userEvent.keyboard('{Escape}'); + + expect(onStop).not.toHaveBeenCalled(); + }); + + it('leaves the key to a message edit', async () => { + const { onStop } = await renderForm(); + + chatStore.setEditModeActive(() => {}); + await userEvent.keyboard('{Escape}'); + + expect(onStop).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts index 3c846682b8c2..ca19b2e9c3c6 100644 --- a/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts +++ b/ui/apps/chat/tests/client/chat-form-voice.svelte.test.ts @@ -43,7 +43,7 @@ function seed( async function renderForm({ isLoading = false } = {}) { const recorder = new FakeVoiceRecorder(); - const state = $state({ files: [] as ChatUploadedFile[], sent: 0, value: '' }); + const state = $state({ files: [] as ChatUploadedFile[], sent: 0, stopped: 0, value: '' }); const screen = render(ChatFormVoiceTestWrapper, { isLoading, state, voiceRecorder: recorder }); await tick(); @@ -287,6 +287,20 @@ describe('while a reply streams', () => { .element(screen.getByRole('button', { name: VOICE_MODE_MESSAGE.voiceMessage }).last()) .toBeEnabled(); }); + + it('drops the recording on Escape, and the reply goes on', async () => { + seed(true, VoiceInputMode.DICTATION); + + const { recorder, recordingRow, screen, state } = await renderForm({ isLoading: true }); + + await screen.getByRole('button', { name: VOICE_MODE_MESSAGE.dictate }).last().click(); + await expect.poll(recordingRow).toBeTruthy(); + + await userEvent.keyboard('{Escape}'); + await expect.poll(recordingRow).toBeNull(); + expect(recorder.cancelled).toBe(1); + expect(state.stopped).toBe(0); + }); }); describe('recording', () => { diff --git a/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte b/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte index badea196b810..c97b0a62846f 100644 --- a/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte +++ b/ui/apps/chat/tests/client/components/ChatFormTestWrapper.svelte @@ -7,11 +7,23 @@ expandable?: boolean; /** The message the form starts with, as a restored draft would be. */ initialValue?: string; + /** A reply is streaming: the form offers stop in place of send. */ + isLoading?: boolean; + onStop?: () => void; onSubmit?: () => void; singleRow?: boolean; + systemMode?: boolean; } - let { expandable = false, initialValue = '', onSubmit, singleRow = false }: Props = $props(); + let { + expandable = false, + initialValue = '', + isLoading = false, + onStop, + onSubmit, + singleRow = false, + systemMode = false + }: Props = $props(); let value = $state(untrack(() => initialValue)); let form: ChatForm | undefined = $state(); @@ -22,5 +34,14 @@ - + diff --git a/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte b/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte index 34dfe4ce77ef..9c02dcd9b0b6 100644 --- a/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte +++ b/ui/apps/chat/tests/client/components/ChatFormVoiceTestWrapper.svelte @@ -6,8 +6,8 @@ interface Props { /** A reply is streaming: the form offers stop in place of send. */ isLoading?: boolean; - /** The form's message and files, kept in step with it for the test to read, and how often it sent. */ - state: { files: ChatUploadedFile[]; sent?: number; value: string }; + /** The form's message and files, kept in step with it for the test to read, and how often it sent or stopped. */ + state: { files: ChatUploadedFile[]; sent?: number; stopped?: number; value: string }; voiceRecorder: VoiceRecorderLike; } @@ -19,6 +19,7 @@ bind:uploadedFiles={state.files} bind:value={state.value} {isLoading} + onStop={() => (state.stopped = (state.stopped ?? 0) + 1)} onSubmit={() => (state.sent = (state.sent ?? 0) + 1)} {voiceRecorder} /> From d9dae03443bd8cae19b2ecd75d5da316b0b238e7 Mon Sep 17 00:00:00 2001 From: lhez Date: Wed, 25 Nov 2026 11:20:30 -0800 Subject: [PATCH 06/47] opencl: Adreno E17 compiler quirks off by default (#33013) --- docs/backend/OPENCL.md | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 10 +++++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/backend/OPENCL.md b/docs/backend/OPENCL.md index c912d331cbc2..1f04e94ba008 100644 --- a/docs/backend/OPENCL.md +++ b/docs/backend/OPENCL.md @@ -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. diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 18d8b9ce56ea..2770c16385ae 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -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; } From acb269e511d256060c88d79a3219e9e6d7c5d681 Mon Sep 17 00:00:00 2001 From: Gabor Nagy Date: Wed, 25 Nov 2026 19:27:14 +0000 Subject: [PATCH 07/47] nix : fix build on darwin (#32955) `darwin.apple_sdk` is deprecated and has been removed. It's not needed anymore to build on darwin. --- .devops/nix/package.nix | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index ba499303b38f..78995be55896 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -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 ] From 8d35ba4f7bbb1c61673f9752fda4dc256524f94f Mon Sep 17 00:00:00 2001 From: bri-prism <288398250+bri-prism@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:28:59 -0800 Subject: [PATCH 08/47] metal : revert "metal: increase default command buffers on iPhone (#31815)" (#33050) This reverts commit 1f3ea67fbf857bb831d3fb9e3a91c0f8ad3fbe78. --- ggml/src/ggml-metal/ggml-metal.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 7aee237cc123..bcd70c797f54 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -9,8 +9,6 @@ #include "ggml-metal-ops.h" #include "ggml-metal-tuning.h" -#include - #include #include @@ -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; From 5917b39ff7b58a808eced9d5c3d63b06f57d6972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergio=20S=C3=A1nchez=20Vall=C3=A9s?= Date: Wed, 25 Nov 2026 20:49:09 +0100 Subject: [PATCH 09/47] 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 --- conversion/inkling2.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/conversion/inkling2.py b/conversion/inkling2.py index 16f030619bca..3b4b140e37ff 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -248,6 +248,12 @@ def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: 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]) From 7135e2fd6979d99f76337c81f42ef4466f801f5a Mon Sep 17 00:00:00 2001 From: Pascal Date: Wed, 25 Nov 2026 22:39:14 +0100 Subject: [PATCH 10/47] 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 --- ggml/src/ggml-metal/ggml-metal-device.cpp | 4 ++-- ggml/src/ggml-metal/kernels/mul_mv.metal | 9 ++++++--- tests/test-backend-ops.cpp | 9 +++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index c4e6ded8b721..47a1b7c07837 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -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); diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index 1d6123f42e97..08873502e4db 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -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; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 098350f9f5a7..922d27cd040d 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -12602,6 +12602,15 @@ static std::vector> make_test_cases_eval() { #endif test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 31, 509, 2051, {1, 1}, {1, 1})); + + // a few rows of a few columns against many rows, batched (the weighted sum over the depth states of Inkling 2) + for (int64_t m : {1, 3, 8, 33}) { + for (int64_t k : {2, 5, 24, 31}) { + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, m, 2304, k, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, m, 97, k, {7, 2}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, m, 33, k, {2, 3}, {2, 1})); + } + } test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 32, 509, 2112, {1, 1}, {1, 1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 32, 509, 2112, {1, 1}, {1, 1})); From 9c003a97ab34a69cc49243f9b02014038205ffae Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Wed, 25 Nov 2026 22:39:55 +0100 Subject: [PATCH 11/47] 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) --- ui/apps/chat/.storybook/preview.ts | 3 +- ui/apps/chat/AGENTS.md | 2 +- ui/apps/chat/DESIGN.md | 10 + ui/apps/chat/alias/package.json | 4 +- ui/apps/chat/demo/helpers.ts | 97 +++- ui/apps/chat/package-lock.json | 4 +- ui/apps/chat/package.json | 2 +- ui/apps/chat/src/app.css | 5 +- .../app/chat/ChatForm/ChatForm.svelte | 3 +- .../ChatFormActionAddDrawer.svelte | 427 ++++++++++++------ .../ChatFormActionAddToolsSubmenu.svelte | 10 +- .../ChatFormActions/ChatFormActions.svelte | 12 +- .../app/dialogs/DialogSearch.svelte | 5 +- .../src/lib/components/app/dialogs/index.ts | 5 +- .../ModelsSelector/ModelsSelector.svelte | 127 ++---- .../ModelsSelectorDrawer.svelte | 58 --- .../ModelsSelector/ModelsSelectorList.svelte | 25 +- .../ModelsSelector/ModelsSelectorSheet.svelte | 396 ++++++++++++++++ .../app/models/ModelsSelector/index.ts | 2 +- .../SidebarNavigation.svelte | 83 ++-- .../SidebarNavigationFooter.svelte | 18 +- .../lib/components/app/navigation/index.ts | 2 +- .../settings/SettingsChat/SettingsChat.svelte | 38 +- .../SettingsChat/SettingsChatFields.svelte | 85 ++-- .../SettingsChatFieldsInset.svelte | 338 ++++++++++++++ .../SettingsChatImportExportSection.svelte | 74 ++- .../SettingsChatImportExportTab.svelte | 250 +++++++--- .../SettingsChat/SettingsChatToolsTab.svelte | 104 ++--- .../SettingsChat/SettingsChatVoiceTab.svelte | 159 +++++-- .../SettingsChatDesktopSidebar.svelte | 2 +- .../SettingsSheet/SettingsSheet.svelte | 377 ++++++++++++++++ .../SettingsSheet/SettingsSheetTools.svelte | 188 ++++++++ .../src/lib/components/app/settings/index.ts | 12 + .../constants/attachment-menu.constants.ts | 14 +- .../lib/constants/css-classes.constants.ts | 8 +- ui/apps/chat/src/lib/constants/index.ts | 1 + .../src/lib/constants/routes.constants.ts | 5 - .../lib/constants/settings-keys.constants.ts | 2 +- .../src/lib/constants/settings.constants.ts | 21 +- .../chat/src/lib/constants/sheet.constants.ts | 82 ++++ .../constants/tool-call-phrasing.constants.ts | 27 ++ .../chat/src/lib/constants/ui.constants.ts | 23 +- ui/apps/chat/src/lib/enums/index.ts | 10 +- ui/apps/chat/src/lib/enums/settings.enums.ts | 19 + ui/apps/chat/src/lib/enums/sheet.enums.ts | 22 + ui/apps/chat/src/lib/enums/ui.enums.ts | 1 - .../use-settings-field-defaults.svelte.ts | 56 +++ .../src/lib/hooks/use-tool-settings.svelte.ts | 61 +++ .../src/lib/hooks/use-tools-panel.svelte.ts | 4 +- .../conversations/preferences.svelte.ts | 2 +- .../chat/src/lib/stores/mcp/index.svelte.ts | 11 + .../src/lib/stores/settings/index.svelte.ts | 8 +- ui/apps/chat/src/lib/stores/ui.svelte.ts | 23 +- ui/apps/chat/src/lib/types/chat.d.ts | 4 + ui/apps/chat/src/lib/types/settings.d.ts | 4 + ui/apps/chat/src/lib/utils/config-helpers.ts | 17 + ui/apps/chat/src/lib/utils/index.ts | 10 +- ui/apps/chat/src/lib/utils/model-list.ts | 30 ++ ui/apps/chat/src/lib/utils/tool-ui.ts | 28 +- ui/apps/chat/src/routes/+layout.svelte | 9 +- .../chat/src/routes/mcp-servers/+page.svelte | 31 -- ui/apps/chat/src/routes/mcp-servers/+page.ts | 11 - .../ModelsSelectorListWrapper.svelte | 12 +- .../client/mcp-enable-setting.svelte.test.ts | 34 ++ .../models-selector-mobile.svelte.test.ts | 30 +- .../models-selector-sections.svelte.test.ts | 57 +++ .../client/nested-surfaces.svelte.test.ts | 2 +- .../ChatFormActionAddDrawer.stories.svelte | 44 ++ .../form/ChatFormAddSheetStoryHost.svelte | 57 +++ .../tests/stories/introduction/sections.ts | 1 + .../stories/mobile/MobileFlows.stories.svelte | 20 + .../chat/tests/stories/mobile/MobileFlows.svx | 77 ++++ .../tests/stories/mobile/SheetFlow.svelte | 27 ++ ui/apps/chat/tests/stories/mobile/flows.ts | 49 ++ .../models/ModelsSelectorSheet.stories.svelte | 72 +++ .../settings/SettingsSheet.stories.svelte | 54 +++ .../chat/tests/unit/chat-only-build.test.ts | 13 +- .../chat/tests/unit/models-quick-list.test.ts | 65 +++ .../chat/tests/unit/settings-platform.test.ts | 36 ++ ui/lib/ui/README.md | 2 +- ui/lib/ui/package-lock.json | 4 +- ui/lib/ui/package.json | 2 +- .../components/app/forms/NativeSelect.svelte | 96 ++++ .../components/app/forms/SearchInput.svelte | 5 +- .../ui/src/lib/components/app/forms/index.ts | 3 + .../components/app/sheets/InsetList.svelte | 39 ++ .../components/app/sheets/InsetListRow.svelte | 62 +++ .../app/sheets/InsetListSplitRow.svelte | 60 +++ .../components/app/sheets/SheetHeader.svelte | 64 +++ .../components/app/sheets/SheetPages.svelte | 68 +++ .../ui/src/lib/components/app/sheets/index.ts | 16 + .../app/sheets/sheet-pages.svelte.ts | 63 +++ .../ui/drawer/drawer-content.svelte | 4 +- .../lib/components/ui/switch/switch.svelte | 11 +- ui/lib/ui/src/lib/constants/index.ts | 1 + .../ui/src/lib/constants/sheet.constants.ts | 20 + ui/lib/ui/src/lib/index.ts | 5 +- ui/lib/ui/src/lib/styles/surfaces.css | 86 ++++ .../ui/src/lib/styles/tokens/components.css | 4 + .../stories/app/InsetList.stories.svelte | 119 +++++ .../stories/app/NativeSelect.stories.svelte | 95 ++++ .../ui/tests/stories/app/Sheet.stories.svelte | 96 ++++ .../foundations/Surfaces.stories.svelte | 21 + 103 files changed, 4324 insertions(+), 743 deletions(-) delete mode 100644 ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorDrawer.svelte create mode 100644 ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorSheet.svelte create mode 100644 ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFieldsInset.svelte create mode 100644 ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheet.svelte create mode 100644 ui/apps/chat/src/lib/components/app/settings/SettingsSheet/SettingsSheetTools.svelte create mode 100644 ui/apps/chat/src/lib/constants/sheet.constants.ts create mode 100644 ui/apps/chat/src/lib/enums/sheet.enums.ts create mode 100644 ui/apps/chat/src/lib/hooks/use-settings-field-defaults.svelte.ts create mode 100644 ui/apps/chat/src/lib/hooks/use-tool-settings.svelte.ts delete mode 100644 ui/apps/chat/src/routes/mcp-servers/+page.svelte delete mode 100644 ui/apps/chat/src/routes/mcp-servers/+page.ts create mode 100644 ui/apps/chat/tests/client/mcp-enable-setting.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/models-selector-sections.svelte.test.ts create mode 100644 ui/apps/chat/tests/stories/chat/form/ChatFormActionAddDrawer.stories.svelte create mode 100644 ui/apps/chat/tests/stories/chat/form/ChatFormAddSheetStoryHost.svelte create mode 100644 ui/apps/chat/tests/stories/mobile/MobileFlows.stories.svelte create mode 100644 ui/apps/chat/tests/stories/mobile/MobileFlows.svx create mode 100644 ui/apps/chat/tests/stories/mobile/SheetFlow.svelte create mode 100644 ui/apps/chat/tests/stories/mobile/flows.ts create mode 100644 ui/apps/chat/tests/stories/models/ModelsSelectorSheet.stories.svelte create mode 100644 ui/apps/chat/tests/stories/settings/SettingsSheet.stories.svelte create mode 100644 ui/apps/chat/tests/unit/models-quick-list.test.ts create mode 100644 ui/apps/chat/tests/unit/settings-platform.test.ts create mode 100644 ui/lib/ui/src/lib/components/app/forms/NativeSelect.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/InsetList.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/InsetListRow.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/InsetListSplitRow.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/SheetHeader.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/SheetPages.svelte create mode 100644 ui/lib/ui/src/lib/components/app/sheets/index.ts create mode 100644 ui/lib/ui/src/lib/components/app/sheets/sheet-pages.svelte.ts create mode 100644 ui/lib/ui/src/lib/constants/sheet.constants.ts create mode 100644 ui/lib/ui/tests/stories/app/InsetList.stories.svelte create mode 100644 ui/lib/ui/tests/stories/app/NativeSelect.stories.svelte create mode 100644 ui/lib/ui/tests/stories/app/Sheet.stories.svelte diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 47c884fd0f99..45fe7809f6a6 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -51,6 +51,7 @@ const preview: Preview = { [ 'Foundations', ['Safe areas', 'Brand'], + 'Mobile', 'Chat', [ 'ChatScreen', @@ -65,7 +66,7 @@ const preview: Preview = { 'MCP', 'Navigation', 'Settings', - ['DialogSettingsChat', 'Navigation', 'Sections'], + ['DialogSettingsChat', 'SettingsSheet', 'Navigation', 'Sections'], 'Dialogs', 'Forms', 'Actions', diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index 0b4884de3167..a80c128cab7b 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -3,7 +3,7 @@ These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`). - **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. -- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. +- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. - **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together. - **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index fc624676d487..cda28f00db3b 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -1097,6 +1097,16 @@ screens. Status lamps, avatars and the round icon buttons in the chat form are f shade, which makes a field. Unlike the other `matte-glass` surfaces it does not blur: it already sits on glass, and a second backdrop blur re-paints the panel's fill behind it and turns the group visibly lighter, whatever its own fill. +- **Inset lists:** a phone's sheets (settings, add to chat, the model picker) list their + options the native way. `inset-list` is an inset group of rows, `inset-list-row` a row a + finger tall (3rem) that is tappable as a whole, and `inset-list-row-body` its label and value, + whose top border is the divider: it starts at the label, past the row's icon, and the first + row has none. `inset-list-title` sits above a group and `inset-list-caption` below it. Inside + a drawer the groups take `--sheet-group-radius` (1.25rem, the chat form's single-row radius) in place of the card radius, to sit + with the sheet's own 2.5rem corners. A sheet's close or back key is `sheet-key`, a round key + 1rem from the top and from the side, with the title centered on its middle. Build them with Llama UI's + `InsetList`, `InsetListRow`, `InsetListSplitRow`, `SheetHeader` and `SheetPages` + (`@ggml-org/llama-ui/app/sheets`) rather than with the utilities by hand. - **Selected rows:** `selected-row-surface` marks the row a sidebar list is on: a conversation, a project or a top action, on desktop and on a phone. It is a 5% tint of the text colour, under hover's 10%, with the inset group's edge and shade, so the selected row diff --git a/ui/apps/chat/alias/package.json b/ui/apps/chat/alias/package.json index 08662397324d..2c306f455e08 100644 --- a/ui/apps/chat/alias/package.json +++ b/ui/apps/chat/alias/package.json @@ -1,6 +1,6 @@ { "name": "llama-chat", - "version": "0.2.0", + "version": "0.3.0", "description": "npx llama-chat: runs Llama Chat, the chat app for llama.cpp. Same as npx @ggml-org/llama-chat.", "keywords": [ "llama.cpp", @@ -28,6 +28,6 @@ "node": ">=20" }, "dependencies": { - "@ggml-org/llama-chat": "0.2.0" + "@ggml-org/llama-chat": "0.3.0" } } diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts index 6712d5c7b887..f814922f3468 100644 --- a/ui/apps/chat/demo/helpers.ts +++ b/ui/apps/chat/demo/helpers.ts @@ -237,6 +237,26 @@ export class Demo { this.y = (viewport?.height ?? 0) / 2; } + /** + * Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a + * phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip. + */ + async hold(target: Locator, ms = 900, after = 500): Promise { + await target.scrollIntoViewIfNeeded(); + + const { x, y } = await this.center(target); + const cdp = await this.session(); + + await this.page.waitForTimeout(this.between(60, 140)); + await cdp.send('Input.dispatchTouchEvent', { touchPoints: [{ x, y }], type: 'touchStart' }); + await this.page.waitForTimeout(ms); + await cdp.send('Input.dispatchTouchEvent', { touchPoints: [], type: 'touchEnd' }); + await this.liftFingers(); + this.x = x; + this.y = y; + await this.pause(after); + } + async hover(target: Locator, ms = 350): Promise { await this.moveTo(target); await this.pause(ms); @@ -326,6 +346,11 @@ export class Demo { await this.pause(ms); } + /** Taps `target` with a fingertip, on a touch device. */ + tap(target: Locator, after = 500): Promise { + return this.hold(target, this.between(60, 110), after); + } + /** Types quickly with uneven key timing, a little slower after spaces and punctuation. */ async type(target: Locator, text: string, ms = 500): Promise { await this.click(target, 200); @@ -447,6 +472,8 @@ export class Demo { } interface DemoOptions { + /** Empty conversations added to the library before the demo starts, e.g. to fill a list. */ + chats: number; /** Path the demo starts from. */ startPath: string; /** Extra UI settings merged into the seeded config. */ @@ -478,7 +505,7 @@ function loadTrace(name: string, dir: string): string { return readFileSync(join(dir, `${name}.jsonl`), 'utf8'); } -/** Imports conversations through Settings > Import/Export, like a user would. */ +/** Imports conversations through Settings > Data, like a user would. */ async function importTraces(page: Page, file: string): Promise { // the expanded sidebar adds the shortcut to the name const settings = page.getByRole('button', { name: /^Settings(\s|$)/ }).first(); @@ -515,7 +542,12 @@ async function importTraces(page: Page, file: string): Promise { const scope = (await page.getByRole('dialog').count()) > 0 ? page.getByRole('dialog') : page; - await scope.getByText('Import/Export', { exact: true }).filter({ visible: true }).click(); + // the section is Data in the regrouped settings, Import/Export before + await scope + .getByText(/^(Data|Import\/Export)$/) + .filter({ visible: true }) + .first() + .click(); const chooser = page.waitForEvent('filechooser'); @@ -544,11 +576,66 @@ async function importTraces(page: Page, file: string): Promise { }); } +/** The app's IndexedDB database and its conversations store, which a demo seeds. */ +const DEMO_DATABASE = 'LlamaUi'; +const DEMO_CONVERSATIONS_STORE = 'conversations'; +const HOUR_MS = 3_600_000; +/** Names of the seeded conversations, repeated when a demo asks for more. */ +const DEMO_CHAT_NAMES = [ + 'Plan a trip to Lisbon', + 'Explain tail recursion', + 'Draft a polite follow-up', + 'Summarize this changelog', + 'Regex for ISO dates', + 'Ideas for a weekend project', + 'Debug a flaky test', + 'Meal plan for the week' +]; + +/** Adds `count` empty conversations to the library, so a list has enough chats to fold. */ +async function seedChats(page: Page, count: number): Promise { + await page.goto('/'); + await page + .getByRole('textbox', { name: 'Type a message...' }) + .waitFor({ timeout: APP_READY_TIMEOUT_MS }); + await page.evaluate( + async ({ database, hourMs, names, store, total }) => { + const request = indexedDB.open(database); + const db = await new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + const tx = db.transaction(store, 'readwrite'); + + for (let i = 0; i < total; i++) { + tx.objectStore(store).put({ + currNode: null, + id: `demo-chat-${i}`, + lastModified: Date.now() - i * hourMs, + name: names[i % names.length] + }); + } + + await new Promise((resolve) => (tx.oncomplete = resolve)); + db.close(); + }, + { + database: DEMO_DATABASE, + hourMs: HOUR_MS, + names: DEMO_CHAT_NAMES, + store: DEMO_CONVERSATIONS_STORE, + total: count + } + ); +} + export const test = base.extend({ + chats: [0, { option: true }], demo: async ({ page }, use, testInfo) => { await use(new Demo(page, `${testInfo.file}:${testInfo.title}`)); }, - page: async ({ page, settings, startPath, traces }, use, testInfo) => { + + page: async ({ chats, page, settings, startPath, traces }, use, testInfo) => { await page.addInitScript(installCursorOverlay); await page.addInitScript(seedSettings, { mcpServers: JSON.stringify(demoMcpServerSettings()), @@ -568,10 +655,12 @@ export const test = base.extend({ await importTraces(page, file); } + if (chats > 0) await seedChats(page, chats); + await page.goto(startPath); // a hash route after the import doesn't reload, which the conversations list needs - if (traces.length > 0) await page.reload(); + if (traces.length > 0 || chats > 0) await page.reload(); // a fresh checkout's dev server optimizes its dependencies on the first load and reloads the // page, which can take well past an action's timeout; the recording has not started yet diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json index 5009e3ac3dd8..5ba3b6f46067 100644 --- a/ui/apps/chat/package-lock.json +++ b/ui/apps/chat/package-lock.json @@ -1,12 +1,12 @@ { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "bin": { "llama-chat": "bin/cli.js" diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index 5273e2497b59..6ff5b6712fbc 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -1,6 +1,6 @@ { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.0", "description": "Llama Chat, the chat app for llama.cpp. Run it with npx @ggml-org/llama-chat against any llama-server.", "keywords": [ "llama.cpp", diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index 03e0e7d27424..6620a32a4d91 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -60,8 +60,9 @@ --chat-form-collapsed-height: 6.375rem; /* the empty chat form card, its text and actions in one row: a new chat centers its top edge */ --chat-form-resting-height: 3.375rem; - /* the chat form's corners while its text and actions share one row */ - --chat-form-single-row-radius: 1.25rem; + /* the chat form's corners while its text and actions share one row: a sheet group's, so the + phone sheets' search, groups and keys round alike */ + --chat-form-single-row-radius: var(--sheet-group-radius); /* the card's translucent fill over the page, made opaque: the phone sheet, and the page and Safari's bars around it */ --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); --max-message-height: max(24rem, min(80dvh, calc(100dvh - var(--chat-form-area-height) - 12rem))); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index ca2c651da467..6fa329d638e0 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -198,7 +198,7 @@ hasPrompts: () => { const prefs = conversationsStore.preferences; - if (!prefs.isCategoryEnabled(ToolSource.MCP)) return false; + if (!mcpStore.isFeatureEnabled || !prefs.isCategoryEnabled(ToolSource.MCP)) return false; return mcpStore .getServers() @@ -911,6 +911,7 @@ isVoiceRefining={voice.isRefining} micWarning={micUnavailableReason ?? micError} onFileUpload={handleFileUpload} + onFilesSelect={handleFileSelect} onMicClick={handleMicClick} {onStop} onSystemPromptClick={() => diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index fe3bff7bdbc2..8cd81d674168 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -1,28 +1,42 @@ + + + + +
- {@render trigger({ disabled: chatFormActions.disabled, onclick: () => (drawerOpen = true) })} - - - - {ATTACHMENT_MENU_TEXT.ADD_TO_CHAT} - - - {ATTACHMENT_MENU_TEXT.DESCRIPTION} - - - -
- - - - - {#if chatFormActions.onWorkingDirectoryClick} - - {/if} + {@render trigger({ disabled: chatFormActions.disabled, onclick: open })} - {#if toolsPanel.totalToolCount > 0} - (toolsExpanded = open)} open={toolsExpanded}> - - {#if toolsExpanded} - - {:else} - - {/if} - - - - {ATTACHMENT_MENU_TEXT.TOOLS} - - - -
- {#each toolsPanel.categoryGroups as group (group.key)} - {@render groupRow(group)} - {/each} - - {#each toolsPanel.mcpGroups as group (group.key)} - {@render groupRow(group)} - {/each} -
-
-
+ + + + {ATTACHMENT_MENU_TEXT.DESCRIPTION} + + + {#if page.id === AddSheetPage.ROOT} + {@render rootPage()} + {:else if page.id === AddSheetPage.TOOLS} + {@render toolsPage()} + {:else if currentGroup} + {@render groupPage(currentGroup)} {/if} -
+
+{#snippet rootPage()} + + {#if canUseCamera} + cameraInput?.click()}> + {ATTACHMENT_MENU_TEXT.CAMERA} + + {/if} + + + {ATTACHMENT_MENU_TEXT.ADD_FILES} + + {#if supportedModalities.length > 0} + + {#each supportedModalities as modality (modality.label)} + + {/each} + + {/if} + + + + + attachmentMenu.callbacks[AttachmentAction.SYSTEM_PROMPT_CLICK]()} + > + {ATTACHMENT_MENU_TEXT.SYSTEM_MESSAGE} + + + {#if chatFormActions.onWorkingDirectoryClick} + { + drawerOpen = false; + chatFormActions.onWorkingDirectoryClick?.(); + }} + > + {ATTACHMENT_MENU_TEXT.WORKING_DIRECTORY} + + + {chatFormActions.workingDirectory ?? ATTACHMENT_MENU_TEXT.NONE} + + + {/if} + + + {#if agenticMode.enabled} + push({ id: AddSheetPage.TOOLS })}> + {ATTACHMENT_MENU_TEXT.TOOLS} + + {#if toolsPanel.totalToolCount > 0} + + {enabledToolCount}/{toolsPanel.totalToolCount} + + {/if} + + {/if} + +{/snippet} + +{#snippet toolsPage()} + {#if toolsPanel.totalToolCount === 0} + + {#if toolsStore.loading} + + + + {ATTACHMENT_MENU_TEXT.LOADING_TOOLS} + + {:else if toolsStore.error && !toolsStore.isToolsEndpointUnreachable} + {ATTACHMENT_MENU_TEXT.TOOLS_FAILED} + {:else} + + + + {toolsPanel.noToolsInfoMessage ?? ATTACHMENT_MENU_TEXT.NO_TOOLS} + + {/if} + + {:else} + {#if toolsPanel.categoryGroups.length > 0} + + {#each toolsPanel.categoryGroups as group (group.key)} + {@render groupRow(group)} + {/each} + + {/if} + + {#if toolsPanel.mcpGroups.length > 0} + + {#each toolsPanel.mcpGroups as group (group.key)} + {@render groupRow(group)} + {/each} + + {/if} + {/if} +{/snippet} + +{#snippet groupSwitch(group: ToolGroup, label?: string)} + toolsPanel.toggleGroupByKey(group.key)} + size="lg" + /> +{/snippet} + {#snippet groupRow(group: ToolGroup)} - {@const checkState = toolsPanel.getGroupCheckState(group)} - {@const enabledCount = toolsPanel.getEnabledToolCount(group)} {@const favicon = toolsPanel.getFavicon(group)} - {@const groupDisabled = toolsPanel.isGroupDisabled(group)} + {@const isChecked = toolsPanel.getGroupCheckState(group).checked} - + {#snippet trailing()} + {@render groupSwitch( + group, + isChecked + ? ATTACHMENT_MENU_TEXT.DISABLE_GROUP(group.label) + : ATTACHMENT_MENU_TEXT.ENABLE_GROUP(group.label) + )} + {/snippet} + +{/snippet} + +{#snippet groupPage(group: ToolGroup)} + + + {ATTACHMENT_MENU_TEXT.ALL_TOOLS} + + {@render groupSwitch(group)} + + + + + {#each group.tools as entry (entry.key)} + + + {entry.definition.function.name} + + + toolsPanel.toggleTool(entry)} + size="lg" + /> + + {/each} + {/snippet} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte index 11474908693b..d14f91cb9a2a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte @@ -26,7 +26,7 @@
- Loading tools... + {ATTACHMENT_MENU_TEXT.LOADING_TOOLS}
{:else if toolsStore.isToolsEndpointUnreachable}
@@ -40,8 +40,8 @@ - - {#if uiStore.isMcpShown} + + {#if uiStore.isMcpEnabled} @@ -55,7 +55,7 @@
{:else if toolsStore.error}
- Failed to load tools + {ATTACHMENT_MENU_TEXT.TOOLS_FAILED}
{:else if toolsPanel.noToolsInfoMessage}
@@ -65,7 +65,7 @@
{:else}
- No tools available + {ATTACHMENT_MENU_TEXT.NO_TOOLS}
{/if} {:else} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index c895ef0c34b7..7db0cdf7845e 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -50,6 +50,7 @@ /** The chat's working directory, which the + menu names. */ workingDirectory?: string | null; onFileUpload?: () => void; + onFilesSelect?: (files: File[]) => void; onMicClick?: () => void; onStop?: () => void; onSystemPromptClick?: () => void; @@ -66,6 +67,7 @@ isSendWaiting = false, isVoiceRefining = false, micWarning = null, + onFilesSelect, onFileUpload, onMicClick, onStop, @@ -132,6 +134,9 @@ get hasVisionModality() { return hasVisionModality; }, + get onFilesSelect() { + return onFilesSelect; + }, get onFileUpload() { return onFileUpload; }, @@ -141,10 +146,13 @@ get onWorkingDirectoryClick() { return onWorkingDirectoryClick; }, - get workingDirectoryLabel() { + get workingDirectory() { return workingDirectory ? abbreviateWorkingDir(workingDirectory, toolsStore.serverHome) - : SET_WORKING_DIRECTORY_LABEL; + : null; + }, + get workingDirectoryLabel() { + return this.workingDirectory ?? SET_WORKING_DIRECTORY_LABEL; } }); diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index 80d0cb5fdc6f..9a241af2835b 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -22,7 +22,7 @@ ICON_CLASS_SM, ICON_CLASS_XS, SIDEBAR_ACTIONS_ITEMS, - sidebarFooterItems + SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts'; import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts'; @@ -32,7 +32,6 @@ HuggingFaceService } from '#lib/services/index.ts'; import { RouterService } from '#lib/services/router.service.ts'; - import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import { conversationsStore, deviceStore, @@ -249,7 +248,7 @@ const actionEntries = $derived.by((): SearchEntry[] => // every sidebar action the sidebar shows but Search itself, which is what opened this // dialog, and the models manager on a phone, which picks its models in the selector - [...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(agenticMode.enabled)] + [...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS] .filter( (item) => item.action && diff --git a/ui/apps/chat/src/lib/components/app/dialogs/index.ts b/ui/apps/chat/src/lib/components/app/dialogs/index.ts index 342a6a6f870a..ac2c655f3e9e 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts +++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts @@ -19,10 +19,9 @@ export { default as DialogMcpServerAddNew } from './DialogMcpServerAddNew.svelte'; /** - * **DialogMcpServers** - MCP servers dialog shown from the chat form + * **DialogMcpServers** - MCP servers dialog, opened with `uiStore.openMcpServers` * - * Shows the same MCP server list as the `/mcp-servers` route inside a modal - * dialog. + * Lists the MCP servers, to add, edit, turn on and remove them. */ export { default as DialogMcpServers } from './DialogMcpServers.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte index 07885351cc5a..6d03d06b448c 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelector.svelte @@ -1,21 +1,19 @@ + +{#snippet modelRow(item: ModelItem)} + {@const inChat = activeId === item.option.id} + {@const dictates = !inChat && voiceStore.isDictationModel(item.option.model)} + {@const isHeld = longPress.isPressing && pressed?.item === item} + {@const isLit = (menuOpen && menuItem === item) || (showFull && highlightedId === item.option.id)} + + + onSelect?.(item.option.id)} + onclickcapture={longPress.handleClickCapture} + oncontextmenu={longPress.handleContextMenu} + onpointercancel={longPress.handlePointerEnd} + onpointerdown={(event) => { + pressed = { item, row: event.currentTarget }; + longPress.handlePointerDown(event); + }} + onpointermove={longPress.handlePointerMove} + onpointerup={longPress.handlePointerEnd} + > + {#snippet leading()} + + {/snippet} + + + + + + + + + {#if inChat} + {@render role(MODELS_SHEET_TEXT.IN_CHAT, Check, 'text-(--action-primary)')} + {:else if dictates} + {@render role(MODELS_SHEET_TEXT.DICTATION, Mic, 'text-destructive')} + {/if} + +{/snippet} + +{#snippet role(label: string, Icon: typeof Check, iconClass: string)} + + {label} + + + +{/snippet} + + +{#snippet unavailableRow(model: string)} + + + + + {MODELS_SHEET_TEXT.NOT_AVAILABLE} + + +{/snippet} + + + + + + + event.preventDefault()} + overlayClass={uiStore.isModelDetailsOpen ? 'z-40' : undefined} + > + + + {MODELS_SHEET_TEXT.DESCRIPTION} + + + {#if unavailableModel} + {@render unavailableRow(unavailableModel)} + {/if} + + {#if showFull} + {#if isEmpty} +

{emptyMessage}

+ {:else} + {#each fullGroups as group (group.key)} + + {#each group.items as item (item.option.id)} + {@render modelRow(item)} + {/each} + + {/each} + {/if} + {:else} + + {#if quickItems.length > 0} + + {#each quickItems as item (item.option.id)} + {@render modelRow(item)} + {/each} + + {:else if isEmpty} +

{emptyMessage}

+ {/if} + + + + {MODELS_SHEET_TEXT.ALL_MODELS} + + + {/if} +
+ + +
+ {#if hasEffort} + + {/if} + + onSearchChange?.(value)} + onKeyDown={handleSearchKeyDown} + placeholder={MODELS_SHEET_TEXT.SEARCH_PLACEHOLDER} + value={searchTerm} + /> +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts index e234fbac33e0..4366be2898d3 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts @@ -3,7 +3,7 @@ export { default as ModelsSelector } from './ModelsSelector.svelte'; export { default as ModelsSelectorDropdown } from './ModelsSelectorDropdown.svelte'; -export { default as ModelsSelectorDrawer } from './ModelsSelectorDrawer.svelte'; +export { default as ModelsSelectorSheet } from './ModelsSelectorSheet.svelte'; export { default as ModelsSelectorList } from './ModelsSelectorList.svelte'; export { default as ModelsSelectorDownloadItem } from './ModelsSelectorDownloadItem.svelte'; export { default as ModelsSelectorOption } from './ModelsSelectorOption.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte index ebbc539f6418..ec77caace11b 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte @@ -1,5 +1,6 @@ - + diff --git a/ui/apps/chat/src/lib/components/app/navigation/index.ts b/ui/apps/chat/src/lib/components/app/navigation/index.ts index a4dc758ad1e9..0f74bc739a70 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/index.ts +++ b/ui/apps/chat/src/lib/components/app/navigation/index.ts @@ -182,7 +182,7 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si export { default as SidebarNavigationConversationList } from './SidebarNavigation/SidebarNavigationConversationList.svelte'; export { default as SidebarNavigationActions } from './SidebarNavigation/SidebarNavigationActions.svelte'; -/** The sidebar's footer: Models, MCP and Settings in a group inset in the sidebar. */ +/** The sidebar's footer: Models and Settings in a group inset in the sidebar. */ export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte'; /** diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index 17b00e9742ad..d150e9699387 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -20,9 +20,11 @@ } from '#lib/constants/index.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; - import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; + import { deviceStore, modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts'; + import { isSettingShownOn } from '#lib/utils/index.ts'; import { setMode } from 'mode-watcher'; + import { tick } from 'svelte'; import { fade } from 'svelte/transition'; interface Props { initialSection?: string; @@ -36,13 +38,32 @@ const sections = $derived(settingsChatSections(agenticMode.enabled)); - let activeSlug = $derived(initialSection ?? 'general'); + let activeSlug = $derived(initialSection ?? SETTINGS_SECTION_SLUGS.GENERAL); + + let contentEl = $state(); + + // a new section starts at its top, whether the dialog, the drawer or the page scrolls + function scrollToTop() { + let el: HTMLElement | null = contentEl ?? null; + + while (el) { + const { overflowY } = getComputedStyle(el); + + if ((overflowY === 'auto' || overflowY === 'scroll') && el.scrollHeight > el.clientHeight) + break; + + el = el.parentElement; + } + + (el ?? document.scrollingElement)?.scrollTo({ top: 0 }); + } function handleSectionChange(section: SettingsSectionTitle) { const found = sections.find((s) => s.title === section); - if (found) { + if (found && found.slug !== activeSlug) { activeSlug = found.slug; + void tick().then(scrollToTop); } onSectionChange?.(section); @@ -54,6 +75,11 @@ let localConfig: SettingsConfigType = $state({ ...settingsStore.config }); + // a setting for another kind of device is left out + let sectionFields = $derived( + (currentSection.fields ?? []).filter((field) => isSettingShownOn(field, deviceStore.isMobile)) + ); + // inputs hand back strings for numeric fields, so compare stringified values let hasChanges = $derived.by(() => { const saved = settingsStore.config; @@ -176,7 +202,7 @@ {sections} /> -
+
{#if currentSection.slug === SETTINGS_SECTION_SLUGS.TOOLS} @@ -185,14 +211,14 @@ {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE && currentSection.fields} {:else if currentSection.fields}
+ import { Button } from '@ggml-org/llama-ui/ui/button'; import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox'; import { Input } from '@ggml-org/llama-ui/ui/input'; import { Label } from '@ggml-org/llama-ui/ui/label'; @@ -6,15 +7,18 @@ import * as Select from '@ggml-org/llama-ui/ui/select'; import { Textarea } from '@ggml-org/llama-ui/ui/textarea'; import { FlaskConical, RotateCcw } from '@lucide/svelte'; + import McpLogo from '#lib/components/app/mcp/McpLogo.svelte'; import { SettingsChatParameterSourceIndicator } from '#lib/components/app/settings/index.ts'; import { ICON_CLASS_DEFAULT, ICON_CLASS_SM, + MANAGE_MCP_SERVERS_LABEL, SETTING_CONFIG_INFO, SETTINGS_KEYS } from '#lib/constants/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; - import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; + import { useSettingsFieldDefaults } from '#lib/hooks/use-settings-field-defaults.svelte.ts'; + import { settingsStore, uiStore } from '#lib/stores/index.ts'; import { normalizeFloatingPoint } from '#lib/utils/precision.ts'; import type { Component } from 'svelte'; @@ -27,35 +31,8 @@ let { fields, localConfig, onConfigChange, onThemeChange }: Props = $props(); - // discover needs the hub metadata reads, and opens from the Models page, so both checkboxes - // are read-only while discover is on - let discoverOn = $derived(Boolean(localConfig[SETTINGS_KEYS.ENABLE_DISCOVER_MODELS])); - - function isLockedField(key: string): boolean { - return ( - discoverOn && - (key === SETTINGS_KEYS.USE_HUGGING_FACE_HUB || key === SETTINGS_KEYS.SHOW_MODELS_MANAGER) - ); - } - - let currentModelParams = $derived.by(() => { - void modelsStore.props.cacheVersion; - - if (serverStore.isRouterMode) { - const currentModelName = modelsStore.selectedModelName; - - if (currentModelName) { - const currentModelProps = modelsStore.props.getModelProps(currentModelName); - - return (currentModelProps?.default_generation_settings?.params ?? {}) as Record< - string, - unknown - >; - } - } - - return (serverStore.defaultParams ?? {}) as Record; - }); + const fieldDefaults = useSettingsFieldDefaults(() => localConfig); + let currentModelParams = $derived(fieldDefaults.serverDefaults); {#each fields as field (field.key)} @@ -63,23 +40,7 @@
{#if field.type === SettingsFieldType.INPUT} {@const currentValue = String(localConfig[field.key] ?? '')} - {@const serverDefault = currentModelParams[field.key]} - {@const isCustomRealTime = (() => { - if (serverDefault == null) return false; - - if (currentValue === '') return false; - - const numericInput = parseFloat(currentValue); - const normalizedInput = !isNaN(numericInput) - ? Math.round(numericInput * 1000000) / 1000000 - : currentValue; - const normalizedDefault = - typeof serverDefault === 'number' - ? Math.round(serverDefault * 1000000) / 1000000 - : serverDefault; - - return normalizedInput !== normalizedDefault; - })()} + {@const isCustomRealTime = fieldDefaults.isCustom(field)}