Commit c94333133 for llama.cpp

commit c943331339fb503503b21cc490f08d986bfdb1cf
Author: Pascal <admin@serveurperso.com>
Date:   Wed Nov 25 18:39:50 2026 +0100

    model : add hy_v4_flash on the DSA iSWA cache (#32960)

    * model : add hy_v4_flash on the DSA iSWA cache

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

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

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

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

    * convert : add hy_v4_flash

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

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

    * tests : add hy_v4_flash to test-llama-archs

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

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

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

    * tests : add the hy_v4_flash Metal fusion baseline

    * model, mtmd : add hy_v4_flash vision

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

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

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

    * CUDA: lightning indexer for 16 heads

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

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

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

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

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

    * llama : use a unified KV cache for Hy4 flash

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

    * rm redundant code in mtmd

    * clean up comments

    ---------

    Co-authored-by: Xuan Son Nguyen <son@huggingface.co>

diff --git a/conversion/__init__.py b/conversion/__init__.py
index 146c309e6..59ea85094 100644
--- a/conversion/__init__.py
+++ b/conversion/__init__.py
@@ -146,6 +146,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
     "HrmTextForCausalLM": "hrm_text",
     "HYV3ForCausalLM": "hunyuan",
     "HYV4ForCausalLM": "hy_v4",
+    "HYV4FlashForCausalLM": "hy_v4_flash",
     "IQuestCoderForCausalLM": "llama",
     "Inkling2ForCausalLM": "inkling2",
     "Inkling2LoopForCausalLM": "inkling2",
@@ -390,6 +391,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
     "GraniteSpeechPlusForConditionalGeneration": "granite",
     "HiggsAudio3Model": "higgs_audio",
     "HunYuanVLForConditionalGeneration": "hunyuan",
+    "HYV4FlashForCausalLM": "hy_v4_flash",
+    "HYV4FlashForConditionalGeneration": "hy_v4_flash",
     "Idefics3ForConditionalGeneration": "smolvlm",
     "Inkling2ForConditionalGeneration": "inkling2",
     "Inkling2LoopForConditionalGeneration": "inkling2",
diff --git a/conversion/hy_v4_flash.py b/conversion/hy_v4_flash.py
new file mode 100644
index 000000000..309b61b64
--- /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 b7939243b..ff6402e47 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 57852fad6..bebc87067 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 @@ MODEL_ARCH_NAMES: dict[MODEL_ARCH, str] = {
     MODEL_ARCH.HUNYUAN_VL:       "hunyuan_vl",
     MODEL_ARCH.HY_V3:            "hy_v3",
     MODEL_ARCH.HY_V4:            "hy_v4",
+    MODEL_ARCH.HY_V4_FLASH:      "hy_v4_flash",
     MODEL_ARCH.SMOLLM3:          "smollm3",
     MODEL_ARCH.GPT_OSS:          "gpt-oss",
     MODEL_ARCH.LFM2:             "lfm2",
@@ -2180,6 +2187,7 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
     MODEL_TENSOR.INDEXER_COMPRESSOR_NORM:   "blk.{bid}.indexer_compressor_norm",
     MODEL_TENSOR.INDEXER_KPOOL_GATE:        "blk.{bid}.indexer_compressor_gate",
     MODEL_TENSOR.INDEXER_KPOOL_APE:         "blk.{bid}.indexer_compressor_ape",
+    MODEL_TENSOR.INDEXER_KPOOL_VALUE:       "blk.{bid}.indexer_compressor_value",
     # vision
     MODEL_TENSOR.V_MMPROJ:                  "mm.{bid}",
     MODEL_TENSOR.V_MMPROJ_FC:               "mm.model.fc",
@@ -2602,6 +2610,10 @@ TENSOR_NAMES: dict[MODEL_TENSOR, str] = {
     MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM:    "markov_ctx_norm",
     MODEL_TENSOR.ENGRAM_KV:                 "blk.{bid}.engram_kv",
     MODEL_TENSOR.ENGRAM_GATE:               "blk.{bid}.engram_gate",
+    MODEL_TENSOR.ENGRAM_KV_B:               "blk.{bid}.engram_kv_b",
+    MODEL_TENSOR.ENGRAM_LOOKUP_NORM:        "blk.{bid}.engram_lookup_norm",
+    MODEL_TENSOR.ENGRAM_PRE_GAMMA:          "blk.{bid}.engram_pre_gamma",
+    MODEL_TENSOR.ENGRAM_HC_SCALE:           "blk.{bid}.engram_hc_scale",
     MODEL_TENSOR.DFLASH_ATTN_CONV_BASE:     "blk.{bid}.attn_conv_base",
     MODEL_TENSOR.DFLASH_ATTN_CONV_PROJ:     "blk.{bid}.attn_conv_proj",
     MODEL_TENSOR.DFLASH_FFN_CONV_BASE:      "blk.{bid}.ffn_conv_base",
@@ -6102,6 +6114,67 @@ MODEL_TENSORS: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
         MODEL_TENSOR.FFN_DOWN_SHEXP,
         MODEL_TENSOR.FFN_UP_SHEXP,
     ],
+    MODEL_ARCH.HY_V4_FLASH: [
+        MODEL_TENSOR.TOKEN_EMBD,
+        MODEL_TENSOR.OUTPUT_NORM,
+        MODEL_TENSOR.OUTPUT,
+        MODEL_TENSOR.ROPE_FREQS,
+        MODEL_TENSOR.HC_HEAD_FN,
+        MODEL_TENSOR.HC_HEAD_BASE,
+        MODEL_TENSOR.HC_HEAD_SCALE,
+        MODEL_TENSOR.ATTN_NORM,
+        MODEL_TENSOR.ATTN_SINKS,
+        MODEL_TENSOR.ATTN_Q_A,
+        MODEL_TENSOR.ATTN_Q_A_NORM,
+        MODEL_TENSOR.ATTN_Q_B,
+        MODEL_TENSOR.ATTN_KV_A_MQA,
+        MODEL_TENSOR.ATTN_KV_A_NORM,
+        MODEL_TENSOR.ATTN_K_B,
+        MODEL_TENSOR.ATTN_V_B,
+        MODEL_TENSOR.ATTN_OUT,
+        MODEL_TENSOR.ATTN_GATE,
+        MODEL_TENSOR.INDEXER_K_NORM,
+        MODEL_TENSOR.INDEXER_PROJ,
+        MODEL_TENSOR.INDEXER_ATTN_K,
+        MODEL_TENSOR.INDEXER_ATTN_Q_B,
+        MODEL_TENSOR.HC_ATTN_FN,
+        MODEL_TENSOR.HC_ATTN_BASE,
+        MODEL_TENSOR.HC_ATTN_SCALE,
+        MODEL_TENSOR.HC_FFN_FN,
+        MODEL_TENSOR.HC_FFN_BASE,
+        MODEL_TENSOR.HC_FFN_SCALE,
+        MODEL_TENSOR.FFN_GATE_INP,
+        MODEL_TENSOR.FFN_EXP_PROBS_B,
+        MODEL_TENSOR.FFN_NORM,
+        MODEL_TENSOR.FFN_GATE,
+        MODEL_TENSOR.FFN_DOWN,
+        MODEL_TENSOR.FFN_UP,
+        MODEL_TENSOR.FFN_GATE_EXP,
+        MODEL_TENSOR.FFN_DOWN_EXP,
+        MODEL_TENSOR.FFN_UP_EXP,
+        MODEL_TENSOR.FFN_GATE_SHEXP,
+        MODEL_TENSOR.FFN_DOWN_SHEXP,
+        MODEL_TENSOR.FFN_UP_SHEXP,
+        MODEL_TENSOR.ATTN_POST_NORM,
+        MODEL_TENSOR.FFN_POST_NORM,
+        MODEL_TENSOR.FFN_ROUTED_DOWN,
+        MODEL_TENSOR.FFN_ROUTED_UP,
+        MODEL_TENSOR.PER_LAYER_TOKEN_EMBD,
+        MODEL_TENSOR.ENGRAM_KV,
+        MODEL_TENSOR.ENGRAM_GATE,
+        MODEL_TENSOR.ENGRAM_KV_B,
+        MODEL_TENSOR.ENGRAM_LOOKUP_NORM,
+        MODEL_TENSOR.ENGRAM_PRE_GAMMA,
+        MODEL_TENSOR.ENGRAM_HC_SCALE,
+        MODEL_TENSOR.INDEXER_KPOOL_GATE,
+        MODEL_TENSOR.INDEXER_KPOOL_APE,
+        MODEL_TENSOR.INDEXER_KPOOL_VALUE,
+        MODEL_TENSOR.INDEXER_COMPRESSOR_NORM,
+        MODEL_TENSOR.NEXTN_EH_PROJ,
+        MODEL_TENSOR.NEXTN_ENORM,
+        MODEL_TENSOR.NEXTN_HNORM,
+        MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
+    ],
     MODEL_ARCH.SMOLLM3: [
         MODEL_TENSOR.TOKEN_EMBD,
         MODEL_TENSOR.OUTPUT_NORM,
@@ -7282,6 +7355,10 @@ MODEL_TENSOR_SKIP: dict[MODEL_ARCH, list[MODEL_TENSOR]] = {
         MODEL_TENSOR.ROPE_FREQS,
         MODEL_TENSOR.ATTN_ROT_EMBD,
     ],
+    MODEL_ARCH.HY_V4_FLASH: [
+        MODEL_TENSOR.ROPE_FREQS,
+        MODEL_TENSOR.ATTN_ROT_EMBD,
+    ],
     MODEL_ARCH.XING4_0: [
         MODEL_TENSOR.ROPE_FREQS,
         MODEL_TENSOR.ATTN_ROT_EMBD,
@@ -7570,6 +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 c0bbfde22..c6946d53c 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 4b7e786fa..e14f91557 100644
--- a/src/llama-arch.cpp
+++ b/src/llama-arch.cpp
@@ -134,6 +134,7 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
     { LLM_ARCH_HUNYUAN_VL,       "hunyuan_vl"       },
     { LLM_ARCH_HY_V3,            "hy_v3"            },
     { LLM_ARCH_HY_V4,            "hy_v4"            },
+    { LLM_ARCH_HY_V4_FLASH,      "hy_v4_flash"      },
     { LLM_ARCH_SMOLLM3,          "smollm3"          },
     { LLM_ARCH_OPENAI_MOE,       "gpt-oss"          },
     { LLM_ARCH_LFM2,             "lfm2"             },
@@ -904,6 +905,7 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
     { LLM_TENSOR_INDEXER_COMPRESSOR_NORM,                "blk.%d.indexer_compressor_norm" },
     { LLM_TENSOR_INDEXER_KPOOL_GATE,                     "blk.%d.indexer_compressor_gate" },
     { LLM_TENSOR_INDEXER_KPOOL_APE,                      "blk.%d.indexer_compressor_ape" },
+    { LLM_TENSOR_INDEXER_KPOOL_VALUE,                    "blk.%d.indexer_compressor_value" },
     { LLM_TENSOR_FFN_GATE_TID2EID,                       "blk.%d.ffn_gate_tid2eid" },
     { LLM_TENSOR_MASKED_EMBD_CENTROIDS,                  "masked_embd_centroids" },
     { LLM_TENSOR_MASKED_EMBD_ORDERING,                   "masked_embd_ordering" },
@@ -918,6 +920,10 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
     { LLM_TENSOR_DSPARK_MARKOV_CTX_NORM,                 "markov_ctx_norm" },
     { LLM_TENSOR_ENGRAM_KV,                              "blk.%d.engram_kv" },
     { LLM_TENSOR_ENGRAM_GATE,                            "blk.%d.engram_gate" },
+    { LLM_TENSOR_ENGRAM_KV_B,                            "blk.%d.engram_kv_b" },
+    { LLM_TENSOR_ENGRAM_LOOKUP_NORM,                     "blk.%d.engram_lookup_norm" },
+    { LLM_TENSOR_ENGRAM_PRE_GAMMA,                       "blk.%d.engram_pre_gamma" },
+    { LLM_TENSOR_ENGRAM_HC_SCALE,                        "blk.%d.engram_hc_scale" },
     { LLM_TENSOR_DFLASH_ATTN_CONV_BASE,                  "blk.%d.attn_conv_base" },
     { LLM_TENSOR_DFLASH_ATTN_CONV_PROJ,                  "blk.%d.attn_conv_proj" },
     { LLM_TENSOR_DFLASH_FFN_CONV_BASE,                   "blk.%d.ffn_conv_base" },
@@ -1269,6 +1275,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
     {LLM_TENSOR_INDEXER_COMPRESSOR_NORM,    {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
     {LLM_TENSOR_INDEXER_KPOOL_GATE,         {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_INDEXER_KPOOL_APE,          {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
+    {LLM_TENSOR_INDEXER_KPOOL_VALUE,        {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_FFN_GATE_TID2EID,           {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}},
     {LLM_TENSOR_NEXTN_PROJ_PRE,             {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_NEXTN_PROJ_POST,            {LLM_TENSOR_LAYER_OUTPUT,    GGML_OP_MUL_MAT}},
@@ -1352,6 +1359,10 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
     {LLM_TENSOR_DSPARK_MARKOV_CTX_NORM,     {LLM_TENSOR_LAYER_OUTPUT,    GGML_OP_MUL}},
     {LLM_TENSOR_ENGRAM_KV,                  {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_ENGRAM_GATE,                {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
+    {LLM_TENSOR_ENGRAM_KV_B,                {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
+    {LLM_TENSOR_ENGRAM_LOOKUP_NORM,         {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
+    {LLM_TENSOR_ENGRAM_PRE_GAMMA,           {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
+    {LLM_TENSOR_ENGRAM_HC_SCALE,            {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}},
     {LLM_TENSOR_DFLASH_ATTN_CONV_BASE,      {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
     {LLM_TENSOR_DFLASH_ATTN_CONV_PROJ,      {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
     {LLM_TENSOR_DFLASH_FFN_CONV_BASE,       {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}},
@@ -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 74ca69fe7..9d0ced590 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 89465d0ce..38a37ae75 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 5fef4c421..9213d2a0e 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 1221f7f2b..42d2ae263 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 bb546f7cd..c7444319b 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<int32_t> idxs;
+    std::vector<int32_t> first;
+    std::map<std::vector<int32_t>, int32_t> pool_of;
+    const bool dedup = ubatch->n_seqs_unq > 1;
+
+    // the pool of each group of each sequence
+    std::vector<std::vector<int32_t>> seq_pools(ubatch->n_seqs_unq);
+
+    // the cells of each sequence in order, and the rank of each cell in its sequence
+    std::vector<std::vector<int32_t>> order(ubatch->n_seqs_unq);
+    std::vector<std::vector<int32_t>> rank (ubatch->n_seqs_unq);
+
+    std::vector<std::pair<llama_pos, int32_t>> seq_cells;
+    std::vector<int32_t> 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<int32_t> 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<int32_t> 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<ggml_fp16_t> pool_mask_data(n_pool*n_tokens, ggml_fp32_to_fp16(-INFINITY));
+    std::vector<int32_t>     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 1b40f6fc4..acff46e19 100644
--- a/src/llama-kv-cache.h
+++ b/src/llama-kv-cache.h
@@ -249,6 +249,15 @@ public:

     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 @@ public:
     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 4a62064e7..51315fb5c 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<uint32_t> 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<uint64_t>(
-                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<uint64_t>(
+                    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<uint64_t>(
                 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 74abd222d..e451b244e 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 e0273d7d1..72e5fd6cb 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<int32_t> engram_token_map;
+    // hy_v4_flash Engram: n_modules*ngram_size hash multipliers, more than hparams.ple_layer_multipliers holds
+    std::vector<uint64_t> 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 d1fc91b10..5381f672a 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 000000000..7f5c39232
--- /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 <cmath>
+
+// 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<uint32_t> e_layers;
+    ml.get_arr(LLM_KV_PLE_LAYERS, e_layers, false);
+    if (!e_layers.empty()) {
+        std::vector<uint64_t> mult;
+        std::vector<uint64_t> offsets;
+        std::vector<uint64_t> 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<llama_token> & prev,
+        std::vector<int32_t> & ids, std::vector<float> & 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<uint64_t> 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<ggml_tensor *> engram_ids;
+    std::vector<ggml_tensor *> 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<llama_token> 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<std::vector<int32_t>> ids(engram_ids.size());
+    std::vector<std::vector<float>>   valid(engram_ids.size());
+    std::vector<int32_t> 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<const llama_kv_cache_dsa_iswa_context *>(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<llm_graph_context> 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<graph>(*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<const llama_kv_cache_dsa_iswa_context *>(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<llm_graph_input_pool>(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<int64_t>(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<llm_graph_input_hy_v4_flash>(
+            static_cast<const llama_model_hy_v4_flash &>(model), inp_attn->get_dsa()->mctx->get_mla());
+    std::vector<ggml_tensor *> engram_rows;
+    std::vector<ggml_tensor *> 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<const llama_model_hy_v4_flash &>(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 d61469120..9f8e7cdcb 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<llm_graph_context> 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<llama_token> & prev,
+            std::vector<int32_t> & ids, std::vector<float> & 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<llm_graph_context> 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 2a4f4b361..5b7ea1868 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 d0deb9109..098350f9f 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -14283,7 +14283,7 @@ static std::vector<std::unique_ptr<test_case>> 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<std::unique_ptr<test_case>> 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 6faa8843d..a7deed9f7 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<uint32_t> 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<uint32_t> 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<uint32_t> 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<uint32_t>({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<uint32_t>({12, 10, 10, 0}));
     } else {
         ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector<uint32_t>({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<uint32_t> 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<uint64_t> primes = {7, 11, 13, 17};
+            std::vector<uint64_t> 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<uint32_t>({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<uint64_t>({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<int32_t> 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<uint32_t>({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 cd9810e6d..273c5148f 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 000000000..aa8ee8555
--- /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 c1feef493..b47574157 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 a22f41d37..576f27b83 100644
--- a/tools/mtmd/mtmd-graph.cpp
+++ b/tools/mtmd/mtmd-graph.cpp
@@ -911,6 +911,10 @@ std::unique_ptr<mtmd_graph> mtmd_get_graph_builder(mtmd_subcontext * ctx, const
             {
                 builder = std::make_unique<mtmd_graph_hunyuanvl>(ctx, img);
             } break;
+        case PROJECTOR_TYPE_HY_V4_FLASH:
+            {
+                builder = std::make_unique<mtmd_graph_hy_v4>(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 12bc9728d..d6b32fae4 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, std::string> 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 97dc47598..508dfbe94 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 078f154c7..640950c5c 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 fdac762ac..e99d25792 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<mtmd_image_preprocessor_dyn_size>(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<mtmd_image_preprocessor_dyn_size>(models.v.get());
+                } break;
             case PROJECTOR_TYPE_EXAONE4_5:
                 {
                     // <vision> ... (image embeddings) ... </vision>