diff --git a/.github/workflows/behavior-check.yml b/.github/workflows/behavior-check.yml index 73c3b8fe223a..544fb6caf600 100644 --- a/.github/workflows/behavior-check.yml +++ b/.github/workflows/behavior-check.yml @@ -140,6 +140,11 @@ jobs: source .venv/Scripts/activate pip install -r requirements/requirements-convert_hf_to_gguf.txt + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build shell: cmd diff --git a/.github/workflows/build-opencl.yml b/.github/workflows/build-opencl.yml index ab9ed3ec2cb6..4b45ae666b4e 100644 --- a/.github/workflows/build-opencl.yml +++ b/.github/workflows/build-opencl.yml @@ -61,6 +61,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Install OpenCL Headers and Libs id: install_opencl run: | diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml index d2375b0141fb..b699f2a1723c 100644 --- a/.github/workflows/build-vulkan.yml +++ b/.github/workflows/build-vulkan.yml @@ -213,6 +213,11 @@ jobs: run: | choco install ninja + - name: Install LLVM + run: | + choco install llvm --version=22.1.8 + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + - name: Build id: cmake_build run: | diff --git a/README.md b/README.md index 0bdcbc8ced79..8f2b10141540 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ LLM inference in C/C++ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) -[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?filter=v*&color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1) +[![Release](https://img.shields.io/github/v/release/ggml-org/llama.cpp?color=brightgreen)](https://github.com/ggml-org/llama.cpp/releases?q=tag:v1) [![Nightly](https://img.shields.io/github/v/release/ggml-org/llama.cpp?label=nightly&filter=b*&color=orange)](https://github.com/ggml-org/llama.cpp/releases?q=b) [![Server](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/server.yml?label=Server)](https://github.com/ggml-org/llama.cpp/actions/workflows/server.yml) [![Docker](https://img.shields.io/github/actions/workflow/status/ggml-org/llama.cpp/docker.yml?label=Docker)](https://github.com/ggml-org/llama.cpp/actions/workflows/docker.yml) diff --git a/conversion/__init__.py b/conversion/__init__.py index 1182c06be3c0..253a18fd48aa 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -78,6 +78,7 @@ "DistilBertForMaskedLM": "bert", "DistilBertForSequenceClassification": "bert", "DistilBertModel": "bert", + "DomynEdgeForCausalLM": "domynedge", "Dots1ForCausalLM": "dots1", "Dots3NoteForCausalLM": "dots3", "Dots3NoteForConditionalGeneration": "dots3", diff --git a/conversion/base.py b/conversion/base.py index 7cfbff321e0d..540a66ba5098 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -2470,6 +2470,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "5635e1c8d621dff7b4825f41f2f97b6ceb39bcf2d5c541db28577080d6efd5e5": # ref: https://huggingface.co/thinkingmachines/Inkling-2-Small res = "inkling2" + if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3": + # ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF + res = "domyn-edge" if res is None: logger.warning("\n") diff --git a/conversion/domynedge.py b/conversion/domynedge.py new file mode 100644 index 000000000000..df07add83cbf --- /dev/null +++ b/conversion/domynedge.py @@ -0,0 +1,53 @@ +from .base import TextModel, ModelBase +import gguf + + +@ModelBase.register("DomynEdgeForCausalLM") +@ModelBase.example("domyn/Domyn-Edge-Teacher-IF") +class DomynEdgeModel(TextModel): + model_arch = gguf.MODEL_ARCH.DOMYN_EDGE + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hparams = self.hparams + self.gguf_writer.add_vocab_size(hparams["vocab_size"]) + + position_layers = hparams["position_layers"] # list of "rope"/"nope" strings per layer + head_sizes = hparams["head_sizes"] # list of int head dims per layer + + # Per-layer rope/SWA pattern: True="rope", False="nope" + rope_pattern = [v == "rope" for v in position_layers] + self.gguf_writer.add_rope_pattern(rope_pattern) + self.gguf_writer.add_sliding_window_pattern(rope_pattern) # SWA <-> RoPE in domyn-edge + + # window_sizes entries are flash-attn style [left, right] (current token excluded; -1 = full attention), + # while llama.cpp's n_swa counts the current token, hence the +1 (matches HF's sliding_window=1025) + swa_window = hparams.get("sliding_window") + if swa_window is None: + window_sizes = hparams.get("window_sizes") # list of [size, offset] pairs per layer + if window_sizes is None: + raise KeyError("Neither `sliding_window` nor `window_sizes` found among domyn edge hyperparameters") + left = next((ws[0] for v, ws in zip(position_layers, window_sizes) if v == "rope"), None) + swa_window = left + 1 if left is not None and left > 0 else None + if swa_window is None: + raise ValueError("No sliding window size found among domyn edge hyperparameters") + self.gguf_writer.add_sliding_window(swa_window) + + # Head dims differ between full-attention ("nope") and SWA ("rope") layers + full_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "nope"} + swa_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "rope"} + + if len(full_head_dims) != 1: + raise ValueError(f"Expected one head dimension for full attention layers, found {len(full_head_dims)}") + full_head_dim = full_head_dims.pop() + + self.gguf_writer.add_key_length(full_head_dim) + self.gguf_writer.add_value_length(full_head_dim) + + if len(swa_head_dims) != 1: + raise ValueError(f"Expected one head dimension for SWA attention layers, found {len(swa_head_dims)}") + swa_head_dim = swa_head_dims.pop() + + self.gguf_writer.add_key_length_swa(swa_head_dim) + self.gguf_writer.add_value_length_swa(swa_head_dim) + self.gguf_writer.add_rope_dimension_count_swa(swa_head_dim) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index ff5fca4fff89..91fb418a5f2d 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -168,6 +168,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "mmbert", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jhu-clsp/mmBERT-base", }, {"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", }, {"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", }, + {"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", }, ] # some models are known to be broken upstream, so we will skip them as exceptions @@ -227,8 +228,6 @@ def download_model(model): repo = model["repo"] tokt = model["tokt"] - os.makedirs(f"models/tokenizers/{name}", exist_ok=True) - files = ["config.json", "tokenizer.json", "tokenizer_config.json"] if name == "gpt-4o": @@ -243,6 +242,7 @@ def download_model(model): if os.path.isdir(repo): # If repo is a path on the file system, copy the directory + os.makedirs(f"models/tokenizers/{name}", exist_ok=True) for file in files: src_path = os.path.join(repo, file) dst_path = f"models/tokenizers/{name}/{file}" @@ -484,7 +484,7 @@ def get_vocab_base_pre(self, tokenizer) -> str: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False) else: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}") - except (OSError, TypeError) as e: + except (OSError, TypeError, ValueError) as e: logger.error(f"Failed to load tokenizer for model {name}. Error: {e}") continue # Skip this model and continue with the next one in the loop diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 0b5615ca2460..a3a94aa16fb6 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -195,6 +195,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C | [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ | ✓ | ✓ | | [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✗ | | [bartowski/inclusionAI_Ling-mini-2.0-Q4_K_M](https://huggingface.co/bartowski/inclusionAI_Ling-mini-2.0-GGUF) | ✓ | ✓ | ✗ | +| [tiiuae/Falcon-H1-0.5B-Instruct-Q4_K_M](https://huggingface.co/tiiuae/Falcon-H1-0.5B-Instruct-GGUF) | ✓ | ✓ | ✗ | | | | | | | [Qwen/Qwen3-Embedding-0.6B-Q8_0](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF) | ✓ | ✓ | ✗ | | [ggml-org/bge-m3-Q8_0](https://huggingface.co/ggml-org/bge-m3-Q8_0-GGUF) | ✓ | ✓ | ✗ | @@ -990,6 +991,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - Multimodal features (audio/image/video) are a work in progress. - Embedding models: reranking models are not validated. - Llama.cpp tool coverage across CPU/GPU/NPU is not uniform. +- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. GPU accuracy is slightly lower than CPU. **GPU-specific** @@ -1012,6 +1014,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - `llama-perplexity`: requires `-b 512` or smaller. - Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. - `llama-embedding` fails on the NPU. +- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch). - Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model. - **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models. - Panther Lake NPU: the load of a Qwen3.5 model can end with a segmentation fault in the NPU compiler of OpenVINO 2026.4.1. diff --git a/docs/ops.md b/docs/ops.md index 7cd9bc2f8c5f..88e92c701d10 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -24,7 +24,7 @@ Legend: | ARGSORT | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CEIL | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CLAMP | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | -| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONV_1D_DW | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | @@ -90,7 +90,7 @@ Legend: | PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ | | PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | | POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | -| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | REPEAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ❌ | ❌ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 2ae3a1d36dd8..2ad8ded659ec 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -1155,134 +1155,134 @@ "WebGPU: WebGPU","SET_ROWS","type_src=f16,type_dst=f16,type_idx=i32,ne=[1,8,1,3],nr23=[1,1],r=2,v=0","support","0","no","WebGPU" "WebGPU: WebGPU","SET_ROWS","type_src=f16,type_dst=f16,type_idx=i64,ne=[1,8,1,3],nr23=[1,1],r=2,v=1","support","0","no","WebGPU" "WebGPU: WebGPU","SET_ROWS","type_src=f16,type_dst=f16,type_idx=i32,ne=[1,8,1,3],nr23=[1,1],r=2,v=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","0","no","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=avg,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=1,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=1,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=1,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=1,s1=2,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=1,p0=1,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" "WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU" "WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU" "WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU" @@ -5426,39 +5426,44 @@ "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,1,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=3,T_in=17,s0=2,p0=1,view=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=255,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=256,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=257,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=16777217,s0=1,p0=0,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[3,2,3,1],ne_kernel=[2,2,1,3],stride=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[10,10,9,1],ne_kernel=[3,3,1,9],stride=2","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[129,63,35,1],ne_kernel=[3,3,48,35],stride=1","support","0","no","WebGPU" diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index da1d4e1f167b..168ee774e488 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -8,10 +8,10 @@ extern "C" { #define RPC_PROTO_MAJOR_VERSION 10 #define RPC_PROTO_MINOR_VERSION 0 -#define RPC_PROTO_PATCH_VERSION 0 +#define RPC_PROTO_PATCH_VERSION 1 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 2341fa6c107e..dc9997514d06 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -429,6 +429,8 @@ extern "C" { GGML_OP_GLU, + GGML_OP_SLEEP, + GGML_OP_COUNT, }; @@ -1314,12 +1316,6 @@ extern "C" { // indirect matrix multiplication // an id of -1 skips the slot and zeroes the matching row of the result - // - // [TAG_MUL_MAT_ID_DUPLICATE_ID] - // note: this op has undefined behaviour if a given `a` is referenced more than once for a given `b` - // (i.e. duplicate experts per token are not guaranteed to be supported in all backends) - // TODO: add backend support: https://github.com/ggml-org/llama.cpp/pull/29998#issuecomment-6153742533 - // the CPU backend skips negative ids, their rows of the result are zero GGML_API struct ggml_tensor * ggml_mul_mat_id( struct ggml_context * ctx, struct ggml_tensor * as, @@ -2599,6 +2595,12 @@ extern "C" { int n_tasks, void * userdata); + // Busy-wait operator for scheduling and backend testing. + GGML_API struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, // wait after this tensor has executed, return value is simply a full view of this tensor + int32_t us); // amount of time to wait in microseconds + // loss function GGML_API struct ggml_tensor * ggml_cross_entropy_loss( diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index 2e2f9c036560..d598ca3d86d1 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -2584,6 +2584,7 @@ bool ggml_op_alloc_size_may_expand(enum ggml_op op) { case GGML_OP_ARGSORT: case GGML_OP_TOP_K: case GGML_OP_ARGMAX: + case GGML_OP_CONV_2D: return true; default: return false; diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 7e692f1b545f..0adc8680f5a4 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2501,6 +2501,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten break; case GGML_OP_SET_ROWS: { + if (op->src[0]->type == GGML_TYPE_BF16) { + return false; + } switch (op->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: @@ -2553,6 +2556,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten if (((const int32_t *) op->op_params)[15] != 0) { return false; // FIXME: support ggml_rope_set_offset } + if (op->src[0]->type != GGML_TYPE_F32 && op->src[0]->type != GGML_TYPE_F16) { + return false; + } if (op->src[0]->ne[0] > 896) { return false; } diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt index 1e759ffcaf83..75bf04cec6de 100644 --- a/ggml/src/ggml-cpu/CMakeLists.txt +++ b/ggml/src/ggml-cpu/CMakeLists.txt @@ -670,7 +670,7 @@ function(ggml_add_cpu_backend_variant_impl tag_name) set(GGML_CPU_KLEIDIAI_AARCH64 OFF) if (GGML_SYSTEM_ARCH STREQUAL "ARM" AND - (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android)$") AND + (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android|OHOS)$") AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64|arm64-v8a)$" OR CMAKE_OSX_ARCHITECTURES MATCHES "arm64" OR CMAKE_GENERATOR_PLATFORM_LWR STREQUAL "arm64" OR diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index fbc9f26a9bb3..5eb39ee2c357 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -2048,6 +2048,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_fill(params, tensor); } break; + case GGML_OP_SLEEP: + { + ggml_compute_forward_sleep(params, tensor); + } break; case GGML_OP_FLASH_ATTN_EXT: { ggml_compute_forward_flash_attn_ext(params, tensor); @@ -2320,6 +2324,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_REPEAT: case GGML_OP_REPEAT_BACK: case GGML_OP_LEAKY_RELU: + case GGML_OP_SLEEP: { n_tasks = 1; } break; @@ -2949,7 +2954,8 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_SET_ROWS: { - if (node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) { + if ((node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) || + (node->src[0]->type == GGML_TYPE_BF16 && node->type != GGML_TYPE_BF16)) { cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; } } break; diff --git a/ggml/src/ggml-cpu/llamafile/sgemm.cpp b/ggml/src/ggml-cpu/llamafile/sgemm.cpp index 68105f029fbf..5d660911316d 100644 --- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp +++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp @@ -1474,6 +1474,282 @@ class tinyBLAS_Q0_VXE { const int32_t ith; const int32_t nth; }; + +template +class tinyBLAS_QK_VXE { + public: + tinyBLAS_QK_VXE(int64_t k, + const TA * A, int64_t lda, + const block_q8_K * B, int64_t ldb, + float * C, int64_t ldc, + int32_t ith, int32_t nth) + : A(A), B(B), C(C), k(k), lda(lda), ldb(ldb), ldc(ldc), ith(ith), nth(nth) { + } + + void matmul(int64_t m, int64_t n) { + const int64_t n4 = n / 4 * 4; + const int64_t n2 = n / 2 * 2; + gemm<4>(m, 0, n4); + gemm<2>(m, n4, n2); + gemm<1>(m, n2, n); + } + + private: + // one block of A is loaded once and used for RN columns of B + template + void gemm(int64_t m, int64_t n0, int64_t n) { + const int64_t tiles = m * ((n - n0) / RN); + const int64_t duty = (tiles + nth - 1) / nth; + const int64_t start = duty * ith; + const int64_t end = MIN(start + duty, tiles); + + for (int64_t job = start; job < end; ++job) { + const int64_t ii = job % m; + const int64_t jj = n0 + RN * (job / m); + float32x4_t v_sum[RN] = {}; + + for (int64_t l = 0; l < k; ++l) { + const TA & x = A[lda * ii + l]; + + int8x16_t v_x[n_group]; + load(x, v_x); + + // scale and minimum of the 16 groups, 8 groups per vector + int16x8_t v_scalel, v_scaleh; + int16x8_t v_minl, v_minh; + load_scale(x, v_scalel, v_scaleh, v_minl, v_minh); + + int16x8_t v_scale[n_group]; + for (int32_t g = 0; g < n_group; ++g) { + v_scale[g] = vec_splats((g < n_group / 2 ? v_scalel : v_scaleh)[g % (n_group / 2)]); + } + + const int8_t * y_qs[RN]; + for (int32_t j = 0; j < RN; ++j) { + y_qs[j] = B[ldb * (jj + j) + l].qs; + } + + // the columns are in the inner loop, so that their sums do not wait for each other + int32x4_t v_dot[RN] = {}; + for (int32_t g = 0; g < n_group; ++g) { + for (int32_t j = 0; j < RN; ++j) { + const int8x16_t v_y = vec_xl(0, y_qs[j] + 16 * g); + const int16x8_t v_xy = vec_meadd(v_x[g], v_y, vec_mulo(v_x[g], v_y)); + v_dot[j] = vec_meadd(v_xy, v_scale[g], vec_moadd(v_xy, v_scale[g], v_dot[j])); + } + } + + const float x_d = unhalf(x.d); + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + v_sum[j] = vec_madd(vec_float(v_dot[j]), vec_splats(x_d * y.d), v_sum[j]); + } + + if (has_min) { + const float x_dmin = dmin(x); + + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + + const int16_t * y_bsums = y.bsums; + const int16x8_t v_bsumsl = vec_xl(0, y_bsums); + const int16x8_t v_bsumsh = vec_xl(0, y_bsums + n_group / 2); + + const int32x4_t v_minsl = vec_meadd(v_bsumsl, v_minl, vec_mulo(v_bsumsl, v_minl)); + const int32x4_t v_minsh = vec_meadd(v_bsumsh, v_minh, vec_mulo(v_bsumsh, v_minh)); + v_sum[j] = vec_madd(vec_float(v_minsl + v_minsh), vec_splats(-x_dmin * y.d), v_sum[j]); + } + } + } + + for (int32_t j = 0; j < RN; ++j) { + C[ldc * (jj + j) + ii] = hsum(v_sum[j]); + } + } + } + + // a block has 16 groups of 16 weights, Q4_K and Q5_K share one scale and minimum per 2 groups + static constexpr int32_t n_group = QK_K / 16; + + // Q3_K and Q6_K have no minimum, their weights are loaded as signed values. + static constexpr bool has_min = !std::is_same::value && !std::is_same::value; + + static float dmin(const block_q2_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q4_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q5_K & x) { return unhalf(x.dmin); } + template static float dmin(const T &) { return 0.0f; } + + static void load(const block_q2_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)vec_and(vec_sr(v_qs, qs_shift), v_mask); + } + } + + static void load(const block_q3_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + + const uint8_t * x_qs = x.qs; + const uint8_t * x_hmask = x.hmask; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + const int32_t hmask_offset = 16 * (g % 2); + const int32_t hmask_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_hmask = vec_xl(0, x_hmask + hmask_offset); + const uint8x16_t v_lo = vec_and(vec_sr(v_qs, qs_shift), v_mask); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_hmask, hmask_shift), v_one), 2); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)4); + } + } + + static void load(const block_q4_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)(qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4)); + } + } + + static void load(const block_q5_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + const uint8_t * x_qs = x.qs; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + const int32_t qh_offset = 16 * (g % 2); + const int32_t qh_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_one), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi); + } + } + + static void load(const block_q6_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask4 = vec_splats((uint8_t)0x0F); + const uint8x16_t v_mask2 = vec_splats((uint8_t)0x03); + const uint8_t * x_ql = x.ql; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t ql_offset = 16 * (4 * (g / 8) + 2 * (g % 4 / 2) + g % 2); + const bool ql_low = g % 8 < 4; + const int32_t qh_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qh_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_ql = vec_xl(0, x_ql + ql_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = ql_low ? vec_and(v_ql, v_mask4) : vec_sr(v_ql, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_mask2), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + } + } + + static void load_scale(const block_q2_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const uint8_t * x_scales = x.scales; + const uint8x16_t v_s = vec_xl(0, x_scales); + const uint8x16_t v_scale = vec_and(v_s, vec_splats((uint8_t)0x0F)); + const uint8x16_t v_min = vec_sr(v_s, 4); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + static void load_scale(const block_q3_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // 6-bit scales: low 4 bits in scales[0..7], high 2 bits in scales[8..11] + const uint8x16_t v_lo_byte = { 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 8, 9, 10, 11 }; + const uint8x16_t v_lo_shift = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4 }; + const uint8x16_t v_hi_byte = { 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15 }; + const uint8x16_t v_hi_shift = { 0, 0, 0, 0, 2, 2, 2, 2, 4, 4, 4, 4, 6, 6, 6, 6 }; + + // the load starts 4 bytes before scales, so that it stays inside the block + const uint8_t * x_qs = x.qs; + const uint8x16_t v_s = vec_xl(0, x_qs + sizeof(x.qs) - 4); + const uint8x16_t v_lo = vec_and(vec_sr(vec_perm(v_s, v_s, v_lo_byte), v_lo_shift), vec_splats((uint8_t)0x0F)); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(vec_perm(v_s, v_s, v_hi_byte), v_hi_shift), vec_splats((uint8_t)0x03)), 4); + const int8x16_t v_scale = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + static void load_scale(const block_q4_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q5_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q6_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const int8_t * x_scales = x.scales; + const int8x16_t v_scale = vec_xl(0, x_scales); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + // 8 scales and 8 minimums of 6 bits, same packing as get_scale_min_k4 in ggml-quants.c + static void load_scale_min_k4(const uint8_t * q, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // bytes 0..3 and 4..7 have the high 2 bits of scale 4..7 and minimum 4..7, move them to bytes 8..11 + const uint8x16_t v_hi_scale = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0 }; + const uint8x16_t v_hi_min = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0 }; + // each scale and minimum is for 2 groups + const uint8x16_t v_group_scale = { 0, 0, 1, 1, 2, 2, 3, 3, 24, 24, 25, 25, 26, 26, 27, 27 }; + const uint8x16_t v_group_min = { 4, 4, 5, 5, 6, 6, 7, 7, 24, 24, 25, 25, 26, 26, 27, 27 }; + + // the 4 bytes after the 12 scale bytes are in the same block + const uint8x16_t v_s = vec_xl(0, q); + const uint8x16_t v_lo = vec_and(v_s, vec_splats((uint8_t)0x3F)); + const uint8x16_t v_hi = vec_sl(vec_sr(v_s, 6), 4); + const uint8x16_t v_scale_47 = vec_or(vec_and(v_s, vec_splats((uint8_t)0x0F)), vec_perm(v_hi, v_hi, v_hi_scale)); + const uint8x16_t v_min_47 = vec_or(vec_sr(v_s, 4), vec_perm(v_hi, v_hi, v_hi_min)); + const uint8x16_t v_scale = vec_perm(v_lo, v_scale_47, v_group_scale); + const uint8x16_t v_min = vec_perm(v_lo, v_min_47, v_group_min); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + const TA * const A; + const block_q8_K * const B; + float * const C; + const int64_t k; + const int64_t lda; + const int64_t ldb; + const int64_t ldc; + const int32_t ith; + const int32_t nth; +}; #endif #if defined(__ARM_FEATURE_DOTPROD) @@ -4488,6 +4764,91 @@ bool llamafile_sgemm(const struct ggml_compute_params * params, int64_t m, int64 #endif } + case GGML_TYPE_Q2_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q2_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q3_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q3_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q4_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q4_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q5_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q5_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q6_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q6_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + case GGML_TYPE_IQ4_NL: { if (Btype != GGML_TYPE_Q8_0) return false; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 72efbc6e9fa9..cd8134740e19 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -2238,6 +2238,19 @@ void ggml_compute_forward_fill(const ggml_compute_params * params, ggml_tensor * } } +// ggml_compute_forward_sleep + +void ggml_compute_forward_sleep(const ggml_compute_params * params, ggml_tensor * dst) { + if (params->ith != 0) { + return; + } + + // same clock as ggml_time_us() callers; on macOS steady_clock is CLOCK_MONOTONIC_RAW, which can run faster + const int64_t t_end = ggml_time_us() + ggml_get_op_params_i32(dst, 0); + + while (ggml_time_us() < t_end) {} +} + // ggml_compute_tri template @@ -5518,7 +5531,7 @@ static void ggml_compute_forward_set_rows_impl( assert(ne0 == nc); assert(ne2 == ne02); assert(ne3 == ne03); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); assert(ne02 % ne11 == 0); assert(ne03 % ne12 == 0); @@ -5565,6 +5578,20 @@ static void ggml_compute_forward_set_rows_impl( from_float(wdata, ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); } + } else if constexpr (std::is_same_v) { + if (dst->type == GGML_TYPE_BF16) { + memcpy( + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), + ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + rs); + } else { + float * wdata = (float *) params->wdata + (nc + CACHE_LINE_SIZE_F32) * ith; + ggml_bf16_to_fp32_row( + (const ggml_bf16_t *) ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + wdata, nc); + from_float(wdata, + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); + } } else { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); } @@ -5601,6 +5628,16 @@ void ggml_compute_forward_set_rows( GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); } } break; + case GGML_TYPE_BF16: + { + if (src1->type == GGML_TYPE_I64) { + ggml_compute_forward_set_rows_impl(params, dst); + } else if (src1->type == GGML_TYPE_I32) { + ggml_compute_forward_set_rows_impl(params, dst); + } else { + GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); + } + } break; default: { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); @@ -6289,7 +6326,7 @@ static void rotate_pairs(const int64_t n, const int64_t n_offset, const float * } } -template //float or ggml_fp16_t +template //float, ggml_fp16_t or ggml_bf16_t static void ggml_compute_forward_rope_flt( const ggml_compute_params * params, ggml_tensor * dst, @@ -6299,7 +6336,7 @@ static void ggml_compute_forward_rope_flt( const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * src2 = dst->src[2]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); GGML_ASSERT(src1->type == GGML_TYPE_I32); float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow; @@ -6459,6 +6496,10 @@ void ggml_compute_forward_rope( { ggml_compute_forward_rope_flt(params, dst, true); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, true); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, true); @@ -6483,6 +6524,10 @@ void ggml_compute_forward_rope_back( { ggml_compute_forward_rope_flt(params, dst, false); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, false); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, false); diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index aac527a64c54..3a4fa0707e49 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -84,6 +84,7 @@ void ggml_compute_forward_top_k(const struct ggml_compute_params * params, struc void ggml_compute_forward_leaky_relu(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_tri(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_fill(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_sleep(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_ext(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_back( const struct ggml_compute_params * params, diff --git a/ggml/src/ggml-cuda/batch-get.cu b/ggml/src/ggml-cuda/batch-copy.cu similarity index 58% rename from ggml/src/ggml-cuda/batch-get.cu rename to ggml/src/ggml-cuda/batch-copy.cu index 60c4747b967c..920b2b15d355 100644 --- a/ggml/src/ggml-cuda/batch-get.cu +++ b/ggml/src/ggml-cuda/batch-copy.cu @@ -1,17 +1,17 @@ -#include "batch-get.cuh" +#include "batch-copy.cuh" #include "common.cuh" #include "ggml-cpp.h" #include #if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) -struct ggml_cuda_batch_get_descriptor { +struct ggml_cuda_batch_copy_descriptor { const unsigned char * src; unsigned char * dst; size_t size; }; -static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_descriptor * copies, size_t count) { +static __global__ void ggml_cuda_batch_copy_kernel(const ggml_cuda_batch_copy_descriptor * copies, size_t count) { // Blocks along y cooperate on each descriptor. const size_t index = blockIdx.x; if (index >= count) { @@ -50,11 +50,11 @@ static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_desc } } -struct ggml_cuda_batch_get_mapping { +struct ggml_cuda_batch_copy_mapping { void * host = nullptr; unsigned char * device = nullptr; - ggml_cuda_batch_get_mapping(void * host, size_t size) { + ggml_cuda_batch_copy_mapping(void * host, size_t size) { const cudaError_t err = cudaHostRegister(host, size, cudaHostRegisterMapped | cudaHostRegisterPortable); if (err != cudaSuccess) { (void) cudaGetLastError(); @@ -70,10 +70,10 @@ struct ggml_cuda_batch_get_mapping { } } - ggml_cuda_batch_get_mapping(const ggml_cuda_batch_get_mapping &) = delete; - ggml_cuda_batch_get_mapping & operator=(const ggml_cuda_batch_get_mapping &) = delete; + ggml_cuda_batch_copy_mapping(const ggml_cuda_batch_copy_mapping &) = delete; + ggml_cuda_batch_copy_mapping & operator=(const ggml_cuda_batch_copy_mapping &) = delete; - ~ggml_cuda_batch_get_mapping() { + ~ggml_cuda_batch_copy_mapping() { if (host) { // Release only the registration acquired by this object. CUDA_CHECK(cudaHostUnregister(host)); @@ -82,11 +82,12 @@ struct ggml_cuda_batch_get_mapping { }; #endif -bool ggml_cuda_get_tensor_n(int device, - const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, +static bool ggml_cuda_copy_tensor_n(int device, cudaMemcpyKind direction, + const ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) { #if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) GGML_UNUSED(device); + GGML_UNUSED(direction); GGML_UNUSED(tensors); GGML_UNUSED(data); GGML_UNUSED(offsets); @@ -94,14 +95,17 @@ bool ggml_cuda_get_tensor_n(int device, GGML_UNUSED(n_tensors); return false; #else + const bool to_host = direction == cudaMemcpyDeviceToHost; // Provisional dispatch values based on experiments. constexpr size_t min_batch_reads = 128; - constexpr size_t max_gather_read_bytes = 128 * 1024; - // Collect non-empty CPU destination ranges. + constexpr size_t max_kernel_read_bytes = 128 * 1024; + // Collect destination ranges; repeated sources are allowed. std::vector> ranges; ranges.reserve(n_tensors); size_t payload_bytes = 0; - // Number of non-empty reads whose size is at most max_gather_read_bytes. + uintptr_t begin = UINTPTR_MAX; + uintptr_t end = 0; + // Number of non-empty reads whose size is at most max_kernel_read_bytes. size_t n_reads_small = 0; for (size_t i = 0; i < n_tensors; ++i) { if (sizes[i] == 0) { @@ -111,15 +115,19 @@ bool ggml_cuda_get_tensor_n(int device, GGML_ASSERT(address <= UINTPTR_MAX - sizes[i]); GGML_ASSERT(payload_bytes <= SIZE_MAX - sizes[i]); payload_bytes += sizes[i]; - n_reads_small += sizes[i] <= max_gather_read_bytes; - ranges.emplace_back(address, address + sizes[i]); + n_reads_small += sizes[i] <= max_kernel_read_bytes; + begin = std::min(begin, address); + end = std::max(end, address + sizes[i]); + const uintptr_t destination = to_host ? address : (uintptr_t) tensors[i]->data + offsets[i]; + GGML_ASSERT(destination <= UINTPTR_MAX - sizes[i]); + ranges.emplace_back(destination, destination + sizes[i]); } if (ranges.empty()) { return true; } // Total number of non-empty reads. const size_t n_reads = ranges.size(); - if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_get_descriptor) || n_reads > INT_MAX) { + if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_copy_descriptor) || n_reads > INT_MAX) { return false; } if (n_reads < 2 || (n_reads < min_batch_reads && n_reads_small == n_reads)) { @@ -127,72 +135,85 @@ bool ggml_cuda_get_tensor_n(int device, } std::sort(ranges.begin(), ranges.end()); for (size_t i = 1; i < ranges.size(); ++i) { - // Preserve the ordered copy path when CPU destinations overlap. + // Preserve the ordered copy path when destinations overlap. if (ranges[i].first < ranges[i - 1].second) { return false; } } - // Find the CPU span to register, including gaps between destinations. - const uintptr_t begin = ranges.front().first; - const uintptr_t end = ranges.back().second; - if (end - begin - payload_bytes > payload_bytes) { + // Limit gaps in the CPU span without underflow when sources overlap. + if (end - begin > payload_bytes && end - begin - payload_bytes > payload_bytes) { return false; } - // Register and map the existing CPU destination so the kernel can write to it directly. - ggml_cuda_batch_get_mapping mapping((void *) begin, end - begin); + // Register and map the CPU span for direct kernel access. + ggml_cuda_batch_copy_mapping mapping((void *) begin, end - begin); if (!mapping.host) { return false; } - // Reads selected for gather; zero means all reads use DMA. - size_t n_reads_gather = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; + // Reads selected for the kernel; zero means all reads use DMA. + size_t n_reads_kernel = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; // Keep descriptor storage alive until the final stream synchronization. constexpr size_t max_batch_descriptors = 128 * 1024; - const size_t bytes = std::min(n_reads_gather, max_batch_descriptors) * sizeof(ggml_cuda_batch_get_descriptor); - ggml_backend_buffer_ptr descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); + const size_t bytes = std::min(n_reads_kernel, max_batch_descriptors) * sizeof(ggml_cuda_batch_copy_descriptor); + ggml_backend_buffer_ptr descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); if (!descriptors) { - n_reads_gather = 0; + n_reads_kernel = 0; } const auto host_type = ggml_backend_cuda_host_buffer_type(); - ggml_backend_buffer_ptr host_descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); + ggml_backend_buffer_ptr host_descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); if (!host_descriptors || ggml_backend_buffer_get_type(host_descriptors.get()) != host_type) { - n_reads_gather = 0; + n_reads_kernel = 0; } - if (n_reads_gather) { - auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); - auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); + if (n_reads_kernel) { + auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); + auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); const int threads = 256; const size_t nsm = ggml_cuda_info().devices[device].nsm; size_t i = 0; - for (size_t first = 0; first < n_reads_gather; first += max_batch_descriptors) { - const size_t n_batch = std::min(n_reads_gather - first, max_batch_descriptors); + for (size_t first = 0; first < n_reads_kernel; first += max_batch_descriptors) { + const size_t n_batch = std::min(n_reads_kernel - first, max_batch_descriptors); size_t count = 0; for (; i < n_tensors && count < n_batch; ++i) { - if (sizes[i] == 0 || sizes[i] > max_gather_read_bytes) { + if (sizes[i] == 0 || sizes[i] > max_kernel_read_bytes) { continue; } - copies[count++] = {(const unsigned char *) tensors[i]->data + offsets[i], - mapping.device + ((uintptr_t) data[i] - begin), sizes[i]}; + auto * host = mapping.device + ((uintptr_t) data[i] - begin); + auto * tensor = (unsigned char *) tensors[i]->data + offsets[i]; + copies[count++] = {to_host ? tensor : host, to_host ? host : tensor, sizes[i]}; } const size_t blocks_per_copy = std::min(UINT16_MAX, std::max(1, (nsm + n_batch - 1) / n_batch)); const dim3 blocks((unsigned int) n_batch, (unsigned int) blocks_per_copy); // Stream ordering keeps each kernel ahead of the next descriptor overwrite. CUDA_CHECK(cudaMemcpyAsync(device_copies, copies, n_batch * sizeof(copies[0]), cudaMemcpyHostToDevice, cudaStreamPerThread)); - ggml_cuda_batch_get_kernel<<>>(device_copies, n_batch); + ggml_cuda_batch_copy_kernel<<>>(device_copies, n_batch); CUDA_CHECK(cudaGetLastError()); - if (first + n_batch < n_reads_gather) { + if (first + n_batch < n_reads_kernel) { // Wait before refilling the pinned host descriptor buffer. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); } } } - // Keep the destination pinned for DMA too; overlapping destinations already declined above. + // Keep the CPU span pinned for DMA too; overlapping destinations already declined above. for (size_t i = 0; i < n_tensors; ++i) { - if (sizes[i] && (!n_reads_gather || sizes[i] > max_gather_read_bytes)) { - CUDA_CHECK(cudaMemcpyAsync(data[i], (const char *) tensors[i]->data + offsets[i], sizes[i], cudaMemcpyDeviceToHost, cudaStreamPerThread)); + if (sizes[i] && (!n_reads_kernel || sizes[i] > max_kernel_read_bytes)) { + void * host = const_cast(data[i]); + void * tensor = (char *) tensors[i]->data + offsets[i]; + CUDA_CHECK(cudaMemcpyAsync(to_host ? host : tensor, to_host ? tensor : host, sizes[i], direction, cudaStreamPerThread)); } } - // Wait for GPU writes before releasing the CPU mapping and descriptor buffers. + // Wait for transfers before releasing the CPU mapping and descriptor buffers. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); return true; #endif } + +bool ggml_cuda_get_tensor_n(int device, + const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors) { + return ggml_cuda_copy_tensor_n(device, cudaMemcpyDeviceToHost, tensors, data, offsets, sizes, n_tensors); +} + +bool ggml_cuda_set_tensor_n(int device, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors) { + return ggml_cuda_copy_tensor_n(device, cudaMemcpyHostToDevice, tensors, data, offsets, sizes, n_tensors); +} diff --git a/ggml/src/ggml-cuda/batch-get.cuh b/ggml/src/ggml-cuda/batch-copy.cuh similarity index 55% rename from ggml/src/ggml-cuda/batch-get.cuh rename to ggml/src/ggml-cuda/batch-copy.cuh index eb9bf0cc81bd..bb7fca4c02dd 100644 --- a/ggml/src/ggml-cuda/batch-get.cuh +++ b/ggml/src/ggml-cuda/batch-copy.cuh @@ -5,3 +5,7 @@ bool ggml_cuda_get_tensor_n(int device, const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); + +bool ggml_cuda_set_tensor_n(int device, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors); diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index fd047d7c3333..053ed60f798b 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -452,6 +452,16 @@ static __device__ __forceinline__ ggml_cuda_thread_mask_t ggml_cuda_ballot(int p return __ballot_sync(mask, predicate); } +static __device__ __forceinline__ int ggml_cuda_popc(ggml_cuda_thread_mask_t x) { + static_assert(sizeof(ggml_cuda_thread_mask_t) == 4 || sizeof(ggml_cuda_thread_mask_t) == 8, "unsupported thread mask type"); + if constexpr (sizeof(ggml_cuda_thread_mask_t) == 4) { + return __popc(x); + } else { + return __popcll(x); + } +} +template static __device__ __forceinline__ int ggml_cuda_popc(T x) = delete; // Makes implicit type casts result in an error. + static __device__ __forceinline__ int ggml_cuda_all(int predicate, ggml_cuda_thread_mask_t mask = GGML_CUDA_FULL_THREAD_MASK) { return __all_sync(mask, predicate); } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 2e32760847bc..10aa5af15863 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -17,15 +17,6 @@ static __global__ void flash_attn_mask_to_sparse_indices( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int values_per_lane = 8; - using lane_mask_t = std::conditional_t; - constexpr uint64_t ballot_mask = ~(lane_mask_t)0; - const auto popc = [](const lane_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; const int tid = threadIdx.x; const int warp = tid / warp_size; const int lane = tid % warp_size; @@ -48,7 +39,7 @@ static __global__ void flash_attn_mask_to_sparse_indices( __syncthreads(); for (int i0 = 0; i0 < ne30; i0 += blockDim.x*values_per_lane) { - lane_mask_t selected_warp[values_per_lane]; + ggml_cuda_thread_mask_t selected_warp[values_per_lane]; int warp_count = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { @@ -60,8 +51,8 @@ static __global__ void flash_attn_mask_to_sparse_indices( selected |= (!oob || q < q1 - q0) && isfinite(__half2float(mask[q*s31 + i])); } } - selected_warp[item] = (lane_mask_t)ggml_cuda_ballot((int) selected, ballot_mask); - warp_count += popc(selected_warp[item]); + selected_warp[item] = ggml_cuda_ballot((int) selected); + warp_count += ggml_cuda_popc(selected_warp[item]); } if (lane == 0) { @@ -81,16 +72,16 @@ static __global__ void flash_attn_mask_to_sparse_indices( } __syncthreads(); - const lane_mask_t lane_mask = lane == 0 ? 0 : ((lane_mask_t)1 << lane) - 1; + const ggml_cuda_thread_mask_t lane_mask = lane == 0 ? 0 : ((ggml_cuda_thread_mask_t)1 << lane) - 1; int warp_item_offset = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { const int i = i0 + (warp*values_per_lane + item)*warp_size + lane; - const int dst = row_count + warp_offsets[warp] + warp_item_offset + popc(selected_warp[item] & lane_mask); - if ((selected_warp[item] & ((lane_mask_t)1 << lane)) && dst < n_kv_max) { + const int dst = row_count + warp_offsets[warp] + warp_item_offset + ggml_cuda_popc(selected_warp[item] & lane_mask); + if ((selected_warp[item] & ((ggml_cuda_thread_mask_t)1 << lane)) && dst < n_kv_max) { indices[dst] = i; } - warp_item_offset += popc(selected_warp[item]); + warp_item_offset += ggml_cuda_popc(selected_warp[item]); } __syncthreads(); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 40e83750efba..8702dd32d366 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -10,7 +10,7 @@ #include "ggml-cuda/arange.cuh" #include "ggml-cuda/argmax.cuh" #include "ggml-cuda/argsort.cuh" -#include "ggml-cuda/batch-get.cuh" +#include "ggml-cuda/batch-copy.cuh" #include "ggml-cuda/binbcast.cuh" #include "ggml-cuda/clamp.cuh" #include "ggml-cuda/col2im-1d.cuh" @@ -48,6 +48,7 @@ #include "ggml-cuda/rope.cuh" #include "ggml-cuda/roll.cuh" #include "ggml-cuda/scale.cuh" +#include "ggml-cuda/sleep.cuh" #include "ggml-cuda/snake.cuh" #include "ggml-cuda/softcap.cuh" #include "ggml-cuda/softmax.cuh" @@ -1116,6 +1117,11 @@ static void ggml_backend_cuda_buffer_set_tensor_n(ggml_backend_buffer_t buffer, ggml_cuda_set_device(ctx->device); + if (!ggml_cuda_pinned_memory_disabled() && + ggml_cuda_set_tensor_n(ctx->device, tensors, data, offsets, sizes, n_tensors)) { + return; + } + for (size_t i = 0; i < n_tensors; i++) { if (sizes[i] == 0) { continue; @@ -2724,7 +2730,8 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ids_from_sorted_host[i12*n_expert_used + iex] = ids_to_sorted_host.size(); ids_to_sorted_host.push_back(i12*ne11 + iex % ne11); tokens_per_expert[i02]++; - break; + // TODO: removing the break here was done to make duplicate IDs work but this caused a ~10% performance regression, better solution needed. + // break; } } } @@ -2776,6 +2783,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ggml_tensor dst_slice; memset(&dst_slice, 0, sizeof(dst_slice)); memcpy(dst_slice.op_params, dst->op_params, sizeof(dst_slice.op_params)); + dst_slice.op = GGML_OP_MUL_MAT; // ggml_prec_get_acc/ggml_prec_get_src check the op dst_slice.buffer = dst->buffer; dst_slice.type = type_dst_sorted; dst_slice.ne[0] = ne0; @@ -3145,6 +3153,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg case GGML_OP_FILL: ggml_cuda_op_fill(ctx, dst); break; + case GGML_OP_SLEEP: + ggml_cuda_op_sleep(ctx, dst); + break; case GGML_OP_LIGHTNING_INDEXER: ggml_cuda_lightning_indexer(ctx, dst); break; @@ -3495,7 +3506,12 @@ static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope, return false; } - if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) { + if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && set_rows->type != GGML_TYPE_BF16) { + return false; + } + + // BF16 rope fuses into an F16 or BF16 cache, other ropes not into a BF16 cache + if (rope->type == GGML_TYPE_BF16 ? set_rows->type == GGML_TYPE_F32 : set_rows->type == GGML_TYPE_BF16) { return false; } @@ -6501,7 +6517,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16 || op->type == GGML_TYPE_F8_E4M3 || op->type == GGML_TYPE_Q4_0 || op->type == GGML_TYPE_Q4_1 || op->type == GGML_TYPE_Q5_0 || op->type == GGML_TYPE_Q5_1 || op->type == GGML_TYPE_Q8_0 || op->type == GGML_TYPE_IQ4_NL) && - op->src[0]->type == GGML_TYPE_F32 + (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16) ) || ( op->type == GGML_TYPE_F16 && op->src[0]->type == GGML_TYPE_F16 ) @@ -6722,7 +6738,9 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return false; case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: { - return op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) && + op->type == op->src[0]->type && + op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); } case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: @@ -6809,6 +6827,12 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return ggml_cuda_lightning_indexer_supported(dev_ctx->device, op); case GGML_OP_TOP_K_MASK: return op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32; + case GGML_OP_SLEEP: +#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) + return false; +#else + return true; +#endif // defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) default: return false; diff --git a/ggml/src/ggml-cuda/mmf.cu b/ggml/src/ggml-cuda/mmf.cu index 040d390e0cc5..396ad1c1184d 100644 --- a/ggml/src/ggml-cuda/mmf.cu +++ b/ggml/src/ggml-cuda/mmf.cu @@ -43,7 +43,6 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr const int64_t s13 = src1->nb[3] / ts_src1; const int64_t s3 = dst->nb[3] / ts_dst; - const int64_t ids_s0 = ids ? ids->nb[0] / ggml_type_size(ids->type) : 0; const int64_t ids_s1 = ids ? ids->nb[1] / ggml_type_size(ids->type) : 0; mmf_ids_data ids_info{}; @@ -70,7 +69,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr nchannels_y = ids->ne[0]; } - if (ids && ncols_dst > 16) { + if (ids) { const int64_t n_expert_used = ids->ne[0]; const int64_t n_experts = ne02; const int64_t n_tokens = ne12; @@ -110,7 +109,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 1; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_F16: { @@ -118,7 +117,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_BF16: { @@ -126,7 +125,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; default: diff --git a/ggml/src/ggml-cuda/mmf.cuh b/ggml/src/ggml-cuda/mmf.cuh index c49f6c47ad1d..46a123a5c3c1 100644 --- a/ggml/src/ggml-cuda/mmf.cuh +++ b/ggml/src/ggml-cuda/mmf.cuh @@ -47,12 +47,11 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr bool ggml_cuda_should_use_mmf(enum ggml_type type, int cc, int warp_size, const int64_t * scr0_ne, const size_t * src0_nb, const int src1_ncols, bool mul_mat_id); -template +template __launch_bounds__(ggml_cuda_get_physical_warp_size()*nwarps, 1) static __global__ void mul_mat_f( - const T * __restrict__ x, const float * __restrict__ y, const int32_t * __restrict__ ids, float * __restrict__ dst, - const int ncols, const int ncols_dst_total, const int nchannels_dst, const int stride_row, const int stride_col_y, const int stride_col_dst, - const int stride_col_id, const int stride_row_id, + const T * __restrict__ x, const float * __restrict__ y, float * __restrict__ dst, + const int ncols, const int stride_row, const int stride_col_y, const int stride_col_dst, const int channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, const int sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst) { // TODO: handle this in a consistent and simpler way after AMD MFMA support has been added @@ -90,85 +89,26 @@ static __global__ void mul_mat_f( constexpr int ntA = rows_per_block / tile_A::I; constexpr int ntB = (cols_per_block + tile_B::I - 1) / tile_B::I; - const int row0 = blockIdx.x * rows_per_block; - - int expert_idx = 0; - [[maybe_unused]] int col_base = 0; - - const int channel_dst = has_ids ? 0 : blockIdx.y; - - if constexpr (has_ids) { - // experts + tiles of ncols_dst are packed in the y dimension - int col_tiles = (ncols_dst_total + cols_per_block - 1) / cols_per_block; - const int nchannels_x = gridDim.y / col_tiles; - const int tile_idx = blockIdx.y / nchannels_x; - expert_idx = blockIdx.y - tile_idx * nchannels_x; - col_base = tile_idx * cols_per_block; - } + const int row0 = blockIdx.x * rows_per_block; - const int channel_x = has_ids ? expert_idx : (channel_dst / channel_ratio); + const int channel_dst = blockIdx.y; + const int channel_x = channel_dst / channel_ratio; const int channel_y = channel_dst; const int sample_dst = blockIdx.z; const int sample_x = sample_dst / sample_ratio; const int sample_y = sample_dst; x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row ; - y += int64_t(sample_y) *stride_sample_y + (has_ids ? 0 : channel_y *stride_channel_y); - dst += int64_t(sample_dst)*stride_sample_dst + (has_ids ? 0 : channel_dst*stride_channel_dst); - - if constexpr (has_ids) { - constexpr int y_stride_scale = std::is_same_v ? 1 : 2; - const int64_t col_offset = col_base; - y += col_offset * stride_col_y * y_stride_scale; - dst += col_offset * stride_col_dst; - ids += col_offset * stride_row_id; - } + y += int64_t(sample_y) *stride_sample_y + channel_y *stride_channel_y; + dst += int64_t(sample_dst)*stride_sample_dst + channel_dst*stride_channel_dst; [[maybe_unused]] const float2 * y2 = (const float2 *) y; extern __shared__ char data_mmv[]; - char * shmem_base = data_mmv; - [[maybe_unused]] int * slot_map = (int *) shmem_base; - char * compute_base = has_ids ? (shmem_base + GGML_PAD(cols_per_block, 16) * sizeof(int)) : shmem_base; - tile_C C[ntA][ntB]; - T * tile_xy = (T *) compute_base + threadIdx.y*(tile_A::I * tile_k_padded); - - if constexpr (has_ids) { - int found = 0; - - for (int j0 = 0; j0 < cols_per_block; j0 += nwarps) { - const int j = j0 + threadIdx.y; - - if (threadIdx.x == 0) { - slot_map[j] = -1; - } - ggml_cuda_syncwarp(); - - if (col_base + j >= ncols_dst_total) { - continue; - } - - const int32_t * __restrict__ id_row = ids + j*stride_row_id; - - for (int k = threadIdx.x; k < nchannels_dst; k += warp_size) { - int match = id_row[k*stride_col_id] == expert_idx; - - if (match) { - slot_map[j] = k; - found = 1; - break; - } - } - } - - if (!__syncthreads_or(found)) { - return; - } - } - + T * tile_xy = (T *) data_mmv + threadIdx.y*(tile_A::I * tile_k_padded); for (int col = threadIdx.y*warp_size + threadIdx.x; col < ncols; col += nwarps*warp_size) { tile_A A[ntA][warp_size / tile_A::J]; @@ -194,26 +134,15 @@ static __global__ void mul_mat_f( for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - tile_xy[j0*tile_k_padded + threadIdx.x] = valid ? y[slot_map[j]*stride_channel_y + j*stride_col_y + col] : 0.0f; - } + tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; } } else if constexpr (std::is_same_v || std::is_same_v) { #pragma unroll for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - float2 tmp = valid ? *(const float2*) &y[slot_map[j]*stride_channel_y + 2*(j*stride_col_y + col)] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } + const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); + tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); } } else { static_assert(std::is_same_v, "unsupported type"); @@ -231,7 +160,7 @@ static __global__ void mul_mat_f( } } - float * buf_iw = (float *) compute_base; + float * buf_iw = (float *) data_mmv; constexpr int kiw = nwarps*rows_per_block + mmf_get_padding(); if (nwarps > 1) { @@ -278,26 +207,15 @@ static __global__ void mul_mat_f( } } - if constexpr (!has_ids) { #pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } else { - const int slot = (j < cols_per_block) ? slot_map[j] : -1; - if (slot >= 0 && (col_base + j) < ncols_dst_total) { -#pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[slot*stride_channel_dst + j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } + for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { + dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; } } } #else - GGML_UNUSED_VARS(x, y, ids, dst, - ncols, ncols_dst_total, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, + GGML_UNUSED_VARS(x, y, dst, + ncols, stride_row, stride_col_y, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); NO_DEVICE_CODE; @@ -588,22 +506,21 @@ static __global__ void mul_mat_f_ids( template static inline void mul_mat_f_switch_ids( - const T * x, const float * y, const int32_t * ids, float * dst, + const T * x, const float * y, float * dst, const int64_t ncols_x, const int64_t ncols_dst, const int64_t nchannels_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t channel_ratio, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t sample_ratio, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, const dim3 & block_nums, const dim3 & block_dims, const int nbytes_shared_total, cudaStream_t stream, const mmf_ids_data * ids_data) { + const bool has_ids_data = ids_data && ids_data->ids_src_compact; - // Use the compact-ids kernel only for larger tiles; for small ncols_dst (< 16) - // we prefer the normal mul_mat_f path with has_ids=true. - if (has_ids_data && ncols_dst > 16) { + if (has_ids_data) { if (ids_data->max_tiles == 0) { return; } + GGML_ASSERT(block_nums.z == 1); dim3 block_nums_ids(block_nums.x, ids_data->max_tiles, 1); const uint3 sis1_fd = ids_data->sis1 > 0 ? init_fastdiv_values((uint32_t) ids_data->sis1) : make_uint3(0, 0, 1); @@ -615,19 +532,10 @@ static inline void mul_mat_f_switch_ids( channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, sis1_fd, nch_fd); - } else if (ids) { - const int64_t col_tiles = (ncols_dst + cols_per_block - 1) / cols_per_block; - dim3 block_nums_ids = block_nums; - block_nums_ids.y *= col_tiles; - - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } else { - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, cols_per_block, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, + mul_mat_f<<>> + (x, y, dst, ncols_x, stride_row, stride_col_y, stride_col_dst, + channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } } @@ -637,7 +545,6 @@ void mul_mat_f_cuda( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -673,70 +580,59 @@ void mul_mat_f_cuda( const int nbytes_shared_iter = nwarps_best * (volta_mma_available(cc) ? tile_A_32::I : tile_A_16::I) * (warp_size + mmf_get_padding(cc)) * 4; const int nbytes_cols_per_block_pad = (amd_wmma_available(cc) || amd_mfma_available(cc)) ? tile_B_16::I : tile_B_8::I; const int nbytes_shared_combine = GGML_PAD(cols_per_block, nbytes_cols_per_block_pad) * (nwarps_best*rows_per_block + mmf_get_padding(cc)) * 4; - const int nbytes_shared = std::max(nbytes_shared_iter, nbytes_shared_combine); - const int nbytes_slotmap = ids ? GGML_PAD(cols_per_block, 16) * sizeof(int) : 0; - const int nbytes_shared_total = nbytes_shared + nbytes_slotmap; - const int64_t grid_y = ids ? nchannels_x : nchannels_dst; + const int nbytes_shared_total = std::max(nbytes_shared_iter, nbytes_shared_combine); - const dim3 block_nums(nrows_x/rows_per_block, grid_y, nsamples_dst); + const dim3 block_nums(nrows_x/rows_per_block, nchannels_dst, nsamples_dst); const dim3 block_dims(warp_size, nwarps_best, 1); switch (nwarps_best) { case 1: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 2: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 3: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 4: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 5: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 6: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 7: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 8: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; default: GGML_ABORT("fatal error"); @@ -750,95 +646,94 @@ static void mul_mat_f_switch_cols_per_block( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, cudaStream_t stream, const mmf_ids_data * ids_data) { - const int ncols_case = (ids && ncols_dst > 16) ? 16 : ncols_dst; + const int ncols_case = ids ? 16 : ncols_dst; GGML_ASSERT(ids || ncols_dst <= 16); switch (ncols_case) { case 1: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 2: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 3: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 4: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 5: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 6: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 7: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 8: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 9: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 10: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 11: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 12: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 13: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 14: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 15: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 16: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -851,7 +746,6 @@ static void mul_mat_f_switch_rows_per_block( const int rows_per_block, const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -860,13 +754,13 @@ static void mul_mat_f_switch_rows_per_block( case MMF_ROWS_PER_BLOCK: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case MMF_ROWS_PER_BLOCK_CDNA: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -878,7 +772,6 @@ static void mul_mat_f_switch_rows_per_block( template void mul_mat_f_cuda( \ const T * x, const float * y, const int32_t * ids, float * dst, \ const int64_t ncols_x, const int64_t nrows_x, int64_t ncols_dst_total, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, \ - const int64_t stride_col_id, const int64_t stride_row_id, \ const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, \ const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x,\ const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, \ diff --git a/ggml/src/ggml-cuda/mmid.cu b/ggml/src/ggml-cuda/mmid.cu index 6b425a377244..fe9458763e13 100644 --- a/ggml/src/ggml-cuda/mmid.cu +++ b/ggml/src/ggml-cuda/mmid.cu @@ -24,6 +24,50 @@ template struct mm_ids_pow2 { static constexpr int value = 2*mm_ids_pow2 template <> struct mm_ids_pow2<1> { static constexpr int value = 1; }; template <> struct mm_ids_pow2<0> { static constexpr int value = 1; }; +template +static __device__ __forceinline__ void check_experts( + mm_ids_helper_store * store, int & nex_prev, int & it_compact, + const int expert, const int it, const int iex, const int expert_found) { + if (increment_nex_prev) { + nex_prev += expert_found < expert; + } + + if (write_to_store) { + const ggml_cuda_thread_mask_t iex_used = ggml_cuda_ballot(expert_found == expert); + const ggml_cuda_thread_mask_t mask = (ggml_cuda_thread_mask_t(1) << threadIdx.x) - 1; + const int it_compact_offset = ggml_cuda_popc(iex_used & mask); + + if (expert_found == expert) { + store[it_compact + it_compact_offset] = mm_ids_helper_store(it, iex); + } + + it_compact += ggml_cuda_popc(iex_used); + } +} + +static __device__ __forceinline__ void dump_store( + int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, + const int n_expert_used, const int nchannels_y, const int sis1, const bool write_inverse, + const mm_ids_helper_store * __restrict__ store, const int nex_prev, int & n_dumped, const int it_compact) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + + for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { + const mm_ids_helper_store store_it = store[itc]; + const int it = store_it.it(); + const int iex_used = store_it.iex_used(); + ids_dst[nex_prev + n_dumped + itc] = it*n_expert_used + iex_used; + // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup + if (write_inverse) { + ids_src1[it*n_expert_used + iex_used] = nex_prev + n_dumped + itc; + } else { + ids_src1[nex_prev + n_dumped + itc] = it*sis1 + iex_used % nchannels_y; + } + } + n_dumped += it_compact; +} + +constexpr int n_unroll = 4; // Manually unroll this many loop iterations for better performance. + // Helper function for mul_mat_id, converts ids to a more convenient format. // ids_src1 describes how to permute the flattened column indices of src1 in order to get a compact src1 tensor sorted by expert. // ids_dst describes the same mapping but for the dst tensor. @@ -36,85 +80,138 @@ static __global__ void mm_ids_helper( const int32_t * __restrict__ ids, int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec, const int n_tokens, const int n_expert_used_var, const int nchannels_y, const uint3 tile_width, - const int si1, const int sis1, const bool write_inverse) { + const int si1, const int sis1, const bool write_inverse, const int ne_store) { constexpr int warp_size = ggml_cuda_get_physical_warp_size(); const int n_expert_used = n_expert_used_template == 0 ? n_expert_used_var : n_expert_used_template; - const int expert = blockIdx.x; + + const int expert = blockIdx.x; // The expert this CUDA block handles. extern __shared__ char data_mm_ids_helper[]; mm_ids_helper_store * store = (mm_ids_helper_store *) data_mm_ids_helper; int nex_prev = 0; // Number of columns for experts with a lower index. + int n_dumped = 0; // Number of data values that have been dumped to output buffers. int it_compact = 0; // Running index for the compact slice of this expert. + // Step 1: Iterate over n_tokens, increment nex_prev to determine the output indices, fill up store. + // Step 1.5: If the store does not have enough space to hold all values, iterate over the rest of the tokens just to increment nex_prev. + // Step 2: Dump the stored values using nex_prev to get the correct output indices. + // Step 3: If we were not able to process all values, resume at the index up to which we were able to dump the output and re-do. + if constexpr (n_expert_used_template == 0) { // Generic implementation: - for (int it = 0; it < n_tokens; ++it) { - int iex_used = -1; // The index at which the expert is used, if any. - for (int iex = threadIdx.x; iex < n_expert_used; iex += warp_size) { - const int expert_used = ids[it*si1 + iex]; - nex_prev += expert_used < expert; - if (expert_used == expert) { - iex_used = iex; - } + int it = 0; + for (; it < n_tokens && it_compact + max(warp_size, n_expert_used) <= ne_store; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it_dumped = it; + for (; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; - if (warp_reduce_any(iex_used != -1)) { - it_compact++; + for (int it = it_dumped; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + max(warp_size, n_expert_used) >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } } } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + } } else { // Implementation optimized for specific numbers of experts used: // a warp holds a whole number of token slots, so the slot count is padded to a power of 2 constexpr int neu_padded = mm_ids_pow2::value; static_assert(neu_padded <= warp_size && warp_size % neu_padded == 0, "bad n_expert_used"); - for (int it0 = 0; it0 < n_tokens; it0 += warp_size/neu_padded) { - const int it = it0 + threadIdx.x / neu_padded; - - const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - const int expert_used = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? - ids[it*si1 + iex] : INT_MAX; - const int iex_used = expert_used == expert ? iex : -1; - nex_prev += expert_used < expert; - - // Whether the threads at this token position have used the expert: - const int it_compact_add_self = warp_reduce_any(iex_used != -1); + const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - // Do a scan over threads at lower token positions in warp to get the correct index for writing data: - int it_compact_add_lower = 0; + int it0 = 0; + for (; it0 < n_tokens && it_compact + n_unroll*warp_size <= ne_store; it0 += n_unroll*warp_size/neu_padded) { #pragma unroll - for (int offset = neu_padded; offset < warp_size; offset += neu_padded) { - const int tmp = ggml_cuda_shfl_up(it_compact_add_self, offset, warp_size); - if (threadIdx.x >= static_cast(offset)) { - it_compact_add_lower += tmp; - } - } + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact + it_compact_add_lower] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it0_dumped = it0; + for (; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - // The thread with the highest index in the warp always has the sum over the whole warp, use it to increment all threads: - it_compact += ggml_cuda_shfl(it_compact_add_lower + it_compact_add_self, warp_size - 1, warp_size); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + } } - } - nex_prev = warp_reduce_sum(nex_prev); - ggml_cuda_syncwarp(); - for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { - const mm_ids_helper_store store_it = store[itc]; - const int it = store_it.it(); - const int iex_used = store_it.iex_used(); - ids_dst[nex_prev + itc] = it*n_expert_used + iex_used; - // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup - if (write_inverse) { - ids_src1[it*n_expert_used + iex_used] = nex_prev + itc; - } else { - ids_src1[nex_prev + itc] = it*sis1 + iex_used % nchannels_y; + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + + for (it0 = it0_dumped; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + warp_size >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } + } + } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); } } @@ -123,7 +220,7 @@ static __global__ void mm_ids_helper( } int col_low = nex_prev; - int col_high = nex_prev + min(int(tile_width.z), it_compact); + int col_high = nex_prev + min(int(tile_width.z), n_dumped); // The while loop covers all tiles at the seams containing the column with % tile_width == 0. while (col_high > fastdiv(col_low + tile_width.z - 1, tile_width) * tile_width.z) { @@ -131,7 +228,7 @@ static __global__ void mm_ids_helper( = {expert, col_low, col_high, /*padding =*/ 0}; col_low = col_high; - col_high = min(col_high + int(tile_width.z), nex_prev + it_compact); + col_high = min(col_high + int(tile_width.z), nex_prev + n_dumped); } // Finally, at most one extra tile_spec between the seams per expert. @@ -157,10 +254,12 @@ static void launch_mm_ids_helper( const dim3 num_blocks(n_experts, 1, 1); const dim3 block_size(warp_size, 1, 1); - const size_t nbytes_shared = n_tokens*sizeof(mm_ids_helper_store); - GGML_ASSERT(nbytes_shared <= smpbo); + const size_t ne_shared_pad = n_expert_used_template == 0 ? std::max(n_expert_used_var, warp_size) : n_unroll*warp_size; + const size_t nbytes_store_core = std::min(smpbo - ne_shared_pad * sizeof(mm_ids_helper_store), n_tokens * sizeof(mm_ids_helper_store)); + const size_t nbytes_shared = nbytes_store_core + ne_shared_pad * sizeof(mm_ids_helper_store); + const size_t ne_store = nbytes_shared / sizeof(mm_ids_helper_store); mm_ids_helper<<>> - (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse, ne_store); } void ggml_cuda_launch_mm_ids_helper( diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index 7fb09a353786..be2f11430079 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -1094,7 +1094,7 @@ static __global__ void mul_mat_q( int col_high = min(col_low + J, ncols_dst); int offset_y = wt*stride_sample_y + zt*stride_channel_y; int offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; - int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int64_t offset_dst = (int64_t) wt*stride_sample_dst + (int64_t) zt*stride_channel_dst + (int64_t) jt*J*stride_col_dst; if (ids_dst) { const ggml_cuda_mm_id_tile_spec tsj = tile_spec[jt]; @@ -1176,7 +1176,7 @@ static __global__ void mul_mat_q( int col_high = min(col_low + J, ncols_dst); int offset_y = wt*stride_sample_y + zt*stride_channel_y; int offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; - int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int64_t offset_dst = (int64_t) wt*stride_sample_dst + (int64_t) zt*stride_channel_dst + (int64_t) jt*J*stride_col_dst; if (ids_dst) { const ggml_cuda_mm_id_tile_spec tsj = tile_spec[jt]; @@ -1257,7 +1257,7 @@ static __global__ void mul_mat_q( int col_high = min(col_low + J, ncols_dst); int offset_y = wt*stride_sample_y + zt*stride_channel_y; int offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; - int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int64_t offset_dst = (int64_t) wt*stride_sample_dst + (int64_t) zt*stride_channel_dst + (int64_t) jt*J*stride_col_dst; if (ids_dst) { const ggml_cuda_mm_id_tile_spec tsj = tile_spec[jt]; @@ -1403,7 +1403,7 @@ static __global__ void mul_mat_q_stream_k_fixup( const int it = tmp2.x; if (!ids_dst) { - const int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst + it*I; + const int64_t offset_dst = (int64_t) wt*stride_sample_dst + (int64_t) zt*stride_channel_dst + (int64_t) jt*J*stride_col_dst + it*I; dst += offset_dst; const int i_max = nrows_x - it*I - 1; diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 612d3e313b25..091fc3071561 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -96,7 +96,8 @@ enum mmvq_parameter_table_id { MMVQ_PARAMETERS_RDNA2, MMVQ_PARAMETERS_RDNA3_0, MMVQ_PARAMETERS_RDNA4, - MMVQ_PARAMETERS_GB10 + MMVQ_PARAMETERS_GB10, + MMVQ_PARAMETERS_ORIN }; static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { @@ -112,6 +113,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_TURING; #elif __CUDA_ARCH__ == GGML_CUDA_CC_GB10 return MMVQ_PARAMETERS_GB10; +#elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN + return MMVQ_PARAMETERS_ORIN; #else return MMVQ_PARAMETERS_GENERIC; #endif @@ -136,6 +139,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_GB10) { return MMVQ_PARAMETERS_GB10; } + if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) { + return MMVQ_PARAMETERS_ORIN; + } return MMVQ_PARAMETERS_GENERIC; } @@ -580,6 +586,9 @@ static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_d } return generic; } + if (table_id == MMVQ_PARAMETERS_ORIN) { + return calc_nwarps(type, ncols_dst, MMVQ_PARAMETERS_GENERIC); + } return 1; } @@ -620,6 +629,41 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int return 1; } } + if (table_id == MMVQ_PARAMETERS_ORIN) { + switch (ncols_dst) { + case 1: + if (small_k) { + return nwarps; + } + // One row per warp (more rows per block, more loads in flight) for these types, measured on Jetson Orin Nano. + // Other types are faster in isolated mat-vec too, but gained at most 2 % end to end. + switch (type) { + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_IQ4_NL: + return nwarps; + default: + break; + } + return mmvq_two_rows_ncols1(type) ? 2 : 1; + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + return 2; + default: + return 1; + } + } return 1; } diff --git a/ggml/src/ggml-cuda/rope.cu b/ggml/src/ggml-cuda/rope.cu index 2604d014f854..657b58a4d05c 100644 --- a/ggml/src/ggml-cuda/rope.cu +++ b/ggml/src/ggml-cuda/rope.cu @@ -92,13 +92,16 @@ static __global__ void rope_norm(const T * x, } else if constexpr (std::is_same_v) { half2 v = make_half2(x0, x1); ggml_cuda_memcpy_1<4>(dst + idst, &v); + } else if constexpr (std::is_same_v) { + const __align__(4) nv_bfloat16 v[2] = { ggml_cuda_cast(x0), ggml_cuda_cast(x1) }; + ggml_cuda_memcpy_1(dst + idst, v); } }; if (i0 < n_offs || i0 >= n_offs + n_dims) { if (inplace) { return; } - store_coaelsced(x[ix + 0], x[ix + 1]); + store_coaelsced(ggml_cuda_cast(x[ix + 0]), ggml_cuda_cast(x[ix + 1])); return; } @@ -113,8 +116,8 @@ static __global__ void rope_norm(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + 1]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + 1]); store_coaelsced(x0 * cos_theta - x1 * sin_theta, x0 * sin_theta + x1 * cos_theta); } @@ -189,8 +192,8 @@ static __global__ void rope_neox(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0 * cos_theta - x1 * sin_theta); dst[idst + n_offs/2 + n_dims / 2] = ggml_cuda_cast(x0 * sin_theta + x1 * cos_theta); @@ -293,8 +296,8 @@ static __global__ void rope_multi(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); dst[idst + n_offs/2 + n_dims/2] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); @@ -357,11 +360,11 @@ static __global__ void rope_vision(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + n_dims]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_dims]); - dst[idst + 0] = x0*cos_theta - x1*sin_theta; - dst[idst + n_dims] = x0*sin_theta + x1*cos_theta; + dst[idst + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); + dst[idst + n_dims] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); } template @@ -569,8 +572,8 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, } cudaStream_t stream = ctx.stream(); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); + GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_BF16); // When not fused, src0 and dst types must match // When fused (ROPE+VIEW+SET_ROWS), src0 may be F32 and dst may be F16 GGML_ASSERT(src0->type == dst->type || (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16)); @@ -655,6 +658,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -674,6 +687,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -686,6 +709,10 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, rope_vision_cuda((const half *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, stream); + } else if (src0->type == GGML_TYPE_BF16) { + rope_vision_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, + s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, + corr_dims, freq_factors, sections, stream); } else { GGML_ABORT("fatal error"); } @@ -705,6 +732,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } diff --git a/ggml/src/ggml-cuda/set-rows.cu b/ggml/src/ggml-cuda/set-rows.cu index 4be3e649b73b..e4fb51619e66 100644 --- a/ggml/src/ggml-cuda/set-rows.cu +++ b/ggml/src/ggml-cuda/set-rows.cu @@ -4,8 +4,8 @@ typedef void (*set_rows_kernel_t)(const char * src, char * dst); // Generic quantized set_rows kernel template -template -static __global__ void k_set_rows_quant(const float * __restrict__ src0, +template +static __global__ void k_set_rows_quant(const src_t * __restrict__ src0, const idx_t * __restrict__ src1, block_type * __restrict__ dst, const int64_t ne_total, @@ -56,13 +56,23 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, ggml_cuda_pdl_sync(); const int64_t dst_row = *(src1 + i10*s10 + i11*s11 + i12*s12); - const float * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; + const src_t * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; block_type * dst_row_ptr = dst + (dst_row*s1 + i02*s2 + i03*s3) / sizeof(block_type); - const float * src_block = src0_row + i00; + const src_t * src_block = src0_row + i00; block_type * dst_block = dst_row_ptr + i00 / qk; - quantize_func(src_block, dst_block); + if constexpr (std::is_same_v) { + quantize_func(src_block, dst_block); + } else { + // the quantize functions take F32 input: widen the block first + float src_block_f32[qk]; +#pragma unroll + for (int j = 0; j < qk; ++j) { + src_block_f32[j] = ggml_cuda_cast(src_block[j]); + } + quantize_func(src_block_f32, dst_block); + } GGML_UNUSED(ne10); GGML_UNUSED(ne11); @@ -71,9 +81,9 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, } // Template dispatch function for quantized set_rows -template +template static void set_rows_cuda_quant( - const float * src0_d, const idx_t * src1_d, block_type * dst_d, + const src_t * src0_d, const idx_t * src1_d, block_type * dst_d, const int64_t ne00, const int64_t ne01, const int64_t ne02, const int64_t ne03, const int64_t ne10, const int64_t ne11, const int64_t ne12, const int64_t ne13, const size_t nb01, const size_t nb02, const size_t nb03, @@ -87,9 +97,9 @@ static void set_rows_cuda_quant( const dim3 block_size(CUDA_SET_ROWS_BLOCK_SIZE); const dim3 grid_size(num_blocks); - const int64_t s01 = nb01/sizeof(float); - const int64_t s02 = nb02/sizeof(float); - const int64_t s03 = nb03/sizeof(float); + const int64_t s01 = nb01/sizeof(src_t); + const int64_t s02 = nb02/sizeof(src_t); + const int64_t s03 = nb03/sizeof(src_t); const int64_t s10 = nb10/sizeof(idx_t); const int64_t s11 = nb11/sizeof(idx_t); const int64_t s12 = nb12/sizeof(idx_t); @@ -104,7 +114,7 @@ static void set_rows_cuda_quant( const uint3 ne11_fd = init_fastdiv_values((uint32_t) ne11); const uint3 ne12_fd = init_fastdiv_values((uint32_t) ne12); - k_set_rows_quant<<>>( + k_set_rows_quant<<>>( src0_d, src1_d, dst_d, ne_total, ne10, ne11, ne12, ne13, s01, s02, s03, s10, s11, s12, s1, s2, s3, ne00_fd, ne01_fd, ne02_fd, ne11_fd, ne12_fd); } @@ -268,7 +278,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -278,7 +288,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -288,7 +298,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -298,7 +308,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -308,7 +318,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q8_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q8_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -318,7 +328,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_IQ4_NL) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_iq4_nl*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -382,12 +392,11 @@ void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_te } } - void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); GGML_ASSERT(src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32); if (src0->type == GGML_TYPE_F32) { @@ -402,6 +411,12 @@ void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { } else { set_rows_cuda(ctx, src0, src1, dst); } + } else if (src0->type == GGML_TYPE_BF16) { + if (src1->type == GGML_TYPE_I64) { + set_rows_cuda(ctx, src0, src1, dst); + } else { + set_rows_cuda(ctx, src0, src1, dst); + } } else { GGML_ABORT("unsupported type %s", ggml_type_name(src0->type)); } diff --git a/ggml/src/ggml-cuda/sleep.cu b/ggml/src/ggml-cuda/sleep.cu new file mode 100644 index 000000000000..e6a40e5f213a --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cu @@ -0,0 +1,32 @@ +#include "sleep.cuh" + +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + +// %globaltimer is a nanosecond wall clock, unlike clock64() it is unaffected by the SM clock and by frequency scaling +static __device__ __forceinline__ uint64_t globaltimer_ns() { + uint64_t t; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); + return t; +} + +// a single thread is enough, the next kernel on the same stream cannot start before this one retires +static __global__ void sleep_ns(const uint64_t ns) { + const uint64_t t0 = globaltimer_ns(); + + while (globaltimer_ns() - t0 < ns) {} +} + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + sleep_ns<<<1, 1, 0, ctx.stream()>>>(1000*(uint64_t) ggml_get_op_params_i32(dst, 0)); + CUDA_CHECK(cudaGetLastError()); +} + +#else + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + GGML_UNUSED(ctx); + GGML_UNUSED(dst); + GGML_ABORT("GGML_OP_SLEEP requires the %%globaltimer register, which is only available on CUDA"); +} + +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/sleep.cuh b/ggml/src/ggml-cuda/sleep.cuh new file mode 100644 index 000000000000..d62c3178565c --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cuh @@ -0,0 +1,3 @@ +#include "common.cuh" + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/top-k.cu b/ggml/src/ggml-cuda/top-k.cu index 227751eeadeb..2639a664d034 100644 --- a/ggml/src/ggml-cuda/top-k.cu +++ b/ggml/src/ggml-cuda/top-k.cu @@ -184,13 +184,6 @@ static __global__ void top_k_radix_gather( constexpr int NBINS = 1 << RADIX_BITS; constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = BLOCK_SIZE / warp_size; - const auto popc = [](const ggml_cuda_thread_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; __shared__ int warp_ties[nwarps]; const int row = blockIdx.x / blocks_per_row; @@ -247,11 +240,11 @@ static __global__ void top_k_radix_gather( const bool is_tie = col < warp_end && top_k_float_to_ordered(row_src[col]) == threshold; const ggml_cuda_thread_mask_t ties = ggml_cuda_ballot(is_tie); - const int tie_pos = pos + popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); + const int tie_pos = pos + ggml_cuda_popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); if (is_tie && tie_pos < pos_end) { row_dst[k - rank + tie_pos] = col; } - pos += popc(ties); + pos += ggml_cuda_popc(ties); } } diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 3fa6856e1629..cd9e0785053c 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -2551,6 +2551,26 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_mm(ggml_ char base[256]; char name[256]; + const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor; + + if (has_tensor) { + // nr0 output positions per threadgroup, nr1 output channels, same tiles as kernel_mul_mm + snprintf(base, 256, "kernel_conv_2d_mm_tensor_%s_%s", ggml_type_name(op->src[0]->type), ggml_type_name(op->src[1]->type)); + snprintf(name, 256, "%s", base); + + ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); + if (!res.pipeline) { + res = ggml_metal_library_compile_pipeline(lib, base, name, nullptr); + } + + res.nr0 = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; + res.nr1 = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; + res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; + res.smem = res.nr0 * N_MM_NK_TOTAL * sizeof(ggml_fp16_t); + + return res; + } + const int nr0 = op->src[0]->ne[3] <= 32 ? 32 : 64; const int nr1 = 2048/nr0; @@ -2564,13 +2584,27 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_mm(ggml_ res.nr0 = nr0; res.nr1 = nr1; - res.nsg = 4; + res.nsg = N_SG_CONV_2D; res.smem = nr0*nr1*sizeof(float); return res; } +ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_mm_reduce(ggml_metal_library_t lib, const ggml_tensor * op) { + assert(op->op == GGML_OP_CONV_2D); + GGML_UNUSED(op); + + const char * name = "kernel_conv_2d_mm_reduce"; + + ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); + if (!res.pipeline) { + res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr); + } + + return res; +} + ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_dw(ggml_metal_library_t lib, const ggml_tensor * op, bool tiled) { assert(op->op == GGML_OP_CONV_2D_DW); diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h index df22635e0df4..c0466d62ff6f 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -170,6 +170,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_col2im_1d struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_snake (ggml_metal_library_t lib, enum ggml_type type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d (ggml_metal_library_t lib, const struct ggml_tensor * op); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_mm (ggml_metal_library_t lib, const struct ggml_tensor * op); +struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_mm_reduce (ggml_metal_library_t lib, const struct ggml_tensor * op); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_2d_dw (ggml_metal_library_t lib, const struct ggml_tensor * op, bool tiled); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_conv_3d (ggml_metal_library_t lib, const struct ggml_tensor * op); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_upscale (ggml_metal_library_t lib, const struct ggml_tensor * op); diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index f4c4991e934d..2e085453adb9 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1713,7 +1713,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32 && (ggml_is_contiguous_rows(op->src[0])); case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: - return ggml_rope_get_truncate(op); + return ggml_rope_get_truncate(op) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); case GGML_OP_IM2COL: return ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 && (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32); case GGML_OP_CONV_2D: @@ -2375,7 +2375,7 @@ void ggml_metal_buffer_memset_tensor(ggml_metal_buffer_t buf, struct ggml_tensor id encoder = [cmd_buf blitCommandEncoder]; [encoder fillBuffer:bid_dst.metal - range:NSMakeRange(bid_dst.offs, bid_dst.offs + size) + range:NSMakeRange(bid_dst.offs, size) value:value]; [encoder endEncoding]; diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index 7fd9d97cff22..aad014d837e9 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -17,6 +17,8 @@ #define N_ARGMAX_NPART_MAX 256 #define N_ARGMAX_CHUNK 4096 +#define N_SG_CONV_2D 4 + // kernel parameters for mat-vec threadgroups // // N_R0: number of src0 rows to process per simdgroup @@ -752,8 +754,14 @@ typedef struct { int32_t p1; int32_t d0; int32_t d1; + int32_t nk; // reduction length per split } ggml_metal_kargs_conv_2d; +typedef struct { + int32_t ne; // output elements + int32_t nsplit; +} ggml_metal_kargs_conv_2d_reduce; + typedef struct { uint64_t nb00; // kernel strides uint64_t nb01; diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 65a81b81e9d0..1ae7f3d5dcf9 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -4959,6 +4959,33 @@ int ggml_metal_op_im2col(ggml_metal_op_t ctx, int idx) { return 1; } +// number of reduction splits of the conv_2d matmul kernels +// A small output with a long reduction leaves the GPU idle, so the reduction is split until there are about 1M partial sums. +static int ggml_metal_op_conv_2d_nsplit(const ggml_tensor * op, int32_t * nk) { + const int64_t K = op->src[0]->ne[0]*op->src[0]->ne[1]*op->src[0]->ne[2]; + const int64_t nsteps = (K + 31)/32; + const int64_t ne = ggml_nelements(op); + + // at least 3 reduction steps of 32 per split, at most 32 splits + const int64_t nsplit = std::max(1, std::min({ (1024*1024 + ne - 1)/ne, nsteps/3, 32 })); + const int64_t steps = (nsteps + nsplit - 1)/nsplit; + + if (nk) { + *nk = (int32_t) (steps*32); + } + + return (int) ((nsteps + steps - 1)/steps); +} + +size_t ggml_metal_op_conv_2d_extra_tmp(const ggml_tensor * op) { + assert(op->op == GGML_OP_CONV_2D); + + const int nsplit = ggml_metal_op_conv_2d_nsplit(op, nullptr); + + // partial sums of the reduction splits + return nsplit > 1 ? nsplit*ggml_nelements(op)*sizeof(float) : 0; +} + int ggml_metal_op_conv_2d(ggml_metal_op_t ctx, int idx) { ggml_tensor * op = ctx->node(idx); @@ -5012,11 +5039,17 @@ int ggml_metal_op_conv_2d(ggml_metal_op_t ctx, int idx) { /*.p1 =*/ p1, /*.d0 =*/ d0, /*.d1 =*/ d1, + /*.nk =*/ 0, }; const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ctx->dev); - if (props_dev->has_simdgroup_mm) { + // the matmul kernels walk the patches with 32-bit byte offsets inside an image + // larger images, possibly a strided view, take the generic kernel + const uint64_t max_off = (ne12 - 1)*nb12 + (ne11 - 1)*nb11 + (ne10 - 1)*nb10 + sizeof(float); + const bool fits_32 = max_off <= UINT32_MAX; + + if (props_dev->has_simdgroup_mm && fits_32) { auto pipeline = ggml_metal_library_get_pipeline_conv_2d_mm(lib, op); const int nr0 = pipeline.nr0; @@ -5026,15 +5059,48 @@ int ggml_metal_op_conv_2d(ggml_metal_op_t ctx, int idx) { const int64_t NP = ne3*ne1*ne0; const int64_t OC = ne03; + const int nsplit = ggml_metal_op_conv_2d_nsplit(op, &args.nk); + + ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(op); + ggml_metal_buffer_id bid_tmp = bid_dst; + bid_tmp.offs += ggml_nbytes(op); + ggml_metal_encoder_set_pipeline(enc, pipeline); ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0); ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[0]), 1); ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[1]), 2); - ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3); + ggml_metal_encoder_set_buffer (enc, nsplit > 1 ? bid_tmp : bid_dst, 3); ggml_metal_encoder_set_threadgroup_memory_size(enc, pipeline.smem, 0); - ggml_metal_encoder_dispatch_threadgroups(enc, (NP + nr1 - 1)/nr1, (OC + nr0 - 1)/nr0, 1, 32, nsg, 1); + if (props_dev->has_tensor) { + // per image: nr0 positions times nr1 channels per threadgroup + const int64_t OHW = ne1*ne0; + ggml_metal_encoder_dispatch_threadgroups(enc, (OC + nr1 - 1)/nr1, (OHW + nr0 - 1)/nr0, ne3*nsplit, 32, nsg, 1); + } else { + ggml_metal_encoder_dispatch_threadgroups(enc, (NP + nr1 - 1)/nr1, (OC + nr0 - 1)/nr0, nsplit, 32, nsg, 1); + } + + if (nsplit > 1) { + GGML_ASSERT(ggml_is_contiguous(op)); + + // sync the 2 kernels + ggml_metal_op_concurrency_reset(ctx); + + ggml_metal_kargs_conv_2d_reduce args0 = { + /*.ne =*/ (int32_t) ggml_nelements(op), + /*.nsplit =*/ nsplit, + }; + + auto pipeline0 = ggml_metal_library_get_pipeline_conv_2d_mm_reduce(lib, op); + + ggml_metal_encoder_set_pipeline(enc, pipeline0); + ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); + ggml_metal_encoder_set_buffer (enc, bid_tmp, 1); + ggml_metal_encoder_set_buffer (enc, bid_dst, 2); + + ggml_metal_encoder_dispatch_threadgroups(enc, (args0.ne + 255)/256, 1, 1, 256, 1, 1); + } return 1; } diff --git a/ggml/src/ggml-metal/ggml-metal-ops.h b/ggml/src/ggml-metal/ggml-metal-ops.h index 47889fa8490a..7dae178d5fb4 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.h +++ b/ggml/src/ggml-metal/ggml-metal-ops.h @@ -49,6 +49,8 @@ size_t ggml_metal_op_flash_attn_ext_extra_rows(const struct ggml_tensor * op); size_t ggml_metal_op_argmax_extra(const struct ggml_tensor * op); +size_t ggml_metal_op_conv_2d_extra_tmp(const struct ggml_tensor * op); + int ggml_metal_op_concat (ggml_metal_op_t ctx, int idx); int ggml_metal_op_repeat (ggml_metal_op_t ctx, int idx); int ggml_metal_op_acc (ggml_metal_op_t ctx, int idx); diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 9bed6421bbdd..9a1bd2c773a3 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -311,6 +311,10 @@ static size_t ggml_backend_metal_buffer_type_get_alloc_size(ggml_backend_buffer_ { res = 2*sizeof(int32_t)*ggml_nelements(tensor->src[0]); } break; + case GGML_OP_CONV_2D: + { + res += ggml_metal_op_conv_2d_extra_tmp(tensor); + } break; case GGML_OP_ARGMAX: { res += ggml_metal_op_argmax_extra(tensor); diff --git a/ggml/src/ggml-metal/kernels/conv.metal b/ggml/src/ggml-metal/kernels/conv.metal index fdc32756ae3a..9f9b6edfc0df 100644 --- a/ggml/src/ggml-metal/kernels/conv.metal +++ b/ggml/src/ggml-metal/kernels/conv.metal @@ -285,7 +285,7 @@ kernel void kernel_conv_2d_mm( ushort tiitg[[thread_index_in_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - constexpr short NSG = 4; + constexpr short NSG = N_SG_CONV_2D; constexpr short NTH = 32*NSG; constexpr short NK = 32; constexpr short NKB = NK/8; @@ -300,6 +300,10 @@ kernel void kernel_conv_2d_mm( const int K = args.IC*args.KH*args.KW; const int NP = args.N*args.OH*args.OW; + // this threadgroup reduces [k_begin, k_end), the splits are summed by kernel_conv_2d_mm_reduce + const int k_begin = tgpig.z*args.nk; + const int k_end = min(K, k_begin + args.nk); + const int r0 = tgpig.y*NR0; const int r1 = tgpig.x*NR1; @@ -308,8 +312,14 @@ kernel void kernel_conv_2d_mm( const short lb_n = 8*sgitg + tiisg%8; const short lb_k = 8*(tiisg/8); + // the patches are walked with 32-bit byte offsets inside the image, the host checks that an image fits + const uint nb10 = args.nb10; + const uint nb11 = args.nb11; + const uint nb12 = args.nb12; + int ix0[NPL]; int iy0[NPL]; + uint off0[NPL]; bool ip_ok[NPL]; device const char * srcb[NPL]; @@ -324,6 +334,8 @@ kernel void kernel_conv_2d_mm( ix0[t] = iow*args.s0 - args.p0; iy0[t] = ioh*args.s1 - args.p1; + off0[t] = iy0[t]*nb11 + ix0[t]*nb10; + ip_ok[t] = ip < NP; srcb[t] = src + in*args.nb13; @@ -337,7 +349,7 @@ kernel void kernel_conv_2d_mm( mc[i] = make_filled_simdgroup_matrix(0.f); } - for (int k0 = 0; k0 < K; k0 += NK) { + for (int k0 = k_begin; k0 < k_end; k0 += NK) { threadgroup_barrier(mem_flags::mem_threadgroup); { @@ -349,7 +361,7 @@ kernel void kernel_conv_2d_mm( const int oc = r0 + row; half v = 0; - if (kk < K && oc < args.OC) { + if (kk < k_end && oc < args.OC) { v = *((device const TK *)(weights + oc*args.nb03) + kk); } @@ -364,7 +376,11 @@ kernel void kernel_conv_2d_mm( int kw = kk % args.KW; int kh = (kk / args.KW) % args.KH; - int ic = kk / (args.KW*args.KH); + int dx = kw*args.d0; + int dy = kh*args.d1; + + // byte offset of the reduction index kk, relative to the patch origin + uint offk = (kk / (args.KW*args.KH))*nb12 + dy*nb11 + dx*nb10; FOR_UNROLL (short i = 0; i < 8; i++) { const short k = lb_k + i; @@ -372,12 +388,12 @@ kernel void kernel_conv_2d_mm( FOR_UNROLL (short t = 0; t < NPL; t++) { const short n = 32*t + lb_n; - const int ix = ix0[t] + kw*args.d0; - const int iy = iy0[t] + kh*args.d1; + const int ix = ix0[t] + dx; + const int iy = iy0[t] + dy; half v = 0; - if (ip_ok[t] && kk < K && ix >= 0 && ix < args.IW && iy >= 0 && iy < args.IH) { - v = *(device const float *)(srcb[t] + ic*args.nb12 + iy*args.nb11 + ix*args.nb10); + if (ip_ok[t] && kk < k_end && (uint) ix < (uint) args.IW && (uint) iy < (uint) args.IH) { + v = *(device const float *)(srcb[t] + (off0[t] + offk)); } const short ib = NKB*(n/8) + k/8; @@ -386,11 +402,17 @@ kernel void kernel_conv_2d_mm( } kk++; + dx += args.d0; + offk += args.d0*nb10; if (++kw == args.KW) { - kw = 0; + kw = 0; + dx = 0; + dy += args.d1; + offk += args.d1*nb11 - args.KW*args.d0*nb10; if (++kh == args.KH) { - kh = 0; - ic++; + kh = 0; + dy = 0; + offk += nb12 - args.KH*args.d1*nb11; } } } @@ -398,7 +420,7 @@ kernel void kernel_conv_2d_mm( threadgroup_barrier(mem_flags::mem_threadgroup); - const short nkb = min((K - k0 + 7)/8, (int) NKB); + const short nkb = min((k_end - k0 + 7)/8, (int) NKB); for (short ik = 0; ik < nkb; ik++) { FOR_UNROLL (short i = 0; i < 4; i++) { @@ -436,7 +458,8 @@ kernel void kernel_conv_2d_mm( const int oh = (p / args.OW) % args.OH; const int n = p / (args.OW*args.OH); - device char * dstp = dst + n*args.nb3 + oh*args.nb1 + ow*args.nb0; + // with several splits, dst is the partial sum buffer, one contiguous output per split + device char * dstp = dst + (uint64_t) tgpig.z*args.N*args.nb3 + n*args.nb3 + oh*args.nb1 + ow*args.nb0; for (short j = 0; j < NR0*NR1/NTH; j++) { const short row = tiitg/NR1 + (NTH/NR1)*j; @@ -448,6 +471,158 @@ kernel void kernel_conv_2d_mm( } } +#ifdef GGML_METAL_HAS_TENSOR +// conv_2d as a matmul on the tensor cores, like kernel_mul_mm +// The patches of NRA output positions are gathered into threadgroup memory, the kernel rows are read from device memory. +// One threadgroup computes NRA positions of one image times NRB output channels, over the reduction range of its split. +template +kernel void kernel_conv_2d_mm_tensor( + constant ggml_metal_kargs_conv_2d & args, + device const char * weights, + device const char * src, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + uint3 tgpg[[threadgroups_per_grid]], + ushort tiitg[[thread_index_in_threadgroup]]) { + constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; // output channels + constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; // output positions + constexpr int NK = N_MM_NK_TOTAL; + constexpr int NTH = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; + + // each thread gathers NK/(NTH/NRA) consecutive reduction indices of one position + constexpr int KPT = NK/(NTH/NRA); + + const int K = args.IC*args.KH*args.KW; + const int OHW = args.OH*args.OW; + + const int nsplit = tgpg.z/args.N; + const int img = tgpig.z/nsplit; + const int split = tgpig.z%nsplit; + + const int k_begin = split*args.nk; + const int k_end = min(K, k_begin + args.nk); + + const int ra = tgpig.y*NRA; + const int rb = tgpig.x*NRB; + + threadgroup half * sa = (threadgroup half *) shmem; + + // the position this thread gathers + const int row = tiitg%NRA; + const int kc = (tiitg/NRA)*KPT; + const int p = ra + row; + const bool pok = p < OHW; + const int ix0 = (p%args.OW)*args.s0 - args.p0; + const int iy0 = (p/args.OW)*args.s1 - args.p1; + + device const char * srcb = src + img*args.nb13; + + // the patch is walked with 32-bit byte offsets inside the image, the host checks that an image fits + const uint nb10 = args.nb10; + const uint nb11 = args.nb11; + const uint nb12 = args.nb12; + + const uint off0 = iy0*nb11 + ix0*nb10; + + device TK * ptrB = (device TK *) weights; + const int strideB = args.nb03/sizeof(TK); + + mpp::tensor_ops::matmul2d< + mpp::tensor_ops::matmul2d_descriptor( + NRB, NRA, static_cast(dynamic_extent), false, true, true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), + execution_simdgroups> mm; + + auto tB0 = tensor(ptrB, dextents(K, args.OC), array({1, strideB})); + auto tA0 = tensor(sa, dextents(NK, NRA)); + auto cT = mm.get_destination_cooperative_tensor(); + + for (int k0 = k_begin; k0 < k_end; k0 += NK) { + // the reduction indices past k_end are beyond the extent given to the matmul, they are not gathered + if (k0 + kc < k_end) { + // gather KPT patch values of this position, walking the reduction index incrementally + int kk = k0 + kc; + int kw = kk % args.KW; + int kh = (kk / args.KW) % args.KH; + int dx = kw*args.d0; + int dy = kh*args.d1; + + // byte offset of the reduction index kk, relative to the patch origin + uint offk = (kk / (args.KW*args.KH))*nb12 + dy*nb11 + dx*nb10; + + FOR_UNROLL (short i = 0; i < KPT; i++) { + const int ix = ix0 + dx; + const int iy = iy0 + dy; + + half v = 0; + if (pok && kk < k_end && (uint) ix < (uint) args.IW && (uint) iy < (uint) args.IH) { + v = *(device const float *)(srcb + (off0 + offk)); + } + sa[row*NK + kc + i] = v; + + kk++; + dx += args.d0; + offk += args.d0*nb10; + if (++kw == args.KW) { + kw = 0; + dx = 0; + dy += args.d1; + offk += args.d1*nb11 - args.KW*args.d0*nb10; + if (++kh == args.KH) { + kh = 0; + dy = 0; + offk += nb12 - args.KH*args.d1*nb11; + } + } + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // clamp the reduction extent so neither operand is read past the end of the split + const int kExt = min(NK, k_end - k0); + + auto tAv = tensor(sa, dextents(kExt, NRA), array({1, NK})); + auto tBv = tensor(ptrB + k0 + rb*strideB, dextents(kExt, args.OC - rb), array({1, strideB})); + + mm.run(tBv, tAv, cT); + + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // dst holds [OHW, OC] per image, with several splits it is the partial sum buffer, one contiguous output per split + const int tileM = min(NRA, OHW - ra); + const int tileN = min(NRB, args.OC - rb); + + device float * dstTile = (device float *) (dst + (uint64_t) split*args.N*args.nb3 + img*args.nb3) + (uint64_t) rb*OHW + ra; + + auto tD = tensor(dstTile, dextents(tileM, tileN), array({1, OHW})); + cT.store(tD); +} + +typedef decltype(kernel_conv_2d_mm_tensor) kernel_conv_2d_mm_tensor_t; + +template [[host_name("kernel_conv_2d_mm_tensor_f32_f32")]] kernel kernel_conv_2d_mm_tensor_t kernel_conv_2d_mm_tensor; +template [[host_name("kernel_conv_2d_mm_tensor_f16_f32")]] kernel kernel_conv_2d_mm_tensor_t kernel_conv_2d_mm_tensor; +#endif + +kernel void kernel_conv_2d_mm_reduce( + constant ggml_metal_kargs_conv_2d_reduce & args, + device const float * tmp, + device float * dst, + uint tpig[[thread_position_in_grid]]) { + if ((int) tpig >= args.ne) { + return; + } + + float sum = 0.0f; + for (int s = 0; s < args.nsplit; ++s) { + sum += tmp[(uint64_t) s*args.ne + tpig]; + } + dst[tpig] = sum; +} + typedef decltype(kernel_conv_2d_mm) kernel_conv_2d_mm_t; template [[host_name("kernel_conv_2d_mm_f32_f32_64x32")]] kernel kernel_conv_2d_mm_t kernel_conv_2d_mm; diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index cdf4a5d54455..325f5c4bfc75 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -323,6 +323,9 @@ set(GGML_OPENCL_KERNELS mul_mm_f16_f32_kq_kqv mul_mm_f16_f32_kq_p8 mul_mm_q8_f32_kqv + mul_mm_q8_kq_p8 + mul_mm_q8_kq_p8_dk512 + flash_attn_q8_rows conv2d conv2d_f16_f32 conv2_dw diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 0d9212232871..894f8235e9a0 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -781,6 +781,10 @@ struct ggml_backend_opencl_context { ggml_cl_buffer prealloc_fa_pd; ggml_cl_buffer prealloc_fa_bmax; ggml_cl_buffer prealloc_fa_bsum; + ggml_cl_buffer prealloc_fa_k8; + ggml_cl_buffer prealloc_fa_k8_scale; + ggml_cl_buffer prealloc_fa_q8; + ggml_cl_buffer prealloc_fa_q8_scale; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_buffer prealloc_adreno_xmem_const; @@ -899,6 +903,10 @@ struct ggml_backend_opencl_context { cl_kernel kernel_fa_kqv_direct_f16 = nullptr; cl_kernel kernel_fa_kqv_direct_reduce = nullptr; cl_kernel kernel_fa_v_transpose_q8 = nullptr; + cl_kernel kernel_fa_q8_rows_f16 = nullptr; + cl_kernel kernel_fa_q8_rows_f32 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8_dk512 = nullptr; ggml_opencl_fa_kernels fa; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; @@ -1506,7 +1514,18 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { - for (cl_kernel kernel : {kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, kernel_fa_v_transpose_q8, kernel_fa_kqv_direct_f16, kernel_fa_kqv_direct_reduce}) { + for (cl_kernel kernel : { + kernel_mul_mm_f16_f32_kq_p8, + kernel_mul_mm_q8_f32_kqv, + kernel_fa_p8_fixup, + kernel_fa_v_transpose_q8, + kernel_fa_kqv_direct_f16, + kernel_fa_kqv_direct_reduce, + kernel_fa_q8_rows_f16, + kernel_fa_q8_rows_f32, + kernel_mul_mm_q8_kq_p8, + kernel_mul_mm_q8_kq_p8_dk512 + }) { if (kernel != nullptr) { CL_CHECK(clReleaseKernel(kernel)); } @@ -1648,7 +1667,7 @@ static cl_program build_program_from_source_ex(cl_context ctx, cl_device_id dev, return NULL; } -static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts) { +static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts, bool fatal = true) { cl_context ctx = backend_ctx->context; cl_device_id dev = backend_ctx->device; @@ -1660,7 +1679,7 @@ static cl_program build_program_from_source(ggml_backend_opencl_context * backen return p_cached; } - cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, /*fatal=*/true); + cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, fatal); // Best-effort save of the freshly-built binary (no-op if cache disabled). if (p != nullptr) { @@ -3995,6 +4014,52 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string rows_src { + #include "flash_attn_q8_rows.cl.h" + }; + const std::string kq_src { + #include "mul_mm_q8_kq_p8.cl.h" + }; +#else + const std::string rows_src = read_file("flash_attn_q8_rows.cl"); + const std::string kq_src = read_file("mul_mm_q8_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, rows_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f16 = clCreateKernel(prog, "kernel_fa_q8_rows_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f32 = clCreateKernel(prog, "kernel_fa_q8_rows_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + prog = build_program_from_source(backend_ctx, kq_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_mul_mm_q8_kq_p8 = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + // mul_mm_q8_kq_p8_dk512 + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_kq_p8_dk512.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_kq_p8_dk512.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8_dk512", &err); + CL_CHECK(clReleaseProgram(prog)); + if (err == CL_SUCCESS) { + backend_ctx->kernel_mul_mm_q8_kq_p8_dk512 = kernel; + } + } + GGML_LOG_CONT("."); + } + // mul_mm_f16_f32_kq_p8 if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -12305,7 +12370,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te } return false; } - return true; + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; } case GGML_OP_SOLVE_TRI: return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); @@ -22922,12 +22987,58 @@ static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_te } #endif // GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_fa_q8_rows( + ggml_backend_t backend, const ggml_tensor * src, const ggml_tensor * dst, + cl_mem values, cl_mem scales, int64_t row0, int nrow +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra = (ggml_tensor_extra_cl *) (src->view_src ? src->view_src->extra : src->extra); + const cl_ulong offset = extra->offset + src->view_offs + row0 * src->nb[1]; + const cl_ulong nb1 = src->nb[1]; + const cl_ulong nb2 = src->nb[2]; + const int dk = src->ne[0]; + const int nhead = src->ne[2]; + cl_kernel kernel; + switch (src->type) { + case GGML_TYPE_F16: kernel = backend_ctx->kernel_fa_q8_rows_f16; break; + case GGML_TYPE_F32: kernel = backend_ctx->kernel_fa_q8_rows_f32; break; + default: GGML_ABORT("unsupported int8 KQ input type"); + } + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &values)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &scales)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nrow)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhead)); + const size_t blocks = (size_t) (dk / 32) * nrow * nhead; + size_t gws[3] = {(blocks + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); +} + +static void ggml_cl_fa_kq_int8_prepare(ggml_backend_t backend, const ggml_tensor * dst, int64_t n_q_chunk) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const size_t k_bytes = (size_t) k->ne[0] * k->ne[1] * k->ne[2]; + const size_t q_bytes = (size_t) q->ne[0] * n_q_chunk * q->ne[2]; + backend_ctx->prealloc_fa_k8.allocate(backend_ctx->context, k_bytes); + backend_ctx->prealloc_fa_k8_scale.allocate(backend_ctx->context, k_bytes / 32 * sizeof(cl_half)); + backend_ctx->prealloc_fa_q8.allocate(backend_ctx->context, q_bytes); + backend_ctx->prealloc_fa_q8_scale.allocate(backend_ctx->context, q_bytes / 32 * sizeof(cl_half)); + ggml_cl_fa_q8_rows(backend, k, dst, backend_ctx->prealloc_fa_k8.buffer, backend_ctx->prealloc_fa_k8_scale.buffer, 0, k->ne[1]); +} + static void ggml_cl_fa_kq_p8_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * mask, const ggml_tensor * sinks, const ggml_tensor * dst, - int64_t q0, int nqc, float scale, float max_bias, int p_pitch + int64_t q0, int nqc, float scale, float max_bias, int p_pitch, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); @@ -22940,64 +23051,103 @@ static void ggml_cl_fa_kq_p8_dispatch( const int D_A = k->ne[2]; const int D_B = q->ne[2]; - cl_int err; - - cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; - cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format fmt = {CL_RGBA, CL_FLOAT}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = region.size / 16; - desc.buffer = k_sub; - cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); - CL_CHECK(err); - - region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; - region.size = (size_t) K * N * D_B * sizeof(float); - cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; const cl_ulong mask_nb1 = mask->nb[1]; const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); const float m0 = powf(2.0f, -max_bias / n_head_log2); const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + cl_kernel kernel; cl_uint a = 0; - cl_kernel kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + if (kq_int8) { + ggml_cl_fa_q8_rows(backend, q, dst, backend_ctx->prealloc_fa_q8.buffer, backend_ctx->prealloc_fa_q8_scale.buffer, q0, nqc); + kernel = K <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + size_t gws[3] = {64 * (((size_t) N + 31) / 32) * (D_B / D_A), ((size_t) M + 511) / 512, (size_t) D_A}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } else { + cl_int err; - const size_t n_tiles = (N + 31) / 32; - size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; + cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); - const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; - size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + cl_image_format fmt = {CL_RGBA, CL_FLOAT}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = region.size / 16; + desc.buffer = k_sub; + cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); + CL_CHECK(err); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - CL_CHECK(clReleaseMemObject(k_img)); - CL_CHECK(clReleaseMemObject(k_sub)); - CL_CHECK(clReleaseMemObject(q_sub)); + region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; + region.size = (size_t) K * N * D_B * sizeof(float); + cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + + // Pack query heads of each KV group into a short batch's tile. + static const bool fold_enabled = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_P8_FOLD"); + return !e || e[0] != '0'; + }(); + const int gqa = D_B / D_A; + const int fold = fold_enabled && gqa > 1 && N < 32 && gqa <= INT_MAX / N ? gqa : 1; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &fold)); + + const size_t n_tiles = ((size_t) N * fold + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * (fold > 1 ? D_A : D_B)}; + + const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; + size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + CL_CHECK(clReleaseMemObject(k_img)); + CL_CHECK(clReleaseMemObject(k_sub)); + CL_CHECK(clReleaseMemObject(q_sub)); + } cl_mem sinks_buf = extra_q->data_device; cl_ulong sinks_off = 0; @@ -23261,7 +23411,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, - int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct + int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; const ggml_tensor * v = dst->src[2]; @@ -23345,13 +23495,17 @@ static void ggml_cl_flash_attn_decompose_kq_p8( backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); } + if (kq_int8) { + ggml_cl_fa_kq_int8_prepare(backend, dst, n_q_chunk); + } + ggml_tensor_extra_cl extra_kqv; ggml_tensor kqv; for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { const int64_t nqc = MIN(n_q_chunk, n_q - q0); - ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch); + ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch, kq_int8); ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); @@ -23408,6 +23562,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( // head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). // GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. // GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. +// GGML_OPENCL_FA_KQ_INT8=0 keeps F16 KQ; =1 enables int8 KQ for supported shapes. static bool ggml_cl_flash_attn_decompose_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst @@ -23537,12 +23692,46 @@ static bool ggml_cl_flash_attn_decompose_dispatch( return false; } + static const int kq_int8_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + static const int dk512_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_DK512_F16"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + const bool dk512 = dk > 256 && dk <= 512 && n_q >= 32 && + (dk512_env == 1 || (dk512_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E)); + const bool kq_int8_possible = kq_p8 && (dk <= 256 || dk512) && dk % 32 == 0 && + backend_ctx->kernel_fa_q8_rows_f16 != nullptr && backend_ctx->kernel_fa_q8_rows_f32 != nullptr && + n_head <= INT_MAX && n_head_kv <= INT_MAX && + n_q <= INT_MAX / n_head / (dk / 32) && n_kv <= INT_MAX / n_head_kv / (dk / 32) && + (dst->src[4] == nullptr || dk > 64) && + (kq_int8_env == 1 || (kq_int8_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_kv >= 2048)) && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f16) >= 64 && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f32) >= 64; + cl_kernel kq_int8_kernel = nullptr; + if (kq_int8_possible) { + kq_int8_kernel = dk <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + } + const bool kq_int8 = kq_int8_kernel != nullptr && backend_ctx->get_kernel_workgroup_size(kq_int8_kernel) >= 64; + + // Fewer query tiles per KV block reduce cache pressure in the int8 KQ kernel. + static const int64_t kq_int8_max_chunk = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8_MAX_CHUNK"); + const int v = (e && e[0]) ? atoi(e) : 96; + return (int64_t) (v >= 32 ? (v / 32) * 32 : 96); + }(); + if (kq_int8) { + n_q_chunk = MIN(n_q_chunk, kq_int8_max_chunk); + } + // even out the chunks, then align to the 32-wide n-tile const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); if (kq_p8) { - ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct); + ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct, kq_int8); } else { ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); } diff --git a/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl new file mode 100644 index 000000000000..f0eda2539bcd --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl @@ -0,0 +1,77 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +// Store 32-element blocks as separate int8 values and half scales. + +kernel void kernel_fa_q8_rows_f16( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const half * p = (global const half *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = convert_float4(vload4(i, p)); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} + +kernel void kernel_fa_q8_rows_f32( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const float * p = (global const float *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = vload4(i, p); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl index 2c0a56c855c7..9c4f71a6d910 100644 --- a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl +++ b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl @@ -119,7 +119,8 @@ __kernel void mul_mm_f16_f32_kq_p8( int N, int D_A, int D_B, - int p_pitch // bytes per P row, >= M, multiple of 32 + int p_pitch, // bytes per P row, >= M, multiple of 32 + int gqa_fold ) { // Match the n-tile-first grid in ggml_cl_fa_kq_p8_dispatch. @@ -135,7 +136,8 @@ __kernel void mul_mm_f16_f32_kq_p8( const uint col = block_id_m * TILESIZE_M; const uint row = block_id_n * TILESIZE_N; - const uint depth_A = block_id_d / (D_B/D_A); + const uint fold = (uint)gqa_fold; + const uint depth_A = fold > 1 ? block_id_d : block_id_d / (D_B/D_A); const uint depth_B = block_id_d; int line_stride_matrix_A_in_bytes = K * D_A * 2; @@ -158,11 +160,18 @@ __kernel void mul_mm_f16_f32_kq_p8( __local float matrix_B_local[1024]; - // Clamp Q loads in the last tile; columns past N are not stored. - const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N - 1); - const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N - 1); - const uint b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; - const uint b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + // Folded columns enumerate (query, head within the KV group). + const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N * fold - 1); + const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N * fold - 1); + uint b_globalOffsetInWords00; + uint b_globalOffsetInWords16; + if (fold > 1) { + b_globalOffsetInWords00 = (c0/fold)*strideBinElements + (depth_B*fold + c0%fold)*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = (c1/fold)*strideBinElements + (depth_B*fold + c1%fold)*K + b_globalOffsetInWords_xy.x; + } else { + b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + } for (uint step=0; step < K; step+=TILESIZE_K) { regA = mm_load_a(matrix_A, subMatrixAStartInElements, line_stride_matrix_A_in_bytes); @@ -199,9 +208,10 @@ __kernel void mul_mm_f16_f32_kq_p8( if (lane < 32) { const int j = lane >> 1; const int b = lane & 1; - const uint n = row + half_*16 + j; - const uint h = depth_B; - if (n < (uint)N) { + const uint c = row + half_*16 + j; + const uint n = c / fold; + const uint h = depth_B*fold + c % fold; + if (c < (uint)N * fold) { float slope = 1.0f; if (max_bias > 0.0f) { const float base = (int)h < n_head_log2 ? m0 : m1; diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl new file mode 100644 index 000000000000..8e04ad393b5b --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl @@ -0,0 +1,174 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DK_MAX 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + __local uint sh_q [KQ_TN][KQ_DK_MAX/4]; + __local half sh_qd[KQ_TN][KQ_DK_MAX/32]; + __local float p8_lds[1024]; + + const size_t qbase = (size_t)head*n_q; + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/16); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/16); + const int u = (i % (KQ_DK_MAX/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < nu) { + v = vload4(0, &qq[(qbase + qi)*nu + u]); + } + vstore4(v, 0, &sh_q[t][u]); + } + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/32); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/32); + const int b = i % (KQ_DK_MAX/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < nblk) ? qd[(qbase + qi)*nblk + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int b = 0; b < nblk; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + b*8]); + const uint4 w1 = vload4(0, &kq[kbase + b*8 + 4]); + const float dks = (float)kd[kdbas + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t][b*8]); + const uint4 a1 = vload4(0, &sh_q[t][b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + + // Each lane owns one complete 32-row softmax block after the transpose. + const int kvblk0 = kv - lid; + #pragma unroll + for (int half_ = 0; half_ < 2; ++half_) { + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int j = 0; j < 16; ++j) { + p8_lds[j*64 + lid] = acc[half_*16 + j]; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (lid < 32) { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + half_*16 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + const __local float * src = p8_lds + j*64 + b*32; + float16 s0 = vload16(0, src); + float16 s1 = vload16(1, src); + const global half * mp = mrow + (size_t)n*mstride + kvb; + const float16 m0v = convert_float16(vload16(0, mp)); + const float16 m1v = convert_float16(vload16(1, mp)); + s0 = s0*scale + slope*m0v; + s1 = s1*scale + slope*m1v; + const float16 mx16 = fmax(s0, s1); + const float8 mx8 = fmax(mx16.lo, mx16.hi); + const float4 mx4 = fmax(mx8.lo, mx8.hi); + const float2 mx2 = fmax(mx4.lo, mx4.hi); + const float amax = fmax(mx2.x, mx2.y); + const size_t prow = qbase + n; + const int blk = kvb >> 5; + float sum = 0.0f; + uchar16 q0 = (uchar16)(0); + uchar16 q1 = (uchar16)(0); + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + const float16 e0 = exp(s0 - amax); + const float16 e1 = exp(s1 - amax); + const float16 a16 = e0 + e1; + const float8 a8 = a16.lo + a16.hi; + const float4 a4 = a8.lo + a8.hi; + const float2 a2 = a4.lo + a4.hi; + sum = a2.x + a2.y; + q0 = convert_uchar16_sat_rte(e0*255.0f); + q1 = convert_uchar16_sat_rte(e1*255.0f); + } + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + vstore16(q0, 0, qdst); + vstore16(q1, 1, qdst); + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl new file mode 100644 index 000000000000..f6ba2b6c2247 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl @@ -0,0 +1,170 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DKC 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8_dk512( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + // Reuse the 256-wide Q slice for the F32 softmax scores after the contraction. + __local uint sh_q [KQ_TN*KQ_DKC/4]; + __local half sh_qd[KQ_TN][KQ_DKC/32]; + __local float * p8_lds = (__local float *)sh_q; + + const size_t qbase = (size_t)head*n_q; + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int c0 = 0; c0 < nblk; c0 += KQ_DKC/32) { + const int cb = min(KQ_DKC/32, nblk - c0); + barrier(CLK_LOCAL_MEM_FENCE); + for (int i = lid; i < KQ_TN*(KQ_DKC/16); i += KQ_WG) { + const int t = i / (KQ_DKC/16); + const int u = (i % (KQ_DKC/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < cb*8) { + v = vload4(0, &qq[(qbase + qi)*nu + c0*8 + u]); + } + vstore4(v, 0, &sh_q[t*(KQ_DKC/4) + u]); + } + for (int i = lid; i < KQ_TN*(KQ_DKC/32); i += KQ_WG) { + const int t = i / (KQ_DKC/32); + const int b = i % (KQ_DKC/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < cb) ? qd[(qbase + qi)*nblk + c0 + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + for (int b = 0; b < cb; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + (c0 + b)*8]); + const uint4 w1 = vload4(0, &kq[kbase + (c0 + b)*8 + 4]); + const float dks = (float)kd[kdbas + c0 + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8]); + const uint4 a1 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + } + + // Finish reading the Q slice before writing scores to the same local memory. + const int kvblk0 = kv - lid; + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + p8_lds[t*64 + lid] = acc[t]; + } + barrier(CLK_LOCAL_MEM_FENCE); + { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + __local float * src = p8_lds + j*64 + b*32; + const global half * mp = mrow + (size_t)n*mstride + kvb; + float4 s = vload4(0, src)*scale + slope*convert_float4(vload4(0, mp)); + vstore4(s, 0, src); + float amax = fmax(fmax(s.x, s.y), fmax(s.z, s.w)); + for (int c = 1; c < 8; ++c) { + s = vload4(c, src)*scale + slope*convert_float4(vload4(c, mp)); + vstore4(s, c, src); + amax = fmax(amax, fmax(fmax(s.x, s.y), fmax(s.z, s.w))); + } + const size_t prow = qbase + n; + const int blk = kvb >> 5; + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + float sum = 0.0f; + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + for (int c = 0; c < 8; ++c) { + const float4 e = exp(vload4(c, src) - amax); + sum += (e.x + e.y) + (e.z + e.w); + vstore4(convert_uchar4_sat_rte(e*255.0f), c, qdst); + } + } else { + for (int c = 0; c < 8; ++c) { + vstore4((uchar4)(0), c, qdst); + } + } + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } +} diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 38db895c532f..519c35bc21a1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -107,7 +107,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::mapn_nodes; ++i) { if ((cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && cgraph->nodes[i]->op_params[0] > 1) || - is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i])) { + is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i]) || + is_ssm_state_writeback(cgraph->nodes[i])) { std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false); add_extra_inputs(); break; @@ -494,6 +495,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } } else if (node->ne[0] == 1 && src->ne[0] * src->ne[1] * src->ne[2] == node->ne[1]) { op_case = 3; + } else if (node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1] && node->ne[2] == src->ne[2] && + node->ne[3] == src->ne[3]) { + // head regroup, e.g. mamba2's [head_dim, n_head, n_tokens, n_seqs] -> [d_inner/n_group, n_group, n_tokens, n_seqs] + op_case = 1; } else if (name.find("linear_attn_qkv_mixed") == 0 || name.find("alpha") == 0) { op_case = 6; } else if (name.find("linear_attn_out") == 0) { @@ -597,6 +602,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { op_case = 3; break; } + if (is_column_set_rows(node)) { + op_case = 4; + break; + } // `-fa off` writes the V cache transposed, through a [1, n] reshape of the cache: one element per row if (node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE && node->src[2]->ne[0] == 1 && is_kvcache(node->src[2]->src[0], nullptr)) { @@ -797,6 +806,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } else { op_case = 1; } + } else if (is_ssm_state_writeback(node)) { + op_case = 13; + break; } else if (GgmlOvDecoder::is_conv_state_writeback(node)) { op_case = 2; break; @@ -1296,6 +1308,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr writeback.snapshot_stride = destination->nb[2] / destination->nb[1]; compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } + if (is_ssm_state_writeback(node)) { + ComputeParams::RsWriteback writeback; + writeback.slot_begin = (int64_t) (node->src[1]->view_offs / node->src[1]->nb[1]); + compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; + } if (is_conv_state_snapshot_writeback(node)) { const auto source = node->src[0]; const auto dest = node->src[2]; @@ -1406,6 +1423,14 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.attention_size = ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); } + // The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of + // 256. Round it up to a power of two the same way, so that a long context uses a few lengths and not one per + // step. The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). + if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && + !compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) { + compute_params.attention_size = + ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); + } model_params.ctx = model_params.ctx_per_seq * model_params.n_seq; return {model_params, compute_params}; } @@ -1416,6 +1441,15 @@ void GgmlOvDecoder::validate_cgraph() const { } } +bool GgmlOvDecoder::has_inp_embd_leaf_use(const ggml_tensor * tensor) const { + for (int i = 0; i < m_cgraph->n_nodes; i++) { + if (is_inp_embd_leaf(tensor, m_cgraph->nodes[i])) { + return true; + } + } + return false; +} + ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, const ggml_tensor * input, int dynamic_dim_index) const { @@ -1530,7 +1564,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, // index list has a static length; on CPU/GPU it may change across compiles (defrag). input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1}; - } else if (input != nullptr && op != nullptr && is_inp_emb(input, op)) { + } else if (input != nullptr && op != nullptr && (is_inp_emb(input, op) || has_inp_embd_leaf_use(input))) { input_shape = ov::PartialShape{get_shape(input)}; if (!m_is_static) { input_shape[2] = -1; @@ -1914,7 +1948,11 @@ void GgmlOvDecoder::compute_model_outputs() { continue; } const bool inactive_top_k = is_sampling_top_k(cur_node) && !(cur_node->flags & GGML_TENSOR_FLAG_COMPUTE); - if ((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) || inactive_top_k) { + auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + // llama flags result_norm in every graph but reads it only with embeddings on, when it has no consumer + // and is kept by the rule below. + const bool unread_embd = strcmp(cur_node->name, "result_norm") == 0 && cur_node_use_count > 0; + if (((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) && !unread_embd) || inactive_top_k) { const auto name = get_tensor_ov_name(m_cgraph, cur_node); m_model_outputs[name] = cur_node; m_model_output_names.insert(name); @@ -1925,7 +1963,12 @@ void GgmlOvDecoder::compute_model_outputs() { m_model_outputs[name] = cache; m_model_output_names.insert(name); } - auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + if (is_ssm_state_writeback(cur_node)) { + auto * cache = cur_node->view_src; + const auto name = get_tensor_ov_name(m_cgraph, cache); + m_model_outputs[name] = cache; + m_model_output_names.insert(name); + } if (cur_node_use_count == 0) { // The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src. if (cur_node != nullptr && ::is_inplace_op(cur_node) && @@ -2641,6 +2684,10 @@ bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const { std::vector GgmlOvDecoder::get_output_names(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // the written state block plus the full updated cache (see translate_cpy op_case 13) + return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)}; + } if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) { std::string attn_name; std::string state_name; @@ -2669,6 +2716,10 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const { std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // translate_cpy publishes the updated cache as a second named output + return ""; + } // Reset lengths (also in static mode) and dynamic remainder views can become nonempty // after compilation. Keep their alias updates in the translated cache chain. const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(node->view_src) && @@ -2786,7 +2837,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 0; continue; } - if (is_inp_scale_rows(src, node)) { + if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) { m_node_dynamic_dims[src] = 1; continue; } @@ -2865,6 +2916,11 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = 2; break; } + if (node->src[0]->op == GGML_OP_SSM_SCAN) { + // y part [head_dim, n_head, n_tokens, n_seqs] at offset 0; the state part is token-independent + m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; + break; + } // Use stride-based matching: the stride of a VIEW dimension directly // encodes which source dimension it indexes into, so it uniquely // identifies the dynamic dim even when two dims share the same size. @@ -3030,6 +3086,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_GATED_DELTA_NET: m_node_dynamic_dims[node] = 1; break; + case GGML_OP_SSM_SCAN: + // packed 1-D [y | state]; the y part grows with tokens + m_node_dynamic_dims[node] = 0; + break; case GGML_OP_RMS_NORM: case GGML_OP_L2_NORM: case GGML_OP_NORM: @@ -3080,12 +3140,15 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_CPY: case GGML_OP_SUM: case GGML_OP_MEAN: + case GGML_OP_ARANGE: m_node_dynamic_dims[node] = -1; break; case GGML_OP_SET_ROWS: - // a cache write returns the cache; other rows writes keep the shape of their destination - m_node_dynamic_dims[node] = (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node)) ? - -1 : m_node_dynamic_dims[node->src[2]]; + // a cache or column write returns its whole buffer; other rows writes keep the shape of their destination + m_node_dynamic_dims[node] = + (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node) || is_column_set_rows(node)) ? + -1 : + m_node_dynamic_dims[node->src[2]]; break; case GGML_OP_IM2COL: { m_node_dynamic_dims[node] = -1; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index b7ff4b715f06..12b08cebce4b 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -477,6 +477,21 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { return tensor->op == GGML_OP_GET_ROWS && op->op == GGML_OP_RMS_NORM; } + // Raw float input [n_embd, n_tokens]: DFlash/DSpark/EAGLE3 features into fc, or raw embd batch / EAGLE3 g-embd into RMS_NORM + // MUL_MAT needs a weight leaf as src[0], so inp_mean (src[0] is computed) does not match + static bool is_inp_embd_leaf(const ggml_tensor * tensor, const ggml_tensor * op) { + if (tensor->op != GGML_OP_NONE || !(tensor->flags & GGML_TENSOR_FLAG_INPUT) || tensor->type != GGML_TYPE_F32) { + return false; + } + if (op->op == GGML_OP_MUL_MAT) { + return op->src[1] == tensor && op->src[0] != nullptr && op->src[0]->op == GGML_OP_NONE; + } + return op->op == GGML_OP_RMS_NORM && op->src[0] == tensor; + } + + // true if any node of the current graph uses tensor as a raw embd input (see is_inp_embd_leaf) + bool has_inp_embd_leaf_use(const ggml_tensor * tensor) const; + static bool is_activation_input(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || op == nullptr || tensor->type != GGML_TYPE_F32 || tensor->ne[2] != 1 || tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { @@ -578,11 +593,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { bool is_direct_gdn_view(const ggml_tensor * node) const; - inline static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { return is_recurrent_cache(tensor) || is_kvcache(tensor, op); } - inline static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || is_recurrent_cache(tensor)) { return false; } @@ -590,27 +605,68 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { (op != nullptr && op->op == GGML_OP_SET_ROWS && op->src[2] == tensor); } - inline static bool is_conv_state_writeback(const ggml_tensor * node) { + static bool is_conv_state_writeback(const ggml_tensor * node) { return node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) && node->src[0] != nullptr && node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && node->src[0]->src[0]->op == GGML_OP_CONCAT && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src; } + // The final-state writeback of SSM_SCAN (K == 1): the state tail of the packed [y | state] + // output copied into a slot block of the recurrent cache. + static bool is_ssm_state_writeback(const ggml_tensor * node) { + if (!(node != nullptr && node->op == GGML_OP_CPY && node->view_src != nullptr && node->src[0] != nullptr && + node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && + node->src[0]->src[0]->op == GGML_OP_SSM_SCAN && node->src[0]->src[0]->op_params[0] == 1 && + node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && + node->src[1]->view_src == node->view_src)) { + return false; + } + const auto * scan = node->src[0]->src[0]; + const auto * src = node->src[0]; + const auto * dst = node->src[1]; + if (node->type != GGML_TYPE_F32 || src->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + src->ne[2] != 1 || src->ne[3] != 1) { + return false; + } + for (int i = 0; i < GGML_MAX_DIMS; ++i) { + if (src->ne[i] != dst->ne[i]) { + return false; + } + } + return dst->nb[1] > 0 && dst->view_offs % dst->nb[1] == 0 && + src->view_offs == (size_t) ggml_nelements(scan->src[1]) * ggml_type_size(scan->type); + } + // build_conv_state_store writes overlapping [history, window, channel, seq] windows into newest-first rollback planes. // Match this layout separately from general SET_ROWS. static bool is_conv_state_snapshot_writeback(const ggml_tensor * node); + // SET_ROWS into a column range of each row of a plain 2-D buffer, e.g. build_layer_inp_dev(): every enabled layer + // input goes to view_2d(layer_inp_dev, n_embd, n_batch, nb1, col * n_embd * elem) at the batch rows of the ubatch. + // The buffer sits in a regular device buffer, so is_kvcache() matches it: check this first + static bool is_column_set_rows(const ggml_tensor * node) { + if (node == nullptr || node->op != GGML_OP_SET_ROWS || node->src[2] == nullptr || + node->src[2]->op != GGML_OP_VIEW) { + return false; + } + const ggml_tensor * dst = node->src[2]; + const ggml_tensor * buf = dst->view_src; + return buf != nullptr && buf->op == GGML_OP_NONE && !is_recurrent_cache(buf) && buf->ne[2] == 1 && + buf->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && dst->ne[0] < buf->ne[0] && + dst->nb[0] == buf->nb[0] && dst->nb[1] == buf->nb[1] && dst->ne[1] == buf->ne[1]; + } + // SET_ROWS into a KV cache, directly or through the [1, n] reshape of the transposed V cache with `-fa off`. // Other SET_ROWS write rows of a compute tensor, e.g. the MoE expert-group mask - inline static bool is_kvcache_write(const ggml_tensor * node) { + static bool is_kvcache_write(const ggml_tensor * node) { const ggml_tensor * dst = node->src[2]; return dst != nullptr && is_kvcache(dst->view_src != nullptr ? dst->view_src : dst, nullptr); } // GET_ROWS batched over ggml dims 2 and 3, e.g. the MoE expert-group scores // ggml_get_rows(ggml_reshape_4d(groups, 1, n_exp_per_group, n_groups, n_tokens), top_groups) - inline static bool is_get_rows_batched_4d(const ggml_tensor * node) { + static bool is_get_rows_batched_4d(const ggml_tensor * node) { return node->op == GGML_OP_GET_ROWS && !ggml_is_quantized(node->src[0]->type) && node->src[1]->ne[1] == node->src[0]->ne[2] && node->src[1]->ne[2] == node->src[0]->ne[3] && node->src[1]->ne[3] == 1; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index c76b423983f3..2537f8af3a31 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -616,6 +616,10 @@ bool ggml_openvino_is_npu() { return ggml_openvino_get_device_config().is_npu; } +bool ggml_openvino_is_static() { + return ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); +} + bool ggml_openvino_is_gpu() { return has_prefix(ggml_openvino_get_device_name(), "GPU"); } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 5a64c67ef9c5..406ac6d4cb5a 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -134,6 +134,9 @@ bool ggml_openvino_release_weights_enabled(); // Check if running on NPU bool ggml_openvino_is_npu(); +// Static graphs: NPU, or any device with GGML_OPENVINO_FORCE_STATIC +bool ggml_openvino_is_static(); + // KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context. // One mechanism, two modes: // dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled. diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index a7f5d177f527..bd49560d8e1e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1504,6 +1504,38 @@ static bool has_strides_on_element_grid(const ggml_tensor * t) { return true; } +// A VIEW that regroups one contiguous span of every row of its contiguous source, e.g. the z/x/B/C +// splits of the fused mamba projections. The strides do not nest on an element grid, but +// process_view_input_new resolves it as a Slice of the source's innermost axis plus a Reshape. +// Keep in sync with the matching branch there; dynamic execution only. +static bool is_row_span_view(const ggml_tensor * t) { + if (ggml_openvino_is_static() || is_stateful_enabled()) { + return false; + } + const ggml_tensor * src = t->op == GGML_OP_VIEW ? t->src[0] : nullptr; + // a RESHAPE source is fine (the translation reads its value); a chained VIEW is not, because + // the view metadata then describes the intermediate view instead of the resolved input + if (src == nullptr || src->op == GGML_OP_VIEW || !ggml_is_contiguous(src) || t->type != src->type) { + return false; + } + const size_t es = ggml_type_size(t->type); + int d = 0; + size_t span = 1; + while (d < GGML_MAX_DIMS && t->nb[d] == span * es) { + span *= t->ne[d]; + d++; + } + if (d < 2) { + return false; + } + for (int s = 1; d < GGML_MAX_DIMS; ++d, ++s) { + if (t->ne[d] != src->ne[s] || t->nb[d] != src->nb[s]) { + return false; + } + } + return t->view_offs % es == 0 && t->view_offs / es + span <= (size_t) src->ne[0]; +} + static bool has_non_contiguous_view_input(const ggml_tensor * op) { for (int i = 0; i < GGML_MAX_SRC; i++) { if (op->src[i] == nullptr) { @@ -1624,7 +1656,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { } return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || - GgmlOvDecoder::is_gdn_snapshot_writeback(op); + GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op); } static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) { @@ -1727,14 +1759,16 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } case GGML_OP_GET_ROWS: case GGML_OP_SET_ROWS: { - if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && - (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"))) { + if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && ggml_openvino_is_static()) { return {false, "convolution snapshots require dynamic execution"}; } if (op->ne[3] != 1 && !GgmlOvDecoder::is_get_rows_batched_4d(op) && !GgmlOvDecoder::is_conv_state_snapshot_writeback(op)) { return {false, "GET_ROWS/SET_ROWS with ne[3] != 1 (ne[3]=" + std::to_string(op->ne[3]) + ") is not supported"}; } + if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) { + return {false, "SET_ROWS with BF16 src0 is not supported"}; + } if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K || op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) { // These are all f16-arithmetic dequant rounding errors that intermittently exceed the @@ -2004,6 +2038,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (op->view_src != nullptr && !ggml_is_contiguous(op->src[0])) { return {false, "ROPE on VIEW / non-contiguous input is not supported"}; } + if (op->type == GGML_TYPE_BF16) { + return {false, "ROPE with BF16 type is not supported"}; + } break; } case GGML_OP_TRANSPOSE: { @@ -2034,7 +2071,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"; } else if (op->op_params[0] > 1) { - if (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC")) { + if (ggml_openvino_is_static()) { reason = "GATED_DELTA_NET snapshots require dynamic execution"; } } @@ -2053,6 +2090,19 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { // return true; break; } + case GGML_OP_SSM_SCAN: { + // SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state + if (op->src[3]->ne[0] != 1) { + return {false, "SSM_SCAN with Mamba-1 state-wise decay is not supported"}; + } + if (op->op_params[0] > 1) { + return {false, "SSM_SCAN with rollback snapshots (K > 1) is not supported"}; + } + if (ggml_openvino_is_static()) { + return {false, "SSM_SCAN requires dynamic execution"}; + } + break; + } case GGML_OP_VIEW: { // Skip TOPK_MOE fused tests until it is fully supported. // The argsort_top_k VIEW wrapping ARGSORT is named "selected_experts" in test_topk_moe. @@ -2274,7 +2324,8 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg if (supported_types.find(src->type) == supported_types.end()) { return {false, "src[" + std::to_string(i) + "] type " + std::string(ggml_type_name(src->type)) + " is not supported"}; } - if (!has_strides_on_element_grid(src) && !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && + if (!has_strides_on_element_grid(src) && !is_row_span_view(src) && + !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && !(i == 2 && GgmlOvDecoder::is_conv_state_snapshot_writeback(op))) { return {false, "src[" + std::to_string(i) + "] strides are not multiples of each other"}; } diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 597233d7e6d9..7bfa7ad08b11 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -197,8 +197,7 @@ void ggml_openvino_model_cache_init() { } return; } - if (cache_only && (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") || - ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || + if (cache_only && (ggml_openvino_is_static() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_FALLBACK"))) { GGML_ABORT("ggml-openvino: cache-only mode requires dynamic CPU/GPU execution with caching and without fallback"); } @@ -368,7 +367,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 5 requantizes K-quant MoE experts to Q4_1_64 on GPU by default. // Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive. // Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter. - h = fnv1a_u64(h, 7); + // Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags. + h = fnv1a_u64(h, 8); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); @@ -391,6 +391,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, const ggml_tensor * node = cgraph->nodes[i]; h = fnv1a_u64(h, static_cast(node->op)); h = fnv1a(h, node->name, strlen(node->name)); + // Each output is a Result of the model; llama_set_embeddings_layer_inp() changes only the flags. + h = fnv1a_u64(h, (node->flags & GGML_TENSOR_FLAG_OUTPUT) ? 1u : 0u); has_gdn = has_gdn || node->op == GGML_OP_GATED_DELTA_NET; } if (has_gdn && ggml_openvino_is_npu()) { diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 0bb6bd054d15..e0d63ac95179 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -75,6 +75,28 @@ OutputVector translate_cpy(const NodeContext & context) { return rename_outputs_with_suffix({result}, context.get_name()); } + if (op_case == 13) { + // SSM_SCAN final-state writeback: output the written state block and the full updated cache + auto src = process_view_input_new(context, 0); + auto base = context.get_input(1); + if (src.get_element_type() != context.get_output_type()) { + src = std::make_shared(src, context.get_output_type()); + } + auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0}); + auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1}); + auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX}); + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); + auto begin = context.get_input("rs_slot_begin_" + context.get_name()); + auto src_len = std::make_shared( + std::make_shared(src, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto end = std::make_shared(begin, src_len); + auto head_part = std::make_shared(base, zero, begin, one, axis); + auto tail_part = std::make_shared(base, end, int_max, one, axis); + auto updated = std::make_shared(ov::OutputVector{head_part, src, tail_part}, 2); + return rename_outputs_with_suffix({src, updated}, context.get_name()); + } + if (op_case == 4) { auto src = process_view_input_new(context, 0); auto base = context.get_input(1); diff --git a/ggml/src/ggml-openvino/openvino/op/scale.cpp b/ggml/src/ggml-openvino/openvino/op/scale.cpp index f77d8ce58a6e..e0d0ea182c19 100644 --- a/ggml/src/ggml-openvino/openvino/op/scale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/scale.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -26,15 +27,20 @@ OutputVector translate_scale(const NodeContext & context) { return translate_recurrent_cache_reset(context); } - auto scaled = std::make_shared(process_view_input_new(context, 0), scale_node); - - std::shared_ptr res; + // Multiply and Add need matching types; compute f16 input in f32 and round once, as the CPU backend does. + auto input = process_view_input_new(context, 0); + const auto input_type = input.get_element_type(); + if (input_type != ov::element::f32) { + input = std::make_shared(input, ov::element::f32); + } + ov::Output res = std::make_shared(input, scale_node); if (bias != 0.0f) { auto bias_node = std::make_shared(ov::element::f32, ov::Shape{}, std::vector{bias}); - res = std::make_shared(scaled, bias_node); - } else { - res = scaled; + res = std::make_shared(res, bias_node); + } + if (input_type != ov::element::f32) { + res = std::make_shared(res, input_type); } return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp new file mode 100644 index 000000000000..509b43e0005f --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Local mirror of OpenVINO's ov::op::internal::SelectiveSSM declaration +// (src/core/dev_api/openvino/op/selective_ssm.hpp). The implementation comes from the linked +// OpenVINO runtime; the class layout must stay in sync with the runtime's declaration. +#pragma once + +#include "openvino/op/op.hpp" + +namespace ov::op::internal { +/// Mamba2 selective state-space recurrence (arXiv:2405.21060). +/// dA = exp(A * dt), dtB = dt * B; per token t: +/// dBx_t = x_t (x) dtB_t, state_t = state_{t-1} * dA_t + dBx_t, y_t = sum(state_t * C_t). +/// B and C are grouped and shared across heads: head h reads group h / (num_heads / num_groups). +class OPENVINO_API SelectiveSSM : public ov::op::Op { +public: + OPENVINO_OP("SelectiveSSM") + + SelectiveSSM() = default; + /// \param A (Negative) log-decay rates per head [num_heads]. + /// \param dt Per-token, per-head time steps [batch_size, seq_len, num_heads]. + /// \param B Grouped input projection [batch_size, seq_len, num_groups, state_size]. + /// \param x Input hidden states [batch_size, seq_len, num_heads, head_dim]. + /// \param C Grouped output projection [batch_size, seq_len, num_groups, state_size]. + /// \param recurrent_state Initial state [batch_size, num_heads, head_dim, state_size]. + SelectiveSSM(const Output & A, + const Output & dt, + const Output & B, + const Output & x, + const Output & C, + const Output & recurrent_state); + + /// \param args Input tensor vector in order: A, dt, B, x, C, recurrent_state. + explicit SelectiveSSM(const ov::OutputVector & args); + + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor & visitor) override; + std::shared_ptr clone_with_new_inputs(const ov::OutputVector & new_args) const override; +}; + +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 1eae9408b83e..476890911c04 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -90,12 +90,71 @@ static OutputVector translate_conv_snapshots(const NodeContext & context) { return rename_outputs_with_suffix({result}, name); } +// SET_ROWS into a column range of a plain 2-D buffer (see GgmlOvDecoder::is_column_set_rows). The result is the +// whole buffer: the indexed rows get the new columns, the other columns and rows keep their values, so the next +// write into another column range of the same buffer reads this one. +static OutputVector translate_column_set_rows(const NodeContext & context) { + using namespace ov::op; + auto i64_const = [](const std::vector & values) { + return v0::Constant::create(ov::element::i64, {values.size()}, values); + }; + + const auto view_shape = context.get_view_input_ggml_shape(2, 0); // [1, 1, rows, width] + FRONT_END_OP_CONVERSION_CHECK(view_shape.size() == 4, "SET_ROWS column write needs a 4-D destination view"); + const int64_t width = (int64_t) view_shape[3]; + + auto base = context.get_input(2); + const auto base_shape = base.get_partial_shape(); + FRONT_END_OP_CONVERSION_CHECK(base_shape.rank().is_static() && base_shape[base_shape.size() - 1].is_static(), + "SET_ROWS column write needs a static buffer row size"); + const int64_t row_size = base_shape[base_shape.size() - 1].get_length(); + const size_t elem_size = context.get_output_type().size(); + const int64_t col_begin = (int64_t) (context.get_view_input_offset(2, 0) / elem_size) % row_size; + const int64_t col_end = col_begin + width; + FRONT_END_OP_CONVERSION_CHECK(col_end <= row_size, "SET_ROWS column range is out of bounds"); + + Output data = std::make_shared(process_view_input_new(context, 0), i64_const({1, 1, -1, width}), + false); + if (data.get_element_type() != context.get_output_type()) { + data = std::make_shared(data, context.get_output_type()); + } + Output rows = std::make_shared(process_view_input_new(context, 1), i64_const({-1}), false); + if (rows.get_element_type() != ov::element::i64) { + rows = std::make_shared(rows, ov::element::i64); + } + + auto axis = v0::Constant::create(ov::element::i64, {}, {2}); + auto buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output updates = data; + if (width < row_size) { + auto existing = std::make_shared(buffer, rows, axis); + auto col_axis = i64_const({3}); + OutputVector parts; + if (col_begin > 0) { + parts.push_back(std::make_shared(existing, i64_const({0}), i64_const({col_begin}), + i64_const({1}), col_axis)); + } + parts.push_back(data); + if (col_end < row_size) { + parts.push_back(std::make_shared(existing, i64_const({col_end}), i64_const({row_size}), + i64_const({1}), col_axis)); + } + updates = std::make_shared(parts, 3); + } + auto updated = std::make_shared(buffer, rows, updates, axis); + auto res = std::make_shared(updated, std::make_shared(base, ov::element::i64), false); + return rename_outputs_with_suffix({res}, context.get_name()); +} + OutputVector translate_set_rows(const NodeContext & context) { num_inputs_check(context, 3, 3); if (context.get_op_case() == 3) { return translate_conv_snapshots(context); } + if (context.get_op_case() == 4) { + return translate_column_set_rows(context); + } auto data = process_view_input_new(context, 0); auto indices = process_view_input_new(context, 1); diff --git a/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp new file mode 100644 index 000000000000..fce8e111ed42 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Adapted from OpenVINO's GGUF frontend (src/frontends/gguf/src/op/ssm_scan.cpp). + +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" +#include "selective_ssm.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +OutputVector translate_ssm_scan(const NodeContext & context) { + num_inputs_check(context, 7, 7); + using namespace ov::op; + + // ggml: s [slots,H,D,S], x [B,T,H,D], dt [1,B,T,H], A [1,1,H,1], + // B/C [B,T,G,S], ids [1,1,1,B]. Only Mamba2 has scalar decay per head. + const auto a_shape = context.get_input_shape(3); + FRONT_END_OP_CONVERSION_CHECK(a_shape.rank() == 4 && a_shape[0] == 1 && a_shape[1] == 1 && a_shape[3] == 1, + "SSM_SCAN: SelectiveSSM requires Mamba2 scalar decay per head; " + "Mamba1 state-wise decay is not supported"); + const auto x = process_view_input_new(context, 1); + const auto flat = v0::Constant::create(element::i64, {1}, {-1}); + const auto axis0 = v0::Constant::create(element::i64, {}, {0}); + const auto ids = std::make_shared(process_view_input_new(context, 6), flat, false); + const auto state = std::make_shared(process_view_input_new(context, 0), ids, axis0); + const auto a = std::make_shared(process_view_input_new(context, 3), flat, false); + const auto dt_shape = std::make_shared(std::make_shared(x), + v0::Constant::create(element::i64, {3}, {0, 1, 2}), + axis0); + const auto dt = + std::make_shared(std::make_shared(process_view_input_new(context, 2), dt_shape, false)); + const auto ssm = std::make_shared(a, + dt, + process_view_input_new(context, 4), + x, + process_view_input_new(context, 5), + state); + // Pack directly in GGML layout so whole-part views can select either Concat input. + const auto packed_shape = v0::Constant::create(element::i64, {4}, {1, 1, 1, -1}); + const auto y = std::make_shared(ssm->output(0), packed_shape, false); + const auto s = std::make_shared(ssm->output(1), packed_shape, false); + const auto result = std::make_shared(OutputVector{y, s}, 3); + result->get_rt_info()[GGML_OV_SSM_SCAN_PACKED] = true; + return rename_outputs_with_suffix({result}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov + diff --git a/ggml/src/ggml-openvino/openvino/op/tri.cpp b/ggml/src/ggml-openvino/openvino/op/tri.cpp index 9b7774a383ec..ba2efdc0bf1f 100644 --- a/ggml/src/ggml-openvino/openvino/op/tri.cpp +++ b/ggml/src/ggml-openvino/openvino/op/tri.cpp @@ -70,7 +70,8 @@ OutputVector translate_tri(const NodeContext & context) { throw std::runtime_error("translate_tri: invalid tri_type " + std::to_string(tri_type)); } - auto zero = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}); + // Select needs the zero in the input's type (f32, f16 or bf16). + auto zero = ov::op::v0::Constant::create(x.get_element_type(), {}, {0.0f}); auto res = std::make_shared(mask, x, zero); return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 399c17ac0162..defc428d1d4c 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -98,6 +98,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_PAD", op::translate_pad }, {"GGML_OP_TOP_K", op::translate_top_k }, {"GGML_OP_SSM_CONV", op::translate_ssm_conv }, + {"GGML_OP_SSM_SCAN", op::translate_ssm_scan }, {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, {"GGML_OP_CUMSUM", op::translate_cumsum }, diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 206966a935ff..54c60c634bf6 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -49,6 +49,7 @@ GGML_OP_CONVERTER(translate_flash_attn_ext); GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); +GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index ec7513951c01..e82a6c92fc47 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -465,6 +465,25 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return input; } + // A VIEW over the packed SSM_SCAN output selects one whole Concat part: y at offset 0, the + // final state after it. The y length is token-dependent, so a static Slice of the flat + // tensor would bake in the captured token count; return the native part instead. + if (view_input_size == 1 && input.get_node_shared_ptr()->get_rt_info().count(GGML_OV_SSM_SCAN_PACKED)) { + const bool is_y = context.get_view_input_offset(input_index, 0) == 0; + auto part = input.get_node_shared_ptr()->input_value(is_y ? 0 : 1).get_node_shared_ptr()->input_value(0); + if (is_y) { + // y keeps its native [n_seqs, n_tokens, n_head, head_dim] layout + return part; + } + // state [n_seqs, n_head, head_dim, d_state] -> view layout [1, 1, n_seqs, d_state * d_inner] + auto n_seqs = get_dimensions(std::make_shared(part, ov::element::i64), {0}); + auto target = std::make_shared( + ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 1}), n_seqs, + ov::op::v0::Constant::create(ov::element::i64, {1}, {-1})}, + 0); + return std::make_shared(part, target, false); + } + // Integer router views can share these strides when their row count is zero. // Packed projections can store query and gate in separate halves of each head. if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { @@ -534,6 +553,70 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } + // A VIEW that regroups one contiguous span of every source row, e.g. the z/x/B/C splits of the + // fused mamba projections: [head_dim, n_head, nt, ns] over [d_in_proj, nt, ns] rows. The span + // dims are packed and the remaining dims carry the source's outer strides, so the view is a + // Slice of the source's innermost axis plus a Reshape. + if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { + const auto source = context.get_view_input_src_ggml_shape(input_index, 0); + const auto view = context.get_view_input_ggml_shape(input_index, 0); + const auto source_stride = context.get_view_input_src_stride(input_index, 0); + const auto view_stride = context.get_view_input_stride(input_index, 0); + const auto in_rank = input.get_partial_shape().rank(); + const size_t nd = view.size(); + if (nd == 4 && source.size() == nd && view_stride.size() == nd && source_stride.size() == nd && + in_rank.is_static() && in_rank.get_length() == static_cast(nd) && + view_stride[nd - 1] == source_stride[nd - 1] && source_stride[nd - 1] > 0) { + const size_t es = source_stride[nd - 1]; + int j = static_cast(nd) - 1; + size_t span = 1; + while (j >= 0 && view_stride[j] == span * es) { + span *= view[j]; + --j; + } + // at least two packed dims replace the source's innermost dim; a one-dim span keeps the + // source rank and is handled by the generic paths below + const int shift = static_cast(nd) - 2 - j; + bool matches = j >= 0 && shift >= 1; + for (int t = 0; matches && t <= j; ++t) { + matches = view[t] == source[t + shift] && view_stride[t] == source_stride[t + shift]; + } + for (int t = 0; matches && t < shift; ++t) { + matches = source[t] == 1; + } + const size_t offset = context.get_view_input_offset(input_index, 0); + const size_t src_offset = context.get_view_input_src_offset(input_index, 0); + if (matches && offset >= src_offset && (offset - src_offset) % es == 0) { + const int64_t begin = static_cast((offset - src_offset) / es); + if (begin + static_cast(span) <= static_cast(source[nd - 1])) { + auto sliced = std::make_shared( + input, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + static_cast(span)}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast(nd) - 1})); + const auto view_ov_shape = context.get_view_input_ov_shape(input_index, 0); + std::vector pattern(nd); + size_t dynamic_dims = 0; + for (size_t i = 0; i < nd; ++i) { + if (view_ov_shape.rank().is_static() && view_ov_shape[i].is_static()) { + pattern[i] = view_ov_shape[i].get_length(); + } else { + pattern[i] = -1; + ++dynamic_dims; + } + } + if (dynamic_dims > 1) { + for (size_t i = 0; i < nd; ++i) { + pattern[i] = static_cast(view[i]); + } + } + return std::make_shared( + sliced, ov::op::v0::Constant::create(ov::element::i64, {nd}, pattern), false); + } + } + } + } + // A row range of a 2D weight (BERT's token type row): slice the rows of the [rows, row_size] Constant if (view_input_size == 1 && input.get_partial_shape().rank().is_static() && input.get_partial_shape().rank().get_length() == 2 && @@ -671,14 +754,17 @@ ov::Output process_view_input_new(const NodeContext & context, int inp exact_chunk = i == static_cast(split_dim) || view_ggml_shape[i] == 1 || view_stride_v[i] == view_src_stride_v[i]; } - // stateful execution drops the leading size-1 axis, so the input can be one rank lower than the - // ggml metadata - const auto input_rank = input.get_partial_shape().rank(); - const int64_t rank_shift = input_rank.is_static() ? - static_cast(ndims) - input_rank.get_length() : - static_cast(ndims); + // num_splits is the captured source size: on a dynamic axis (e.g. the token axis of DSpark's + // result_norm, read one block position at a time) the graph is reused with other sizes, and + // each Split output would then hold several rows or the wrong one + const auto input_shape = input.get_partial_shape(); + const int64_t split_axis = input_shape.rank().is_static() ? + split_dim - (int64_t) ndims + input_shape.rank().get_length() : + -1; + const bool split_axis_static = split_axis >= 0 && input_shape[split_axis].is_static() && + input_shape[split_axis].get_length() == num_splits; if (split_index >= 0 && split_index < num_splits && dynamic_split && exact_chunk && - split_dim >= rank_shift) { + split_axis_static) { // the Split keeps its input alive, so only keep a weak reference to it on the input auto src_node = input.get_node_shared_ptr(); std::string rt_key = @@ -689,8 +775,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp split_node = rt_info[rt_key].as>().lock(); } if (split_node == nullptr) { - auto axis_const = ov::op::v0::Constant::create( - ov::element::i64, {}, {static_cast(split_dim) - rank_shift}); + auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {split_axis}); split_node = std::make_shared(input, axis_const, static_cast(num_splits)); split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); @@ -722,7 +807,8 @@ ov::Output process_view_input_new(const NodeContext & context, int inp // Lambda function to process a single view operation auto process_single_view = - [](ov::Output current, size_t view_offset, const std::vector & view_stride, + [is_static = context.is_static()]( + ov::Output current, size_t view_offset, const std::vector & view_stride, const ov::Shape & view_ggml_shape, const ov::PartialShape & view_ov_shape, const std::string & view_name, size_t view_src_offset, const std::vector & view_src_stride, const ov::Shape & view_src_ggml_shape, const ov::PartialShape & view_src_ov_shape, const std::string & view_src_name) -> ov::Output { @@ -847,7 +933,12 @@ ov::Output process_view_input_new(const NodeContext & context, int inp ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim - axis_shift})); - if (view_ov_shape.is_static()) { + // In a static graph a rank-preserving slice (diff_dims has one entry) already has the view + // shape. Skip the Reshape: its target bakes the static chunk size into the token axis, which + // is wrong after the output-ids GET_ROWS of the last layer (1 token in the prefill graph). + const bool rank_kept = is_static && current_rank.is_static() && + static_cast(current_rank.get_length()) == ndims; + if (view_ov_shape.is_static() && !rank_kept) { auto reshaped = std::make_shared( sliced, ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()), diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 10344675b21e..aaee05116445 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -97,6 +97,9 @@ constexpr const char * GGML_OV_GROUPED_ROWS = "ggml_ov_grouped_rows"; // rt_info key on the stateful V cache read with `-fa off` (permute): V is [.., kv, head_size], not transposed constexpr const char * GGML_OV_V_TOKEN_MAJOR = "ggml_ov_v_token_major"; +// rt_info key on the packed SSM_SCAN output Concat [1, 1, 1, y | state]; whole-part VIEWs select one Concat input +constexpr const char * GGML_OV_SSM_SCAN_PACKED = "ggml_ov_ssm_scan_packed"; + namespace op { template OutputVector translate_1to1_match_2_inputs(const NodeContext & context) { num_inputs_check(context, 2, 2); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 7c5f6b7567b3..c959ce0d9203 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -657,6 +657,30 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ return *sliced; } + // KQ mask with fewer columns than the rounded KV length (see compute_llm_params): pad it with -inf + const auto & compute_params = ggml_decoder->get_compute_params(); + if (!ggml_decoder->is_static() && name == compute_params.mask_name && + compute_params.attention_size > ggml_tensor->ne[0] && ggml_is_contiguous(ggml_tensor)) { + const size_t rows = ggml_nrows(ggml_tensor); + const size_t cols = ggml_tensor->ne[0]; + const size_t padded_cols = compute_params.attention_size; + ov::Shape shape = GgmlOvDecoder::get_shape(ggml_tensor); + shape.back() = padded_cols; + ov::Tensor padded(GgmlOvDecoder::get_ov_type(ggml_tensor), shape); + auto pad = [&](auto fill) { + using T = decltype(fill); + auto data = pad_input((const T *) ggml_tensor->data, rows, cols, rows, padded_cols, fill); + std::memcpy(padded.data(), data.data(), padded.get_byte_size()); + }; + if (ggml_tensor->type == GGML_TYPE_F16) { + pad(GGML_FP32_TO_FP16(-INFINITY)); + } else { + GGML_ASSERT(ggml_tensor->type == GGML_TYPE_F32); + pad(-INFINITY); + } + return padded; + } + if (ggml_decoder->is_static() && GgmlOvDecoder::is_kvcache(ggml_tensor, ggml_decoder->get_tensor_used_op(ggml_tensor))) { const auto type = ggml_decoder->get_ov_type(ggml_tensor); @@ -2192,8 +2216,21 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared old_m_params = ggml_decoder->get_model_params(); cache_hit = old_m_params.can_reuse_statically(m_params); if (cache_hit && is_prefill && ggml_openvino_kv_slice_enabled()) { - cache_hit = entry->prefill_attention_size == c_params.attention_size && - entry->prefill_attention_size_swa == c_params.attention_size_swa; + // A larger compiled prefill also serves a smaller attended length: the extra KV rows are masked, as with + // the power-of-two rounding. Without this, a new prompt walks up the sizes again, and since only one + // prefill model is kept, every prompt longer than one chunk recompiles. Head-major KV is bound at the + // storage size, so it keeps the exact match. + // The output count is part of the static prefill shape (more than 1 only for llama-perplexity). + const bool reuse_larger = !ggml_openvino_npu_kv_head_major_enabled(); + cache_hit = entry->prefill_output_len == c_params.output_len && + (reuse_larger ? entry->prefill_attention_size >= c_params.attention_size && + entry->prefill_attention_size_swa >= c_params.attention_size_swa : + entry->prefill_attention_size == c_params.attention_size && + entry->prefill_attention_size_swa == c_params.attention_size_swa); + if (cache_hit) { + c_params.attention_size = entry->prefill_attention_size; + c_params.attention_size_swa = entry->prefill_attention_size_swa; + } prefill_size_changed = !cache_hit; } } @@ -2260,6 +2297,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = compiled.decode_attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -2274,6 +2312,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared r_ctx->ov_output_names_cache_prefill[key] = compiled.prefill_output_names; decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us(); GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n"); + if (prefill_size_changed) { + GGML_LOG_INFO("ggml-openvino: reuse the compiled prefill model of attention size %d\n", + c_params.attention_size); + } } else { auto decode_c_params = c_params; if (ggml_openvino_kv_slice_enabled()) { @@ -2600,6 +2642,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = decode_c_params.attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -3180,7 +3223,7 @@ enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) GgmlOvDecoder::dump_cgraph(cgraph, filename); } - const auto is_static = ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); + const auto is_static = ggml_openvino_is_static(); GGML_ASSERT(ctx->runtime_context != nullptr); std::shared_ptr r_ctx = std::static_pointer_cast(ctx->runtime_context); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 31fa7abc2435..c4450a387748 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -42,6 +42,11 @@ struct graph_key { if (GgmlOvDecoder::is_sampling_view(node)) { input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); } + // The output set is part of the model (one Result per output). Enabling outputs on an existing graph, + // e.g. llama_set_embeddings_layer_inp() for a DFlash/DSpark drafter, changes only the flags. + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i)); + } } static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; @@ -95,9 +100,11 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; - // Attention sizes the cached prefill model was built with; decode calls overwrite the decoder's. + // Attention sizes and output count the cached prefill model was built with; decode calls overwrite the + // decoder's. int prefill_attention_size = -1; int prefill_attention_size_swa = -1; + int prefill_output_len = -1; // KV window of the decode model in the compiled pair (GGML_OPENVINO_NPU_BLOB_PREBUILD). int decode_attention_size = -1; std::string shared_key; diff --git a/ggml/src/ggml-quants.c b/ggml/src/ggml-quants.c index 3586f67ae9fd..40ffe1e6bfda 100644 --- a/ggml/src/ggml-quants.c +++ b/ggml/src/ggml-quants.c @@ -3307,6 +3307,85 @@ static int iq2_find_best_neighbour(const uint16_t * GGML_RESTRICT neighbours, co return grid_index; } +// same result as iq2_find_best_neighbour: score = s*(s*quad_coef - lin_coef) + const, and the coefs do not depend on the scale s, so cache them per pattern +// take the cached winner only if all other neighbours are worse by more than the float rounding bound of the exact search, else run the exact search +#define IQ2_NEIGHBOUR_CACHE_MAX 512 + +typedef struct { + int pattern; // pattern whose coefs are cached, -1 if none + int last_best; // last winner for this pattern + // sums for the rounding bound: |w|, |w|*|x|, |w|*x^2, and the same with 1 + |w| + double sum_w, sum_wx, sum_wxx, sum_w1, sum_w1x, sum_w1xx; + double lin_term[8][8], quad_term[8][8]; // 2*w*x*q and w*q*q per element, indexed by the grid level q + double lin_coef[IQ2_NEIGHBOUR_CACHE_MAX]; + double quad_coef[IQ2_NEIGHBOUR_CACHE_MAX]; +} iq2_neighbour_cache; + +static void iq2_neighbour_cache_init(iq2_neighbour_cache * cache, const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight) { + cache->pattern = -1; + cache->sum_w = cache->sum_wx = cache->sum_wxx = cache->sum_w1 = cache->sum_w1x = cache->sum_w1xx = 0; + for (int i = 0; i < 8; ++i) { + const double w = (double)weight[i], x = (double)xval[i], abs_w = fabs(w), abs_x = fabs(x); + cache->sum_w += abs_w; cache->sum_wx += abs_w*abs_x; cache->sum_wxx += abs_w*abs_x*abs_x; + cache->sum_w1 += 1 + abs_w; cache->sum_w1x += (1 + abs_w)*abs_x; cache->sum_w1xx += (1 + abs_w)*abs_x*abs_x; + for (int q = 0; q < 8; ++q) { + cache->lin_term[i][q] = 2*w*x*q; + cache->quad_term[i][q] = w*q*q; + } + } +} + +static int iq2_count_at_most(const double * GGML_RESTRICT values, int n, double limit) { + int count = 0; + for (int j = 0; j < n; ++j) count += values[j] <= limit; + return count; +} + +static int iq2_find_best_neighbour_cached(iq2_neighbour_cache * cache, int pattern, const uint16_t * GGML_RESTRICT neighbours, const uint64_t * GGML_RESTRICT grid, + const float * GGML_RESTRICT xval, const float * GGML_RESTRICT weight, float scale, int8_t * GGML_RESTRICT L) { + const int num_neighbors = neighbours[0]; + const double scale_d = (double)scale; + const double max_level = 7*scale_d; + // size of the numbers in the exact search, its rounding error is a multiple of 2^-24*size (+ size_subnormal for underflow) + const double size = max_level*max_level*cache->sum_w + 2*max_level*cache->sum_wx + cache->sum_wxx; + const double size_subnormal = (1 + max_level)*(1 + max_level)*cache->sum_w1 + 2*(1 + max_level)*cache->sum_w1x + cache->sum_w1xx; + // the cached score is (exact score - const)/s, so the 2^-18*size margin on the exact score is divided by s + const double tolerance = (0x1p-18*size + 0x1p-100*size_subnormal)/scale_d; + if (num_neighbors <= 0 || num_neighbors > IQ2_NEIGHBOUR_CACHE_MAX || !(scale_d > 0 && size < 0x1p100 && size_subnormal < 0x1p100 && tolerance > 0)) { + return iq2_find_best_neighbour(neighbours, grid, xval, weight, scale, L); + } + if (cache->pattern != pattern) { + for (int j = 0; j < num_neighbors; ++j) { + const int8_t * levels = (const int8_t *)(grid + neighbours[j+1]); + double lin = 0, quad = 0; + for (int i = 0; i < 8; ++i) { + lin += cache->lin_term[i][levels[i]]; + quad += cache->quad_term[i][levels[i]]; + } + cache->lin_coef[j] = lin; cache->quad_coef[j] = quad; + } + cache->pattern = pattern; + cache->last_best = 0; + } + double score[IQ2_NEIGHBOUR_CACHE_MAX]; + for (int j = 0; j < num_neighbors; ++j) score[j] = scale_d*cache->quad_coef[j] - cache->lin_coef[j]; + // the winner must be the only neighbour within tolerance, try the previous winner for this pattern first + int best = cache->last_best; + if (iq2_count_at_most(score, num_neighbors, score[best] + tolerance) != 1) { + for (int j = 0; j < num_neighbors; ++j) { + if (score[j] < score[best]) best = j; + } + if (iq2_count_at_most(score, num_neighbors, score[best] + tolerance) != 1) { + return iq2_find_best_neighbour(neighbours, grid, xval, weight, scale, L); + } + cache->last_best = best; + } + const int grid_index = neighbours[best+1]; + const int8_t * levels = (const int8_t *)(grid + grid_index); + for (int i = 0; i < 8; ++i) L[i] = (levels[i] - 1)/2; + return grid_index; +} + static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t n, const float * GGML_RESTRICT quant_weights) { const int gindex = iq2_data_index(GGML_TYPE_IQ2_XXS); @@ -3335,6 +3414,8 @@ static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML float waux[32]; uint8_t block_signs[4]; uint32_t q2[2*(QK_K/32)]; + iq2_neighbour_cache neighbour_cache[4]; + int8_t Laux_prev[32]; for (int ibl = 0; ibl < nbl; ++ibl) { @@ -3390,6 +3471,7 @@ static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML continue; } float best = 0; + for (int k = 0; k < 4; ++k) iq2_neighbour_cache_init(&neighbour_cache[k], xval + 8*k, waux + 8*k); for (int is = -6; is <= 6; ++is) { float id = (2*kMaxQ-1+is*0.1f)/eff_max; float this_scale = 1/id; @@ -3403,9 +3485,14 @@ static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML int grid_index = kmap_q2xs[u]; if (grid_index < 0) { const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); } } + // same candidate as for the previous scale: it cannot change the result + if (is > -6 && memcmp(Laux, Laux_prev, 32) == 0) { + continue; + } + memcpy(Laux_prev, Laux, 32); float sumqx = 0, sumq2 = 0; for (int i = 0; i < 32; ++i) { float w = weight[i]; @@ -3430,7 +3517,7 @@ static void quantize_row_iq2_xxs_impl(const float * GGML_RESTRICT x, void * GGML int grid_index = kmap_q2xs[u]; if (grid_index < 0) { const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); } const int8_t * pg = (const int8_t *)(kgrid_q2xs + grid_index); for (int i = 0; i < 8; ++i) L[8*k+i] = (pg[i] - 1)/2; @@ -3515,6 +3602,9 @@ static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_ bool is_on_grid_aux[2]; uint8_t block_signs[2]; uint16_t q2[2*(QK_K/16)]; + iq2_neighbour_cache neighbour_cache[2]; + int8_t Laux_prev[16]; + bool is_on_grid_prev[2]; for (int ibl = 0; ibl < nbl; ++ibl) { @@ -3566,6 +3656,7 @@ static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_ float best = 0; float scale = max/(2*kMaxQ-1); is_on_grid[0] = is_on_grid[1] = true; + for (int k = 0; k < 2; ++k) iq2_neighbour_cache_init(&neighbour_cache[k], xval + 8*k, waux + 8*k); for (int is = -9; is <= 9; ++is) { float id = (2*kMaxQ-1+is*0.1f)/max; float this_scale = 1/id; @@ -3581,9 +3672,15 @@ static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_ if (grid_index < 0) { is_on_grid_aux[k] = false; const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); } } + // same candidate as for the previous scale: it cannot change the result + if (is > -9 && memcmp(Laux, Laux_prev, 16) == 0 && is_on_grid_aux[0] == is_on_grid_prev[0] && is_on_grid_aux[1] == is_on_grid_prev[1]) { + continue; + } + memcpy(Laux_prev, Laux, 16); + is_on_grid_prev[0] = is_on_grid_aux[0]; is_on_grid_prev[1] = is_on_grid_aux[1]; float sumqx = 0, sumq2 = 0; for (int i = 0; i < 16; ++i) { float w = weight[i]; @@ -3613,7 +3710,7 @@ static void quantize_row_iq2_xs_impl(const float * GGML_RESTRICT x, void * GGML_ int grid_index = kmap_q2xs[u]; if (grid_index < 0) { const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); } } float sumqx = 0, sumq2 = 0; @@ -5155,6 +5252,9 @@ static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_R bool is_on_grid[2]; bool is_on_grid_aux[2]; uint8_t block_signs[2]; + iq2_neighbour_cache neighbour_cache[2]; + int8_t Laux_prev[16]; + bool is_on_grid_prev[2]; for (int ibl = 0; ibl < nbl; ++ibl) { @@ -5197,6 +5297,7 @@ static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_R float best = 0; float scale = max/(2*kMaxQ-1); is_on_grid[0] = is_on_grid[1] = true; + for (int k = 0; k < 2; ++k) iq2_neighbour_cache_init(&neighbour_cache[k], xval + 8*k, waux + 8*k); for (int is = -9; is <= 9; ++is) { float id = (2*kMaxQ-1+is*0.1f)/max; float this_scale = 1/id; @@ -5212,9 +5313,15 @@ static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_R if (grid_index < 0) { is_on_grid_aux[k] = false; const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, this_scale, Laux + 8*k); } } + // same candidate as for the previous scale: it cannot change the result + if (is > -9 && memcmp(Laux, Laux_prev, 16) == 0 && is_on_grid_aux[0] == is_on_grid_prev[0] && is_on_grid_aux[1] == is_on_grid_prev[1]) { + continue; + } + memcpy(Laux_prev, Laux, 16); + is_on_grid_prev[0] = is_on_grid_aux[0]; is_on_grid_prev[1] = is_on_grid_aux[1]; float sumqx = 0, sumq2 = 0; for (int i = 0; i < 16; ++i) { float w = weight[i]; @@ -5244,7 +5351,7 @@ static void quantize_row_iq2_s_impl(const float * GGML_RESTRICT x, void * GGML_R int grid_index = kmap_q2xs[u]; if (grid_index < 0) { const uint16_t * neighbours = kneighbors_q2xs - kmap_q2xs[u] - 1; - grid_index = iq2_find_best_neighbour(neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); + grid_index = iq2_find_best_neighbour_cached(&neighbour_cache[k], u, neighbours, kgrid_q2xs, xval + 8*k, waux + 8*k, scale, L + 8*k); } } float sumqx = 0, sumq2 = 0; diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 4fc90e543166..9da436ced3c1 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7434,8 +7434,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons if (op->type == GGML_TYPE_TQ2_0 || op->type == GGML_TYPE_TQ1_0) { return false; } - auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || - op->src[0]->type == GGML_TYPE_BF16) && + auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32); return res; } @@ -7624,6 +7623,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons } case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: case GGML_OP_UPSCALE: diff --git a/ggml/src/ggml-vulkan/CMakeLists.txt b/ggml/src/ggml-vulkan/CMakeLists.txt index 791753a8cf9a..d8fa6ef409bb 100644 --- a/ggml/src/ggml-vulkan/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/CMakeLists.txt @@ -101,6 +101,12 @@ if (Vulkan_FOUND) "GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT" ) + test_shader_extension_support( + "GL_EXT_cooperative_matrix_maintenance1" + "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat_maintenance1.comp" + "GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT" + ) + test_shader_extension_support( "GL_EXT_integer_dot_product" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/integer_dot.comp" diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h index 69028c04251b..ea3b3b4b8772 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h @@ -101,7 +101,7 @@ void deferred_memset(void * dst, uint32_t val, size_t size, std::vectorprealloc_split_k), m, n, k, k, k, m, k*m, k*n, m*n, - split_k, batch, batch, batch, 1, 1, n, + split_k, 0, batch, batch, batch, 1, 1, n, k * sizeof(Y_TYPE), m * sizeof(float) ); } @@ -693,7 +693,7 @@ void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t ctx, subctx, p, { qx_buf, 0, qx_sz }, { qy_buf, 0, qy_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k }, m, n, k, k, k, m, k*m, k*n, m*n, - split_k, batch, batch, batch, 1, 1, n, + split_k, 0, batch, batch, batch, 1, 1, n, (uint64_t)(k / ggml_blck_size(GGML_TYPE_Q8_1)) * ggml_type_size(GGML_TYPE_Q8_1), m * sizeof(float) ); } @@ -703,7 +703,7 @@ void ggml_vk_test_dequant_matmul(ggml_backend_vk_context * ctx, size_t m, size_t ctx, subctx, p, { qx_buf, 0, qx_sz }, { y_buf, 0, y_sz }, { d_buf, 0, d_sz }, { ctx->prealloc_split_k, 0, ctx->prealloc_size_split_k }, m, n, k, k, k, m, k*m, k*n, m*n, - split_k, batch, batch, batch, 1, 1, n, + split_k, 0, batch, batch, batch, 1, 1, n, k * sizeof(float), m * sizeof(float) ); } @@ -1043,6 +1043,8 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_FILL) { const float value = ggml_get_op_params_f32(tensor, 0); tensor_clone = ggml_fill(ggml_ctx, src_clone[0], value); + } else if (tensor->op == GGML_OP_SLEEP) { + tensor_clone = ggml_sleep(ggml_ctx, src_clone[0], ggml_get_op_params_i32(tensor, 0)); } else if (tensor->op == GGML_OP_SQR) { tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]); } else if (tensor->op == GGML_OP_SQRT) { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index caa852e28bf7..0a04c1d56892 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -13,8 +13,38 @@ struct vk_mat_mat_push_constants { uint32_t k_split; uint32_t ne02; uint32_t ne12; uint32_t broadcast2; uint32_t broadcast3; uint32_t padded_N; + uint32_t k_units_per_tile; + uint32_t work_units_per_group; + uint32_t groups_with_extra_unit; + uint32_t k_units_mp; + uint32_t blocks_m_mp; + uint32_t blocks_n_mp; + uint32_t ne12_mp; + uint32_t broadcast2_mp; + uint32_t broadcast3_mp; + uint32_t div_Ls0; + uint32_t div_Ls1; }; +struct vk_mat_mat_stream_k_fixup_push_constants { + uint32_t M; uint32_t N; + uint32_t BM; uint32_t BN; + uint32_t k_units_per_tile; + uint32_t blocks_m; + uint32_t blocks_n; + uint32_t work_units_per_group; + uint32_t groups_with_extra_unit; + uint32_t k_units_mp; + uint32_t blocks_m_mp; + uint32_t blocks_n_mp; + uint32_t work_units_mp; + uint32_t large_group_work_mp; + uint32_t div_Ls0; + uint32_t div_Ls1; +}; + +static_assert(sizeof(vk_mat_mat_push_constants) <= 128); + struct vk_mat_vec_push_constants { uint32_t ncols; uint32_t stride_a; @@ -159,6 +189,10 @@ struct vk_op_push_constants { float param4; }; +struct vk_op_sleep_push_constants { + uint32_t ticks; +}; + struct vk_op_fwht_push_constants { uint32_t n_rows; uint32_t src_offset; @@ -403,6 +437,34 @@ template void init_pushconst_fastdiv(T &p) { static_assert(!std::is_const::value, "unexpected type"); } +inline void init_pushconst_fastdiv(vk_mat_mat_push_constants &p) { + uint32_t ne12_L, broadcast2_L, broadcast3_L; + init_fastdiv_values(p.ne12, p.ne12_mp, ne12_L); + init_fastdiv_values(p.broadcast2, p.broadcast2_mp, broadcast2_L); + init_fastdiv_values(p.broadcast3, p.broadcast3_mp, broadcast3_L); + p.div_Ls1 = pack_fastdiv_L(ne12_L, broadcast2_L, broadcast3_L); +} + +inline void init_pushconst_fastdiv(vk_mat_mat_push_constants &p, uint32_t blocks_m, uint32_t blocks_n) { + uint32_t k_units_L, blocks_m_L, blocks_n_L; + init_fastdiv_values(p.k_units_per_tile, p.k_units_mp, k_units_L); + init_fastdiv_values(blocks_m, p.blocks_m_mp, blocks_m_L); + init_fastdiv_values(blocks_n, p.blocks_n_mp, blocks_n_L); + p.div_Ls0 = pack_fastdiv_L(k_units_L, blocks_m_L, blocks_n_L); + init_pushconst_fastdiv(p); +} + +template <> inline void init_pushconst_fastdiv(vk_mat_mat_stream_k_fixup_push_constants &p) { + uint32_t k_units_L, blocks_m_L, blocks_n_L, work_units_L, large_group_work_L; + init_fastdiv_values(p.k_units_per_tile, p.k_units_mp, k_units_L); + init_fastdiv_values(p.blocks_m, p.blocks_m_mp, blocks_m_L); + init_fastdiv_values(p.blocks_n, p.blocks_n_mp, blocks_n_L); + init_fastdiv_values(p.work_units_per_group, p.work_units_mp, work_units_L); + init_fastdiv_values(p.work_units_per_group + 1, p.large_group_work_mp, large_group_work_L); + p.div_Ls0 = pack_fastdiv_L(k_units_L, blocks_m_L, blocks_n_L); + p.div_Ls1 = pack_fastdiv_L(work_units_L, large_group_work_L, 0); +} + template <> inline void init_pushconst_fastdiv(vk_op_unary_push_constants &p) { // Compute magic values to divide by these six numbers. uint32_t ne0_012L; @@ -725,6 +787,7 @@ struct vk_op_gated_delta_net_push_constants { uint32_t n_seqs; uint32_t s_off; uint32_t sq1, sq2, sq3; + uint32_t sk1, sk2, sk3; uint32_t sv1, sv2, sv3; uint32_t sb1, sb2, sb3; uint32_t neq1, rq3; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 54c7a36909e4..211948ee793b 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -36,6 +36,21 @@ typedef struct VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV { } VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV; #endif +#ifndef VK_EXT_cooperative_matrix_maintenance1 +#define VK_EXT_cooperative_matrix_maintenance1 1 +#define VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME "VK_EXT_cooperative_matrix_maintenance1" +#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT ((VkStructureType)1000659000) +typedef struct VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT { + VkStructureType sType; + void* pNext; + VkBool32 cooperativeMatrixProperties2; + VkBool32 cooperativeMatrixReductions; + VkBool32 cooperativeMatrixConversions; + VkBool32 cooperativeMatrixPerElementOperations; + VkBool32 cooperativeMatrixGetCoordinate; +} VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT; +#endif + #if __has_include() # include #elif __has_include() @@ -221,6 +236,12 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) +#define GGML_VK_GDN_CM_V 64u +#define GGML_VK_GDN_CM2_V 32u +#define GGML_VK_GDN_CM_D 128u +#define GGML_VK_GDN_CM_PAD 8u +#define GGML_VK_GDN_CM_LDP (GGML_VK_GDN_CM_D + GGML_VK_GDN_CM_PAD) + struct vk_pipeline_struct; typedef std::shared_ptr vk_pipeline; @@ -259,10 +280,11 @@ struct vk_matmul_pipeline_key { ggml_type type_b; bool mul_mat_id; bool f16acc; + bool stream_k = false; bool operator<(const vk_matmul_pipeline_key & o) const { - return std::tie(type_a, type_b, mul_mat_id, f16acc) - < std::tie(o.type_a, o.type_b, o.mul_mat_id, o.f16acc); + return std::tie(type_a, type_b, mul_mat_id, f16acc, stream_k) + < std::tie(o.type_a, o.type_b, o.mul_mat_id, o.f16acc, o.stream_k); } }; @@ -738,6 +760,7 @@ struct vk_device_struct { bool shader_int64; bool buffer_device_address; bool vulkan_memory_model; + bool shader_clock; bool add_rms_fusion; uint32_t partials_binding_alignment; @@ -746,6 +769,10 @@ struct vk_device_struct { bool shader_64b_indexing; bool integer_dot_product; + // Which 4x8 bit packed integer dot products are accelerated + bool integer_dot_signed {}; + bool integer_dot_mixed {}; + bool integer_dot_unsigned {}; // 0: default, 1: force mmvq, -1: disable mmvq int32_t mmvq_mode; @@ -761,6 +788,12 @@ struct vk_device_struct { bool coopmat_acc_f32_support {}; bool coopmat_acc_f16_support {}; bool coopmat_bf16_support {}; + bool coopmat_bf16_acc_support {}; + bool coopmat_maintenance1 {}; + bool coopmat_m1_reductions {}; + bool coopmat_m1_conversions {}; + bool coopmat_m1_per_element_ops {}; + bool coopmat_m1_get_coordinate {}; bool coopmat_support_16x16x16_f16acc {}; bool coopmat_support_16x16x16_f32acc {}; bool coopmat1_fa_support {}; @@ -775,6 +808,7 @@ struct vk_device_struct { bool coopmat2; bool coopmat2_bf16_support {}; + bool coopmat2_gdn_support {}; bool coopmat2_decode_vector; bool dot2_f16 {}; @@ -819,6 +853,7 @@ struct vk_device_struct { matmul_tile_selector_t matmul_id_tile_selector; vk_pipeline pipeline_matmul_split_k_reduce; + vk_pipeline pipeline_matmul_stream_k_fixup; vk_pipeline pipeline_quantize_q8_1_x4; vk_pipeline pipeline_dequant[GGML_TYPE_COUNT]; @@ -917,6 +952,8 @@ struct vk_device_struct { vk_pipeline pipeline_fill_f32; vk_pipeline pipeline_fill_f16; + vk_pipeline pipeline_sleep; + // [src/dst 0=fp32,1=fp16,2=bf16] vk_pipeline pipeline_glu[GGML_GLU_OP_COUNT][3]; @@ -978,6 +1015,9 @@ struct vk_device_struct { vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 vk_pipeline pipeline_gated_delta_net[4][2]; + vk_pipeline pipeline_gated_delta_net_cm; + vk_pipeline pipeline_gated_delta_net_cm_v32; + vk_pipeline pipeline_gated_delta_net_cm_v128; vk_pipeline pipeline_ssm_scan_f32_d128; vk_pipeline pipeline_ssm_scan_f32_d256; vk_pipeline pipeline_ssm_conv_f32; @@ -1023,6 +1063,8 @@ struct vk_device_struct { std::map fusion_counts; bool disable_descriptor_reuse; std::atomic buffer_destroy_count {}; + bool disable_stream_k; + bool force_stream_k; bool disable_host_visible_vidmem; bool allow_sysmem_fallback; bool disable_graph_optimize; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 616a17c4c8c4..a9d60d6af57a 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1667,6 +1667,22 @@ static uint32_t ggml_vk_mul_mat_vec_max_cols(const vk_device & device) { return device->coopmat2 && !device->disable_narrow_mul_mat ? 4u : mul_mat_vec_max_cols; } +static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2) { + const uint32_t C = 16; + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t bf16_size = sizeof(ggml_bf16_t); + const bool gmem_mirror = !coopmat2 && v == 128; + + const uint32_t qk = 4 * C * LDP * bf16_size; + const uint32_t state = gmem_mirror ? 0 : 2 * v * LDP * bf16_size; + const uint32_t p_inv = 4 * C * C * bf16_size; + const uint32_t delta_solved = coopmat2 ? 2 * C * (v + GGML_VK_GDN_CM_PAD) * bf16_size : 4 * C * v * bf16_size; + const uint32_t lower = (coopmat2 ? C * (C - 1) / 2 : C * C) * sizeof(float); + const uint32_t scan = 4 * C * sizeof(float); + + return qk + state + p_inv + delta_solved + lower + scan; +} + static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { uint32_t lut_size = 0; @@ -1726,6 +1742,11 @@ static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vec return supported; } +// MMQ uses the mixed signedness dot product (MMQ_SUDOT) when the signed one is not accelerated +static bool ggml_vk_mmq_use_sudot(const vk_device& device) { + return device->integer_dot_mixed && !device->integer_dot_signed; +} + static bool ggml_vk_matmul_int_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { // FLOAT_TYPE in the shader is float16_t with fp16 support, otherwise float. @@ -1782,7 +1803,12 @@ static bool ggml_vk_matmul_int_shmem_support(const vk_device& device, const std: const uint32_t buf_b_size = BN * BK_STEP * block_b_size; const uint32_t mmid_row_ids = mul_mat_id ? (BN * 2u * (uint32_t)sizeof(uint16_t)) : 0u; - const uint32_t total_size = buf_a_size + buf_b_size + mmid_row_ids + lut_size; + // Signed quants declare buf_b_qsum: 2 int32_t per B block with MMQ_SUDOT, a single int32_t without + const bool b_sums = src0_type == GGML_TYPE_Q8_0 || src0_type == GGML_TYPE_MXFP4 || src0_type == GGML_TYPE_IQ4_XS || + src0_type == GGML_TYPE_IQ3_S || src0_type == GGML_TYPE_Q3_K || src0_type == GGML_TYPE_Q6_K; + const uint32_t qsum_size = !b_sums ? 0u : ggml_vk_mmq_use_sudot(device) ? BN * BK_STEP * 2u * 4u : 4u; + + const uint32_t total_size = buf_a_size + buf_b_size + mmid_row_ids + lut_size + qsum_size; const bool supported = total_size <= device->properties.limits.maxComputeSharedMemorySize; VK_LOG_DEBUG("ggml_vk_matmul_int_shmem_support(warptile=(" << warptile[0] << "," << warptile[1] << "," << warptile[2] << "), " @@ -1906,7 +1932,7 @@ static bool ggml_vk_fa_type_needs_shmem(ggml_type type) { static bool ggml_vk_fa_scalar_uses_mmq(const vk_device& device, ggml_type k_type, ggml_type v_type) { #if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) - return device->integer_dot_product && device->subgroup_clustered && + return device->integer_dot_product && device->integer_dot_signed && device->subgroup_clustered && !ggml_vk_fa_type_needs_shmem(v_type) && (k_type == GGML_TYPE_Q4_0 || k_type == GGML_TYPE_Q4_1 || k_type == GGML_TYPE_Q5_0 || k_type == GGML_TYPE_Q5_1 || @@ -2467,6 +2493,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { FOR_EACH_LUT_FP4_TYPE(X) const int mul_mat_id_param_count = 5; + constexpr uint32_t stream_k_spec_id = 15; using spec_fn_t = std::function(const std::vector&, bool)>; auto const &create_mm_pipelines = [&]( @@ -2478,6 +2505,11 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { bool disable_robustness = false, bool require_full_subgroups = false, uint32_t required_subgroup_size = 0, bool create_aligned = true, bool pin_subgroup_to_warp = false ) { + GGML_ASSERT(!key.stream_k || (!key.mul_mat_id && param_count == 3 && push_constant_size == sizeof(vk_mat_mat_push_constants) && create_aligned)); + // Non-ID matmul shaders declare the Stream-K scratch binding in all specializations. + if (!key.mul_mat_id) { + ++param_count; + } auto& vec = device->pipeline_matmul[key]; const bool first_call = vec.empty(); for (size_t i = 0; i < tile_configs.size(); i++) { @@ -2495,25 +2527,40 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { vk_matmul_pipeline_pair pair{}; pair.align = tc.align; pair.narrow_n_max = tc.narrow_n_max; - std::string suffix = "_" + std::to_string(i); - pair.unaligned = std::make_shared(); + if (!key.stream_k) { + pair.unaligned = std::make_shared(); + } if (create_aligned) { pair.aligned = std::make_shared(); } + if (key.stream_k) { + // Tile selection reads unaligned even when selecting an aligned pipeline. + pair.unaligned = pair.aligned; + } vec.push_back(pair); } - ggml_vk_create_pipeline(device, vec[i].unaligned, - vec[i].unaligned->name.empty() ? (shader_name + "_" + std::to_string(i)).c_str() : vec[i].unaligned->name.c_str(), - spv_len, spv_data, "main", param_count, push_constant_size, - tc.wg_denoms, spec_fn(tc.warptile, false), 1, - disable_robustness, rfs, rsgs); + if (!key.stream_k) { + ggml_vk_create_pipeline(device, vec[i].unaligned, + vec[i].unaligned->name.empty() ? (shader_name + "_" + std::to_string(i)).c_str() : vec[i].unaligned->name.c_str(), + spv_len, spv_data, "main", param_count, push_constant_size, + tc.wg_denoms, spec_fn(tc.warptile, false), 1, + disable_robustness, rfs, rsgs); + } if (vec[i].aligned) { + auto spec = spec_fn(tc.warptile, true); + if (key.stream_k) { + if (spec.size() <= stream_k_spec_id) { + spec.resize(stream_k_spec_id + 1); + } + spec[stream_k_spec_id] = 1; + } + const std::string name = shader_name + (key.stream_k ? "_stream_k_" : "_aligned_") + std::to_string(i); ggml_vk_create_pipeline(device, vec[i].aligned, - vec[i].aligned->name.empty() ? (shader_name + "_aligned_" + std::to_string(i)).c_str() : vec[i].aligned->name.c_str(), + vec[i].aligned->name.empty() ? name.c_str() : vec[i].aligned->name.c_str(), spv_len, spv_data, "main", param_count, push_constant_size, - tc.wg_denoms, spec_fn(tc.warptile, true), tc.align, + tc.wg_denoms, spec, tc.align, disable_robustness, rfs, rsgs); } } @@ -2611,13 +2658,19 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } spec_fn_t cm2_spec = [&](const std::vector& wt, bool a) { return ggml_vk_mul_mm_cm2_spec(wt, a); }; + auto create_cm2_pipelines = [&](vk_matmul_pipeline_key key, const std::vector& tc, + const std::string& name, size_t len, const void* data, uint32_t pc_size, uint32_t pc, const spec_fn_t& spec) { + create_mm_pipelines(key, tc, name, len, data, pc_size, pc, spec, true); + key.stream_k = true; + create_mm_pipelines(key, tc, name, len, data, pc_size, pc, spec, true); + }; // F16 x F16 - create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", matmul_f16_f16acc_cm2_len, matmul_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); - create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm2_len, matmul_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); + create_cm2_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, true}, tc_mm, "matmul_f16_f16acc", matmul_f16_f16acc_cm2_len, matmul_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); + create_cm2_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, false, false}, tc_mm, "matmul_f16", matmul_f16_cm2_len, matmul_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); #if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) if (device->coopmat_bf16_support) { - create_mm_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_cm2_len, matmul_bf16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); + create_cm2_pipelines({GGML_TYPE_BF16, GGML_TYPE_BF16, false, false}, tc_mm, "matmul_bf16", matmul_bf16_cm2_len, matmul_bf16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); } #endif for (const auto type : non_lut_quant_types) { @@ -2627,18 +2680,18 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { } auto& tc = ((type >= GGML_TYPE_Q2_K && type <= GGML_TYPE_Q6_K) || type == GGML_TYPE_TQ1_0 || type == GGML_TYPE_TQ2_0) ? tc_mmq_k : tc_mmq; spec_fn_t qs = [&, type](const std::vector& wt, bool a) { return ggml_vk_mul_mm_cm2_spec(wt, a, (uint32_t)type); }; - create_mm_pipelines({type, GGML_TYPE_F16, false, true}, tc, "matmul_quant_f16_f16acc", matmul_quant_f16_f16acc_cm2_len, matmul_quant_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs, true); - create_mm_pipelines({type, GGML_TYPE_F16, false, false}, tc, "matmul_quant_f16", matmul_quant_f16_cm2_len, matmul_quant_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs, true); + create_cm2_pipelines({type, GGML_TYPE_F16, false, true}, tc, "matmul_quant_f16_f16acc", matmul_quant_f16_f16acc_cm2_len, matmul_quant_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs); + create_cm2_pipelines({type, GGML_TYPE_F16, false, false}, tc, "matmul_quant_f16", matmul_quant_f16_cm2_len, matmul_quant_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, qs); } - create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q4_k_f16_f16acc", matmul_q4_k_f16_f16acc_cm2_len, matmul_q4_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); - create_mm_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q4_k_f16", matmul_q4_k_f16_cm2_len, matmul_q4_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); - create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q5_k_f16_f16acc", matmul_q5_k_f16_f16acc_cm2_len, matmul_q5_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); - create_mm_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q5_k_f16", matmul_q5_k_f16_cm2_len, matmul_q5_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); + create_cm2_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q4_k_f16_f16acc", matmul_q4_k_f16_f16acc_cm2_len, matmul_q4_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); + create_cm2_pipelines({GGML_TYPE_Q4_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q4_k_f16", matmul_q4_k_f16_cm2_len, matmul_q4_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); + create_cm2_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, true}, tc_mmq_k, "matmul_q5_k_f16_f16acc", matmul_q5_k_f16_f16acc_cm2_len, matmul_q5_k_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); + create_cm2_pipelines({GGML_TYPE_Q5_K, GGML_TYPE_F16, false, false}, tc_mmq_k, "matmul_q5_k_f16", matmul_q5_k_f16_cm2_len, matmul_q5_k_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); #define X_CM2(TYPE, tstr) \ { auto tc = filter_tc(tc_mmq, TYPE, false); \ if (!tc.empty()) { \ - create_mm_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_f16acc", matmul_##tstr##_f16_f16acc_cm2_len, matmul_##tstr##_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ - create_mm_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16", matmul_##tstr##_f16_cm2_len, matmul_##tstr##_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ + create_cm2_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_f16acc", matmul_##tstr##_f16_f16acc_cm2_len, matmul_##tstr##_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); \ + create_cm2_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16", matmul_##tstr##_f16_cm2_len, matmul_##tstr##_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); \ } } FOR_EACH_LUT_TYPE_NONFP4(X_CM2) #if defined(GGML_VULKAN_FLOAT_E2M1_GLSLC_SUPPORT) && defined(GGML_VULKAN_FLOAT_E4M3_GLSLC_SUPPORT) @@ -2646,8 +2699,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { #define X_CM2_OCP(TYPE, tstr) \ { auto tc = filter_tc(tc_mmq, TYPE, false); \ if (!tc.empty()) { \ - create_mm_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_ocp_f16acc", matmul_##tstr##_f16_ocp_f16acc_cm2_len, matmul_##tstr##_f16_ocp_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ - create_mm_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16_ocp", matmul_##tstr##_f16_ocp_cm2_len, matmul_##tstr##_f16_ocp_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true); \ + create_cm2_pipelines({TYPE, GGML_TYPE_F16, false, true}, tc, "matmul_" #tstr "_f16_ocp_f16acc", matmul_##tstr##_f16_ocp_f16acc_cm2_len, matmul_##tstr##_f16_ocp_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); \ + create_cm2_pipelines({TYPE, GGML_TYPE_F16, false, false}, tc, "matmul_" #tstr "_f16_ocp", matmul_##tstr##_f16_ocp_cm2_len, matmul_##tstr##_f16_ocp_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec); \ } } FOR_EACH_LUT_FP4_TYPE(X_CM2_OCP) #undef X_CM2_OCP @@ -2925,8 +2978,13 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { uint32_t rsgs = 0) { auto tc = filter_tc(tc_base, key.type_a, key.mul_mat_id, true); if (!tc.empty()) { - spec_fn_t identity = [](const std::vector& wt, bool) { return wt; }; - create_mm_pipelines(key, tc, name, len, data, pc_size, pc, identity, false, rsgs > 0, rsgs, false); + // constant_id 11 is MMQ_SUDOT + spec_fn_t mmq_spec = [&](const std::vector& wt, bool) { + std::vector spec = wt; + spec.push_back(ggml_vk_mmq_use_sudot(device) ? 1u : 0u); + return spec; + }; + create_mm_pipelines(key, tc, name, len, data, pc_size, pc, mmq_spec, false, rsgs > 0, rsgs, false); } }; #endif @@ -3515,6 +3573,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_get_rows_back_f32, "get_rows_back_f32", get_rows_back_f32_len, get_rows_back_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {256, 1, 1}, {}, 1, true); ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_matmul_stream_k_fixup, "stream_k_fixup", stream_k_fixup_len, stream_k_fixup_data, "main", 2, sizeof(vk_mat_mat_stream_k_fixup_push_constants), {1, 32, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_flash_attn_split_k_reduce, "fa_split_k_reduce", fa_split_k_reduce_len, fa_split_k_reduce_data, "main", 3, sizeof(vk_op_flash_attn_split_k_reduce_push_constants), {1, device->subgroup_size, 1}, {device->subgroup_size}, 1, true); #if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) @@ -3849,6 +3908,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_fill_f16, "fill_f16", fill_f16_len, fill_f16_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); + if (device->shader_clock) { + ggml_vk_create_pipeline(device, device->pipeline_sleep, "sleep", sleep_len, sleep_data, "main", 1, sizeof(vk_op_sleep_push_constants), {1, 1, 1}, {}, 1); + } + #define CREATE_GLU(name, op) \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ @@ -4077,13 +4140,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { device->subgroup_min_size <= 16u && device->subgroup_max_size >= 16u) { gdn_subgroup_size = 16u; } + const bool gdn_packed_rows = S_V == 128u && device->vendor_id == VK_VENDOR_ID_NVIDIA && + gdn_subgroup_size == 32u && device->subgroup_arithmetic && device->subgroup_clustered; uint32_t lanes_per_column; if (device->vendor_id == VK_VENDOR_ID_INTEL) { // Intel Xe: full-width reduction (min rows/lane) ~10x over the COLS_PER_WG=8 rule. lanes_per_column = std::min(gdn_subgroup_size, S_V); } else if (S_V >= 128u && device->subgroup_clustered) { - // COLS_PER_WG=8: measured optimum (Ampere sg32->4, Vega20 sg64->8). - lanes_per_column = std::max(1u, gdn_subgroup_size / 8u); + lanes_per_column = gdn_packed_rows ? 8u : std::max(1u, gdn_subgroup_size / 8u); } else { // Use largest power-of-two that divides both S_V and subgroup_size so that // (1) S_V % lanes_per_column == 0 and (2) S_V % (subgroup_size / lanes_per_column) == 0. @@ -4130,9 +4194,60 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { for (uint32_t kda = 0; kda < 2; kda++) { ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column}, 1, true, use_subgroup_ops, gdn_subgroup_size); + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size); } } + + // Chunked GDN prefill uses workgroup matrices on CM2 and subgroup matrices on CM1. + const bool gdn_chunked = getenv("GGML_VK_DISABLE_GDN_CHUNKED") == nullptr; + const uint32_t gdn_shmem = device->properties.limits.maxComputeSharedMemorySize; +#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + if (gdn_chunked && device->coopmat2 && device->coopmat2_gdn_support) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + "gated_delta_net_f32_cm2", gated_delta_net_f32_cm2_len, gated_delta_net_f32_cm2_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, {}, 1, true, true, 32); + } +#endif +#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + // shader needs >= 16 lanes and 16 subgroups per WG; prefer wave64 + auto gdn_sg_ok = [&](uint32_t sg) { + const bool reachable = device->subgroup_size_control ? device->subgroup_min_size <= sg && sg <= device->subgroup_max_size + : device->subgroup_size == sg; + return reachable && 16u * sg <= device->properties.limits.maxComputeWorkGroupInvocations && + 16u * sg <= device->properties.limits.maxComputeWorkGroupSize[0]; + }; + const uint32_t gdn_sg = gdn_sg_ok(64) ? 64u : device->subgroup_size; + if (gdn_chunked && !device->coopmat2 && device->coopmat_support && device->coopmat_bf16_support && device->coopmat_m1_per_element_ops && + gdn_sg >= 16 && gdn_sg_ok(gdn_sg)) { + const bool bf16acc = device->coopmat_bf16_acc_support; + const std::vector gdn_spec = { 16u * gdn_sg }; + // V=64: state mirror in shared, 7 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM_V, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc" : "gated_delta_net_f32_cm1", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_len : gated_delta_net_f32_cm1_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_data : (const void *)gated_delta_net_f32_cm1_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(32u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v32, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v32" : "gated_delta_net_f32_cm1_v32", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v32_len : gated_delta_net_f32_cm1_v32_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v32_data : (const void *)gated_delta_net_f32_cm1_v32_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + // V=128: state mirror in a gmem scratch buffer, 8 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(128u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v128, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v128" : "gated_delta_net_f32_cm1_v128", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v128_len : gated_delta_net_f32_cm1_v128_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v128_data : (const void *)gated_delta_net_f32_cm1_v128_data, + "main", 8, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + } +#endif + GGML_UNUSED(gdn_chunked); + GGML_UNUSED(gdn_shmem); } if (device->subgroup_arithmetic && device->subgroup_require_full_support) { @@ -4478,6 +4593,7 @@ vk_device ggml_vk_get_device(size_t idx) { bool ocp_microscaling_extension = false; bool shader_float8_extension = false; bool workgroup_memory_explicit_layout_support = false; + bool shader_clock_support = false; for (const auto& properties : ext_props) { if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) { @@ -4506,6 +4622,11 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + device->coopmat_maintenance1 = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -4528,6 +4649,9 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME, properties.extensionName) == 0) { shader_float8_extension = true; #endif + } else if (strcmp("VK_KHR_shader_clock", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_SHADER_CLOCK")) { + shader_clock_support = true; } else if (strcmp("VK_VALVE_shader_mixed_float_dot_product", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_DOT2")) { dot2_f16_support = true; @@ -4684,6 +4808,10 @@ vk_device ggml_vk_get_device(size_t idx) { device->subgroup_arithmetic = false; } #endif + // Workaround for subgroupAdd() returning wrong sums on Adreno after divergent code + if (device->driver_id == vk::DriverId::eQualcommProprietary) { + device->subgroup_arithmetic = false; + } device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle); #ifdef __APPLE__ @@ -4716,7 +4844,10 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat_support = false; } - device->integer_dot_product = device->integer_dot_product && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated; + device->integer_dot_signed = shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated; + device->integer_dot_mixed = shader_integer_dot_product_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated; + device->integer_dot_unsigned = shader_integer_dot_product_props.integerDotProduct4x8BitPackedUnsignedAccelerated; + device->integer_dot_product = device->integer_dot_product && (device->integer_dot_signed || device->integer_dot_mixed); device->min_imported_host_pointer_alignment = external_memory_host_props.minImportedHostPointerAlignment; @@ -4822,6 +4953,15 @@ vk_device ggml_vk_get_device(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (device->coopmat_support && device->coopmat_maintenance1) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV coopmat2_decode_vector_features {}; coopmat2_decode_vector_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_DECODE_VECTOR_FEATURES_NV; if (coopmat2_decode_vector_support) { @@ -4873,6 +5013,14 @@ vk_device ggml_vk_get_device(size_t idx) { device_extensions.push_back("VK_KHR_shader_integer_dot_product"); } + VkPhysicalDeviceShaderClockFeaturesKHR shader_clock_features {}; + shader_clock_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR; + if (shader_clock_support) { + last_struct->pNext = (VkBaseOutStructure *)&shader_clock_features; + last_struct = (VkBaseOutStructure *)&shader_clock_features; + device_extensions.push_back("VK_KHR_shader_clock"); + } + VkPhysicalDeviceShaderMixedFloatDotProductFeaturesVALVE dot2_features {}; dot2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MIXED_FLOAT_DOT_PRODUCT_FEATURES_VALVE; if (dot2_f16_support) { @@ -4979,6 +5127,7 @@ vk_device ggml_vk_get_device(size_t idx) { device->shader_int64 = device_features2.features.shaderInt64; device->buffer_device_address = vk12_features.bufferDeviceAddress; device->vulkan_memory_model = vk12_features.vulkanMemoryModel; + device->shader_clock = shader_clock_support && shader_clock_features.shaderDeviceClock; if (device->subgroup_size_control) { device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize; @@ -4997,6 +5146,17 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + device->coopmat_maintenance1 = device->coopmat_support && device->coopmat_maintenance1; + if (device->coopmat_maintenance1) { + device->coopmat_m1_reductions = coopmat_m1_features.cooperativeMatrixReductions; + device->coopmat_m1_conversions = coopmat_m1_features.cooperativeMatrixConversions; + device->coopmat_m1_per_element_ops = coopmat_m1_features.cooperativeMatrixPerElementOperations; + device->coopmat_m1_get_coordinate = coopmat_m1_features.cooperativeMatrixGetCoordinate; + device_extensions.push_back(VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME); + } +#endif + if (coopmat2_support) { #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) if (coopmat2_features.cooperativeMatrixWorkgroupScope && @@ -5080,6 +5240,13 @@ vk_device ggml_vk_get_device(size_t idx) { prop.KGranularity <= 16) { found_bf16_128 = true; } + // GDN uses M=32, with N/K dimensions that are multiples of 16. + if (prop.workgroupInvocations == 128 && + prop.MGranularity != 0 && 32 % prop.MGranularity == 0 && + prop.NGranularity != 0 && 16 % prop.NGranularity == 0 && + prop.KGranularity != 0 && 16 % prop.KGranularity == 0) { + device->coopmat2_gdn_support = true; + } if (prop.workgroupInvocations == 256 && prop.MGranularity <= 32 && prop.NGranularity <= 32 && @@ -5090,6 +5257,12 @@ vk_device ggml_vk_get_device(size_t idx) { #endif } } + device->coopmat2_gdn_support = device->coopmat2_gdn_support && + coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 && + device->properties.limits.maxComputeWorkGroupInvocations >= 128 && + device->properties.limits.maxComputeWorkGroupSize[0] >= 128 && + uint64_t(ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM2_V, true)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <= + device->properties.limits.maxComputeSharedMemorySize; if (found_fp16_128 && found_fp16_256 && found_fp32_128 && found_fp32_256 && coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) { @@ -5207,6 +5380,18 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat_bf16_support = true; } } + // bf16 accumulator (bf16/bf16/bf16/bf16) at the shader's fixed 16x16x16 + // shape lets the GDN coopmat1 path keep the hi/lo split as accumulators. + if (bfloat16_support && + prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.CType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.ResultType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup && + prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16 + ) { + device->coopmat_bf16_acc_support = true; + } #endif } @@ -5375,6 +5560,8 @@ vk_device ggml_vk_get_device(size_t idx) { device->serialize_submissions = getenv("GGML_VK_SERIALIZE_SUBMISSIONS") != nullptr; device->disable_fusion = getenv("GGML_VK_DISABLE_FUSION") != nullptr; + device->disable_stream_k = getenv("GGML_VK_DISABLE_STREAM_K") != nullptr; + device->force_stream_k = getenv("GGML_VK_FORCE_STREAM_K") != nullptr; device->disable_descriptor_reuse = getenv("GGML_VK_DISABLE_DESCRIPTOR_REUSE") != nullptr; @@ -5420,6 +5607,7 @@ static void ggml_vk_print_gpu_info(size_t idx) { bool coopmat_support = false; bool coopmat2_support = false; bool coopmat2_decode_vector_support = false; + bool coopmat_maintenance1_support = false; bool integer_dot_product = false; bool bfloat16_support = false; bool dot2_f16_support = false; @@ -5440,6 +5628,11 @@ static void ggml_vk_print_gpu_info(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + coopmat_maintenance1_support = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -5523,6 +5716,15 @@ static void ggml_vk_print_gpu_info(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (coopmat_support && coopmat_maintenance1_support) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {}; shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR; if (integer_dot_product) { @@ -5593,7 +5795,8 @@ static void ggml_vk_print_gpu_info(size_t idx) { const bool rebar = ggml_vk_has_rebar(physical_device); integer_dot_product = integer_dot_product - && shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated + && (shader_integer_dot_product_props.integerDotProduct4x8BitPackedSignedAccelerated || + shader_integer_dot_product_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) && shader_integer_dot_product_features.shaderIntegerDotProduct; coopmat_support = coopmat_support @@ -5615,13 +5818,17 @@ static void ggml_vk_print_gpu_info(size_t idx) { coopmat2_support = false; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + coopmat_maintenance1_support = coopmat_maintenance1_support && coopmat_m1_features.cooperativeMatrixPerElementOperations; +#endif + coopmat2_decode_vector_support = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector; #if !defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) coopmat2_decode_vector_support = false; #endif std::string matrix_cores = coopmat2_support ? (coopmat2_decode_vector_support ? "NV_coopmat2v" : "NV_coopmat2") - : coopmat_support ? "KHR_coopmat" + : coopmat_support ? (coopmat_maintenance1_support ? "KHR_coopmat_m1" : "KHR_coopmat") : "none"; bool dot2_f16 = dot2_f16_support && dot2_features.shaderMixedFloatDotProductFloat16AccFloat32; @@ -6408,14 +6615,113 @@ static uint32_t ggml_vk_guess_split_k(ggml_backend_vk_context * ctx, uint32_t m, return split_k; } +static uint32_t ggml_vk_guess_stream_k_groups( + ggml_backend_vk_context * ctx, const vk_pipeline & pipeline, + uint32_t m, uint32_t n, uint32_t k, uint32_t stride_d, uint32_t batch, uint32_t split_k, bool disable_split_k) { + if (disable_split_k) { + return 0; + } + if (ctx->device->disable_stream_k) { + return 0; + } + // TODO: Tune the CM1 and scalar workgroup counts before enabling Stream-K. + if (!ctx->device->coopmat2) { + return 0; + } + if (ctx->device->shader_core_count == 0) { + return 0; + } + + const uint32_t bm = pipeline->wg_denoms[0]; + const uint32_t bn = pipeline->wg_denoms[1]; + if (bm % 32 != 0 || m % bm != 0 || n % bn != 0 || k % 256 != 0 || stride_d != m) { + return 0; + } + + const uint32_t k_units = k / 256; + if (k_units == 1) { + return 0; + } + + const uint64_t tiles = uint64_t(m / bm) * (n / bn) * batch; + const uint64_t total_work_units = tiles * k_units; + if (total_work_units > UINT32_MAX) { + return 0; + } + + // Coopmat2 tiles are tuned for one resident workgroup per SM. + const uint32_t target_groups = ctx->device->shader_core_count; + const uint64_t regular_groups = tiles * split_k; + const uint64_t regular_waves = CEIL_DIV(regular_groups, target_groups); + const uint64_t regular_capacity = regular_waves * target_groups; + + const uint32_t stream_k_groups = std::min(target_groups, total_work_units); + if (stream_k_groups > ctx->device->properties.limits.maxComputeWorkGroupCount[0] || + bm / 32 > ctx->device->properties.limits.maxComputeWorkGroupCount[1]) { + return 0; + } + if (!ctx->device->force_stream_k) { + if (regular_waves == 1 && stream_k_groups == regular_groups) { + return 0; + } + // Stream-K does not offset its overhead when the regular grid fills most of the last wave. + // Use a lower cutoff for short K with no K split and narrow N tiles. + if ((split_k == 1 && k <= 4096 && bn <= 128 && regular_groups * 4 >= regular_capacity * 3) || + regular_groups * 10 >= regular_capacity * 9) { + return 0; + } + } + + return stream_k_groups; +} + void ggml_vk_matmul( ggml_backend_vk_context * ctx, vk_context& subctx, vk_pipeline& pipeline, vk_subbuffer&& a, vk_subbuffer&& b, vk_subbuffer&& d, vk_subbuffer&& split_k_buffer, uint32_t m, uint32_t n, uint32_t k, uint32_t stride_a, uint32_t stride_b, uint32_t stride_d, uint32_t batch_stride_a, uint32_t batch_stride_b, uint32_t batch_stride_d, - uint32_t split_k, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, + uint32_t split_k, uint32_t stream_k_groups, uint32_t batch, uint32_t ne02, uint32_t ne12, uint32_t broadcast2, uint32_t broadcast3, uint32_t padded_n, uint64_t b_col_bytes, uint64_t d_col_bytes) { VK_LOG_DEBUG("ggml_vk_matmul(a: (" << a.buffer->buffer << ", " << a.offset << ", " << a.size << "), b: (" << b.buffer->buffer << ", " << b.offset << ", " << b.size << "), d: (" << d.buffer->buffer << ", " << d.offset << ", " << d.size << "), split_k: (" << (split_k_buffer.buffer != nullptr ? split_k_buffer.buffer->buffer : VK_NULL_HANDLE) << ", " << split_k_buffer.offset << ", " << split_k_buffer.size << "), m: " << m << ", n: " << n << ", k: " << k << ", stride_a: " << stride_a << ", stride_b: " << stride_b << ", stride_d: " << stride_d << ", batch_stride_a: " << batch_stride_a << ", batch_stride_b: " << batch_stride_b << ", batch_stride_d: " << batch_stride_d << ", split_k: " << split_k << ", batch: " << batch << ", ne02: " << ne02 << ", ne12: " << ne12 << ", broadcast2: " << broadcast2 << ", broadcast3: " << broadcast3 << ", padded_n: " << padded_n << ")"); + if (stream_k_groups != 0) { + GGML_ASSERT(batch_stride_d == m * n); + if (ctx->prealloc_split_k_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_stream_k_fixup, 1); + + const uint32_t bm = pipeline->wg_denoms[0]; + const uint32_t bn = pipeline->wg_denoms[1]; + const uint32_t k_units_per_tile = k / 256; + const uint32_t blocks_m = m / bm; + const uint32_t blocks_n = n / bn; + const uint32_t total_work_units = blocks_m * blocks_n * batch * k_units_per_tile; + const uint32_t work_units_per_group = total_work_units / stream_k_groups; + const uint32_t groups_with_extra_unit = total_work_units % stream_k_groups; + + vk_mat_mat_push_constants pc1 = { + m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, 0, batch, k, ne02, ne12, broadcast2, broadcast3, padded_n, + k_units_per_tile, work_units_per_group, groups_with_extra_unit, + 0, 0, 0, 0, 0, 0, 0, 0 + }; + init_pushconst_fastdiv(pc1, blocks_m, blocks_n); + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, d, split_k_buffer }, pc1, { stream_k_groups * pipeline->wg_denoms[0], 1, 1 }); + ggml_vk_sync_buffers(ctx, subctx); + + vk_mat_mat_stream_k_fixup_push_constants pc2 = { + m, n, bm, bn, k_units_per_tile, blocks_m, blocks_n, work_units_per_group, groups_with_extra_unit, + 0, 0, 0, 0, 0, 0, 0 + }; + init_pushconst_fastdiv(pc2); + + ggml_vk_dispatch_pipeline(ctx, subctx, ctx->device->pipeline_matmul_stream_k_fixup, { split_k_buffer, d }, pc2, { stream_k_groups, bm, 1 }); + ctx->prealloc_split_k_need_sync = true; + return; + } + if (split_k == 1) { // a small tile can still produce more workgroups than the device allows on the n axis: // split the dispatch into n-chunks, shifting the B and D column windows @@ -6438,8 +6744,12 @@ void ggml_vk_matmul( while (base_work_group_z < batch) { uint32_t groups_z = std::min(batch - base_work_group_z, ctx->device->properties.limits.maxComputeWorkGroupCount[2]); - const vk_mat_mat_push_constants pc = { m, n_chunk, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k, ne02, ne12, broadcast2, broadcast3, uint32_t(padded_n - n_base) }; - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b_chunk, d_chunk }, pc, { m, n_chunk, groups_z }); + vk_mat_mat_push_constants pc = { + m, n_chunk, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k, ne02, ne12, broadcast2, broadcast3, uint32_t(padded_n - n_base), + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + init_pushconst_fastdiv(pc); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b_chunk, d_chunk, d_chunk }, pc, { m, n_chunk, groups_z }); base_work_group_z += groups_z; } } @@ -6462,9 +6772,13 @@ void ggml_vk_matmul( while (base_work_group_z < batch) { uint32_t groups_z = std::min(batch - base_work_group_z, ctx->device->properties.limits.maxComputeWorkGroupCount[2]); - const vk_mat_mat_push_constants pc1 = { m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k_split, ne02, ne12, broadcast2, broadcast3, padded_n }; + vk_mat_mat_push_constants pc1 = { + m, n, k, stride_a, stride_b, stride_d, batch_stride_a, batch_stride_b, batch_stride_d, base_work_group_z, batch, k_split, ne02, ne12, broadcast2, broadcast3, padded_n, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + init_pushconst_fastdiv(pc1); // Make sure enough workgroups get assigned for split k to work - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, groups_z }); + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { a, b, split_k_buffer, split_k_buffer }, pc1, { (CEIL_DIV(m, pipeline->wg_denoms[0]) * pipeline->wg_denoms[0]) * split_k, n, groups_z }); base_work_group_z += groups_z; } ggml_vk_sync_buffers(ctx, subctx); @@ -6518,10 +6832,11 @@ static bool ggml_vk_get_mul_mat_mat_f16acc(ggml_backend_vk_context * ctx, ggml_t return ctx->device->fp16 && prec_allows_f16; } -static const std::vector* ggml_vk_get_mul_mat_mat_pipeline_map( - ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec, bool mul_mat_id = false) { +static const std::vector * ggml_vk_get_mul_mat_mat_pipeline_map( + ggml_backend_vk_context * ctx, ggml_type src0_type, ggml_type src1_type, ggml_prec prec, + bool mul_mat_id = false, bool stream_k = false) { bool f16acc = ggml_vk_get_mul_mat_mat_f16acc(ctx, src0_type, src1_type, prec); - vk_matmul_pipeline_key key{src0_type, src1_type, mul_mat_id, f16acc}; + vk_matmul_pipeline_key key{src0_type, src1_type, mul_mat_id, f16acc, stream_k}; auto it = ctx->device->pipeline_matmul.find(key); if (it == ctx->device->pipeline_matmul.end() || it->second.empty()) { // Try without f16acc @@ -6894,25 +7209,50 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub const bool y_f32_kernel = y_kernel_type == GGML_TYPE_F32; const bool y_needs_reformat = !quantize_y && (!ggml_vk_dim01_contiguous(src1) || y_kernel_type != src1->type); - const std::vector* mmp_map = - ggml_vk_get_mul_mat_mat_pipeline_map(ctx, src0->type, y_kernel_type, ggml_prec_get_acc(dst)); + ggml_type mmp_type_a = src0->type; + const ggml_type mmp_type_b = y_kernel_type; + const std::vector * mmp_map = + ggml_vk_get_mul_mat_mat_pipeline_map(ctx, mmp_type_a, mmp_type_b, ggml_prec_get_acc(dst)); const bool qx_needs_dequant = mmp_map == nullptr || x_non_contig; const bool qy_needs_dequant = y_needs_reformat; if (qx_needs_dequant) { // dequant src0 to f16 - mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, f16_type, y_kernel_type, ggml_prec_get_acc(dst)); + mmp_type_a = f16_type; + mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, mmp_type_a, mmp_type_b, ggml_prec_get_acc(dst)); } GGML_ASSERT(mmp_map != nullptr); + const std::vector * regular_mmp_map = mmp_map; + bool use_stream_k = ctx->device->coopmat2 && !ctx->device->disable_stream_k && !disable_split_k; + if (use_stream_k) { + mmp_map = ggml_vk_get_mul_mat_mat_pipeline_map(ctx, mmp_type_a, mmp_type_b, ggml_prec_get_acc(dst), false, true); + if (mmp_map == nullptr) { + mmp_map = regular_mmp_map; + use_stream_k = false; + } + } + const uint32_t kpad = quantize_y ? 0 : ggml_vk_align_size(ne10, ggml_vk_guess_matmul_pipeline_align_map(ctx, *mmp_map, ne01, ne11, false)); const bool aligned = !quantize_y && ne10 == kpad && ne01 > 8 && ne11 > 8; + const bool needs_64b_indexing = ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange; + if (use_stream_k && !aligned) { + mmp_map = regular_mmp_map; + use_stream_k = false; + } vk_pipeline pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *mmp_map, ne01, ne11, aligned, false); - if (ggml_nbytes(src0) > ctx->device->properties.limits.maxStorageBufferRange) { + const bool narrow_n = mmp_map->back().narrow_n_max != 0 && ne11 <= mmp_map->back().narrow_n_max; + const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline, narrow_n); + const uint32_t stream_k_groups = use_stream_k ? ggml_vk_guess_stream_k_groups(ctx, pipeline, ne01, ne11, ne10, stride_d, ne12 * ne13, split_k, disable_split_k) : 0; + if (use_stream_k && stream_k_groups == 0) { + pipeline = ggml_vk_guess_matmul_pipeline_map(ctx, *regular_mmp_map, ne01, ne11, aligned, false); + } + + if (needs_64b_indexing) { pipeline = ggml_vk_get_64b_indexing_pipeline(ctx, pipeline); } @@ -6923,9 +7263,6 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub const uint64_t y_ne = padded_n * ne10 * ne12 * ne13; const uint64_t d_ne = ggml_nelements(dst); - const bool narrow_n = mmp_map->back().narrow_n_max != 0 && ne11 <= mmp_map->back().narrow_n_max; - const uint32_t split_k = ggml_vk_guess_split_k(ctx, ne01, ne11, ne10, disable_split_k, pipeline, narrow_n); - const uint64_t qx_sz = ggml_type_size(src0->type) * x_ne / ggml_blck_size(src0->type); const uint64_t qy_sz = ggml_type_size(src1->type) * y_ne / ggml_blck_size(src1->type); const uint64_t x_sz = !qx_needs_dequant ? qx_sz : sizeof(ggml_fp16_t) * x_ne; @@ -6953,12 +7290,13 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub to_q8_1 = ggml_vk_get_quantize_pipeline(ctx, GGML_TYPE_Q8_1); } + const uint64_t stream_k_size = stream_k_groups != 0 ? uint64_t(stream_k_groups) * pipeline->wg_denoms[0] * pipeline->wg_denoms[1] * sizeof(float) : 0; + const uint64_t split_k_size = stream_k_groups != 0 ? stream_k_size : (split_k > 1 ? d_sz * split_k : 0); { - const uint64_t split_k_size = split_k > 1 ? d_sz * split_k : 0; if ( (qx_needs_dequant && x_sz > ctx->device->properties.limits.maxStorageBufferRange) || (qy_needs_dequant && y_sz > ctx->device->properties.limits.maxStorageBufferRange) || - (split_k > 1 && split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) { + (split_k_size > ctx->device->properties.limits.maxStorageBufferRange)) { GGML_ABORT("Requested preallocation size is too large"); } if (qx_needs_dequant && ctx->prealloc_size_x < x_sz) { @@ -6969,7 +7307,7 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub ctx->prealloc_size_y = y_sz; ggml_vk_preallocate_buffers(ctx, subctx); } - if (split_k > 1 && ctx->prealloc_size_split_k < split_k_size) { + if (split_k_size != 0 && ctx->prealloc_size_split_k < split_k_size) { ctx->prealloc_size_split_k = split_k_size; ggml_vk_preallocate_buffers(ctx, subctx); } @@ -6984,7 +7322,7 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub if (quantize_y) { ggml_pipeline_request_descriptor_sets(ctx, to_q8_1, 1); } - if (split_k > 1) { + if (stream_k_groups == 0 && split_k > 1) { ggml_pipeline_request_descriptor_sets(ctx, ctx->device->pipeline_matmul_split_k_reduce, 1); } } @@ -7092,10 +7430,10 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub ggml_vk_matmul( ctx, subctx, pipeline, { d_X, x_buf_offset, x_range }, { d_Y, y_buf_offset, y_range }, - ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, d_sz * split_k }, + ggml_vk_subbuffer(ctx, d_D, d_buf_offset), { ctx->prealloc_split_k, 0, split_k_size }, ne01, ne11, ne10, ne10, ne10, stride_d, stride_batch_x, stride_batch_y, stride_batch_d, - split_k, ne12*ne13, ne02, ne12, r2, r3, padded_n, + split_k, stream_k_groups, ne12*ne13, ne02, ne12, r2, r3, padded_n, b_col_bytes, (uint64_t)dst->nb[1] ); // NOLINT @@ -7234,7 +7572,7 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& const ggml_type y_kernel_type = widen_bf16 ? GGML_TYPE_F32 : src1->type; const bool f16_f32_kernel = y_kernel_type == GGML_TYPE_F32; - bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && (swap_inputs || ggml_vk_src1_prec_allows_q8(dst)) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type); + bool quantize_y = ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && (swap_inputs || ggml_vk_src1_prec_allows_q8(dst)) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne11, ne10, src0->type); vk_pipeline to_fp16_vk_0 = nullptr; vk_pipeline to_fp16_vk_1 = nullptr; @@ -8302,7 +8640,7 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte const bool y_non_contig = !ggml_vk_dim01_contiguous(src1); const bool f16_f32_kernel = src1->type == GGML_TYPE_F32; - bool quantize_y = ctx->device->integer_dot_product && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type); + bool quantize_y = ctx->device->integer_dot_signed && src1->type == GGML_TYPE_F32 && ggml_is_contiguous(src1) && !y_non_contig && (ne11 * ne10) % 4 == 0 && ggml_vk_src1_prec_allows_q8(dst) && ggml_vk_should_use_mmvq(ctx->device, ne01, ne12, ne10, src0->type); vk_pipeline to_fp16_vk_0 = nullptr; vk_pipeline to_fp16_vk_1 = nullptr; @@ -10055,6 +10393,8 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return ctx->device->pipeline_arange_f32; } return nullptr; + case GGML_OP_SLEEP: + return ctx->device->pipeline_sleep; case GGML_OP_FILL: if (dst->type == GGML_TYPE_F32) { return ctx->device->pipeline_fill_f32; @@ -10969,6 +11309,7 @@ void ggml_vk_lightning_indexer(ggml_backend_vk_context * ctx, vk_context& subctx void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { const ggml_tensor * src_q = dst->src[0]; + const ggml_tensor * src_k = dst->src[1]; const ggml_tensor * src_v = dst->src[2]; const ggml_tensor * src_beta = dst->src[4]; @@ -10984,7 +11325,39 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const uint32_t s_off = S_v * H * n_tokens * n_seqs; - vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); + const ggml_tensor * src_g = dst->src[3]; + // RDNA3: the scan is faster below ~4k tokens + const uint32_t cm_min_tokens = ctx->device->architecture == AMD_RDNA3 ? 4096u : 64u; + const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) && + src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens; + + const bool use_cm2 = use_cm && ctx->device->coopmat2; + const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr; + bool use_v32 = use_cm && !use_cm2 && !have_v64 && ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr; + bool use_v128 = use_cm && !use_cm2 && !have_v64 && !use_v32; + const uint32_t nsm = ctx->device->shader_core_count; + if (use_cm && !use_cm2 && have_v64 && nsm != 0) { + const uint32_t wg64 = 2u * H * n_seqs; + // V=32 only pays off while V=64 leaves at least half the cores idle + use_v32 = ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr && 2u * wg64 <= nsm; + if (!use_v32 && ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) { + const uint32_t wg128 = H * n_seqs; + const uint32_t waves64 = (wg64 + nsm - 1) / nsm; + const uint32_t waves128 = (wg128 + nsm - 1) / nsm; + // prefer v128 when occupancy (wgs / (waves * nsm)) is at least as good + use_v128 = (uint64_t)wg128 * waves64 >= (uint64_t)wg64 * waves128; + } + } + + const uint32_t cm_V = use_cm2 ? GGML_VK_GDN_CM2_V : (use_v128 ? 128u : (use_v32 ? 32u : GGML_VK_GDN_CM_V)); + + vk_pipeline pipeline = use_v128 + ? ctx->device->pipeline_gated_delta_net_cm_v128 + : use_v32 ? ctx->device->pipeline_gated_delta_net_cm_v32 + : (use_cm ? ctx->device->pipeline_gated_delta_net_cm + : ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op)); GGML_ASSERT(pipeline != nullptr); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); @@ -10995,9 +11368,27 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); } + vk_subbuffer mirror_buf{}; + if (use_v128) { + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t blocks = (S_v / cm_V) * n_seqs * H; + const size_t scratch_size = (size_t)blocks * LDP * cm_V * 2u * sizeof(uint16_t); + if (ctx->prealloc_size_x < scratch_size) { + ctx->prealloc_size_x = scratch_size; + ggml_vk_preallocate_buffers(ctx, subctx); + } + if (ctx->prealloc_x_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size }; + } + const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); + const uint32_t sk1 = (uint32_t)(src_k->nb[1] / sizeof(float)); + const uint32_t sk2 = (uint32_t)(src_k->nb[2] / sizeof(float)); + const uint32_t sk3 = (uint32_t)(src_k->nb[3] / sizeof(float)); const uint32_t sv1 = (uint32_t)(src_v->nb[1] / sizeof(float)); const uint32_t sv2 = (uint32_t)(src_v->nb[2] / sizeof(float)); const uint32_t sv3 = (uint32_t)(src_v->nb[3] / sizeof(float)); @@ -11012,6 +11403,7 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_op_gated_delta_net_push_constants pc = { H, n_tokens, n_seqs, s_off, sq1, sq2, sq3, + sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neq1, rq3, @@ -11019,9 +11411,16 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, K }; - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, - pc, { H, n_seqs, S_v }); + if (use_v128) { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf}, + pc, std::array{ S_v / cm_V, n_seqs, H }); + ctx->prealloc_x_need_sync = true; + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, + pc, use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }); + } } void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { @@ -11291,6 +11690,31 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); } +static void ggml_vk_sleep(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { + VK_LOG_DEBUG("ggml_vk_sleep(dst=" << dst << ", us=" << ggml_get_op_params_i32(dst, 0) << ")"); + + // Vulkan does not specify the period of the shader realtime clock this assumes it matches the timestamp counter. + // A driver where this does not hold could sleep too short or too long by that ratio + const float ns_per_tick = ctx->device->properties.limits.timestampPeriod; + const uint64_t ns = 1000 * (uint64_t) ggml_get_op_params_i32(dst, 0); + const uint64_t ticks = std::min(ns_per_tick > 0.0f ? (uint64_t)(ns / ns_per_tick) : ns, std::numeric_limits::max()); + + vk_op_sleep_push_constants pc = { + (uint32_t) ticks, + }; + + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_SLEEP); + GGML_ASSERT(pipeline != nullptr); + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); + + // a single invocation spins, the buffer is bound only to keep the spin from being optimized out + std::array elements = { 1, 1, 1 }; + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); +} + void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst)); } @@ -13137,6 +13561,10 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_OP_FILL: ggml_vk_fill(ctx, compute_ctx, node); + break; + case GGML_OP_SLEEP: + ggml_vk_sleep(ctx, compute_ctx, node); + break; case GGML_OP_SCALE: if (ctx->fused_hc_post_gate) { @@ -16501,8 +16929,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_REPEAT_BACK: return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_ROPE: - return ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_VIEW: @@ -16588,6 +17017,8 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm return op->type == GGML_TYPE_F32; case GGML_OP_FILL: return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16; + case GGML_OP_SLEEP: + return device->shader_clock; case GGML_OP_SCALE: return ggml_is_contiguous(op->src[0]) && ggml_vk_is_float_elementwise(op); case GGML_OP_PAD: diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt index cbe7a68bf372..273a80233e61 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt @@ -15,6 +15,10 @@ if (GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) message(STATUS "Enabling coopmat2 decode_vector glslc support") endif() +if (GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + add_compile_definitions(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + message(STATUS "Enabling coopmat maintenance1 glslc support") +endif() if (GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) message(STATUS "Enabling dot glslc support") diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/diag.comp b/ggml/src/ggml-vulkan/vulkan-shaders/diag.comp index 790a5421d08f..8a9b219e6d72 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/diag.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/diag.comp @@ -22,6 +22,6 @@ void main() { if (i10 == i11) { data_d[get_doffset() + dst_idx(idx)] = D_TYPE(data_a[get_aoffset() + i13*p.nb03 + i12*p.nb02 + 0*p.nb01 + i10*p.nb00]); } else { - data_d[get_doffset() + dst_idx(idx)] = D_TYPE(0); + data_d[get_doffset() + dst_idx(idx)] = D_TYPE(0.0); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp new file mode 100644 index 000000000000..049ca2867393 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp @@ -0,0 +1,8 @@ +#version 460 + +#extension GL_KHR_cooperative_matrix : require +#extension GL_EXT_cooperative_matrix_maintenance1 : require + +void main() +{ +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index 0e384330b9b9..ad2ced78aa39 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -15,10 +15,19 @@ layout(constant_id = 0) const uint S_V = 128; layout(constant_id = 1) const uint KDA = 0; layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; +layout(constant_id = 4) const bool PACKED_ROWS = false; const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; +uint row_index(uint r, uint lane) { + // Keep four adjacent rows together in each lane. + if (PACKED_ROWS) { + return (r / 4u * LANES_PER_COLUMN + lane) * 4u + r % 4u; + } + return r * LANES_PER_COLUMN + lane; +} + layout(local_size_x_id = 2, local_size_y = 1, local_size_z = 1) in; layout(push_constant) uniform Parameters { @@ -27,6 +36,7 @@ layout(push_constant) uniform Parameters { uint n_seqs; uint s_off; uint sq1, sq2, sq3; + uint sk1, sk2, sk3; uint sv1, sv2, sv3; uint sb1, sb2, sb3; uint neq1, rq3; @@ -110,7 +120,7 @@ void main() { FLOAT_TYPE s_shard[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + r * LANES_PER_COLUMN + lane]); + s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); } // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. @@ -120,7 +130,7 @@ void main() { for (uint t = 0; t < n_tokens; t++) { const uint q_off = iq3 * sq3 + t * sq2 + iq1 * sq1; - const uint k_off = q_off; + const uint k_off = iq3 * sk3 + t * sk2 + iq1 * sk1; const uint v_off = seq_id * sv3 + t * sv2 + head_id * sv1; const uint gb_off = seq_id * sb3 + t * sb2 + head_id * sb1; const FLOAT_TYPE beta_val = FLOAT_TYPE(data_beta[gb_off]); @@ -128,7 +138,7 @@ void main() { FLOAT_TYPE k_reg[ROWS_PER_LANE]; FLOAT_TYPE q_reg[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); k_reg[r] = FLOAT_TYPE(data_k[k_off + i]); q_reg[r] = FLOAT_TYPE(data_q[q_off + i]); } @@ -142,7 +152,7 @@ void main() { } else { const uint g_base = gb_off * S_V; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); g_exp[r] = exp(FLOAT_TYPE(data_g[g_base + i])); } } @@ -175,7 +185,7 @@ void main() { if (target_slot >= 0 && target_slot < int(K)) { const uint slot_base = s_off + uint(target_slot) * state_size_per_snap + state_out_base; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[slot_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[slot_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } @@ -183,7 +193,7 @@ void main() { if (K == 1u) { [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[s_off + state_out_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp new file mode 100644 index 000000000000..c5b4e4084faf --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp @@ -0,0 +1,437 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : enable +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_cooperative_matrix : enable +#extension GL_EXT_cooperative_matrix_maintenance1 : enable + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1), port of CUDA PR 29353. +// State in register tiles, mirrored ([D x V]) for the projections. +// bf16 hi/lo 3x products for ~fp32 accuracy. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define TM 16 // tile rows +#define TN 16 // tile cols (bf16 cm has only m16n16k16; n8 would pad) +#ifndef V +#define V 64 // value columns per workgroup block (V=128 = whole head) +#endif +#define NSUB 16 // subgroups per workgroup +layout(constant_id = 0) const uint WGS = NSUB * 32; // NSUB * subgroup size +#define KT 16 // K-tile width for deep (K=D) matmuls (bf16 cm: m16n16k16 only) +#define PAD 8 // shared padding to break COL-load bank conflicts (keep LDP*2 a multiple of 16B) +#define LDP (D + PAD) + +// GMEM_MIRROR: state mirror in a gmem scratch buffer (too big for shared) + +#define STATE_TILES ((D / TM) * (V / TN)) +#define PER_WARP (STATE_TILES / NSUB) +#define VT (V / TN) // value tiles +#define CT (C / TN) // C-column tiles (gram/pmat halves) +const uint NQK = C * D / WGS; + +#define TILE_R(ti) (((ti) / VT) * TM) +#define TILE_C(ti) (((ti) % VT) * TN) + +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; +#ifdef GMEM_MIRROR +layout(binding = 7) coherent buffer MirrorBuf { OPD data_mirror[]; }; +#endif + +shared OPD sh_qh[C * LDP], sh_ql[C * LDP]; // q*scale hi/lo (D padded) +shared OPD sh_kh[C * LDP], sh_kl[C * LDP]; // k hi/lo (D padded) +#ifndef GMEM_MIRROR +shared OPD sh_sh[LDP * V], sh_sl[LDP * V]; // state mirror [D x V] column-major (D padded) +#endif +shared OPD sh_dh[C * V], sh_dl[C * V]; // delta (pre-inv) / delta2 [C x V] row-major +shared OPD sh_soh[C * V], sh_sol[C * V]; // solved [C x V] row-major +shared OPD sh_ph[C * C], sh_pl[C * C]; // decayed P +shared OPD sh_ih[C * C], sh_il[C * C]; // (I + L)^-1 +shared float sh_lower[C * C]; // strictly-lower decayed L + +shared float sh_prefix[C], sh_beta[C], sh_ep[C], sh_carry[C]; + +#define SG gl_ScopeSubgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + + +// 3x bf16 product accumulated into acc (hi/lo split for ~fp32 accuracy). +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); \ + acc = coopMatMulAdd(ah, bh, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +#ifdef BF16ACC +// split through a bf16 accumulator +#define SPLIT_STORE(m, arr_h, off_h, arr_l, off_l, ld, layout) { \ + const coopmat h_ = coopmat(m); \ + const coopmat l_ = coopmat(m - coopmat(h_)); \ + coopMatStore(h_, arr_h, off_h, ld, layout); \ + coopMatStore(l_, arr_l, off_l, ld, layout); \ +} + +#ifdef GMEM_MIRROR +#define STORE_MIRROR(m, off) SPLIT_STORE(m, data_mirror, mir_h + off, data_mirror, mir_l + off, LDP, COL) +#else +#define STORE_MIRROR(m, off) SPLIT_STORE(m, sh_sh, off, sh_sl, off, LDP, COL) +#endif +#define STORE_DELTA(m, off) SPLIT_STORE(m, sh_dh, off, sh_dl, off, V, ROW) +#define STORE_SOLVED(m, off) SPLIT_STORE(m, sh_soh, off, sh_sol, off, V, ROW) +#else +// split per element +#ifdef GMEM_MIRROR +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, data_mirror[idx], data_mirror[idx + LDP * V]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, mir_h + off) +#else +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, sh_sh[idx], sh_sl[idx]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, off) +#endif + +float SplitRowD(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_dh[idx], sh_dl[idx]); + return elem; +} + +float SplitRowSO(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_soh[idx], sh_sol[idx]); + return elem; +} + +#define STORE_DELTA(m, off) coopMatPerElementEXT(m, m, SplitRowD, off) +#define STORE_SOLVED(m, off) coopMatPerElementEXT(m, m, SplitRowSO, off) +#endif + +#ifdef GMEM_MIRROR +#define LOAD_S(h, l, off) \ + coopMatLoad(h, data_mirror, mir_h + off, LDP, COL); \ + coopMatLoad(l, data_mirror, mir_l + off, LDP, COL); +// mirror is workgroup-private +#define MIRROR_BARRIER() controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, \ + gl_StorageSemanticsBuffer | gl_StorageSemanticsShared, \ + gl_SemanticsAcquireRelease) +#else +#define LOAD_S(h, l, off) \ + coopMatLoad(h, sh_sh, off, LDP, COL); \ + coopMatLoad(l, sh_sl, off, LDP, COL); +#define MIRROR_BARRIER() barrier() +#endif + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (r < valid) { + data_dst[out_base + r * (D * p.H) + c] = elem; + } + return elem; +} + +float StoreState(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t base) { + data_dst[base + c * D + r] = elem; + return elem; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return r < valid ? data_v[v_base + r * sv2 + c] : 0.0; +} + +// sh_beta[r] == 0 for r >= valid +float ComputeDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, + const in float vv) { + return sh_beta[r] * (vv - sh_ep[r] * ks); +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[r] * qs; +} + +float StoreLower(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + if (cc < r) { + sh_lower[r * C + cc] = elem * exp(sh_prefix[r] - sh_prefix[cc]) * sh_beta[r]; + } + return elem; +} + +float StorePmat(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + float v = 0.0; + if (cc <= r) { + v = elem * exp(sh_prefix[r] - sh_prefix[cc]); + } + split(v, sh_ph[r * C + cc], sh_pl[r * C + cc]); + return elem; +} + +void prefetch(const uint t0, const uint iq1, const uint iq3, const uint seq_id, const uint head_id, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint n = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint t = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (t < n) { + const uint q_off = iq3 * p.sq3 + (t0 + t) * p.sq2 + iq1 * p.sq1 + i % D; + const uint k_off = iq3 * p.sk3 + (t0 + t) * p.sk2 + iq1 * p.sk1 + i % D; + q[j] = data_q[q_off] * p.scale; + k[j] = data_k[k_off]; + } + } + g = 0.0; + b = 0.0; + const uint t = gl_SubgroupInvocationID; + if (gl_SubgroupID == 0 && t < n) { + const uint gb = seq_id * p.sb3 + (t0 + t) * p.sb2 + head_id * p.sb1; + g = data_g[gb]; + b = data_beta[gb]; + } +} + +// sg0: gram K@K^T -> L, sg1: pmat Q@K^T -> P +void gram_pmat(const uint sg) { + const bool gram = sg < CT; + const uint c_o = (sg % CT) * TN; + coopmat x = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + if (gram) { + coopMatLoad(ah, sh_kh, kk, LDP, ROW); + coopMatLoad(al, sh_kl, kk, LDP, ROW); + } else { + coopMatLoad(ah, sh_qh, kk, LDP, ROW); + coopMatLoad(al, sh_ql, kk, LDP, ROW); + } + coopmat bh, bl; + coopMatLoad(bh, sh_kh, c_o * LDP + kk, LDP, COL); + coopMatLoad(bl, sh_kl, c_o * LDP + kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + if (gram) { + coopMatPerElementEXT(x, x, StoreLower, c_o); + } else { + coopMatPerElementEXT(x, x, StorePmat, c_o); + } +} + +// (I + L)^-1, forward substitution: subgroup per row, lane per column +void invert(const uint sg) { + const uint col = gl_SubgroupInvocationID; + [[unroll]] for (uint row = sg; row < C; row += NSUB) { + float x = col < C ? (col == row ? 1.0 : (col < row ? -sh_lower[row * C + col] : 0.0)) : 0.0; + for (int pivot = int(row) - 1; pivot > 0; pivot--) { + const float xp = subgroupShuffle(x, uint(pivot)); + if (col < uint(pivot)) { + x -= xp * sh_lower[uint(pivot) * C + col]; + } + } + if (col < C) { + split(x, sh_ih[row * C + col], sh_il[row * C + col]); + } + } +} + +float carry_decay(const uint valid) { + const float plast = sh_prefix[valid - 1]; + if (gl_LocalInvocationID.x < C) { + sh_carry[gl_LocalInvocationID.x] = exp(plast - sh_prefix[gl_LocalInvocationID.x]); + } + return exp(plast); +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint sg = gl_SubgroupID; + const uint tid = gl_LocalInvocationID.x; + const uint v0 = gl_WorkGroupID.x * V; + + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + + const uint state_base = (seq_id * p.H + head_id) * (D * D); + +#ifdef GMEM_MIRROR + const uint mir_stride = uint(LDP) * V; + const uint mir_block = (head_id * p.n_seqs + seq_id) * gl_NumWorkGroups.x + gl_WorkGroupID.x; + const uint mir_h = mir_block * mir_stride * 2u; + const uint mir_l = mir_h + mir_stride; +#endif + + coopmat state[PER_WARP]; + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatLoad(state[j], data_state, state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti), D, COL); + } + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + + for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + + barrier(); + if (sg == 0) { + const uint t = gl_SubgroupInvocationID; + const float acc = subgroupInclusiveAdd(greg); + if (t < C) { + sh_prefix[t] = acc; + sh_ep[t] = exp(acc); + sh_beta[t] = breg; + } + } + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = tid + j * WGS; + const uint pi = (i / D) * LDP + (i % D); + split(qreg[j], sh_qh[pi], sh_ql[pi]); + split(kreg[j], sh_kh[pi], sh_kl[pi]); + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + STORE_MIRROR(state[j], TILE_C(ti) * LDP + TILE_R(ti)); + } + MIRROR_BARRIER(); + + prefetch(t0 + C, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + const float cdecay = carry_decay(valid); + + // qs -> base_r and ks -> delta on sg2..2+VT-1 + coopmat base_r = coopmat(0); + if (sg < 2 * CT) { + gram_pmat(sg); + } else if (sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0 + c_o + t0 * p.sv2; + coopmat vmat = coopmat(0); + coopMatPerElementEXT(vmat, vmat, LoadV, v_base, p.sv2, valid); + coopmat qs = coopmat(0); + coopmat ks = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat qh, ql, kh, kl; + coopMatLoad(qh, sh_qh, kk, LDP, ROW); + coopMatLoad(ql, sh_ql, kk, LDP, ROW); + coopMatLoad(kh, sh_kh, kk, LDP, ROW); + coopMatLoad(kl, sh_kl, kk, LDP, ROW); + coopmat sbh, sbl; + LOAD_S(sbh, sbl, c_o * LDP + kk); + PRODUCT(qs, qh, ql, sbh, sbl); + PRODUCT(ks, kh, kl, sbh, sbl); + } + coopMatPerElementEXT(base_r, qs, ApplyExpPrefix); + coopmat delta; + coopMatPerElementEXT(delta, ks, ComputeDeltaV, vmat); + STORE_DELTA(delta, c_o); + } + barrier(); + + invert(sg); + barrier(); + + // solved = (I+L)^-1 @ delta (sg0..VT-1) + if (sg < VT) { + const uint c_o = sg * TN; + coopmat solved = coopmat(0); + coopmat ih, il; + coopMatLoad(ih, sh_ih, 0, C, ROW); + coopMatLoad(il, sh_il, 0, C, ROW); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, c_o, V, ROW); + coopMatLoad(dl, sh_dl, c_o, V, ROW); + PRODUCT(solved, ih, il, dh, dl); + STORE_SOLVED(solved, c_o); + } + barrier(); + + // out = base + P@solved (sg2..2+VT-1) + if (sg >= 2 * CT && sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + coopmat O = base_r; + coopmat ph, pl; + coopMatLoad(ph, sh_ph, 0, C, ROW); + coopMatLoad(pl, sh_pl, 0, C, ROW); + coopmat svh, svl; + coopMatLoad(svh, sh_soh, c_o, V, ROW); + coopMatLoad(svl, sh_sol, c_o, V, ROW); + PRODUCT(O, ph, pl, svh, svl); + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0 + c_o + t0 * (D * p.H); + coopMatPerElementEXT(O, O, StoreOut, out_base, valid); + } + // delta2 = solved * carry -> sh_dh/dl (all threads) + for (uint i = tid; i < C * V; i += WGS) { + const float sv = float(sh_soh[i]) + float(sh_sol[i]); + split(sv * sh_carry[i / V], sh_dh[i], sh_dl[i]); + } + barrier(); + + // state = cdecay*state + K^T @ delta2 + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopmat kth, ktl; + coopMatLoad(kth, sh_kh, TILE_R(ti), LDP, COL); + coopMatLoad(ktl, sh_kl, TILE_R(ti), LDP, COL); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, TILE_C(ti), V, ROW); + coopMatLoad(dl, sh_dl, TILE_C(ti), V, ROW); + state[j] = state[j] * cdecay; + PRODUCT(state[j], kth, ktl, dh, dl); + } + // no end-of-chunk barrier: covered by the chunk-top barrier + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatPerElementEXT(state[j], state[j], StoreState, + p.s_off + state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti)); + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp new file mode 100644 index 000000000000..270ef35db3a5 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp @@ -0,0 +1,320 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_cooperative_matrix : require +#extension GL_NV_cooperative_matrix2 : require + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1). +// BF16 hi/lo products use FP32 accumulators. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define V 32 // value columns per workgroup block +#define WGS 128 +#define NSUB (WGS / 32) +#define KT 32 // K-tile width for deep (K=D) matmuls +#define PAD 8 +#define LDP (D + PAD) +#define LDV (V + PAD) +#define KQ_ROWS (2 * C) +#define NQK (C * D / WGS) + +layout(local_size_x = WGS, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; + +// K and scaled Q occupy the two row blocks of one 32-row operand. +shared OPD sh_kqh[2 * C * LDP], sh_kql[2 * C * LDP]; +shared OPD sh_sh[V * LDP], sh_sl[V * LDP]; // state mirror [V x D] row-major (D padded) +shared OPD sh_ph[C * C], sh_pl[C * C]; +shared OPD sh_ih[C * C], sh_il[C * C]; +shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta / solved [C x V] row-major (V padded) +shared float sh_lower[C * (C - 1) / 2]; // packed strictly-lower Gram entries +shared float sh_prefix[C], sh_ep[C], sh_beta[C], sh_carry[C]; + +#define WG gl_ScopeWorkgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(ah, bh, acc); \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +float StoreGramPmat(const in uint32_t r, const in uint32_t c, const in float elem) { + if (r < C) { + if (c < r) { + sh_lower[r * (r - 1) / 2 + c] = elem * exp(sh_prefix[r] - sh_prefix[c]) * sh_beta[r]; + } + } else { + const uint row = r - C; + const float y = c <= row ? elem * exp(sh_prefix[row] - sh_prefix[c]) : 0.0; + split(y, sh_ph[row * C + c], sh_pl[row * C + c]); + } + return elem; +} + +float SplitRowS(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = r * LDP + c; + split(elem, sh_sh[i], sh_sl[i]); + return elem; +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[c] * qs; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return c < valid ? data_v[v_base + c * sv2 + r] : 0.0; +} + +float StoreDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, const in float vv) { + const float x = sh_beta[c] * (vv - sh_ep[c] * ks); + const uint i = c * LDV + r; + split(x, sh_dh[i], sh_dl[i]); + return ks; +} + +float StoreSolved(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = c * LDV + r; + split(elem, sh_dh[i], sh_dl[i]); + // The state mirror is no longer needed after KS/QS. + const uint j = r * LDP + c; + split(sh_carry[c] * elem, sh_sh[j], sh_sl[j]); + return elem; +} + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (c < valid) { + data_dst[out_base + c * (p.H * D) + r] = elem; + } + return elem; +} + +void prefetch(const uint t0, const uint q_base, const uint k_base, const uint gb_base, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint valid = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + const uint r = gl_SubgroupInvocationID; + g = 0.0; + b = 0.0; + if (gl_SubgroupID == 0 && r < valid) { + const uint off = gb_base + (t0 + r) * p.sb2; + g = data_g[off]; + b = data_beta[off]; + } + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (token < valid) { + const uint q_off = q_base + (t0 + token) * p.sq2 + i % D; + const uint k_off = k_base + (t0 + token) * p.sk2 + i % D; + q[j] = data_q[q_off]; + k[j] = data_k[k_off]; + } + } +} + +void stage_inputs(const in float q[NQK], const in float k[NQK]) { + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + const uint key = i % D; + const uint ki = token * LDP + key; + const uint qi = (C + token) * LDP + key; + split(k[j], sh_kqh[ki], sh_kql[ki]); + split(p.scale * q[j], sh_kqh[qi], sh_kql[qi]); + } +} + +// [K; Q] * K^T computes Gram and P in one 32-row matrix. +void gram_pmat() { + coopmat x = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat bh, bl; + coopMatLoad(ah, sh_kqh, kk, LDP, ROW); + coopMatLoad(al, sh_kql, kk, LDP, ROW); + coopMatLoad(bh, sh_kqh, kk, LDP, COL); + coopMatLoad(bl, sh_kql, kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + coopMatPerElementNV(x, x, StoreGramPmat); +} + +void invert() { + const uint col = gl_SubgroupInvocationID % C; + // Each half-subgroup covers all columns of its assigned rows. + const uint section = gl_SubgroupInvocationID / C; + const uint row_base = (gl_SubgroupID * 2u + section) * (C / (2 * NSUB)); + // Keep the diagonal zero so pivots at or above the row do nothing. + float x[C / (2 * NSUB)]; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + x[j] = col < row ? -sh_lower[row * (row - 1) / 2 + col] : 0.0; + } + [[dont_unroll]] for (int pivot = C - 2; pivot > 0; --pivot) { + const float lower = col < uint(pivot) ? sh_lower[uint(pivot) * uint(pivot - 1) / 2 + col] : 0.0; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const float xp = subgroupShuffle(x[j], uint(pivot) + section * C); + x[j] -= xp * lower; + } + } + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + split(col == row ? 1.0 : x[j], sh_ih[row * C + col], sh_il[row * C + col]); + } +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint v0 = gl_WorkGroupID.x * V; + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + const uint q_base = iq3 * p.sq3 + iq1 * p.sq1; + const uint k_base = iq3 * p.sk3 + iq1 * p.sk1; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0; + const uint gb_base = seq_id * p.sb3 + head_id * p.sb1; + const uint state_base = (seq_id * p.H + head_id) * (D * D) + v0 * D; + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0; + + // Transposing the state-side products gives them V=32 rows with C=16 columns. + coopmat state; + coopMatLoad(state, data_state, state_base, D, ROW); + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + [[dont_unroll]] for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + barrier(); + if (gl_SubgroupID == 0) { + const uint r = gl_SubgroupInvocationID; + // shuffle scan instead of subgroupInclusiveAdd: works around an NVIDIA r620 shader compiler crash + float sum = greg; + [[unroll]] for (uint d = 1; d < C; d <<= 1) { + const float t = subgroupShuffleUp(sum, d); + if (r >= d) { + sum += t; + } + } + const float last = subgroupShuffle(sum, valid - 1); + if (r < C) { + sh_prefix[r] = sum; + sh_ep[r] = exp(sum); + sh_beta[r] = breg; + sh_carry[r] = exp(last - sum); + } + } + stage_inputs(qreg, kreg); + coopmat vmat; + if (valid == C && (v_base % 4u) == 0 && (p.sv2 % 4u) == 0) { + coopMatLoad(vmat, data_v, v_base + t0 * p.sv2, p.sv2, COL); + } else { + vmat = coopmat(0.0); + coopMatPerElementNV(vmat, vmat, LoadV, v_base + t0 * p.sv2, p.sv2, valid); + } + barrier(); + // Current inputs are in shared memory; keep the next chunk in registers. + prefetch(t0 + C, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + gram_pmat(); + barrier(); + invert(); + coopMatPerElementNV(state, state, SplitRowS); + barrier(); + + coopmat ks = coopmat(0.0), base_r = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat kh, kl, qh, ql; + coopMatLoad(ah, sh_sh, kk, LDP, ROW); + coopMatLoad(al, sh_sl, kk, LDP, ROW); + coopMatLoad(kh, sh_kqh, kk, LDP, COL); + coopMatLoad(kl, sh_kql, kk, LDP, COL); + coopMatLoad(qh, sh_kqh, C * LDP + kk, LDP, COL); + coopMatLoad(ql, sh_kql, C * LDP + kk, LDP, COL); + PRODUCT(ks, ah, al, kh, kl); + PRODUCT(base_r, ah, al, qh, ql); + } + coopMatPerElementNV(base_r, base_r, ApplyExpPrefix); + coopMatPerElementNV(ks, ks, StoreDeltaV, vmat); + barrier(); + + coopmat solved = coopmat(0.0); + { + coopmat rh, rl; + coopmat ih, il; + coopMatLoad(rh, sh_dh, 0, LDV, COL); + coopMatLoad(rl, sh_dl, 0, LDV, COL); + coopMatLoad(ih, sh_ih, 0, C, COL); + coopMatLoad(il, sh_il, 0, C, COL); + PRODUCT(solved, rh, rl, ih, il); + } + barrier(); + coopMatPerElementNV(solved, solved, StoreSolved); + barrier(); + + { + coopmat xh, xl; + coopmat ph, pl; + coopMatLoad(xh, sh_dh, 0, LDV, COL); + coopMatLoad(xl, sh_dl, 0, LDV, COL); + coopMatLoad(ph, sh_ph, 0, C, COL); + coopMatLoad(pl, sh_pl, 0, C, COL); + PRODUCT(base_r, xh, xl, ph, pl); + } + coopMatPerElementNV(base_r, base_r, StoreOut, out_base + t0 * (p.H * D), valid); + + coopmat xh, xl; + coopmat kh, kl; + coopMatLoad(xh, sh_sh, 0, LDP, ROW); + coopMatLoad(xl, sh_sl, 0, LDP, ROW); + coopMatLoad(kh, sh_kqh, 0, LDP, ROW); + coopMatLoad(kl, sh_kql, 0, LDP, ROW); + state *= sh_ep[valid - 1]; + PRODUCT(state, xh, xl, kh, kl); + } + + coopMatStore(state, data_dst, p.s_off + state_base, D, ROW); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_stream_k_fixup.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_stream_k_fixup.comp new file mode 100644 index 000000000000..c8a1961569be --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mat_stream_k_fixup.comp @@ -0,0 +1,86 @@ +#version 450 + +#include "utils.glsl" + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; + +layout (binding = 0) readonly buffer S4 {vec4 data_s4[];}; +layout (binding = 1) buffer D4 {vec4 data_d4[];}; + +layout (push_constant) uniform parameter { + uint M; + uint N; + uint BM; + uint BN; + uint k_units_per_tile; + uint blocks_m; + uint blocks_n; + uint work_units_per_group; + uint groups_with_extra_unit; + uint k_units_mp; + uint blocks_m_mp; + uint blocks_n_mp; + uint work_units_mp; + uint large_group_work_mp; + uint div_Ls0; + uint div_Ls1; +} p; + +const uint RESOLVE_ROWS = 32; + +// A normal matmul workgroup accumulates one BM x BN output tile over the full K range. +// Stream-K divides that accumulation into work units. Each work unit covers 256 consecutive K values and produces a BM x BN partial sum. +// Work units are ordered [K unit, M tile, N tile, batch] and divided into one contiguous range per main workgroup. +// A main workgroup writes its partial sum to D when it reaches the end of an output tile, or to scratch when its range stops within a tile. +// Scratch has shape [BM, BN, stream_k_groups] and stores float partial sums. +// Element [r, c, g] is workgroup g's contribution to local output element [r, c] in the last output tile of its range. +// The output tile for each scratch slot is derived from the workgroup's range and is not stored in scratch. +// Only the last output tile in a workgroup's range can stop early, so one scratch slot is enough. +// Fixup workgroup (x, y) handles main workgroup x and rows 32*y through 32*y+31. +// If main workgroup x starts within a tile and completes it, fixup adds the earlier groups' partial sums from scratch to D. + +// Find the main workgroup whose range contains work. +// With q = work_units_per_group and r = groups_with_extra_unit, the first r workgroups get q + 1 units and all others get q. +// group(work) = work / (q + 1) when work < r*(q + 1), otherwise r + (work - r*(q + 1))/q. +uint group_for_work(uint work) { + const uint large_group_work = p.work_units_per_group + 1; + const uint large_work = large_group_work * p.groups_with_extra_unit; + if (work < large_work) { + return fastdiv(work, p.large_group_work_mp, fastdiv_L(p.div_Ls1, 1)); + } + return p.groups_with_extra_unit + fastdiv(work - large_work, p.work_units_mp, fastdiv_L(p.div_Ls1, 0)); +} + +void main() { + const uint group_idx = gl_WorkGroupID.x; + const uint work_unit = group_idx * p.work_units_per_group + min(group_idx, p.groups_with_extra_unit); + const uint work_unit_end = work_unit + p.work_units_per_group + uint(group_idx < p.groups_with_extra_unit); + + const uint tile_idx = fastdiv(work_unit, p.k_units_mp, fastdiv_L(p.div_Ls0, 0)); + const uint tile_work = tile_idx * p.k_units_per_tile; + // Only a range that starts within a tile and completes it needs fixup. + if (work_unit == tile_work || work_unit_end < tile_work + p.k_units_per_tile) { + return; + } + + const uint first_group = group_for_work(tile_work); + const uint outer_tile = fastdiv(tile_idx, p.blocks_m_mp, fastdiv_L(p.div_Ls0, 1)); + const uint ir = tile_idx - outer_tile * p.blocks_m; + const uint batch_idx = fastdiv(outer_tile, p.blocks_n_mp, fastdiv_L(p.div_Ls0, 2)); + const uint ic = outer_tile - batch_idx * p.blocks_n; + const uint row_base = gl_WorkGroupID.y * RESOLVE_ROWS; + + for (uint stripe_elem = gl_LocalInvocationIndex * 4; stripe_elem < RESOLVE_ROWS * p.BN; stripe_elem += gl_WorkGroupSize.x * 4) { + const uint r = row_base + (stripe_elem & (RESOLVE_ROWS - 1)); + const uint c = stripe_elem / RESOLVE_ROWS; + const uint elem_idx = c * p.BM + r; + const uint dst_idx = batch_idx * p.M * p.N + (ic * p.BN + c) * p.M + ir * p.BM + r; + + // D contains the completing segment. Add the earlier segments from scratch. + vec4 result = data_d4[dst_idx / 4]; + for (uint previous_group = first_group; previous_group < group_idx; ++previous_group) { + result += data_s4[(previous_group * p.BM * p.BN + elem_idx) / 4]; + } + data_d4[dst_idx / 4] = result; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp index 19d37870bd69..68de7637347e 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm.comp @@ -38,6 +38,7 @@ layout (constant_id = 12) const uint MmTypeA = 0; #include "types.glsl" #include "dot_product_funcs.glsl" +#include "utils.glsl" #ifndef MULMAT_QUANT #ifndef LOAD_VEC_A @@ -121,6 +122,9 @@ layout (binding = 0) readonly buffer BUF_Q5_K_P32 { block_q5_K_packed32 data[] layout (binding = 1) readonly buffer B {B_TYPE data_b[];}; layout (binding = 1) readonly buffer B_SCALAR {B_TYPE_SCALAR data_b_scalar[];}; layout (binding = 2) writeonly buffer D {D_TYPE data_d[];}; +#ifndef MUL_MAT_ID +layout (binding = 3) writeonly buffer S {D_TYPE data_s[];}; +#endif #ifdef MUL_MAT_ID layout (binding = 3) readonly buffer IDS {int data_ids[];}; @@ -155,6 +159,18 @@ layout (push_constant) uniform parameter uint ne12; uint broadcast2; uint broadcast3; + uint padded_N; + uint k_units_per_tile; + uint work_units_per_group; + uint groups_with_extra_unit; + uint k_units_mp; + uint blocks_m_mp; + uint blocks_n_mp; + uint ne12_mp; + uint broadcast2_mp; + uint broadcast3_mp; + uint div_Ls0; + uint div_Ls1; #endif } p; @@ -189,6 +205,9 @@ layout(constant_id = 13) const bool APPLY_SLM_A_RESHAPE = false; const uint SHMEM_STRIDE_PAD = 1; const bool APPLY_SLM_A_RESHAPE = false; #endif +#ifndef MUL_MAT_ID +layout(constant_id = 15) const bool stream_k = false; +#endif #define SHMEM_STRIDE (BK / 2 + SHMEM_STRIDE_PAD) shared FLOAT_TYPEV2 buf_a[BM * SHMEM_STRIDE]; @@ -218,27 +237,24 @@ void main() { _ne1 = data_row_map[2 + 2 * tile_idx]; const uint ic = 0; #else - const uint ic = gl_WorkGroupID.y; + const uint group_idx = gl_WorkGroupID.x; + uint stream_k_work_unit; + uint stream_k_work_unit_end; + + if (stream_k) { + stream_k_work_unit = group_idx * p.work_units_per_group + min(group_idx, p.groups_with_extra_unit); + stream_k_work_unit_end = stream_k_work_unit + p.work_units_per_group + uint(group_idx < p.groups_with_extra_unit); + } #endif #if defined(NEEDS_INIT_IQ_SHMEM) || defined(MULMAT_QUANT) init_iq_shmem(gl_WorkGroupSize); #endif -#ifndef MUL_MAT_ID - const uint batch_idx = gl_WorkGroupID.z + p.base_work_group_z; - - const uint i13 = batch_idx / p.ne12; - const uint i12 = batch_idx % p.ne12; - - const uint i03 = i13 / p.broadcast3; - const uint i02 = i12 / p.broadcast2; - - const uint batch_idx_a = i03 * p.ne02 + i02; -#endif - +#ifdef MUL_MAT_ID const uint blocks_m = (p.M + BM - 1) / BM; const uint ir = gl_WorkGroupID.x % blocks_m; const uint ik = gl_WorkGroupID.x / blocks_m; +#endif const uint WNITER = (WM * WN) / (WARP * TM * TN * WMITER); const uint WSUBM = WM / WMITER; @@ -288,6 +304,41 @@ void main() { const uint loadstride_a = gl_WorkGroupSize.x * LOAD_VEC_A_EFF * LOAD_VEC_BATCH_A / BK; const uint loadstride_b = gl_WorkGroupSize.x * LOAD_VEC_B_EFF * LOAD_VEC_BATCH_B / BK; +#ifndef MUL_MAT_ID + do { + uint stream_k_tile_k_unit; + uint stream_k_tile_k_units; + uint ir; + uint ic; + uint batch_idx; + uint ik; + + if (stream_k) { + const uint tile_idx = fastdiv(stream_k_work_unit, p.k_units_mp, fastdiv_L(p.div_Ls0, 0)); + stream_k_tile_k_unit = stream_k_work_unit - tile_idx * p.k_units_per_tile; + stream_k_tile_k_units = min(stream_k_work_unit_end - stream_k_work_unit, p.k_units_per_tile - stream_k_tile_k_unit); + + const uint blocks_m = p.M / BM; + const uint blocks_n = p.N / BN; + const uint outer_tile = fastdiv(tile_idx, p.blocks_m_mp, fastdiv_L(p.div_Ls0, 1)); + ir = tile_idx - outer_tile * blocks_m; + batch_idx = fastdiv(outer_tile, p.blocks_n_mp, fastdiv_L(p.div_Ls0, 2)); + ic = outer_tile - batch_idx * blocks_n; + } else { + const uint blocks_m = (p.M + BM - 1) / BM; + ic = gl_WorkGroupID.y; + batch_idx = gl_WorkGroupID.z + p.base_work_group_z; + ir = group_idx % blocks_m; + ik = group_idx / blocks_m; + } + + const uint i13 = fastdiv(batch_idx, p.ne12_mp, fastdiv_L(p.div_Ls1, 0)); + const uint i12 = batch_idx - i13 * p.ne12; + const uint i03 = fastdiv(i13, p.broadcast3_mp, fastdiv_L(p.div_Ls1, 2)); + const uint i02 = fastdiv(i12, p.broadcast2_mp, fastdiv_L(p.div_Ls1, 1)); + const uint batch_idx_a = i03 * p.ne02 + i02; +#endif + #ifdef MUL_MAT_ID load_row_ids(row_begin); uint required_work_items = _ne1 * BK / LOAD_VEC_B_EFF / LOAD_VEC_BATCH_B; @@ -298,8 +349,15 @@ void main() { const uint start_k = 0; const uint end_k = p.K; #else - const uint start_k = ik * p.k_split; - const uint end_k = min(p.K, (ik + 1) * p.k_split); + uint start_k; + uint end_k; + if (stream_k) { + start_k = stream_k_tile_k_unit * 256; + end_k = (stream_k_tile_k_unit + stream_k_tile_k_units) * 256; + } else { + start_k = ik * p.k_split; + end_k = min(p.K, (ik + 1) * p.k_split); + } #endif uint pos_a = @@ -438,7 +496,17 @@ void main() { const uint dc = ic * BN + warp_c * WN; #ifndef MUL_MAT_ID - const uint offsets = batch_idx * p.batch_stride_d + ik * p.batch_stride_d * p.num_batches; + uint offsets = batch_idx * p.batch_stride_d; + if (!stream_k) { + offsets += ik * p.batch_stride_d * p.num_batches; + } +#endif + +#ifndef MUL_MAT_ID + bool stream_k_store_scratch; + if (stream_k) { + stream_k_store_scratch = stream_k_tile_k_unit + stream_k_tile_k_units != p.k_units_per_tile; + } #endif #ifdef COOPMAT @@ -462,36 +530,44 @@ void main() { } } #else - const bool is_aligned = p.stride_d % 4 == 0; // Assumption: D_TYPE == float - [[unroll]] for (uint cm_row = 0; cm_row < cms_per_row; cm_row++) { [[unroll]] for (uint cm_col = 0; cm_col < cms_per_col; cm_col++) { - const bool is_in_bounds = dr + (cm_row + 1) * TM <= p.M && dc + (cm_col + 1) * TN <= p.N; - - if (is_aligned && is_in_bounds) { - // Full coopMat is within bounds and stride_d is aligned with 16B - coopmat cm_dtype = coopmat(sums[cm_col * cms_per_row + cm_row]); - coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); - } else if (is_in_bounds) { - // Full coopMat is within bounds, but stride_d is not aligned - coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); - - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); - [[unroll]] for (uint col = 0; col < TN; col += storestride) { - data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + coopmat cm_dtype = coopmat(sums[cm_col * cms_per_row + cm_row]); + if (stream_k) { + if (stream_k_store_scratch) { + const uint scratch_offset = group_idx * BM * BN + (warp_c * WN + cm_col * TN) * BM + warp_r * WM + cm_row * TM; + coopMatStore(cm_dtype, data_s, scratch_offset, BM, gl_CooperativeMatrixLayoutColumnMajor); + } else { + coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); } - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); - } else if (dr + cm_row * TM < p.M && dc + cm_col * TN < p.N) { - // Partial coopMat is within bounds - coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); - - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); - [[unroll]] for (uint col = 0; col < TN; col += storestride) { - if (dr + cm_row * TM + store_r < p.M && dc + cm_col * TN + col + store_c < p.N) { + } else { + const bool is_aligned = p.stride_d % 4 == 0; // Assumption: D_TYPE == float + const bool is_in_bounds = dr + (cm_row + 1) * TM <= p.M && dc + (cm_col + 1) * TN <= p.N; + + if (is_aligned && is_in_bounds) { + // Full coopMat is within bounds and stride_d is aligned with 16B + coopMatStore(cm_dtype, data_d, offsets + (dc + cm_col * TN) * p.stride_d + dr + cm_row * TM, p.stride_d, gl_CooperativeMatrixLayoutColumnMajor); + } else if (is_in_bounds) { + // Full coopMat is within bounds, but stride_d is not aligned + coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint col = 0; col < TN; col += storestride) { data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + } else if (dr + cm_row * TM < p.M && dc + cm_col * TN < p.N) { + // Partial coopMat is within bounds + coopMatStore(sums[cm_col * cms_per_row + cm_row], coopmat_stage, warp_i * TM * TN, TM, gl_CooperativeMatrixLayoutColumnMajor); + + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); + [[unroll]] for (uint col = 0; col < TN; col += storestride) { + if (dr + cm_row * TM + store_r < p.M && dc + cm_col * TN + col + store_c < p.N) { + data_d[offsets + (dc + cm_col * TN + col + store_c) * p.stride_d + dr + cm_row * TM + store_r] = D_TYPE(coopmat_stage[warp_i * TM * TN + (col + store_c) * TM + store_r]); + } + } + controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); } - controlBarrier(gl_ScopeSubgroup, gl_ScopeSubgroup, gl_StorageSemanticsShared, gl_SemanticsAcquireRelease); } } } @@ -519,11 +595,22 @@ void main() { data_d[row_idx.y * p.batch_stride_d + row_idx.x * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); } #else - if (dr_warp + 2 * cr < p.M && dc_warp + cc < p.N) { - data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr] = D_TYPE(sums[sums_idx].x); - } - if (dr_warp + 2 * cr + 1 < p.M && dc_warp + cc < p.N) { - data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); + if (stream_k) { + const uint scratch_offset = group_idx * BM * BN + (dc_warp + cc - ic * BN) * BM + dr_warp + 2 * cr - ir * BM; + if (stream_k_store_scratch) { + data_s[scratch_offset] = D_TYPE(sums[sums_idx].x); + data_s[scratch_offset + 1] = D_TYPE(sums[sums_idx].y); + } else { + data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr] = D_TYPE(sums[sums_idx].x); + data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); + } + } else { + if (dr_warp + 2 * cr < p.M && dc_warp + cc < p.N) { + data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr] = D_TYPE(sums[sums_idx].x); + } + if (dr_warp + 2 * cr + 1 < p.M && dc_warp + cc < p.N) { + data_d[offsets + (dc_warp + cc) * p.stride_d + dr_warp + 2 * cr + 1] = D_TYPE(sums[sums_idx].y); + } } #endif // MUL_MAT_ID } @@ -531,4 +618,10 @@ void main() { } } #endif // COOPMAT +#ifndef MUL_MAT_ID + if (stream_k) { + stream_k_work_unit += stream_k_tile_k_units; + } + } while (stream_k && stream_k_work_unit < stream_k_work_unit_end); +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_cm2.comp index dad9260b9894..1416cf72a82c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_cm2.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mm_cm2.comp @@ -61,6 +61,10 @@ uint mm_quant_k() { } #endif +#ifndef MUL_MAT_ID +layout (constant_id = 15) const bool stream_k = false; +#endif + layout (push_constant) uniform parameter { uint M; @@ -91,6 +95,17 @@ layout (push_constant) uniform parameter uint broadcast3; // N dimension for the B matrix can be >= p.N uint padded_N; + uint k_units_per_tile; + uint work_units_per_group; + uint groups_with_extra_unit; + uint k_units_mp; + uint blocks_m_mp; + uint blocks_n_mp; + uint ne12_mp; + uint broadcast2_mp; + uint broadcast3_mp; + uint div_Ls0; + uint div_Ls1; #endif } p; @@ -102,6 +117,9 @@ layout (binding = 0) readonly buffer A {uint8_t data_a[];}; #endif layout (binding = 1) readonly buffer B {B_TYPE data_b[];}; layout (binding = 2) writeonly buffer D {D_TYPE data_d[];}; +#ifndef MUL_MAT_ID +layout (binding = 3) writeonly buffer S {D_TYPE data_s[];}; +#endif #if defined(MUL_MAT_ID) && defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR) layout (binding = 1) readonly buffer B4 {B_TYPEV4 data_b_v4[];}; #endif @@ -261,6 +279,17 @@ void main() { const uint row_begin = tile_idx * BN; _ne1 = data_row_map[2 + 2 * tile_idx]; const uint ic = 0; +#else + const uint group_idx = gl_WorkGroupID.x; + uint stream_k_work_unit; + uint stream_k_work_unit_end; + + if (stream_k) { + // A work unit covers 256 consecutive K elements of one output tile. + // Work units are flattened as [K unit, M tile, N tile, batch]. + stream_k_work_unit = group_idx * p.work_units_per_group + min(group_idx, p.groups_with_extra_unit); + stream_k_work_unit_end = stream_k_work_unit + p.work_units_per_group + uint(group_idx < p.groups_with_extra_unit); + } #endif #ifdef MUL_MAT_ID @@ -278,43 +307,61 @@ void main() { #endif #ifndef MUL_MAT_ID - const uint batch_idx = gl_WorkGroupID.z + p.base_work_group_z; - - const uint i13 = batch_idx / p.ne12; - const uint i12 = batch_idx % p.ne12; - - const uint i03 = i13 / p.broadcast3; - const uint i02 = i12 / p.broadcast2; + do { + uint stream_k_tile_k_unit; + uint stream_k_tile_k_units; + uint ir; + uint ic; + uint batch_idx; + uint ik; + + if (stream_k) { + // The 256-element granularity does not split any supported quant block. + const uint tile_idx = fastdiv(stream_k_work_unit, p.k_units_mp, fastdiv_L(p.div_Ls0, 0)); + stream_k_tile_k_unit = stream_k_work_unit - tile_idx * p.k_units_per_tile; + stream_k_tile_k_units = min(stream_k_work_unit_end - stream_k_work_unit, p.k_units_per_tile - stream_k_tile_k_unit); + + const uint blocks_m = p.M / BM; + const uint blocks_n = p.N / BN; + const uint outer_tile = fastdiv(tile_idx, p.blocks_m_mp, fastdiv_L(p.div_Ls0, 1)); + ir = tile_idx - outer_tile * blocks_m; + batch_idx = fastdiv(outer_tile, p.blocks_n_mp, fastdiv_L(p.div_Ls0, 2)); + ic = outer_tile - batch_idx * blocks_n; + } else { + const uint blocks_m = (p.M + BM - 1) / BM; + // L2-friendly workgroup scheduling + const uint blocks_n = (p.N + BN - 1) / BN; +#if defined(MULMAT_QUANT) + const uint a_panel_bytes = (BM * p.K / mm_quant_k()) * MmABlockBytes; +#elif defined(DATA_A_F32) + const uint a_panel_bytes = BM * p.K * 4; +#elif QUANT_K == 1 + const uint a_panel_bytes = BM * p.K * 2; +#else + const uint a_panel_bytes = (BM * p.K) / 2 + (BM * p.K) / 16; +#endif + const uint group_m = clamp(GROUP_A_BUDGET / max(a_panel_bytes, 1u), 1u, min(blocks_m, 32u)); + const uint tiles_per_group = group_m * blocks_n; + const uint lin = gl_WorkGroupID.y * blocks_m + (gl_WorkGroupID.x % blocks_m); + const uint group_id = lin / tiles_per_group; + const uint first_m = group_id * group_m; + const uint gsize = min(blocks_m - first_m, group_m); + const uint in_group = lin - group_id * tiles_per_group; + ir = first_m + in_group % gsize; + ic = in_group / gsize; + batch_idx = gl_WorkGroupID.z + p.base_work_group_z; + ik = group_idx / blocks_m; + } + const uint i13 = fastdiv(batch_idx, p.ne12_mp, fastdiv_L(p.div_Ls1, 0)); + const uint i12 = batch_idx - i13 * p.ne12; + const uint i03 = fastdiv(i13, p.broadcast3_mp, fastdiv_L(p.div_Ls1, 2)); + const uint i02 = fastdiv(i12, p.broadcast2_mp, fastdiv_L(p.div_Ls1, 1)); const uint batch_idx_a = i03 * p.ne02 + i02; -#endif - +#else const uint blocks_m = (p.M + BM - 1) / BM; const uint ik = gl_WorkGroupID.x / blocks_m; - -#ifdef MUL_MAT_ID const uint ir = gl_WorkGroupID.x % blocks_m; -#else - // L2-friendly workgroup scheduling - const uint blocks_n = (p.N + BN - 1) / BN; -#if defined(MULMAT_QUANT) - const uint a_panel_bytes = (BM * p.K / mm_quant_k()) * MmABlockBytes; -#elif defined(DATA_A_F32) - const uint a_panel_bytes = BM * p.K * 4; -#elif QUANT_K == 1 - const uint a_panel_bytes = BM * p.K * 2; -#else - const uint a_panel_bytes = (BM * p.K) / 2 + (BM * p.K) / 16; -#endif - const uint group_m = clamp(GROUP_A_BUDGET / max(a_panel_bytes, 1u), 1u, min(blocks_m, 32u)); - const uint tiles_per_group = group_m * blocks_n; - const uint lin = gl_WorkGroupID.y * blocks_m + (gl_WorkGroupID.x % blocks_m); - const uint group_id = lin / tiles_per_group; - const uint first_m = group_id * group_m; - const uint gsize = min(blocks_m - first_m, group_m); - const uint in_group = lin - group_id * tiles_per_group; - const uint ir = first_m + in_group % gsize; - const uint ic = in_group / gsize; #endif #ifdef MUL_MAT_ID @@ -325,8 +372,15 @@ void main() { uint start_k = 0; const uint end_k = p.K; #else - uint start_k = ik * p.k_split; - const uint end_k = min(p.K, (ik + 1) * p.k_split); + uint start_k; + uint end_k; + if (stream_k) { + start_k = stream_k_tile_k_unit * 256; + end_k = (stream_k_tile_k_unit + stream_k_tile_k_units) * 256; + } else { + start_k = ik * p.k_split; + end_k = min(p.K, (ik + 1) * p.k_split); + } #endif #ifdef MULMAT_QUANT @@ -341,7 +395,10 @@ void main() { #else uint pos_a = batch_idx_a * (p.batch_stride_a / qk); uint pos_b = batch_idx * p.batch_stride_b; - uint pos_d = batch_idx * p.batch_stride_d + ik * p.batch_stride_d * p.num_batches; + uint pos_d = batch_idx * p.batch_stride_d; + if (!stream_k) { + pos_d += ik * p.batch_stride_d * p.num_batches; + } #endif #ifdef MULMAT_QUANT @@ -404,12 +461,15 @@ void main() { const uint UNROLL_K = (qk == 256) ? 256 : (BK * 8); const uint unroll_count = UNROLL_K / BK; - // Detect a fast path where all loads are entirely in bounds and no clamping is required - if ((ir + 1) * BM <= p.M && (ic + 1) * BN <= p.padded_N && (start_k % START_ALIGN_K) == 0 && (end_k % BK) == 0 && + bool fast_path = stream_k; + if (!stream_k) { + fast_path = (ir + 1) * BM <= p.M && (ic + 1) * BN <= p.padded_N && (start_k % START_ALIGN_K) == 0 && (end_k % BK) == 0 && #if !defined(MULMAT_QUANT) && QUANT_K == 1 - (stride_a % 8) == 0 && + (stride_a % 8) == 0 && #endif - (stride_b % 8) == 0) { + (stride_b % 8) == 0; + } + if (fast_path) { // Hint to the compiler that values are aligned (want 16B alignment) start_k &= ~(START_ALIGN_K-1); stride_b &= ~7; @@ -427,7 +487,7 @@ void main() { // The fetches and stores are pipelined to hide the latency. fetch_scales(ir * BM, pos_a, stride_a, start_k, tid, true); - if (enable_smaller_matrices && ic * BN + BNover4 >= p.N) { + if (!stream_k && enable_smaller_matrices && ic * BN + BNover4 >= p.N) { coopmat sum = coopmat(0.0); for (uint i = 0; i < k_iters; ++i) { @@ -470,7 +530,7 @@ void main() { coopMatStoreTensorNV(mat_d, data_d, pos_d, sliceTensorLayoutNV(tensorLayoutD, ic * BN, BNover4, ir * BM, BM), tensorViewTranspose); return; - } else if (enable_smaller_matrices && ic * BN + BNover2 >= p.N) { + } else if (!stream_k && enable_smaller_matrices && ic * BN + BNover2 >= p.N) { coopmat sum = coopmat(0.0); for (uint i = 0; i < k_iters; ++i) { @@ -555,8 +615,18 @@ void main() { coopmat mat_d = coopmat(sum); - coopMatStoreTensorNV(mat_d, data_d, pos_d, sliceTensorLayoutNV(tensorLayoutD, ic * BN, BN, ir * BM, BM), tensorViewTranspose); - return; + if (stream_k) { + if (stream_k_tile_k_unit + stream_k_tile_k_units != p.k_units_per_tile) { + tensorLayoutNV<2> tensorLayoutS = createTensorLayoutNV(2); + tensorLayoutS = setTensorLayoutDimensionNV(tensorLayoutS, BN, BM); + tensorLayoutS = setTensorLayoutStrideNV(tensorLayoutS, BM, 1); + coopMatStoreTensorNV(mat_d, data_s, group_idx * BM * BN, tensorLayoutS, tensorViewTranspose); + } else { + coopMatStoreTensorNV(mat_d, data_d, pos_d, sliceTensorLayoutNV(tensorLayoutD, ic * BN, BN, ir * BM, BM), tensorViewTranspose); + } + } else { + coopMatStoreTensorNV(mat_d, data_d, pos_d, sliceTensorLayoutNV(tensorLayoutD, ic * BN, BN, ir * BM, BM), tensorViewTranspose); + } } } else #endif // !defined(MUL_MAT_ID) @@ -720,4 +790,10 @@ void main() { coopMatStoreTensorNV(mat_d, data_d, pos_d, sliceTensorLayoutNV(tensorLayoutD, ic * BN, BN, ir * BM, BM), tensorViewTranspose); #endif } +#ifndef MUL_MAT_ID + if (stream_k) { + stream_k_work_unit += stream_k_tile_k_units; + } + } while (stream_k && stream_k_work_unit < stream_k_work_unit_end); +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq.comp b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq.comp index 1866386a7359..f831fd788a85 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq.comp @@ -82,6 +82,8 @@ layout (constant_id = 7) const uint TM = 4; layout (constant_id = 8) const uint TN = 2; layout (constant_id = 9) const uint TK = 1; // Only needed for coopmat layout (constant_id = 10) const uint WARP = 32; +// Use the mixed signedness dot product, for devices that accelerate only that one +layout (constant_id = 11) const bool MMQ_SUDOT = false; #define BK 32 @@ -102,6 +104,13 @@ shared block_b_cache buf_b[BN * BK_STEP]; block_a_cache cache_a[WMITER * TM]; block_b_cache cache_b; +#if defined(DATA_A_Q8_0) || defined(DATA_A_MXFP4) || defined(DATA_A_IQ4_XS) || defined(DATA_A_IQ3_S) || defined(DATA_A_Q3_K) || defined(DATA_A_Q6_K) +// These quants are signed. MMQ_SUDOT gives them a bias and uses the sum of each half of the q8_1 block to remove it. +#define MMQ_B_SUMS +shared int32_t buf_b_qsum[MMQ_SUDOT ? BN * BK_STEP * 2 : 1]; +int32_t cache_b_qsum[2]; +#endif + #define LOAD_VEC_A (4 * QUANT_R_MMQ) #define LOAD_VEC_B 16 diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl index d9f2f5748c6c..9d94fd2b7577 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/mul_mmq_funcs.glsl @@ -4,6 +4,19 @@ #include "types.glsl" +int32_t mmq_dot(const int32_t a, const int32_t b) { + // With MMQ_SUDOT the A quants must be unsigned + if (MMQ_SUDOT) { + return dotPacked4x8EXT(uint32_t(a), b); + } + return dotPacked4x8EXT(a, b); +} + +// With MMQ_SUDOT, flip the sign bit of each byte. This adds a bias of 128 to signed quants. +int32_t mmq_a_store(const int32_t v) { + return MMQ_SUDOT ? v ^ int32_t(0x80808080) : v; +} + // Each iqs value maps to a 32-bit integer #if defined(DATA_A_Q2_0) @@ -41,7 +54,7 @@ void block_a_to_registers(const uint reg_ib, const uint buf_ib) { ACC_TYPE mmq_dot_product(const uint ib_a) { int32_t q_sum = 0; [[unroll]] for (uint iqs = 0; iqs < 8; ++iqs) { - q_sum += dotPacked4x8EXT(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); + q_sum += mmq_dot(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); } return ACC_TYPE(float(cache_a[ib_a].dm) * (float(q_sum) * float(cache_b.ds.x) - float(cache_b.ds.y))); @@ -102,8 +115,8 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { const int32_t qs_b0 = cache_b.qs[iqs]; const int32_t qs_b1 = cache_b.qs[iqs + 4]; - q_sum += dotPacked4x8EXT(qs_a.x, qs_b0); - q_sum += dotPacked4x8EXT(qs_a.y, qs_b1); + q_sum += mmq_dot(qs_a.x, qs_b0); + q_sum += mmq_dot(qs_a.y, qs_b1); } #ifdef DATA_A_Q4_0 @@ -176,8 +189,8 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { const int32_t qs_b0 = cache_b.qs[iqs]; const int32_t qs_b1 = cache_b.qs[iqs + 4]; - q_sum += dotPacked4x8EXT(qs_a0, qs_b0); - q_sum += dotPacked4x8EXT(qs_a1, qs_b1); + q_sum += mmq_dot(qs_a0, qs_b0); + q_sum += mmq_dot(qs_a1, qs_b1); } #ifdef DATA_A_Q5_0 @@ -192,8 +205,8 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { // 2-byte loads for Q8_0 blocks (34 bytes) void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bool is_in_bounds) { if (is_in_bounds) { - buf_a[buf_ib].qs[iqs] = pack32(i16vec2(data_a_packed16[ib].qs[iqs * 2], - data_a_packed16[ib].qs[iqs * 2 + 1])); + buf_a[buf_ib].qs[iqs] = mmq_a_store(pack32(i16vec2(data_a_packed16[ib].qs[iqs * 2], + data_a_packed16[ib].qs[iqs * 2 + 1]))); if (iqs == 0) { buf_a[buf_ib].dm = FLOAT_TYPE(data_a_packed16[ib].d); @@ -221,7 +234,10 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { const int32_t qs_a = cache_a[ib_a].qs[iqs]; const int32_t qs_b = cache_b.qs[iqs]; - q_sum += dotPacked4x8EXT(qs_a, qs_b); + q_sum += mmq_dot(qs_a, qs_b); + } + if (MMQ_SUDOT) { + q_sum -= 128 * (cache_b_qsum[0] + cache_b_qsum[1]); } return ACC_TYPE(float(q_sum) * float(cache_a[ib_a].dm) * float(cache_b.ds.x)); @@ -240,8 +256,8 @@ void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo const u8vec4 i_a0 = unpack8( qs & 0x0F0F0F0F); const u8vec4 i_a1 = unpack8((qs >> 4) & 0x0F0F0F0F); - buf_a[buf_ib].qs[iqs ] = pack32(i8vec4(kvalues_mxfp4[i_a0.x], kvalues_mxfp4[i_a0.y], kvalues_mxfp4[i_a0.z], kvalues_mxfp4[i_a0.w])); - buf_a[buf_ib].qs[iqs + 4] = pack32(i8vec4(kvalues_mxfp4[i_a1.x], kvalues_mxfp4[i_a1.y], kvalues_mxfp4[i_a1.z], kvalues_mxfp4[i_a1.w])); + buf_a[buf_ib].qs[iqs ] = mmq_a_store(pack32(i8vec4(kvalues_mxfp4[i_a0.x], kvalues_mxfp4[i_a0.y], kvalues_mxfp4[i_a0.z], kvalues_mxfp4[i_a0.w]))); + buf_a[buf_ib].qs[iqs + 4] = mmq_a_store(pack32(i8vec4(kvalues_mxfp4[i_a1.x], kvalues_mxfp4[i_a1.y], kvalues_mxfp4[i_a1.z], kvalues_mxfp4[i_a1.w]))); if (iqs == 0) { buf_a[buf_ib].d = FLOAT_TYPE(e8m0_to_fp32(data_a[ib].e) * 0.5); @@ -269,7 +285,10 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { [[unroll]] for (uint iqs = 0; iqs < 8; iqs++) { const int32_t qs_a = cache_a[ib_a].qs[iqs]; - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 128 * (cache_b_qsum[0] + cache_b_qsum[1]); } return ACC_TYPE(float(cache_a[ib_a].d) * float(cache_b.ds.x) * float(q_sum)); @@ -284,8 +303,8 @@ void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo const uint32_t vui = data_a_packed32[ib_k].qs[4 * ib32 + iqs]; const i32vec2 qs = iq4nl_to_i8x8(vui); - buf_a[buf_ib].qs[iqs ] = qs.x; - buf_a[buf_ib].qs[iqs + 4] = qs.y; + buf_a[buf_ib].qs[iqs ] = mmq_a_store(qs.x); + buf_a[buf_ib].qs[iqs + 4] = mmq_a_store(qs.y); if (iqs == 0) { const uint sl = (data_a_packed32[ib_k].scales_l >> (4 * ib32)) & 0xF; @@ -313,7 +332,10 @@ void block_a_to_registers(const uint reg_ib, const uint buf_ib) { ACC_TYPE mmq_dot_product(const uint ib_a) { int32_t q_sum = 0; [[unroll]] for (uint iqs = 0; iqs < 8; iqs++) { - q_sum += dotPacked4x8EXT(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); + q_sum += mmq_dot(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 128 * (cache_b_qsum[0] + cache_b_qsum[1]); } return ACC_TYPE(float(cache_a[ib_a].d) * float(cache_b.ds.x) * float(q_sum)); @@ -372,8 +394,8 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { const int32_t scale_m = int32_t(scale >> 4) * 0x01010101; // Duplicate 8-bit value across 32-bits. const int32_t qs_a = int32_t((cache_a[ib_a].qs[iqs / 4] >> ((iqs % 4) * 2)) & 0x03030303); - sum_d += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]) * (scale & 0xF); - sum_m += dotPacked4x8EXT(scale_m, cache_b.qs[iqs]); + sum_d += mmq_dot(qs_a, cache_b.qs[iqs]) * (scale & 0xF); + sum_m += mmq_dot(scale_m, cache_b.qs[iqs]); } return ACC_TYPE(float(cache_b.ds.x) * (float(cache_a[ib_a].dm.x) * float(sum_d) - float(cache_a[ib_a].dm.y) * float(sum_m))); @@ -435,18 +457,26 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { int32_t q_sum = 0; [[unroll]] for (uint iqs = 0; iqs < 4; iqs++) { - // Subtract 4 from the quants to correct the 3rd bit offset - const int32_t qs_a = pack32(unpack8(int32_t((cache_a[ib_a].qs[iqs / 2] >> ((iqs % 2) * 4)) & 0x0F0F0F0F)) - int8_t(4)); + // Subtract 4 from the quants to correct the 3rd bit offset. MMQ_SUDOT keeps them unsigned and subtracts 4 times the B sum. + const int32_t qs_u = int32_t((cache_a[ib_a].qs[iqs / 2] >> ((iqs % 2) * 4)) & 0x0F0F0F0F); + const int32_t qs_a = MMQ_SUDOT ? qs_u : pack32(unpack8(qs_u) - int8_t(4)); - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 4 * cache_b_qsum[0]; } result += float(cache_a[ib_a].d_scales[0]) * float(q_sum); q_sum = 0; [[unroll]] for (uint iqs = 4; iqs < 8; iqs++) { - const int32_t qs_a = pack32(unpack8(int32_t((cache_a[ib_a].qs[iqs / 2] >> ((iqs % 2) * 4)) & 0x0F0F0F0F)) - int8_t(4)); + const int32_t qs_u = int32_t((cache_a[ib_a].qs[iqs / 2] >> ((iqs % 2) * 4)) & 0x0F0F0F0F); + const int32_t qs_a = MMQ_SUDOT ? qs_u : pack32(unpack8(qs_u) - int8_t(4)); - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 4 * cache_b_qsum[1]; } result += float(cache_a[ib_a].d_scales[1]) * float(q_sum); @@ -518,7 +548,7 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { const int32_t qs_a = cache_a[ib_a].qs[iqs]; #endif - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); } return ACC_TYPE(float(cache_b.ds.x) * float(cache_a[ib_a].dm.x) * float(q_sum) - float(cache_a[ib_a].dm.y) * float(cache_b.ds.y)); @@ -539,10 +569,11 @@ void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo const uint qh_shift = ((iqs_k % 32) / 8) * 2; const i8vec2 vals00 = (unpack8(int32_t((data_a_packed16[ib_k].ql[ql_idx * 2 ] >> ql_shift) & uint16_t(0x0F0F))).xy | - unpack8(int32_t(((data_a_packed16[ib_k].qh[qh_idx * 2 ] >> qh_shift) & uint16_t(0x0303)) << 4)).xy) - int8_t(32); + unpack8(int32_t(((data_a_packed16[ib_k].qh[qh_idx * 2 ] >> qh_shift) & uint16_t(0x0303)) << 4)).xy); const i8vec2 vals01 = (unpack8(int32_t((data_a_packed16[ib_k].ql[ql_idx * 2 + 1] >> ql_shift) & uint16_t(0x0F0F))).xy | - unpack8(int32_t(((data_a_packed16[ib_k].qh[qh_idx * 2 + 1] >> qh_shift) & uint16_t(0x0303)) << 4)).xy) - int8_t(32); - buf_a[buf_ib].qs[iqs] = pack32(i8vec4(vals00.x, vals00.y, vals01.x, vals01.y)); + unpack8(int32_t(((data_a_packed16[ib_k].qh[qh_idx * 2 + 1] >> qh_shift) & uint16_t(0x0303)) << 4)).xy); + // MMQ_SUDOT keeps the quants unsigned and subtracts 32 times the B sum + buf_a[buf_ib].qs[iqs] = MMQ_SUDOT ? pack32(i8vec4(vals00, vals01)) : pack32(i8vec4(vals00 - int8_t(32), vals01 - int8_t(32))); if (iqs == 0) { const uint is = iqs_k / 4; @@ -574,7 +605,10 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { [[unroll]] for (uint iqs = 0; iqs < 4; iqs++) { const int32_t qs_a = cache_a[ib_a].qs[iqs]; - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 32 * cache_b_qsum[0]; } result += float(cache_a[ib_a].d_scales[0]) * float(q_sum); q_sum = 0; @@ -582,7 +616,10 @@ ACC_TYPE mmq_dot_product(const uint ib_a) { [[unroll]] for (uint iqs = 4; iqs < 8; iqs++) { const int32_t qs_a = cache_a[ib_a].qs[iqs]; - q_sum += dotPacked4x8EXT(qs_a, cache_b.qs[iqs]); + q_sum += mmq_dot(qs_a, cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 32 * cache_b_qsum[1]; } result += float(cache_a[ib_a].d_scales[1]) * float(q_sum); @@ -612,8 +649,8 @@ void block_a_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo const ivec4 m0 = -(ivec4(signs, signs >> 1, signs >> 2, signs >> 3) & 1); const ivec4 m1 = -(ivec4(signs >> 4, signs >> 5, signs >> 6, signs >> 7) & 1); - buf_a[buf_ib].qs[2 * iqs ] = pack32(i8vec4((vals0 ^ m0) - m0)); - buf_a[buf_ib].qs[2 * iqs + 1] = pack32(i8vec4((vals1 ^ m1) - m1)); + buf_a[buf_ib].qs[2 * iqs ] = mmq_a_store(pack32(i8vec4((vals0 ^ m0) - m0))); + buf_a[buf_ib].qs[2 * iqs + 1] = mmq_a_store(pack32(i8vec4((vals1 ^ m1) - m1))); if (iqs == 0) { const uint scale = (uint(data_a_packed16[ib_k].scales[ib32 / 4]) >> ((ib32 & 3) * 4)) & 0xF; @@ -641,7 +678,10 @@ void block_a_to_registers(const uint reg_ib, const uint buf_ib) { ACC_TYPE mmq_dot_product(const uint ib_a) { int32_t q_sum = 0; [[unroll]] for (uint iqs = 0; iqs < 8; iqs++) { - q_sum += dotPacked4x8EXT(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); + q_sum += mmq_dot(cache_a[ib_a].qs[iqs], cache_b.qs[iqs]); + } + if (MMQ_SUDOT) { + q_sum -= 128 * (cache_b_qsum[0] + cache_b_qsum[1]); } return ACC_TYPE(float(cache_a[ib_a].d) * float(cache_b.ds.x) * float(q_sum)); @@ -662,6 +702,12 @@ void block_b_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo buf_b[buf_ib].qs[iqs * 4 + 1] = values.y; buf_b[buf_ib].qs[iqs * 4 + 2] = values.z; buf_b[buf_ib].qs[iqs * 4 + 3] = values.w; +#ifdef MMQ_B_SUMS + if (MMQ_SUDOT) { + buf_b_qsum[buf_ib * 2 + iqs] = dotPacked4x8EXT(values.x, 0x01010101u) + dotPacked4x8EXT(values.y, 0x01010101u) + + dotPacked4x8EXT(values.z, 0x01010101u) + dotPacked4x8EXT(values.w, 0x01010101u); + } +#endif } else { if (iqs == 0) { buf_b[buf_ib].ds = FLOAT_TYPEV2(0.0f); @@ -671,6 +717,11 @@ void block_b_to_shmem(const uint buf_ib, const uint ib, const uint iqs, const bo buf_b[buf_ib].qs[iqs * 4 + 1] = 0; buf_b[buf_ib].qs[iqs * 4 + 2] = 0; buf_b[buf_ib].qs[iqs * 4 + 3] = 0; +#ifdef MMQ_B_SUMS + if (MMQ_SUDOT) { + buf_b_qsum[buf_ib * 2 + iqs] = 0; + } +#endif } } @@ -679,4 +730,10 @@ void block_b_to_registers(const uint ib) { [[unroll]] for (uint iqs = 0; iqs < BK / 4; iqs++) { cache_b.qs[iqs] = buf_b[ib].qs[iqs]; } +#ifdef MMQ_B_SUMS + if (MMQ_SUDOT) { + cache_b_qsum[0] = buf_b_qsum[ib * 2]; + cache_b_qsum[1] = buf_b_qsum[ib * 2 + 1]; + } +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp index b9f0a1841b51..b73fdeca48fd 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp @@ -87,6 +87,12 @@ void rms_norm(uint num_iters) { #endif FLOAT_TYPE sum = FLOAT_TYPE(0.0f); // partial sum for thread in warp +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + const FLOAT_TYPE xi = FLOAT_TYPE(data_a[a_offset + col]); + sum += xi * xi; + } +#else [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { FLOAT_TYPE xi = FLOAT_TYPE(0); if (col < ncols) { @@ -94,6 +100,7 @@ void rms_norm(uint num_iters) { } sum += xi * xi; } +#endif #if USE_SUBGROUP_ADD sum = subgroupAdd(sum); @@ -131,6 +138,15 @@ void rms_norm(uint num_iters) { const FLOAT_TYPE mean = sum / FLOAT_TYPE(ncols); const FLOAT_TYPE scale = inversesqrt(mean + FLOAT_TYPE(p.param1)); +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + FLOAT_TYPE value = scale * FLOAT_TYPE(data_a[a_offset + col]); + if (do_multiply) { + value *= FLOAT_TYPE(data_b[b_offset + fastmod(col, p.ne10)]); + } + data_d[d_offset + col] = D_TYPE(value); + } +#else if (do_multiply) { if (ncols > p.ne10) { [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { @@ -169,6 +185,7 @@ void rms_norm(uint num_iters) { data_d[d_offset + col] = FLOAT_TO_D(scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col]))); } } +#endif #if RMS_NORM_ROPE_FUSION barrier(); rope_params rp = p.rope; @@ -185,6 +202,10 @@ void rms_norm(uint num_iters) { } void main() { +#if RMS_NORM_ROPE_FUSION + const uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; + rms_norm(num_blocks); +#else // instantiate the rms_norm function for several different // dimensions, to allow loop unrolling uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; @@ -209,4 +230,5 @@ void main() { } else if (num_blocks == 1) { rms_norm(1); } +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp new file mode 100644 index 000000000000..07f6cafc9715 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp @@ -0,0 +1,37 @@ +#version 450 + +#extension GL_EXT_shader_realtime_clock : require + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +// never written, it only anchors the spin below so the compiler cannot drop it +layout (binding = 0) writeonly buffer D {uint data_d[];}; + +layout (push_constant) uniform parameter { + uint ticks; +} p; + +// bounds the spin in case the clock does not advance, turning a hang into a too-short sleep +const uint MAX_ITER = 1u << 27; + +void main() { + const uvec2 t0 = clockRealtime2x32EXT(); + + uvec2 t = t0; + + for (uint iter = 0; iter < MAX_ITER; ++iter) { + t = clockRealtime2x32EXT(); + + const uint lo = t.x - t0.x; + const uint hi = t.y - t0.y - (t.x < t0.x ? 1u : 0u); + + if (hi != 0u || lo >= p.ticks) { + break; + } + } + + // the store never runs, but the compiler cannot prove it and has to keep the spin + if (t.x == 0xFFFFFFFFu && t.y == 0xFFFFFFFFu) { + data_d[0] = t.x; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/tri.comp b/ggml/src/ggml-vulkan/vulkan-shaders/tri.comp index 2585540af181..d77139aefc3e 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/tri.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/tri.comp @@ -36,6 +36,6 @@ void main() { if (pass) { data_d[get_doffset() + dst_idx(idx)] = D_TYPE(data_a[get_aoffset() + src0_idx(idx)]); } else { - data_d[get_doffset() + dst_idx(idx)] = D_TYPE(0); + data_d[get_doffset() + dst_idx(idx)] = D_TYPE(0.0); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 86b69d15f614..e20c94758900 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -348,7 +348,10 @@ compile_count_guard acquire_compile_slot() { } void string_to_spv_func(std::string name, std::string in_path, std::string out_path, std::map defines, bool coopmat, bool dep_file, compile_count_guard slot) { - std::string target_env = (name.find("_cm2") != std::string::npos) ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; + // coopmat2 and the maintenance1 GDN coopmat1 variants need SPIR-V 1.6 (vulkan1.3) + const bool needs_spv16 = name.find("_cm2") != std::string::npos || + name.find("gated_delta_net_f32_cm1") != std::string::npos; + std::string target_env = needs_spv16 ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; #ifdef _WIN32 std::vector cmd = {GLSLC, "-fshader-stage=compute", target_env, "\"" + in_path + "\"", "-o", "\"" + out_path + "\""}; @@ -948,6 +951,7 @@ void process_shaders() { string_to_spv("acc_f32", "acc.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("split_k_reduce", "mul_mat_split_k_reduce.comp", {}); + string_to_spv("stream_k_fixup", "mul_mat_stream_k_fixup.comp", {}); string_to_spv("fa_split_k_reduce", "flash_attn_split_k_reduce.comp", {}); string_to_spv("fa_mask_opt", "flash_attn_mask_opt.comp", {}); @@ -1027,6 +1031,7 @@ void process_shaders() { string_to_spv("arange_f32", "arange.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f32", "fill.comp", {{"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f16", "fill.comp", {{"D_TYPE", "float16_t"}, {"FLOAT_TYPE", "float"}}); + string_to_spv("sleep", "sleep.comp", {}); string_to_spv("silu_back_f32", "silu_back.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}); @@ -1126,6 +1131,20 @@ void process_shaders() { string_to_spv("gated_delta_net_f32_nocluster", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); string_to_spv("gated_delta_net_f32_shmem", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "0"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm2.comp", base_dict, true, false, true); +#endif +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}}), true, true, false, false, "_bf16acc"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", base_dict, true, true); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"V", "32"}}), true, true, false, false, "_bf16acc_v32"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"V", "32"}}), true, true, false, false, "_v32"); + // whole-head V=128 variant: state mirror in a gmem scratch buffer (won't fit LDS). + // For head counts that tail the CU grid at V=64 (e.g. 48-head 27B on 64 CUs). + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_bf16acc_v128"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_v128"); +#endif + string_to_spv("opt_step_adamw_f32", "opt_step_adamw.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); string_to_spv("opt_step_sgd_f32", "opt_step_sgd.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 6a57e9f3d7e7..cc7f660ef8e4 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -1269,9 +1269,11 @@ class ggml_webgpu_shader_lib { std::unordered_map argsort_pipelines; // key is order std::unordered_map argsort_merge_pipelines; // key is order std::unordered_map cumsum_pipelines; // key is fixed, no variants yet + std::unordered_map col2im_1d_pipelines; // key is fixed, no variants yet std::unordered_map arange_pipelines; // key is fixed, no variants yet std::unordered_map count_equal_pipelines; // key is src_overlap std::unordered_map timestep_embedding_pipelines; // key is fixed, no variants yet + std::unordered_map pool2d_pipelines; // key is ggml_op_pool std::unordered_map row_norm_pipelines; // op/inplace @@ -2067,6 +2069,51 @@ class ggml_webgpu_shader_lib { return arange_pipelines[1]; } + webgpu_pipeline get_pool2d_pipeline(const ggml_webgpu_shader_lib_context & context) { + const int key = ggml_get_op_params_i32(context.dst, 0); + + auto it = pool2d_pipelines.find(key); + if (it != pool2d_pipelines.end()) { + return it->second; + } + + std::vector defines; + std::string variant = "pool2d"; + if (key == GGML_OP_POOL_MAX) { + defines.push_back("POOL_MAX"); + variant += "_max"; + } else { + variant += "_avg"; + } + + defines.push_back(std::string("WG_SIZE=") + std::to_string(context.max_wg_size)); + + auto processed = preprocessor.preprocess(wgsl_pool2d, defines); + auto decisions = std::make_shared(); + decisions->wg_size = context.max_wg_size; + webgpu_pipeline pipeline = ggml_webgpu_create_pipeline(device, processed, variant); + pipeline.context = decisions; + pool2d_pipelines[key] = pipeline; + return pool2d_pipelines[key]; + } + + webgpu_pipeline get_col2im_1d_pipeline(const ggml_webgpu_shader_lib_context & context) { + auto it = col2im_1d_pipelines.find(1); + if (it != col2im_1d_pipelines.end()) { + return it->second; + } + + const uint32_t wg_size = std::min(256u, context.max_wg_size); + std::vector defines = { "WG_SIZE=" + std::to_string(wg_size) }; + auto processed = preprocessor.preprocess(wgsl_col2im_1d, defines); + auto decisions = std::make_shared(); + decisions->wg_size = wg_size; + webgpu_pipeline pipeline = ggml_webgpu_create_pipeline(device, processed, "col2im_1d"); + pipeline.context = decisions; + col2im_1d_pipelines[1] = pipeline; + return pipeline; + } + webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) { ggml_webgpu_pad_pipeline_key key = {}; key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index fc2c2797de41..75527b111f6a 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -908,6 +908,32 @@ static webgpu_encoded_op ggml_webgpu_arange(webgpu_context & ctx, ggml_tensor * return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_col2im_1d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + webgpu_pipeline pipeline = ctx->shader_lib->get_col2im_1d_pipeline(shader_lib_ctx); + auto * decisions = static_cast(pipeline.context.get()); + + std::vector params = { + (uint32_t) ggml_nelements(dst), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / sizeof(float)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / sizeof(float)), + (uint32_t) src->ne[0], + (uint32_t) src->ne[1], + (uint32_t) dst->ne[0], + (uint32_t) (src->ne[0] / dst->ne[1]), + (uint32_t) ggml_get_op_params_i32(dst, 0), + (uint32_t) ggml_get_op_params_i32(dst, 2), + }; + std::vector entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) }; + uint32_t wg_x; + uint32_t wg_y; + const uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { ggml_webgpu_shader_lib_context shader_lib_ctx = {}; shader_lib_ctx.src0 = src; @@ -961,6 +987,46 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_pool2d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.src0 = src; + shader_lib_ctx.dst = dst; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + + webgpu_pipeline pipeline = ctx->shader_lib->get_pool2d_pipeline(shader_lib_ctx); + + auto * decisions = static_cast(pipeline.context.get()); + + const uint32_t ne = (uint32_t) ggml_nelements(dst); + + std::vector params = { + ne, + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / ggml_type_size(src->type)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / ggml_type_size(dst->type)), + (uint32_t) src->ne[0], + (uint32_t) src->ne[1], + (uint32_t) dst->ne[0], + (uint32_t) dst->ne[1], + (uint32_t) ggml_get_op_params_i32(dst, 1), // k0 + (uint32_t) ggml_get_op_params_i32(dst, 2), // k1 + (uint32_t) ggml_get_op_params_i32(dst, 3), // s0 + (uint32_t) ggml_get_op_params_i32(dst, 4), // s1 + (uint32_t) ggml_get_op_params_i32(dst, 5), // p0 + (uint32_t) ggml_get_op_params_i32(dst, 6), // p1 + }; + + std::vector entries = { + ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst), + }; + + uint32_t wg_x; + uint32_t wg_y; + uint32_t total_wg = CEIL_DIV(ne, decisions->wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_solve_tri(webgpu_context & ctx, ggml_tensor * src0, ggml_tensor * src1, @@ -3670,6 +3736,10 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, } case GGML_OP_ARANGE: return ggml_webgpu_arange(ctx, node); + case GGML_OP_POOL_2D: + return ggml_webgpu_pool2d(ctx, src0, node); + case GGML_OP_COL2IM_1D: + return ggml_webgpu_col2im_1d(ctx, src0, node); case GGML_OP_PAD_REFLECT_1D: case GGML_OP_PAD: return ggml_webgpu_pad(ctx, src0, node); @@ -5219,6 +5289,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const case GGML_OP_ARANGE: supports_op = op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); break; + case GGML_OP_POOL_2D: + supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0); + break; case GGML_OP_PAD_REFLECT_1D: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32; break; @@ -5247,6 +5320,10 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const supports_op = src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1); break; + case GGML_OP_COL2IM_1D: + supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0) && + ggml_is_contiguous(op); + break; case GGML_OP_SUM_ROWS: case GGML_OP_MEAN: supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type && ggml_is_contiguous_rows(src0); diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl new file mode 100644 index 000000000000..f89528f2476d --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl @@ -0,0 +1,45 @@ +@group(0) @binding(0) +var src: array; + +@group(0) @binding(1) +var dst: array; + +struct Params { + ne: u32, + offset_src: u32, + offset_dst: u32, + src_ne0: u32, + t_in: u32, + t_out: u32, + kernel: u32, + stride: u32, + padding: u32, +}; + +@group(0) @binding(2) +var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, + @builtin(global_invocation_id) gid: vec3) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { + return; + } + + let channel = idx / params.t_out; + let t_abs = idx % params.t_out + params.padding; + var first: u32 = 0; + if (t_abs >= params.kernel) { + first = (t_abs - params.kernel) / params.stride + 1; + } + let last = min(t_abs / params.stride, params.t_in - 1); + + // Gather overlapping columns in the same order as the CPU reference. + var sum: f32 = 0.0; + for (var t = first; t <= last; t++) { + let k = t_abs - t * params.stride; + sum += src[params.offset_src + t * params.src_ne0 + channel * params.kernel + k]; + } + dst[params.offset_dst + idx] = sum; +} diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl index 0d0d81ab650f..2466b2f0b7ca 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl @@ -53,12 +53,14 @@ var params: Params; @compute @workgroup_size(WG_SIZE) fn main( @builtin(global_invocation_id) gid: vec3, + @builtin(num_workgroups) num_wg: vec3, ) { - if (gid.x >= params.ne) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { return; } - var i = gid.x; + var i = idx; let i3 = i / (params.src_ne2 * params.src_ne1 * params.src_ne0); i = i % (params.src_ne2 * params.src_ne1 * params.src_ne0); let i2 = i / (params.src_ne1 * params.src_ne0); @@ -66,7 +68,7 @@ fn main( let i1 = i / params.src_ne0; let i0 = i % params.src_ne0; - var j = gid.x; + var j = idx; let j3 = j / (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); j = j % (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); let j2 = j / (params.dst_ne1 * params.dst_ne0); diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/pool2d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/pool2d.wgsl new file mode 100644 index 000000000000..7152adeb11ca --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/pool2d.wgsl @@ -0,0 +1,74 @@ +@group(0) @binding(0) +var src: array; + +@group(0) @binding(1) +var dst: array; + +struct Params { + ne: u32, // total number of elements + offset_src: u32, // in elements + offset_dst: u32, // in elements + + // Logical shapes + src_ne0: u32, + src_ne1: u32, + + dst_ne0: u32, + dst_ne1: u32, + + k0: u32, + k1: u32, + s0: u32, + s1: u32, + p0: u32, + p1: u32 +} + + +@group(0) @binding(2) +var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, + @builtin(global_invocation_id) gid: vec3) { + + let gid_i = gid.x + (num_wg.x * u32(WG_SIZE)) * gid.y; + if (gid_i >= params.ne) { + return; + } + + let out_x = gid_i % params.dst_ne0; + let out_y = (gid_i / params.dst_ne0) % params.dst_ne1; + let out_z = (gid_i / (params.dst_ne0 * params.dst_ne1)); + + let x0 = i32(out_x * params.s0) - i32(params.p0); + let y0 = i32(out_y * params.s1) - i32(params.p1); + let in_x_start = max(0, x0); + let in_x_end = min(i32(params.src_ne0), x0 + i32(params.k0)); + let in_y_start = max(0, y0); + let in_y_end = min(i32(params.src_ne1), y0 + i32(params.k1)); + + let base = params.offset_src + out_z * params.src_ne0 * params.src_ne1; + +#ifdef POOL_MAX + var res: f32 = bitcast(0xff7fffffu); +#else + var res: f32 = 0.0; +#endif + + for(var y = in_y_start; y < in_y_end; y++){ + let row = base + u32(y) * params.src_ne0; + for(var x = in_x_start; x < in_x_end; x++){ +#ifdef POOL_MAX + res = max(res, src[row + u32(x)]); +#else + res += src[row + u32(x)]; +#endif + } + } + +#ifndef POOL_MAX + res = res / f32(params.k0 * params.k1); +#endif + dst[params.offset_dst + gid_i] = res; +} diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 7132abc51f3b..ecd667753ee3 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1112,9 +1112,11 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "OPT_STEP_SGD", "GLU", + + "SLEEP", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1225,9 +1227,11 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sgd(x)", "glu(x)", + + "sleep(x)", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -4015,7 +4019,7 @@ struct ggml_tensor * ggml_set_rows( GGML_ASSERT(b->ne[2] % c->ne[1] == 0); GGML_ASSERT(b->ne[3] % c->ne[2] == 0); GGML_ASSERT(c->ne[3] == 1); - GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16); + GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16 || b->type == GGML_TYPE_BF16); GGML_ASSERT(c->type == GGML_TYPE_I64 || c->type == GGML_TYPE_I32); GGML_ASSERT(ggml_is_contiguous_rows(a)); @@ -6176,6 +6180,27 @@ struct ggml_tensor * ggml_custom_inplace( return result; } + +// ggml_sleep + +// the result aliases a, the op only delays and never touches the data +struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, + int32_t us) { + GGML_ASSERT(us >= 0); + + struct ggml_tensor * result = ggml_view_tensor(ctx, a); + ggml_format_name(result, "%s (sleep)", a->name); + + ggml_set_op_params_i32(result, 0, us); + + result->op = GGML_OP_SLEEP; + result->src[0] = a; + + return result; +} + // ggml_cross_entropy_loss struct ggml_tensor * ggml_cross_entropy_loss( diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index e07ea2f4b7c2..f36566a815d9 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -778,6 +778,7 @@ class MODEL_ARCH(IntEnum): KOLIBRI1 = auto() LIMITE = auto() INKLING2 = auto() + DOMYN_EDGE = auto() class VISION_PROJECTOR_TYPE(IntEnum): @@ -1778,6 +1779,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KOLIBRI1: "kolibri1", MODEL_ARCH.LIMITE: "limite", MODEL_ARCH.INKLING2: "inkling2", + MODEL_ARCH.DOMYN_EDGE: "domynedge", } VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = { @@ -7085,6 +7087,22 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_POST_CONV, MODEL_TENSOR.FFN_RES_QUERY, ], + MODEL_ARCH.DOMYN_EDGE: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_PRE_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.OUTPUT_NORM, + ], } # tensors that will not be serialized diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c844a9322b12..d48d46b9a307 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -272,6 +272,7 @@ class TensorNameMap: "model.layers.{bid}.pre_attention_layernorm", # kormo "head.layers.{bid}.norm1", # laya "model.layers.{bid}.attn_norm", # inkling2 + "model.layers.{bid}.pre_attention_norm", # domynedge ), # Attention norm 2 @@ -440,6 +441,7 @@ class TensorNameMap: "model.layers.{bid}.post_attn_norm", # kolibri1 "model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2 "model.layers.{bid}.post_operator_norm", # lfm3 + "model.layers.{bid}.post_attention_norm", # domynedge ), # Rotary embeddings @@ -579,6 +581,7 @@ class TensorNameMap: "layers.{bid}.pre_feedforward_layernorm", # embeddinggemma "model.layers.{bid}.pre_ff_layernorm.weight", "model.layers.{bid}.pre_mlp_layernorm", # afmoe + "model.layers.{bid}.pre_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_PRE_NORM_2: ( @@ -603,6 +606,7 @@ class TensorNameMap: "model.layers.{bid}.feed_forward.up_proj", "model.layers.{bid}.post_moe_norm", # grok-2 "model.layers.{bid}.post_ffn_norm", # lfm3 + "model.layers.{bid}.post_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_POST_NORM_1: ( @@ -692,6 +696,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_h_to_4h", # chatglm "transformer.h.{bid}.mlp.c_fc_1", # exaone "model.layers.{bid}.feed_forward.up_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.up_proj", # domynedge "transformer_encoder.{bid}.ffn.w12", # neobert "model.layers.{bid}.block_sparse_moe.up", # smallthinker "model.transformer.blocks.{bid}.up_proj", # llada @@ -755,6 +760,7 @@ class TensorNameMap: "layers.{bid}.mlp.gate_proj", # qwen3-embedding "model.layers.{bid}.mlp.language_mlp.gate_proj", # cogvlm "model.blocks.{bid}.mlp.mlp_gate", # talkie + "model.layers.{bid}.feedforward.gate_proj", # domynedge ), MODEL_TENSOR.FFN_GATE_EXP: ( @@ -923,6 +929,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_4h_to_h", # chatglm "model.layers.h.{bid}.mlp.c_proj", # exaone "model.layers.{bid}.feed_forward.down_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.down_proj", # domynedge "transformer_encoder.{bid}.ffn.w3", # neobert "model.layers.{bid}.block_sparse_moe.down", # smallthinker "model.transformer.blocks.{bid}.ff_out", # llada @@ -997,6 +1004,7 @@ class TensorNameMap: "layers.{bid}.self_attn.k_norm", # qwen3-embedding "model.layers.{bid}.self_attn.k_rope_only_layernorm", # dots3note "model.layers.{bid}.attention.key_layernorm", # apertus + "model.layers.{bid}.attention.k_norm", # domynedge ), MODEL_TENSOR.ROPE_FREQS: ( diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index bfaa4ca4cdc5..90d0bdf338b8 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -41,7 +41,7 @@ function(mime_from_ext name out_var) set(m "text/html; charset=utf-8") elseif(ext_str STREQUAL "css") set(m "text/css") - elseif(ext_str STREQUAL "js") + elseif(ext_str STREQUAL "js" OR ext_str STREQUAL "mjs") set(m "application/javascript") elseif(ext_str STREQUAL "json") set(m "application/json") @@ -98,9 +98,12 @@ function(ui_validate_assets files in_dir) set(found_build_json TRUE) elseif(base STREQUAL "version.json") set(found_version_json TRUE) - elseif(base MATCHES "^bundle.*\\.js$") + # the app's entry: bundle[hash].js/.css from a single-bundle build (builds before the + # split one, prebuilt archives included), or entry/start[hash].js and the CSS in + # _app/immutable/assets from a split build + elseif(base MATCHES "^bundle.*\\.js$" OR f MATCHES "(^|/)_app/immutable/entry/start\\.[^/]*\\.js$") set(found_bundle_js TRUE) - elseif(base MATCHES "^bundle.*\\.css$") + elseif(base MATCHES "^bundle.*\\.css$" OR f MATCHES "(^|/)_app/immutable/assets/[^/]*\\.css$") set(found_bundle_css TRUE) endif() endforeach() @@ -125,10 +128,10 @@ function(ui_validate_assets files in_dir) list(APPEND missing "version.json") endif() if(NOT found_bundle_js) - list(APPEND missing "bundle[hash].js") + list(APPEND missing "_app/immutable/entry/start[hash].js (or bundle[hash].js)") endif() if(NOT found_bundle_css) - list(APPEND missing "bundle[hash].css") + list(APPEND missing "_app/immutable/assets/[name][hash].css (or bundle[hash].css)") endif() if(missing) diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index c50e9f98a200..1c90b2180bfd 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -184,6 +184,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KOLIBRI1, "kolibri1" }, { LLM_ARCH_RICURSIVE, "ricursive" }, { LLM_ARCH_INKLING2, "inkling2" }, + { LLM_ARCH_DOMYN_EDGE, "domynedge" }, { LLM_ARCH_UNKNOWN, "(unknown)" }, }; diff --git a/src/llama-arch.h b/src/llama-arch.h index 9c517a9fe15d..a8c0fdf098fd 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -188,6 +188,7 @@ enum llm_arch { LLM_ARCH_LIMITE, LLM_ARCH_RICURSIVE, LLM_ARCH_INKLING2, + LLM_ARCH_DOMYN_EDGE, LLM_ARCH_UNKNOWN, }; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 2ca4b1661c84..456fb6f23110 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2924,42 +2924,15 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { - uint32_t res; - if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || - model.arch == LLM_ARCH_HRM_TEXT) { - res = std::max(1024u, 64u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_QWEN3NEXT || - model.arch == LLM_ARCH_KIMI_LINEAR || - model.arch == LLM_ARCH_METIS16 || - model.arch == LLM_ARCH_BAILINGMOE3 || - model.arch == LLM_ARCH_QWEN35 || - model.arch == LLM_ARCH_QWEN35MOE || - model.arch == LLM_ARCH_ZONOS3 || - model.arch == LLM_ARCH_CLEF || - model.arch == LLM_ARCH_CLOVER_MOE || - model.arch == LLM_ARCH_QWEN4EXP || - model.arch == LLM_ARCH_DEEPSEEK4 || - model.arch == LLM_ARCH_DEEPSEEK41 || - model.arch == LLM_ARCH_XING4_0 || - (model.arch == LLM_ARCH_DFLASH && model.hparams.dsv4_hc_mult > 0) || - model.arch == LLM_ARCH_NANBEIGE || - model.arch == LLM_ARCH_MINIMAX_01 || - model.arch == LLM_ARCH_MINIMAX_M3 || - model.arch == LLM_ARCH_HY_V4 || - model.arch == LLM_ARCH_INKLING2) { - res = std::max(1024u, 32u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_DFLASH && model.hparams.dflash_selector_rank > 0) { - // DFlash2's convolutions and selector are shape work rather than matmuls, - // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. - // The selector lattice scales with the draft block size; 12u was calibrated - // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). - const uint32_t block_scale = std::max(1u, model.hparams.dflash_block_size/8u); - res = std::max(1024u, 12u*block_scale*model.n_tensors()); - } else { - res = std::max(1024u, 8u*model.n_tensors()); - for (const auto & lora : model.loras) { - res += lora->get_n_nodes(); - } + uint32_t res = std::max(1024u, model.graph_nodes_per_tensor()*model.n_tensors()); + for (const auto & lora : model.loras) { + res += lora->get_n_nodes(); + } + + // the MoE cache adds a lookup to each MoE layer, and a second expert path with a CPU share (up to ~16 tensors per layer), + // which the per-tensor estimates above do not cover for models with few tensors per layer + if (cparams.moe_cache_size > 0) { + res += 32u*model.hparams.n_layer_all; } // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling @@ -3108,7 +3081,6 @@ llm_graph_params llama_context::graph_params( llm_graph_type gtype) const { return { /*.model =*/ &model, - /*.hparams =*/ model.hparams, /*.cparams =*/ cparams, /*.ubatch =*/ ubatch, /*.gtype =*/ gtype, @@ -3119,8 +3091,6 @@ llm_graph_params llama_context::graph_params( /*.mctx =*/ mctx, /*.cross =*/ &cross, /*.moe_cache =*/ moe_cache.get(), - /*.prec_policy =*/ &model.prec_policy, - /*.hdmd =*/ model.hdmd.rot.empty() ? nullptr : &model.hdmd, /*.layer_inp_dev =*/ layer_inp_dev, /*.layer_inp_src =*/ supports_embd_row() ? cparams.ctx_other->get_layer_inp_dev() : nullptr, /*.h_nextn_dev =*/ cparams.embeddings_nextn_dev ? h_nextn_dev : nullptr, diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 58c5b6c9c724..269b920fb8e3 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1400,6 +1400,91 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) return res; } +void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) { + const auto * attn_ctx = mctx->get_attn(); + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); + attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); + } + + if (inp_attn->self_attn_mask.raw && inp_attn->self_attn_mask.raw->buffer) { + attn_ctx->get_base()->set_input_attn_mask(inp_attn->self_attn_mask, ubatch, cparams.causal_attn); + } + + if (self_rel_pos->buffer) { + attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); + } + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); + attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); + } + + if (inp_attn->self_attn_mask_swa.raw && inp_attn->self_attn_mask_swa.raw->buffer) { + attn_ctx->get_swa()->set_input_attn_mask(inp_attn->self_attn_mask_swa, ubatch, cparams.causal_attn); + } + + if (self_rel_pos_swa->buffer) { + attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); + } + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + + if (inp_rs->s_copy) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + + // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n + for (uint32_t i = 0; i < n_rs; ++i) { + data[i] = mctx->get_recr()->s_copy(i); + } + } +} + +bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { + const auto * mctx = static_cast(params.mctx); + + this->mctx = mctx; + + bool res = true; + + const auto * attn_ctx = mctx->get_attn(); + + // the masks are always dense, see build_inp_mem_hybrid_iswa_rel() + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); + + res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); + res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); + + res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); + res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + + res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); + + res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; + + res &= inp_rs->head == mctx->get_recr()->get_head(); + res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + + return res; +} + void llm_graph_input_sampling::set_input(const llama_ubatch * ubatch) { // set the inputs only for the active samplers in the current ubatch std::unordered_set active_samplers; @@ -1594,9 +1679,10 @@ void llm_graph_result::set_params(const llm_graph_params & params) { llm_graph_context::llm_graph_context(const llm_graph_params & params) : model (*params.model), - hparams (params.hparams), + hparams (model.hparams), cparams (params.cparams), ubatch (params.ubatch), + prec_policy (model.prec_policy), n_embd (hparams.n_embd), n_layer (hparams.n_layer()), n_layer_nextn (hparams.n_layer_nextn), @@ -1630,8 +1716,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) : mctx (params.mctx), cross (params.cross), moe_cache (params.moe_cache), - prec_policy (params.prec_policy), - hdmd (params.hdmd), + hdmd (model.hdmd.rot.empty() ? nullptr : &model.hdmd), layer_inp_dev (params.layer_inp_dev), layer_inp_src (params.layer_inp_src), h_nextn_dev (params.h_nextn_dev), @@ -1728,9 +1813,7 @@ ggml_tensor * llm_graph_context::build_lora_mm( ggml_tensor * cur_mm = build_hadamard_input(w, cur); ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm); - if (prec_policy) { - prec_policy->apply(res); - } + prec_policy.apply(res); if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); @@ -1812,9 +1895,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_mul_mat_id(ctx0, w, cur_mm, ids) : ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots); - if (prec_policy) { - prec_policy->apply(res); - } + prec_policy.apply(res); if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); @@ -3117,7 +3198,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * cur; - const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr && (!sinks || ggml_is_vector(sinks)); + const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; GGML_ASSERT(use_flash_attn || kv_rows == nullptr); if (use_flash_attn) { GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); @@ -3200,16 +3281,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( cb(kq, "kq_plus_kq_b", il); } - if (sinks && !ggml_is_vector(sinks)) { - // Per-query sinks are extra logits with zero values. - const int64_t n_kv = kq->ne[0]; - kq = ggml_add(ctx0, ggml_scale(ctx0, kq, kq_scale), ggml_cast(ctx0, kq_mask, GGML_TYPE_F32)); - kq = ggml_soft_max(ctx0, ggml_concat(ctx0, kq, sinks, 0)); - kq = ggml_cont(ctx0, ggml_view_4d(ctx0, kq, n_kv, kq->ne[1], kq->ne[2], kq->ne[3], kq->nb[1], kq->nb[2], kq->nb[3], 0)); - } else { - kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); - ggml_soft_max_add_sinks(kq, sinks); - } + kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); + ggml_soft_max_add_sinks(kq, sinks); cb(kq, "kq_soft_max", il); if (!v_trans) { @@ -3691,7 +3764,9 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } -ggml_tensor * llm_graph_context::build_attn( +// the iswa build_attn with the KQ mask and kv_rows given by the caller, which has to keep them in sync +static ggml_tensor * build_attn_iswa_impl( + const llm_graph_context & gctx, llm_graph_input_attn_kv_iswa * inp, ggml_tensor * wo, ggml_tensor * wo_b, @@ -3700,11 +3775,18 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * k_cur, ggml_tensor * v_cur, ggml_tensor * kq_b, + ggml_tensor * kq_mask, + ggml_tensor * kv_rows, ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il, - ggml_tensor * kq_mask) const { + int il) { + ggml_context * ctx0 = gctx.ctx0; + ggml_cgraph * gf = gctx.gf; + + const auto & hparams = gctx.hparams; + const auto & cparams = gctx.cparams; + const bool is_swa = hparams.is_swa(il); auto * k_rot = is_swa ? inp->self_k_rot_swa[il] : inp->self_k_rot[il]; @@ -3742,7 +3824,7 @@ ggml_tensor * llm_graph_context::build_attn( // whole seq fits into batch in training mode const bool use_kv_cur = cparams.training && k_cur && v_cur; if (use_kv_cur) { - GGML_ASSERT(mctx_cur->get_n_kv() == n_tokens); + GGML_ASSERT(mctx_cur->get_n_kv() == gctx.n_tokens); } const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; @@ -3760,25 +3842,20 @@ ggml_tensor * llm_graph_context::build_attn( ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); } - if (!kq_mask) { - kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; - } - const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; - ggml_tensor * q = q_cur; ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); - cb(cur, "kqv_out", il); + gctx.cb(cur, "kqv_out", il); if (v_rot) { cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); } if (wo) { - cur = build_lora_mm(wo, cur, wo_s); + cur = gctx.build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3792,6 +3869,27 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_attn_kv_iswa * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + ggml_tensor * v_mla, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + const auto & kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; + const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; + + return build_attn_iswa_impl(*this, inp, wo, wo_b, wo_s, q_cur, k_cur, v_cur, kq_b, kq_mask, kv_rows, sinks, v_mla, kq_scale, il); +} + ggml_tensor * llm_graph_context::build_attn( llm_graph_input_attn_k_iswa * inp, ggml_tensor * wo, @@ -4314,14 +4412,14 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + inp_attn->self_attn_mask = build_attn_inp_attn_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); } { inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + inp_attn->self_attn_mask_swa = build_attn_inp_attn_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); } inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); @@ -4335,6 +4433,87 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); } +llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const { + const auto * mctx_cur = static_cast(mctx); + + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + + const auto * attn_ctx = mctx_cur->get_attn(); + + auto inp_attn = std::make_unique(hparams, cparams, attn_ctx); + + // dense masks: the bias is gathered by the distance to each cell of the K/V view + { + inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + } + + { + inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + } + + inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); + inp_attn->self_v_rot = attn_ctx->get_base()->get_v_rot(); + + inp_attn->self_k_rot_swa = attn_ctx->get_swa()->get_k_rot(); + inp_attn->self_v_rot_swa = attn_ctx->get_swa()->get_v_rot(); + + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); + + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos); + ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); + + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos_swa); + ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + + return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); +} + +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + auto * inp_attn = inp->get_attn(); + + const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; + + // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, + // needs a kv_rows flash attention with a per-head mask (CUDA has none) + GGML_ASSERT(attn_mask.rows == nullptr); + + // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 + ggml_tensor * kq_mask = attn_mask.raw; + if (kq_mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_add(ctx0, kq_b, kq_mask); + if (cparams.flash_attn) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + cb(kq_mask, "kq_mask_rel_pos", il); + + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); +} + void llm_graph_context::build_dense_out( ggml_tensor * dense_2, ggml_tensor * dense_2_b, diff --git a/src/llama-graph.h b/src/llama-graph.h index 862e64e056ef..b5956ead9120 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -774,6 +774,48 @@ class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i { const llama_memory_hybrid_iswa_context * mctx; }; +// hybrid iswa memory with a per-head attention bias that depends on the distance from the query to the cell (Inkling) +// the KQ masks are always dense (rows == nullptr) and are filled from the same cells as the distances, so that the bias +// gathered by distance lines up with the mask +class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { +public: + llm_graph_input_mem_hybrid_iswa_rel( + const llama_cparams & cparams, + std::unique_ptr inp_attn, + std::unique_ptr inp_rs, + const llama_memory_hybrid_iswa_context * mctx, + uint32_t extent, + uint32_t extent_swa) : + inp_attn(std::move(inp_attn)), + inp_rs(std::move(inp_rs)), + extent(extent), + extent_swa(extent_swa), + cparams(cparams), + mctx(mctx) { } + virtual ~llm_graph_input_mem_hybrid_iswa_rel() = default; + + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params & params) override; + + std::unique_ptr inp_attn; + std::unique_ptr inp_rs; + + llm_graph_input_attn_kv_iswa * get_attn() const { return inp_attn.get(); } + llm_graph_input_rs * get_recr() const { return inp_rs.get(); } + + // distance from the token to the cell, extent for the empty, future and more distant cells + ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] + ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + + const uint32_t extent; + const uint32_t extent_swa; + + const llama_cparams cparams; + + const llama_memory_hybrid_iswa_context * mctx; +}; + class llm_graph_input_sampling : public llm_graph_input_i { public: llm_graph_input_sampling(std::map samplers) : @@ -804,7 +846,6 @@ class llm_graph_result; struct llm_graph_params { const llama_model * model = nullptr; - llama_hparams hparams; llama_cparams cparams; llama_ubatch ubatch; // note: intentionally make a copy @@ -820,10 +861,6 @@ struct llm_graph_params { const llama_cross * cross; const llama_moe_cache * moe_cache; - const llama_prec_policy * prec_policy = nullptr; - - const llama_hadamard * hdmd = nullptr; - ggml_tensor * layer_inp_dev = nullptr; // own layer input device buffer (write) ggml_tensor * layer_inp_src = nullptr; // ctx_other's layer input device buffer (read) ggml_tensor * h_nextn_dev = nullptr; // own h_nextn device buffer (write) @@ -1056,6 +1093,8 @@ struct llm_graph_context { const llama_cparams & cparams; const llama_ubatch & ubatch; + const llama_prec_policy & prec_policy; + const int64_t n_embd; const int64_t n_layer; const int64_t n_layer_nextn; @@ -1096,8 +1135,6 @@ struct llm_graph_context { const llama_cross * cross; const llama_moe_cache * moe_cache; - const llama_prec_policy * prec_policy; - const llama_hadamard * hdmd; ggml_tensor * layer_inp_dev; @@ -1406,8 +1443,7 @@ struct llm_graph_context { ggml_tensor * sinks, // [n_head_q] ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] float kq_scale, - int il, - ggml_tensor * kq_mask = nullptr) const; + int il) const; llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa() const; @@ -1500,6 +1536,25 @@ struct llm_graph_context { llm_graph_input_mem_hybrid_iswa * build_inp_mem_hybrid_iswa() const; + // extent, extent_swa: the distance that the bias tables of the full and the SWA layers stop at + llm_graph_input_mem_hybrid_iswa_rel * build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const; + + // kq_b is added to the KQ mask, after the KQ scale + ggml_tensor * build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] + ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] + ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] + ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * sinks, // [n_head_q] + float kq_scale, + int il) const; + // // pooling // diff --git a/src/llama-mmap.cpp b/src/llama-mmap.cpp index 9688a7ed4e92..02e4ede7c4d6 100644 --- a/src/llama-mmap.cpp +++ b/src/llama-mmap.cpp @@ -5,7 +5,6 @@ #include "ggml.h" #include -#include #include #include #include @@ -32,9 +31,6 @@ #endif #include #include - #ifndef PATH_MAX - #define PATH_MAX MAX_PATH - #endif #include #endif @@ -513,7 +509,7 @@ struct llama_file::impl { if (errno == EINTR) { continue; } - if (errno == EFAULT || errno == EINVAL) { + if (errno == EFAULT || errno == EINVAL || errno == EIO) { LLAMA_LOG_WARN("%s: file '%s' falling back to buffered I/O due to %s\n", __func__, fname.c_str(), strerror(errno)); const size_t read_offset = tell(); @@ -522,7 +518,7 @@ struct llama_file::impl { alignment = 1; init_fp("rb"); seek(read_offset, SEEK_SET); - read_raw_unsafe(ptr, len); + read_raw_unsafe(static_cast(ptr) + bytes_read, to_read); return; } throw std::runtime_error(format("read error: %s", strerror(errno))); @@ -1140,7 +1136,3 @@ void llama_prefetch(llama_memory_ranges mr) { GGML_UNUSED(mr); #endif } - -size_t llama_path_max() { - return PATH_MAX; -} diff --git a/src/llama-mmap.h b/src/llama-mmap.h index 6c6393d5734d..39715bfc38b5 100644 --- a/src/llama-mmap.h +++ b/src/llama-mmap.h @@ -88,5 +88,3 @@ using llama_memory_ranges = std::vector; // Prefetch the host pages covering these memory ranges. void llama_prefetch(llama_memory_ranges mr); - -size_t llama_path_max(); diff --git a/src/llama-model-loader.cpp b/src/llama-model-loader.cpp index 548ade1019a0..808fb44d881f 100644 --- a/src/llama-model-loader.cpp +++ b/src/llama-model-loader.cpp @@ -84,7 +84,7 @@ const char * llama_ftype_name(llama_ftype ftype) { static std::vector llama_get_list_splits(const std::string & path, const int idx, const int n_split) { std::vector paths; std::string split_prefix; - std::vector buf(llama_path_max(), 0); + std::vector buf(path.size() + 1, 0); { int ret = llama_split_prefix(buf.data(), buf.size(), path.c_str(), idx, n_split); @@ -610,7 +610,7 @@ llama_model_loader::llama_model_loader( throw std::runtime_error(format("illegal split file idx: %d (file: %s), model must be loaded with the first split", idx, fname.c_str())); } - std::vector prefix(llama_path_max(), 0); + std::vector prefix(fname.size() + 1, 0); if (paths.empty() || llama_split_prefix(prefix.data(), prefix.size(), fname.c_str(), idx, n_split)) { auto backbone = llama_get_list_splits(fname, idx, n_split); auto file_name = [](const std::string & path) { diff --git a/src/llama-model.cpp b/src/llama-model.cpp index ac5266a42d2a..629b3a7a6899 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -394,6 +394,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_k2_horizon(params); case LLM_ARCH_KOLIBRI1: return new llama_model_kolibri1(params); + case LLM_ARCH_DOMYN_EDGE: + return new llama_model_domyn_edge(params); default: throw std::runtime_error(std::string("unsupported model architecture: '") + llm_arch_name(arch) + "'"); } @@ -3873,6 +3875,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_HRM_TEXT: case LLM_ARCH_BEAM: case LLM_ARCH_KOLIBRI1: + case LLM_ARCH_DOMYN_EDGE: return LLAMA_ROPE_TYPE_NEOX; case LLM_ARCH_DFLASH: diff --git a/src/llama-model.h b/src/llama-model.h index 8d2f5629efae..1cc5d743a781 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -1052,6 +1052,9 @@ struct llama_model { llama_memory_i * create_memory(const llama_memory_params & params, const llama_cparams & cparams) const; + // graph size budget: max graph nodes per model tensor + virtual uint32_t graph_nodes_per_tensor() const { return 8; } + ggml_cgraph * build_graph(const llm_graph_params & params) const; virtual void load_stats (llama_model_loader & ml) = 0; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 0f3f982b063f..79d964972831 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -1266,7 +1266,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: GGML_ASSERT(ctx_outs[cur_split] && "Find uninitialized gguf_context"); std::string fname = fname_out; if (params->keep_split) { - std::vector split_path(llama_path_max(), 0); + std::vector split_path(fname_out.size() + sizeof("-00000-of-00000.gguf"), 0); llama_split_path(split_path.data(), split_path.size(), fname_out.c_str(), cur_split, n_split); fname = std::string(split_path.data()); } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 3aecacb516bc..f3e1d0192414 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2566,7 +2566,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "qwen2" || tokenizer_pre == "deepseek-r1-qwen" || tokenizer_pre == "kormo" || - tokenizer_pre == "f2llmv2") { + tokenizer_pre == "f2llmv2" || + tokenizer_pre == "domyn-edge") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; } else if ( diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 000222f4c0d1..98a8d1d9acec 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -125,6 +125,20 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { } } +uint32_t llama_model_dflash::graph_nodes_per_tensor() const { + if (hparams.dsv4_hc_mult > 0) { + return 32; + } + if (hparams.dflash_selector_rank > 0) { + // DFlash2's convolutions and selector are shape work rather than matmuls, + // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. + // The selector lattice scales with the draft block size; 12u was calibrated + // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). + return 12u*std::max(1u, hparams.dflash_block_size/8u); + } + return llama_model_base::graph_nodes_per_tensor(); +} + void llama_model_dflash::load_tensors_layers_base() { LLAMA_LOAD_LOCALS; diff --git a/src/models/domyn-edge.cpp b/src/models/domyn-edge.cpp new file mode 100644 index 000000000000..6452894d34be --- /dev/null +++ b/src/models/domyn-edge.cpp @@ -0,0 +1,164 @@ +#include "models.h" + +void llama_model_domyn_edge::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + // required: the base loader defaults it to n_rot_full if the key is not found + ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT_SWA, hparams.n_rot_swa); + // RoPE cannot rotate more dims than the SWA head has: CPU aborts, GPU backends read past the row + if (hparams.n_rot_swa > hparams.n_embd_head_k_swa) { + throw std::runtime_error(format("invalid n_rot_swa: %u, max %u", hparams.n_rot_swa, hparams.n_embd_head_k_swa)); + } + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + ml.get_arr(LLM_KV_ATTENTION_ROPE_PATTERN, hparams.rope_pattern); + + // only for print_info / saver; get_rope_params uses cparams + hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; + hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; + + switch (hparams.n_layer()) { + case 36: type = LLM_TYPE_4B; break; + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_domyn_edge::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + 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}, TENSOR_NOT_REQUIRED); + + // if output is NULL, init from the input tok embed + if (output == NULL) { + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + const int64_t n_embd_head_i = hparams.n_embd_head_k(i); + const int64_t n_embd_k_i = hparams.n_embd_k_gqa(i); + const int64_t n_embd_v_i = hparams.n_embd_v_gqa(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0); + + const int64_t n_embd_q_i = n_embd_head_i * n_head; + create_tensor_qkv(layer, i, n_embd, n_embd_q_i, n_embd_k_i, n_embd_v_i, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_i * n_head, n_embd}, 0); + + // K-norm has a learnable weight; Q-norm does not + layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_i}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0); + + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } +} + +llama_rope_params llama_model_domyn_edge::get_rope_params(const llama_cparams & cparams, int il) const { + auto res = llama_model::get_rope_params(cparams, il); + + // the SWA layers use the global base and scale + res.freq_base = cparams.rope_freq_base; + res.freq_scale = cparams.rope_freq_scale; + + return res; +} + +llama_model_domyn_edge::graph::graph(const llm_graph_params & params) + : llm_graph_context(params) { + ggml_tensor * cur; + ggml_tensor * inpL = build_inp_embd(model.tok_embd); + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = build_attn_inp_kv_iswa(); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_head_il = hparams.n_head(il); + const int64_t n_head_kv_il = hparams.n_head_kv(il); + const float kq_scale = 1.0f / sqrtf((float)n_embd_head); + + ggml_tensor * residual = inpL; + + // pre-attention norm + cur = build_norm(inpL, layer.attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head_il, n_head_kv_il, il); + + // Q-norm: RMSNorm without learnable weight (elementwise_affine=False) + Qcur = build_norm(Qcur, NULL, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + + // K-norm: RMSNorm with learnable weight + Kcur = build_norm(Kcur, layer.attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + + // build_rope already applies RoPE only if the current layer is a RoPE layer + Qcur = build_rope(Qcur, inp_pos, il); + cb(Qcur, "Qcur_rope", il); + + Kcur = build_rope(Kcur, inp_pos, il); + cb(Kcur, "Kcur_rope", il); + + cur = build_attn(inp_attn, + layer.wo, NULL, layer.wo_s, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il); + cb(cur, "attn_out", il); + + // post-attention norm applied to attn output before residual add + cur = build_norm(cur, layer.attn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_post_norm", il); + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + residual = ggml_get_rows(ctx0, residual, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, residual); + cb(ffn_inp, "ffn_inp", il); + + // pre-FFN norm + cur = build_norm(ffn_inp, layer.ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + // SwiGLU FFN + 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); + cb(cur, "ffn_out", il); + + // post-FFN norm applied to ffn output before residual add + cur = build_norm(cur, layer.ffn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_post_norm", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + inpL = build_cvec(cur, il); + cb(inpL, "l_out", il); + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur, model.output_s); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + +std::unique_ptr llama_model_domyn_edge::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} diff --git a/src/models/hrm-text.cpp b/src/models/hrm-text.cpp index 8e3b34c57580..4c3d52e32702 100644 --- a/src/models/hrm-text.cpp +++ b/src/models/hrm-text.cpp @@ -1,5 +1,7 @@ #include "models.h" +#include + // HRM-Text: alternating low/high transformer stacks over the same token stream. // Reference: HrmTextModel in transformers, DFM Mimir 1B. @@ -19,8 +21,15 @@ void llama_model_hrm_text::load_arch_hparams(llama_model_loader & ml) { GGML_ASSERT(hparams.n_hrm_l_cycles > 0); // the GGUF block count is the expanded cache-slot count - const uint32_t n_slot = hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); - GGML_ASSERT(hparams.n_layer() == n_slot); + // 64-bit: a 32-bit product can wrap and match n_layer(), then load_arch_tensors() indexes past model.layers + const uint64_t n_slot = (uint64_t) hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); + if (hparams.n_hrm_layers_per_stack >= hparams.n_layer() || n_slot != hparams.n_layer()) { + throw std::runtime_error(format( + "hrm: cache-slot count %" PRIu64 " (layers_per_stack %u, h_cycles %u, l_cycles %u) " + "does not match block_count %u", + n_slot, hparams.n_hrm_layers_per_stack, hparams.n_hrm_h_cycles, + hparams.n_hrm_l_cycles, hparams.n_layer())); + } switch (hparams.n_embd) { case 1536: diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 41eebd1908df..3ba20ffe83d4 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -2,111 +2,157 @@ #include "../llama-memory-hybrid-iswa.h" void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { - 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_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); + ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); + ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); + + // relative-position bias, and the log-scaled positions of the full-attention layers ml.get_key(LLM_KV_ATTENTION_RELATIVE_LENGTH, hparams.n_relative); ml.get_key(LLM_KV_ATTENTION_RELATIVE_EXTENT, hparams.n_relative_extent); - ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); - ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); + ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_FLOOR, hparams.n_log_scale_floor); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_ALPHA, hparams.f_log_scale_alpha); - ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); - ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); - ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); + + // the embedding and output tensors are padded past the vocabulary + ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); ml.get_key(LLM_KV_VOCAB_SIZE_UNPADDED, hparams.n_vocab_unpadded); - ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); + + // MoE + 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_ACTIVATION_SITU_BETA, hparams.situ_beta); ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta); - ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); - ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping); - ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + + hparams.f_final_logit_softcapping = 0.0f; + ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false); + + // sliding window + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + uint32_t n_pattern = 0; ml.get_arr_n(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, n_pattern); + if (n_pattern != hparams.n_layer() || !hparams.n_relative || !hparams.n_relative_extent || !hparams.n_swa || !hparams.attn_res_block_size || !hparams.n_log_scale_floor || hparams.n_shortconv_l_cache < 2 || hparams.n_shortconv_l_cache > 64 || hparams.n_relative_extent > INT32_MAX || hparams.n_swa > INT32_MAX || !hparams.n_vocab_unpadded || hparams.n_vocab_unpadded > hparams.n_vocab_padded) { throw std::runtime_error("inkling2: invalid dimensions, vocabulary, or layer pattern"); } - for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, - hparams.situ_linear_beta, hparams.expert_weights_scale, hparams.f_final_logit_softcapping}) { + + for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, hparams.situ_linear_beta}) { if (!std::isfinite(value) || value <= 0.0f) { throw std::runtime_error("inkling2: normalization, clipping and scaling parameters must be finite and positive"); } } + if (!std::isfinite(hparams.f_log_scale_alpha) || hparams.f_log_scale_alpha < 0.0f) { throw std::runtime_error("inkling2: invalid logarithmic scale"); } - hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; - hparams.expert_router_f32 = true; + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + hparams.expert_router_f32 = true; hparams.expert_weights_norm_eps = 1e-20f; + + // no RoPE, the relative-position bias carries the positions hparams.rope_pattern.fill(false); - uint64_t max_channels = 0; + + // the convolution state keeps K, V, the attention output and the FFN output of the widest layer + uint64_t n_channels_max = 0; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { if (!hparams.n_head_kv(il) || hparams.n_head(il) % hparams.n_head_kv(il) || hparams.n_embd_head_k(il) != hparams.n_embd_head_v(il) || !hparams.n_expert_used(il) || hparams.n_expert_used(il) > hparams.n_expert || !hparams.n_ff_exp(il)) { throw std::runtime_error("inkling2: invalid attention or expert dimensions"); } - max_channels = std::max(max_channels, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); + + n_channels_max = std::max(n_channels_max, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); } - if (max_channels * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { + + if (n_channels_max * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { throw std::runtime_error("inkling2: convolution state is too large"); } - hparams.n_sconv_channels = max_channels; + + hparams.n_sconv_channels = n_channels_max; + type = LLM_TYPE_UNKNOWN; } void llama_model_inkling2::load_arch_tensors(llama_model_loader &) { LLAMA_LOAD_LOCALS; + if (hparams.n_vocab_unpadded != vocab.n_tokens()) { throw std::runtime_error("inkling2: tokenizer size must equal the unpadded vocabulary size"); } - tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, hparams.n_vocab_padded}, 0); + + const int64_t n_vocab_padded = hparams.n_vocab_padded; + const int64_t n_rel = hparams.n_relative; + const int64_t n_conv = hparams.n_shortconv_l_cache; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab_padded}, 0); tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight", 0), {n_embd}, 0); - output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, hparams.n_vocab_padded}, 0); - output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + + // output + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_padded}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); output_res_query = create_tensor(tn(LLM_TENSOR_OUTPUT_RES_QUERY, "weight"), {n_embd}, 0); + for (int i = 0; i < n_layer; ++i) { - auto & l = layers[i]; - const int64_t nh = hparams.n_head(i); - const int64_t nk = hparams.n_head_kv(i); - const int64_t hd = hparams.n_embd_head_k(i); - const int64_t nr = hparams.n_relative; - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; - l.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, nh*hd}, 0); - l.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, nk*hd}, 0); - l.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, nk*hd}, 0); - l.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {nh*hd, n_embd}, 0); - l.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, nh*hd}, 0); - l.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, nh*nr}, 0); - l.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {nr, extent}, 0); - l.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {hd, nh}, 0); - l.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {nr, nh}, 0); - l.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, nh}, 0); - l.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {kernel, n_embd}, 0); - l.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {kernel, n_embd}, 0); + auto & layer = layers[i]; + + const int64_t n_head = hparams.n_head(i); + const int64_t n_head_kv = hparams.n_head_kv(i); + const int64_t n_embd_head = hparams.n_embd_head_k(i); + const int64_t n_ff_exp = hparams.n_ff_exp(i); + const int64_t n_extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; + + // attention + layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head*n_head}, 0); + layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head*n_head, n_embd}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_embd_head*n_head}, 0); + + layer.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {n_embd_head, n_head}, 0); + layer.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, n_head}, 0); + + // relative-position bias + layer.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, n_rel*n_head}, 0); + layer.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {n_rel, n_extent}, 0); + layer.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {n_rel, n_head}, 0); + + // short convolutions + layer.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + layer.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + if (hparams.is_swa(i)) { - l.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); } else { - l.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); - l.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); + // full-attention layers: separate Q, K and V input norms, and input-dependent taps for the K and V convolutions + layer.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); + layer.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); } + + // block attention residuals if (i > 0) { - l.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); + layer.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); } - l.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); - l.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); - l.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); - l.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); - l.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*hparams.n_ff_exp(i), n_expert}, 0); - l.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {hparams.n_ff_exp(i), n_embd, n_expert}, 0); + layer.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); + + // MoE + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); + layer.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); } } @@ -114,202 +160,250 @@ std::unique_ptr llama_model_inkling2::build_arch_graph(const return std::make_unique(params); } -class llm_graph_input_inkling2_pos : public llm_graph_input_i { -public: - const llama_kv_cache_context * cache[2]; - ggml_tensor * distance[2]; - uint32_t extent[2]; - - bool can_reuse(const llm_graph_params & params) override { - const auto * memory = static_cast(params.mctx); - cache[0] = memory->get_attn()->get_base(); - cache[1] = memory->get_attn()->get_swa(); - for (int i = 0; i < 2; ++i) { - if (distance[i]->ne[0] != cache[i]->get_n_kv() || distance[i]->ne[1] != params.ubatch.n_tokens) { - return false; - } - } - return true; - } - - void set_input(const llama_ubatch * ubatch) override { - for (int i = 0; i < 2; ++i) { - if (distance[i]->buffer) { - cache[i]->set_input_relative_pos(distance[i], ubatch, extent[i]); - } - } - } -}; - +// scale each row down to an L2 norm of at most threshold, after the optional per-channel scale ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold) { if (scale) { cur = ggml_mul(ctx0, cur, scale); } - auto * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); + + ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - auto * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + + ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); } +// attention over the depth: mix the earlier block outputs and cur with learned queries ggml_tensor * llama_model_inkling2::graph::mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query) { - auto * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); - for (auto * block : blocks) { + ggml_tensor * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); + for (ggml_tensor * block : blocks) { states = ggml_concat(ctx0, ggml_reshape_3d(ctx0, block, n_embd, 1, n_tokens), states, 1); } states = ggml_rms_norm(ctx0, states, 1e-6f); - auto * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); - auto * scores = ggml_mul_mat(ctx0, states, queries); + + ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); + + ggml_tensor * scores = ggml_mul_mat(ctx0, states, queries); scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); + return ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, states)), scores); } -ggml_tensor * llama_model_inkling2::graph::convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, - ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset) { - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t channels = cur->ne[0]; - const int64_t nt = ubatch.n_seq_tokens; - const int64_t ns = ubatch.n_seqs; - auto * past = ggml_view_3d(ctx0, history, kernel - 1, channels, ns, history->nb[1], history->nb[2], offset*history->nb[1]); - auto * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, channels, nt, ns)); +// causal short convolution with a residual; dynamic adds input-dependent taps per head +// the last n_conv - 1 inputs of each sequence live in the recurrent state at channel offset `offset` +ggml_tensor * llama_model_inkling2::graph::convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset) { + const int64_t n_conv = hparams.n_shortconv_l_cache; + const int64_t n_channels = cur->ne[0]; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]); + + ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs)); x = ggml_concat(ctx0, past, x, 0); - build_conv_state_store(inp, state, x, kernel - 1, offset*(kernel - 1)*ggml_element_size(state)); - auto * out = ggml_ssm_conv(ctx0, x, weight); - out = ggml_reshape_2d(ctx0, out, channels, n_tokens); + + build_conv_state_store(inp, state, x, n_conv - 1, offset*(n_conv - 1)*ggml_element_size(state)); + + ggml_tensor * out = ggml_ssm_conv(ctx0, x, weight); + out = ggml_reshape_2d(ctx0, out, n_channels, n_tokens); + if (dynamic) { - const int64_t heads = dynamic->ne[0]/kernel; - dynamic = ggml_reshape_3d(ctx0, dynamic, kernel, heads, n_tokens); - for (int64_t lag = 0; lag < kernel; ++lag) { - auto * tap = ggml_view_3d(ctx0, dynamic, 1, heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); - auto * window = ggml_view_3d(ctx0, x, nt, channels, ns, x->nb[1], x->nb[2], (kernel - 1 - lag)*x->nb[0]); + const int64_t n_heads = dynamic->ne[0]/n_conv; + + dynamic = ggml_reshape_3d(ctx0, dynamic, n_conv, n_heads, n_tokens); + + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_3d(ctx0, dynamic, 1, n_heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); + ggml_tensor * window = ggml_view_3d(ctx0, x, n_seq_tokens, n_channels, n_seqs, x->nb[1], x->nb[2], (n_conv - 1 - lag)*x->nb[0]); + window = ggml_cont(ctx0, ggml_transpose(ctx0, window)); - window = ggml_reshape_3d(ctx0, window, channels/heads, heads, n_tokens); - auto * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), channels, n_tokens); + window = ggml_reshape_3d(ctx0, window, n_channels/n_heads, n_heads, n_tokens); + + ggml_tensor * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), n_channels, n_tokens); + out = ggml_add(ctx0, out, term); } } - return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*kernel + 1)); + + return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1)); } llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { - auto * inp = build_inp_mem_hybrid_iswa(); + auto * inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); auto * attn = inp->get_attn(); auto * recr = inp->get_recr(); - auto * positions = build_inp_pos(); - auto * out_ids = build_inp_out_ids(); - auto rel = std::make_unique(); - rel->cache[0] = attn->mctx->get_base(); - rel->cache[1] = attn->mctx->get_swa(); - rel->extent[0] = hparams.n_relative_extent; - rel->extent[1] = hparams.n_swa; - ggml_tensor * distances[2]; - for (int i = 0; i < 2; ++i) { - distances[i] = rel->distance[i] = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, rel->cache[i]->get_n_kv(), n_tokens); - ggml_set_input(distances[i]); - } - res->add_input(std::move(rel)); - auto * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, positions, GGML_TYPE_F32), 1.0f, 1.0f); + + ggml_tensor * inp_pos = build_inp_pos(); + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + // log-scaled positions: 1 + alpha*log(max(1, (pos + 1)/floor)), multiplies q and r of the full-attention layers + ggml_tensor * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f); tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY)); tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens); - auto * cur = build_inp_embd(model.tok_embd); + + ggml_tensor * cur = build_inp_embd(model.tok_embd); + // important: do not normalize raw embeddings input (i.e. encoded image embeddings) if (ubatch.token) { cur = build_norm(cur, model.tok_norm, nullptr, LLM_NORM_RMS, -1); } + std::vector blocks; + for (int il = 0; il < n_layer; ++il) { - const auto & l = model.layers[il]; - const bool swa = hparams.is_swa(il); - const int64_t nh = hparams.n_head(il); - const int64_t nk = hparams.n_head_kv(il); - const int64_t hd = hparams.n_embd_head_k(il); - const int64_t kv = nk*hd; - auto * state = recr->mctx->get_r_l(il); - auto * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); + const auto & layer = model.layers[il]; + + const bool is_swa = hparams.is_swa(il); + const int64_t n_head = hparams.n_head(il); + const int64_t n_head_kv = hparams.n_head_kv(il); + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; + + ggml_tensor * state = recr->mctx->get_r_l(il); + ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); - auto * residual = cur; + + ggml_tensor * inpSA = cur; + + // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V ggml_tensor * inputs[3] = {cur, cur, cur}; - if (l.attn_res_query) { - auto * mixed = mix(blocks, cur, l.attn_res_query); + if (layer.attn_res_query) { + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); for (int j = 0; j < 3; ++j) { - inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (swa ? 0 : j)*mixed->nb[1])); + inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[1])); } } - if (swa) { - inputs[0] = build_norm(inputs[0], l.attn_norm, nullptr, LLM_NORM_RMS, il); + + if (is_swa) { + inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); inputs[1] = inputs[2] = inputs[0]; } else { - inputs[0] = build_norm(inputs[0], l.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = build_norm(inputs[1], l.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[2] = build_norm(inputs[2], l.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); - } - auto * q = build_lora_mm(l.wq, inputs[0]); - auto * k = convolve(build_lora_mm(l.wk, inputs[1]), l.attn_k_conv, - swa ? nullptr : build_lora_mm(l.attn_k_conv_proj, inputs[1]), state, history, recr, 0); - auto * v = convolve(build_lora_mm(l.wv, inputs[2]), l.attn_v_conv, - swa ? nullptr : build_lora_mm(l.attn_v_conv_proj, inputs[2]), state, history, recr, kv); - auto * r = build_lora_mm(l.attn_rel, inputs[0]); - q = clip(ggml_reshape_3d(ctx0, q, hd, nh, n_tokens), l.attn_q_clip, hparams.f_qk_clip); - k = clip(ggml_reshape_3d(ctx0, k, hd, nk, n_tokens), nullptr, hparams.f_qk_clip); - v = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, v, hd, nk, n_tokens), hparams.f_norm_rms_eps); - r = clip(ggml_reshape_3d(ctx0, r, hparams.n_relative, nh, n_tokens), l.attn_rel_clip, hparams.f_relative_clip); - if (!swa) { - q = ggml_mul(ctx0, q, tau); - r = ggml_mul(ctx0, r, tau); - } - auto * mask = swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - const int64_t streams = mask->ne[3]; - const int64_t n_kv = distances[swa]->ne[0]; - auto * sinks = build_lora_mm(l.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x nh - auto * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, l.attn_rel_bias, 0, 1, 0, 0), r); - if (cparams.flash_attn) { - // exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))). - table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, nh, n_tokens)); - } else { - // build_attn scales the bias along with QK; FA adds the mask after scaling QK. - table = ggml_scale(ctx0, table, sqrtf(hd)); + inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); } - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - auto * bias = ggml_get_rows(ctx0, table, distances[swa]); - bias = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_4d(ctx0, bias, nh, n_kv, n_tokens/streams, streams), 2, 0, 1, 3)); - ggml_tensor * fa_mask = nullptr; - if (cparams.flash_attn) { - fa_mask = ggml_cast(ctx0, ggml_add(ctx0, bias, ggml_cast(ctx0, mask, GGML_TYPE_F32)), GGML_TYPE_F16); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, nh), 0.0f); - bias = nullptr; - } else { - sinks = ggml_reshape_4d(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, - ggml_reshape_3d(ctx0, sinks, nh, n_tokens/streams, streams), 1, 0, 2, 3)), 1, n_tokens/streams, nh, streams); + + // self-attention + { + ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); + ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); + ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); + ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + + Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); + Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); + Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + + if (!is_swa) { + Qcur = ggml_mul(ctx0, Qcur, tau); + Rcur = ggml_mul(ctx0, Rcur, tau); + } + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + cb(Rcur, "Rcur", il); + + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + + const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; + const int64_t n_kv = rel_pos->ne[0]; + + ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + + // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); + + // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink + table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); + table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); + + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + cb(kq_b, "kq_b", il); + + sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + + cur = build_attn(inp, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + + cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); + cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); + cb(cur, "attn_out", il); } - cur = build_attn(attn, nullptr, nullptr, nullptr, q, k, v, bias, sinks, nullptr, 1.0f/sqrtf(hd), il, fa_mask); - cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(l.wqkv_gate, inputs[0]))); - cur = convolve(build_lora_mm(l.wo, cur), l.attn_post_conv, nullptr, state, history, recr, 2*kv); + + // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks if (il % hparams.attn_res_block_size == 0) { - blocks.push_back(residual); + blocks.push_back(inpSA); } else { - cur = ggml_add(ctx0, residual, cur); + cur = ggml_add(ctx0, inpSA, cur); } - residual = cur; - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, l.ffn_res_query), n_embd, n_tokens); - cur = build_norm(cur, l.ffn_norm, nullptr, LLM_NORM_RMS, il); - cur = build_moe_ffn(cur, l.ffn_gate_inp, nullptr, nullptr, l.ffn_down_exps, l.ffn_exp_probs_b, - hparams.n_expert, hparams.n_expert_used(il), LLM_FFN_SITU, true, hparams.expert_weights_scale, - LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, nullptr, l.ffn_gate_up_exps); - cur = convolve(cur, l.ffn_post_conv, nullptr, state, history, recr, 2*kv + n_embd); - cur = ggml_add(ctx0, residual, cur); + + ggml_tensor * ffn_inp = cur; + cb(ffn_inp, "ffn_inp", il); + + // MoE + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + + cur = build_moe_ffn(cur, + layer.ffn_gate_inp, + nullptr, + nullptr, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, + hparams.n_expert_used(il), + LLM_FFN_SITU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, + il, + nullptr, + layer.ffn_gate_up_exps); + + cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, ffn_inp, cur); cb(cur, "l_out", il); } + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, model.output_res_query), n_embd, n_tokens); cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); - if (out_ids) { - cur = ggml_get_rows(ctx0, cur, out_ids); + + if (inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); } + + cb(cur, "result_norm", -1); res->t_embd = cur; + + // lm_head cur = build_lora_mm(model.output, cur); ggml_prec_set_acc(cur, GGML_PREC_F32); - const float cap = hparams.f_final_logit_softcapping; - cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + + if (hparams.f_final_logit_softcapping != 0.0f) { + const float cap = hparams.f_final_logit_softcapping; + + cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + } + + // drop the padded vocabulary cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); - res->t_logits = cur; + cb(cur, "result_output", -1); + res->t_logits = cur; } diff --git a/src/models/models.h b/src/models/models.h index 8d74c5018920..979ceffc271b 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -442,6 +442,7 @@ struct llama_model_nanbeige : public llama_model_base { llama_model_nanbeige(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; } int n_loops = 1; int n_layer_phys = 0; @@ -801,6 +802,7 @@ struct llama_model_zonos3 : public llama_model_base { llama_model_zonos3(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -1282,6 +1284,7 @@ struct llama_model_deepseek4 : public llama_model_base { llama_model_deepseek4(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; } struct graph : public llm_graph_context { struct no_build {}; @@ -1439,6 +1442,7 @@ struct llama_model_xing4_0 : public llama_model_base { llama_model_xing4_0(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; } struct graph : public llm_graph_context { graph(const llama_model & model, const llm_graph_params & params); @@ -1571,6 +1575,7 @@ struct llama_model_dflash : public llama_model_base { llama_model_dflash(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; enum variant_type { VARIANT_DFLASH, @@ -1833,6 +1838,7 @@ struct llama_model_metis16 : public llama_model_base { llama_model_metis16(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; } uint32_t n_pass = 1; uint32_t n_stream = 1; @@ -2134,6 +2140,7 @@ struct llama_model_hrm_text : public llama_model_base { llama_model_hrm_text(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2176,6 +2183,7 @@ struct llama_model_bailingmoe3 : public llama_model_base { llama_model_bailingmoe3(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2346,6 +2354,7 @@ struct llama_model_hy_v4 : public llama_model_base { llama_model_hy_v4(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; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2475,12 +2484,20 @@ struct llama_model_inkling2 : public llama_model_base { llama_model_inkling2(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; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold); - ggml_tensor * convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset); + ggml_tensor * convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset); }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; @@ -2592,6 +2609,7 @@ struct llama_model_minimax_01 : public llama_model_base { llama_model_minimax_01(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; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2622,6 +2640,7 @@ struct llama_model_minimax_m3 : public llama_model_base { llama_model_minimax_m3(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; } msa_params msa_p; struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2666,6 +2685,7 @@ struct llama_model_qwen3next : public llama_model_base { llama_model_qwen3next(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2708,6 +2728,7 @@ struct llama_model_qwen35 : public llama_model_base { llama_model_qwen35(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2844,6 +2865,7 @@ struct llama_model_qwen4exp : public llama_model_base { 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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2958,6 +2980,7 @@ struct llama_model_qwen35moe : public llama_model_base { llama_model_qwen35moe(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3000,6 +3023,7 @@ struct llama_model_clover_moe : public llama_model_base { llama_model_clover_moe(const 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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3048,6 +3072,7 @@ struct llama_model_kimi_k3 : public llama_model_base { llama_model_kimi_k3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3088,6 +3113,7 @@ struct llama_model_kimi_k31 : public llama_model_base { llama_model_kimi_k31(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3134,6 +3160,7 @@ struct llama_model_glm5_next : public llama_model_base { llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } // k-pool indexer inputs on top of the generic hybrid input class llm_graph_input_kpool; @@ -3218,6 +3245,7 @@ struct llama_model_kimi_linear : public llama_model_base { llama_model_kimi_linear(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; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3301,3 +3329,16 @@ struct llama_model_kolibri1 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; + +struct llama_model_domyn_edge : public llama_model_base { + llama_model_domyn_edge(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; + llama_rope_params get_rope_params(const llama_cparams & cparams, int il) const override; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; diff --git a/src/models/qwen3vl.cpp b/src/models/qwen3vl.cpp index ed9fe6507e68..1bc56e7f4f8d 100644 --- a/src/models/qwen3vl.cpp +++ b/src/models/qwen3vl.cpp @@ -85,6 +85,8 @@ llama_model_qwen3vl::graph::graph(const llm_graph_params & params) : llm_graph_c ggml_tensor * inp_out_ids = build_inp_out_ids(); for (int il = 0; il < n_layer; ++il) { + res->t_layer_inp[il] = inpL; + ggml_tensor * inpSA = inpL; // norm diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0b7e8e4a9b35..5b997e91bbcf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -367,6 +367,8 @@ endif() llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) llama_build_and_test(test-backend-tensor.cpp LINK ggml) +llama_build_and_test(test-sleep.cpp LINK ggml) +llama_build_and_test(test-backend-sched.cpp LINK ggml) if (BUILD_SHARED_LIBS) llama_build_and_test(test-llama-mmap.cpp ${PROJECT_SOURCE_DIR}/src/llama-impl.cpp ${PROJECT_SOURCE_DIR}/src/llama-mmap.cpp LABEL behavior) diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 310934e31725..295740c7cd3c 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -65,6 +65,8 @@ deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAM deepseek41 ,0 ,any ,MUL+ADD , 12 deepseek41 ,0 ,any ,RMS_NORM+MUL , 29 deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 +domynedge ,0 ,any ,RMS_NORM+MUL , 8 +domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3 dots1 ,0 ,any ,ADD+ADD , 1 dots1 ,0 ,any ,MUL+ADD , 2 dots1 ,0 ,any ,RMS_NORM+MUL , 9 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index b20e0d3fe76e..42e356ae0617 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2830,6 +2830,12 @@ struct test_set_rows : public test_case { if (type_src == GGML_TYPE_F16) { err_estimate *= 16.0f; } + if (type_src == GGML_TYPE_BF16) { + // BF16 values have 8 significant bits, so many of them land exactly on a rounding tie, + // and backends break ties differently (e.g. the CPU q8_0 rounds half to even, CUDA half away from zero). + // Allow 1 in 32 values to be off by one instead of one value in total. + return err_estimate / (0.25f*32.0f); + } err_estimate /= 0.25f*float(ne[0] * r * ne[2]*nr23[0] * ne[3]*nr23[1]); return err_estimate; } @@ -2860,10 +2866,15 @@ struct test_rope_set_rows : public test_case { const int n_dims; const bool yarn; const bool truncate; + const ggml_type type_a; // type of the rope input const int n_ctx{512}; std::string vars() override { - return VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + std::string s = VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + if (type_a != GGML_TYPE_F32) { + s += "," + VAR_TO_STR(type_a); + } + return s; } std::string op_desc(ggml_tensor * t) override { @@ -2871,17 +2882,27 @@ struct test_rope_set_rows : public test_case { return "ROPE_SET_ROWS"; } + double max_nmse_err() override { + if (type_a != GGML_TYPE_BF16) { + return 1e-7; + } + // into F16 the reference rounds the BF16 rope result to BF16 first, the fused rope + set_rows does not + // otherwise the limit of a BF16 test_rope: the angle error n_ctx*FLT_EPSILON can flip a BF16 rounding + return type == GGML_TYPE_F16 ? 1e-5 : n_ctx * FLT_EPSILON / 128.0; + } + bool run_whole_graph() override { return true; } test_rope_set_rows(ggml_type type, ggml_type type_idx, std::array ne_a, int mode, - int n_dims = 128, bool yarn = false, bool truncate = true) - : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate) {} + int n_dims = 128, bool yarn = false, bool truncate = true, + ggml_type type_a = GGML_TYPE_F32) + : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate), type_a(type_a) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne_a[0], ne_a[1], ne_a[2], 1); + ggml_tensor * a = ggml_new_tensor_4d(ctx, type_a, ne_a[0], ne_a[1], ne_a[2], 1); ggml_set_name(a, "a"); const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; @@ -5240,16 +5261,20 @@ struct test_gated_delta_net : public test_case { const bool permuted; const bool kda; const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states + const bool correlated; + const bool padded_v; + const bool padded_q; + const bool permuted_k; std::string vars() override { - return VARS_TO_STR9(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K); + return VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); } test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1) + int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5259,11 +5284,15 @@ struct test_gated_delta_net : public test_case { // create with dims 1 and 2 swapped, then permute back to get non-contiguous layout q = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); - v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); + v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); } else { q = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); k = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); - v = ggml_new_tensor_4d(ctx, type, head_size, head_count * v_repeat, n_seq_tokens, n_seqs); + v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, head_count * v_repeat, n_seq_tokens, n_seqs); + } + if (padded_v) { + ggml_set_name(v, "v"); + v = ggml_view_4d(ctx, v, head_size, head_count * v_repeat, n_seq_tokens, n_seqs, v->nb[1], v->nb[2], v->nb[3], 0); } ggml_set_name(q, "q"); ggml_set_name(k, "k"); @@ -5278,6 +5307,17 @@ struct test_gated_delta_net : public test_case { // q/k are L2-normalised in qwen35/kimi-linear before delta_net q = ggml_l2_norm(ctx, q, 1e-6f); k = ggml_l2_norm(ctx, k, 1e-6f); + // Set layouts after normalization, which produces contiguous tensors. + if (padded_q) { + ggml_tensor * q_padded = ggml_new_tensor_4d(ctx, type, head_size + 1, head_count, n_seq_tokens, n_seqs); + q_padded = ggml_view_4d(ctx, q_padded, head_size, head_count, n_seq_tokens, n_seqs, q_padded->nb[1], q_padded->nb[2], q_padded->nb[3], 0); + q = ggml_cpy(ctx, q, q_padded); + } + if (permuted_k) { + ggml_tensor * k_permuted = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs); + k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3); + k = ggml_cpy(ctx, k, k_permuted); + } ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); return out; } @@ -5286,9 +5326,17 @@ struct test_gated_delta_net : public test_case { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { if (ggml_is_view_op(t->op)) { continue; } if (strcmp(t->name, "g") == 0) { - init_tensor_uniform(t, -20.0f, -1e-4f); + init_tensor_uniform(t, correlated ? -1e-4f : -20.0f, -1e-4f); } else if (strcmp(t->name, "beta") == 0) { - init_tensor_uniform(t, 0.0f, 1.0f); + init_tensor_uniform(t, correlated ? 0.9f : 0.0f, correlated ? 0.9f : 1.0f); + } else if (correlated && strcmp(t->name, "k") == 0) { + // Identical unit keys and weak decay stress cancellation in the triangular solve. + GGML_ASSERT(t->type == GGML_TYPE_F32); + std::vector data(ggml_nelements(t), 0.0f); + for (size_t i = 0; i < data.size(); i += size_t(t->ne[0])) { + data[i] = 1.0f; + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float)); } else if (strcmp(t->name, "v") == 0) { init_tensor_uniform(t, -0.3f, 5.0f); } else { @@ -6793,6 +6841,10 @@ struct test_rope : public test_case { // the f32 rotation angle of a position below n_ctx carries a rounding error of up to n_ctx*FLT_EPSILON radians // backends compute the angle with different rounding sequences, so their agreement is bounded by that error const double eps_theta = n_ctx * FLT_EPSILON; + if (type == GGML_TYPE_BF16) { + // with BF16 output that error can also change the rounding: a step of 2^-7 with a chance of about eps_theta/2^-7 + return std::max(test_case::max_nmse_err(), eps_theta / 128.0); + } return std::max(test_case::max_nmse_err(), eps_theta * eps_theta); } @@ -6915,9 +6967,10 @@ struct test_col2im_1d : public test_case { const int64_t T_in; // input length (number of columns) const int s0; // stride const int p0; // padding cropped from both sides + const bool view; std::string vars() override { - return VARS_TO_STR6(type, K, OC, T_in, s0, p0); + return VARS_TO_STR7(type, K, OC, T_in, s0, p0, view); } double max_nmse_err() override { @@ -6926,11 +6979,17 @@ struct test_col2im_1d : public test_case { test_col2im_1d(ggml_type type = GGML_TYPE_F32, int64_t K = 4, int64_t OC = 3, int64_t T_in = 7, - int s0 = 2, int p0 = 0) - : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0) {} + int s0 = 2, int p0 = 0, bool view = false) + : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0), view(view) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * cols = ggml_new_tensor_2d(ctx, type, K*OC, T_in); + ggml_tensor * cols; + if (view) { + ggml_tensor * base = ggml_new_tensor_1d(ctx, type, K * OC * T_in + 1); + cols = ggml_view_2d(ctx, base, K * OC, T_in, K * OC * ggml_type_size(type), ggml_type_size(type)); + } else { + cols = ggml_new_tensor_2d(ctx, type, K * OC, T_in); + } ggml_set_name(cols, "cols"); ggml_tensor * out = ggml_col2im_1d(ctx, cols, s0, (int) OC, p0); @@ -9657,6 +9716,33 @@ struct test_fill : public test_case { } }; +// GGML_OP_SLEEP (for scheduler testing only) +struct test_sleep : public test_case { + const ggml_type type; + const std::array ne; + const int32_t us; + + std::string vars() override { return VARS_TO_STR3(type, ne, us); } + + // the op only delays, the output aliases the input and must match it exactly + double max_nmse_err() override { return 0.0; } + + test_sleep(int32_t us = 100, ggml_type type = GGML_TYPE_F32, + std::array ne = { 10, 10, 4, 3 }) + : type(type), ne(ne), us(us) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); + ggml_set_name(a, "a"); + + ggml_tensor * out = ggml_sleep(ctx, a, us); + + ggml_set_name(out, "out"); + + return out; + } +}; + // GGML_OP_SOLVE_TRI struct test_solve_tri : public test_case { const ggml_type type; @@ -10868,6 +10954,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); + // BF16 source: one case per type covers batch dims, broadcast indices and gaps between rows + for (ggml_type type : all_types) { + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, type, GGML_TYPE_I64, { 256, 11, 1, 1 }, { 2, 3, }, 7, true)); + } + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_I32, { 256, 5, 1, 3 }, { 1, 1, }, 1, false)); + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -10878,11 +10970,19 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F32, GGML_TYPE_I32, { 128, 32, 8, 1 }, GGML_ROPE_TYPE_IMROPE)); + for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { + for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16}) { + for (int ne2 : {1, 8, 512}) { + test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 128, 32, ne2, 1 }, mode, 128, false, true, GGML_TYPE_BF16)); + } + } + } // partial rotation for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64)); } + test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F16, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64, false, true, GGML_TYPE_BF16)); } for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX}) { @@ -11275,6 +11375,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_col2im_1d(type, 8, 2, 3, 2, 5)); // cropping eats most of the signal, T_out = 2 } + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 5, 3, 17, 2, 1, true)); + for (int64_t n : {255, 256, 257, 16777217}) { + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 1, 1, n, 1, 0)); + } + for (ggml_type kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) { test_cases.emplace_back(new test_conv_transpose_2d({3, 2, 3, 1}, {2, 2, 1, 3}, 1, kernel_type)); test_cases.emplace_back(new test_conv_transpose_2d({10, 10, 9, 1}, {3, 3, 1, 9}, 2, kernel_type)); @@ -11402,7 +11507,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {128, 2, 3, 1}, {128, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, false, {128, 4, 3, 1})); // strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst - + test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {2, 2, 524281, 1}, {-1,-1,-1,-1}, {1, 0, 2, 3})); // CPY - different src/dst shapes (reshaping via CPY) // Use permutations of {3, 5, 7, 32}. Total elements: 3*5*7*32 = 3360. // Each src permutation is tested against canonical sorted and reverse dst (skip self). @@ -11917,6 +12022,9 @@ static std::vector> make_test_cases_eval() { // > 2^31-element dst (8.9 GB), about 45 GB peak memory. Too large to be enabled by default. // kernel_mul_mm dst offset of the last batch is past INT32_MAX: rows 0-31 use full tiles, rows 32-39 use edge tiles. test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 1048576, 40, 64, {1, 1}, {53, 1})); + // CUDA mul_mat_q: > 2^31-element dst (8.9 GB), the dst offset of column tiles starting past column 8648 does not fit in 32 bits + // (same shape class as a 248k-vocab output head with a 16k ubatch of outputs) + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 248320, 8960, 32, {1, 1}, {1, 1})); // kernel_mul_mm_id: the index of tokens 32768-33791 does not fit in 16 bits (about 0.3 GB peak memory). test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F32, GGML_TYPE_F32, 4, 2, false, 64, 33792, 64)); @@ -12262,6 +12370,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_F32, 576, 512, 576, {1,1}, {1,1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_F32, 1, 2048, 8192, {1, 1}, {1, 1})); + + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F16, 128, 128, 4352, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 64, 192, 17664, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_F32, 128, 128, 4096, {1, 1}, {2, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 128, 256, 4096, {1, 1}, {1, 1})); + for (ggml_type type_a : all_types) { test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1, 64, 256, {1, 1}, {1, 1})); } @@ -12332,6 +12446,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_F32, 16, 16, b, 50, 200, 64)); } + // One very large one to trigger a code path in CUDA requiring >1 pass over expert IDs due to shared memory limits: + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q8_0, GGML_TYPE_F32, 16, 16, false, 32, 65536, 256)); + // For issue 27873 test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_IQ2_XXS, GGML_TYPE_F32, 1, 1, false, 1, 8192, 4096)); @@ -12366,8 +12483,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_TQ1_0, GGML_TYPE_F32, 28, 10, false, 1024, 1, 4096)); test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_TQ1_0, GGML_TYPE_F32, 128, 8, false, 1024, 1, 2048)); - // TODO: disabled until CUDA backend support is added [TAG_MUL_MAT_ID_DUPLICATE_ID] -#if 0 // repeated expert ids within a row for (ggml_type ta : {GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { for (int n : {9, 16, 33, 64}) { @@ -12379,7 +12494,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 1025, 10, false, 64, 33, 256, 0, true)); test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 2050, 10, true, 64, 33, 256)); } -#endif for (ggml_type type_a : all_types) { test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 4, 2, false, 64, 16, 3*ggml_blck_size(type_a))); @@ -12680,8 +12794,17 @@ static std::vector> make_test_cases_eval() { } } + // BF16: each mode forward on a strided view and backward on an offset view, with and without freq factors, and one in place + for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE, GGML_ROPE_TYPE_VISION}) { + for (bool ff : {false, true}) { + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 1, true)); + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 2, false)); + } + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, false, 0, true, true)); + } + // rotated dims window at an offset (ggml_rope_set_offset), not supported for vision mode - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool fw : {true, false}) { // fw == forward for (bool ff : {false, true}) { test_cases.emplace_back(new test_rope(type, {128, 32, 2, 1}, 32, GGML_ROPE_TYPE_NORMAL, 512, 1.4245f, 0.7465f, 1.4245f, ff, 0, fw, false, 32)); @@ -12987,6 +13110,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 })); test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 })); + test_cases.emplace_back(new test_sleep(0)); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 })); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F32, { 128, 4, 2, 2 })); + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { test_cases.emplace_back(new test_diag(type)); test_cases.emplace_back(new test_diag(type, { 79, 1, 19, 13 })); @@ -13534,6 +13661,15 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 33, 1, 1, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 100, 1, 1, false, true)); + // KDA at D=128: decode, prefill, tails, strides, and snapshots. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4)); + // MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold. test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 3, 4)); @@ -13545,6 +13681,30 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 2)); // Keep the WebGPU dispatch below 65535 workgroups (32 per token for this shape). test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2047, 2, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4097, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 127, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 513, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2)); + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2)); + + // Correlated keys, high beta, and weak decay stress the chunked triangular solve. + for (int64_t n_tokens : {64, 65, 257}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true)); + } + + // Odd V strides require element loads instead of aligned matrix loads. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true)); + + // Q and K can have different strides in both scalar and chunked paths. + for (int64_t n_tokens : {4, 65}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); + } // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first // (slot 0 = final state, slot s = state s tokens back). @@ -14068,7 +14228,7 @@ static std::vector> make_test_cases_perf() { } for (bool fw : {true, false}) { // fw == forward - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool ff : {false, true}) { // freq_factors for (float v : { 0, 1 }) { test_cases.emplace_back(new test_rope(type, {128, 32, 512, 1}, 128, GGML_ROPE_TYPE_NORMAL, 512, 1.0f, 0.0f, 1.0f, ff, v, fw)); // llama 7B @@ -14196,12 +14356,34 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 256, 1)); // PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 512, 1)); // PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1024, 1)); // PP-1024 + // MMA-eligible prefill sweep (16 heads, d=128, K=1): Vulkan cm2 vs CUDA MMA + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 64, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 128, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 1024, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 4096, 1)); // Small model configs (fewer heads = less GPU occupancy for autoregressive) test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1)); // 4h PP-64 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 256, 1)); // 4h PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 512, 1)); // 4h PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1)); // 4h PP-1024 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 64, 1, 1, false, true)); // KDA PP-64 + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1, 1, false, true)); + // GDN model shapes: 35B (v_repeat=2), 27B (v_repeat=3), batch sweep + for (int T : { 2048, 4096, 8192, 16384, 32768 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 3)); + } + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4096, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); // lightning_indexer for (int kv : { 256, 4096, 65536 }) { diff --git a/tests/test-backend-sched.cpp b/tests/test-backend-sched.cpp new file mode 100644 index 000000000000..8afdcc7caadd --- /dev/null +++ b/tests/test-backend-sched.cpp @@ -0,0 +1,1084 @@ +// Test suite for scheduler and backend behavior + +// Towards formalized scheduling behavior: +// - a single inference pass can run on several backends. The subset of nodes running on a single backend is a split +// - synchronous backends: +// - explicit synchronization (ggml_backend_synchronize()) is required between each operation +// - asynchronous backends: +// - Activations from one split can be copied asynchronously to the next (output of split N -> input of split N+1) +// - Several scheduling patterns must be supported by async backends. The scheduler may: +// - not explicitly synchronize between CPU->backend memcpy and graph execution on backend +// - dispatch several parallel memcpys to the same backend at once +// - schedule splits without inputs at any point in the graph + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include +#include +#include + + + +enum test_result { + TEST_FAIL = 0, + TEST_OK = 1, + TEST_SKIP = 2, // in case a backend does not support a required OP (e.g. OP_SLEEP) +}; + +// global counters for pass/fail/skip +static int n_ok = 0; +static int n_skip = 0; +static int n_test = 0; + +// default silent on success; --verbose / -v prints progress +static bool print_log = false; + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void log_maybe(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); +} + +// pretty-print helpers start +static constexpr int status_column = 82; // for ok/fail column alignment +static int case_len = 0; +static char case_label[256]; // max length of a case label + +static void case_end(test_result res) { + n_ok += res == TEST_OK; + n_skip += res == TEST_SKIP; + n_test++; + + if (res != TEST_FAIL && !print_log) { + case_len = 0; + return; + } + + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + const char * status = "FAIL"; + if (res == TEST_OK) { + status = "OK"; + } else if (res == TEST_SKIP) { + status = "SKIP"; + } + + printf("%*s%s\n", std::max(1, status_column - case_len), "", status); + case_len = 0; +} + +static void vnote(const char * fmt, va_list args) { + if (case_len != 0) { + printf("\n"); + } + printf(" "); + vprintf(fmt, args); + printf("\n"); + + case_len = 0; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void note(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result fail(const char * fmt, ...) { + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + + return TEST_FAIL; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result skip(const char * fmt, ...) { + if (print_log) { + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + } + + return TEST_SKIP; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void case_begin(const char * fmt, ...) { + va_list args; + va_start(args, fmt); + vsnprintf(case_label, sizeof(case_label), fmt, args); + va_end(args); + + if (print_log) { + case_len = printf(" %s", case_label); + fflush(stdout); + } else { + case_len = 0; + } +} +// pretty-print helpers end + + +// NB: the last backend passed has to be the CPU backend (cf. ggml_backend_sched_new) +static ggml_backend_sched_ptr create_test_scheduler(std::vector backends, size_t graph_size, + bool use_device_host_buft, bool parallel = false) { + + std::vector bufts(backends.size()); + for (size_t b = 0; b < backends.size(); b++) { + bufts[b] = ggml_backend_get_default_buffer_type(backends[b]); + } + + // pinned memory for the CPU backend (always required to be the last backend) enables async copies to other devices + // the host buffer type comes from the first backend, (cf. llama_context::llama_context()) + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + bufts.back() = host; + } + } + + return ggml_backend_sched_ptr(ggml_backend_sched_new(backends.data(), bufts.data(), (int) backends.size(), + graph_size, parallel, /*op_offload =*/ false)); +} + +// the nodes of the graph together with the backend each of them is assigned to +struct helper_graph { + ggml_cgraph * gf; + std::vector nodes; + std::vector backend_id; + + helper_graph(ggml_context * ctx, size_t graph_size) : gf(ggml_new_graph_custom(ctx, graph_size, /*grads =*/ false)) {} + + ggml_tensor * add(ggml_tensor * node, int backend) { + nodes.push_back(node); + backend_id.push_back(backend); + ggml_build_forward_expand(gf, node); + + return node; + } +}; + +struct helper_check { + ggml_tensor * tensor; // Tensor for which to check the data. + float expected; // The expected value that the tensor data should have after graph execution. +}; + +// asks whether the backend implements the op, independent of where the sources of this node currently live. +static bool backend_supports_op(ggml_backend_t backend, const ggml_tensor * node) { + ggml_init_params params = { + /*.mem_size =*/ GGML_MAX_SRC*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + + ggml_tensor probe = *node; + probe.buffer = nullptr; + probe.view_src = nullptr; + probe.data = nullptr; + + for (ggml_tensor *& src : probe.src) { + if (src != nullptr) { + src = ggml_dup_tensor(ctx.get(), src); + } + } + + return ggml_backend_supports_op(backend, &probe); +} + +// executes the graph, then checks the number of splits and the results +static test_result run_and_check(ggml_backend_sched_t sched, const helper_graph & g, + const std::vector & backends, const std::vector & checks, int64_t ne) { + + // ggml_backend_sched_set_tensor_backend does not validate the op, an unsupported one would abort inside the backend + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_t backend = backends[g.backend_id[i]]; + if (!backend_supports_op(backend, g.nodes[i])) { + return skip("%s does not support %s", ggml_backend_name(backend), ggml_op_name(g.nodes[i]->op)); + } + } + + // to later check if any further graph logic alters the number of splits + int n_splits_expected = g.nodes.empty() ? 0 : 1; + for (size_t i = 1; i < g.backend_id.size(); i++) { + n_splits_expected += g.backend_id[i] != g.backend_id[i - 1]; + } + + ggml_backend_sched_reset(sched); + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_sched_set_tensor_backend(sched, g.nodes[i], backends[g.backend_id[i]]); + } + + if (!ggml_backend_sched_alloc_graph(sched, g.gf)) { + return fail("failed to allocate the graph"); + } + + if (ggml_backend_sched_graph_compute(sched, g.gf) != GGML_STATUS_SUCCESS) { + return fail("failed to compute the graph"); + } + + const int n_splits = ggml_backend_sched_get_n_splits(sched); + if (n_splits != n_splits_expected) { + return fail("n_splits = %d, expected %d, each split consisting of just a single node", n_splits, n_splits_expected); + } + + std::vector data(ne); + for (const helper_check & c : checks) { + ggml_backend_tensor_get(c.tensor, data.data(), 0, ggml_nbytes(c.tensor)); + for (int64_t i = 0; i < ne; i++) { + if (data[i] != c.expected) { + return fail("%s[%" PRId64 "] = %f, expected %f", ggml_get_name(c.tensor), i, data[i], c.expected); + } + } + } + + return TEST_OK; +} + +// helper struct for inputless splits, and constants like 0 and 1 +struct backend_consts { + // the buffers are declared after the contexts, so that they are released first + std::vector ctxs; + std::vector bufs; + std::vector zero; + std::vector one; + + backend_consts(const std::vector & backends, int64_t ne) { + std::vector data(ne); + + for (size_t b = 0; b < backends.size(); b++) { + ggml_init_params params = { + /*.mem_size =*/ 2*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context * ctx = ggml_init(params); + + ggml_tensor * z = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(z, "zero_%s", ggml_backend_name(backends[b])); + + ggml_tensor * o = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(o, "one_%s", ggml_backend_name(backends[b])); + + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backends[b]); + GGML_ASSERT(buf != nullptr); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(z, data.data(), 0, ggml_nbytes(z)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(o, data.data(), 0, ggml_nbytes(o)); + + ctxs.emplace_back(ctx); + bufs.emplace_back(buf); + zero.push_back(z); + one.push_back(o); + } + } +}; + +// TODO add tests for the auto-assign logic of nodes to backends of the scheduler. Possible tests: +// - test of CPU backend with any other backend. Expectation is that GEMM-nodes (usually the first accelerated components) are assigned to the non-CPU backend +// - test of the property that tensor location influences backend assignment. +// - test of neighbor propagation logic? 3 nodes, with the middle one initially on CPU, moved to the other backend? + + +// stress test: a tensor is incremented and sent back and forth between the backends in a ping-pong pattern. +// One pass pairs every backend a with every other backend b via nested loops. +// The counter is brought to a, then bounced to b and back for every partner in turn. +// So one pass copies an activation across every ordered pair of backends. +// Every lap runs two passes: one where the nodes add the constant 1, one where they add a user input +// from the CPU backend, so that every transition is tested with and without an input next to the activation. +// The input values come from a fixed seed. +static test_result stress_test_linked_list(const std::vector & backends, int n_laps, + int64_t tensor_len, bool use_device_host_buft) { + const int n_backends = (int) backends.size(); + + // per pass and backend a: one node to bring the counter to a, then two per partner for the ping-pong + const int n_nodes_pass = n_backends*(2*n_backends - 1); + const int n_nodes = 2*n_laps*n_nodes_pass; + const int n_inputs = n_laps*n_nodes_pass; // one per node of the pass that takes user inputs + + // initial pseudo-random value draw so that the expected result is known before graph execution + std::mt19937 rng(42); + std::uniform_int_distribution draw_value(1, 10000); + + std::vector input_value(n_inputs); // random values store + int64_t sum_inputs = 0; + + for (int i = 0; i < n_inputs; i++) { + input_value[i] = draw_value(rng); + sum_inputs += input_value[i]; + } + + // see sched->hash_set FIXME, the set has to hold the nodes and the leafs: two constants per backend + // plus the user inputs + const size_t graph_size = n_nodes + 2*n_backends + n_inputs; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + // the user inputs all live on the CPU backend, with the same buffer type the scheduler uses for it + ggml_init_params params_input = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_input(ggml_init(params_input)); + ggml_backend_buffer_ptr buf_input; + + std::vector input(n_inputs); + for (int i = 0; i < n_inputs; i++) { + input[i] = ggml_new_tensor_1d(ctx_input.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(input[i], "input%d", i); + ggml_set_input(input[i]); + } + + // the inputs follow the buffer type the scheduler uses for the CPU backend (cf. create_test_scheduler) + ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backends.back()); + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + buft = host; + } + } + + buf_input.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_input.get(), buft)); + GGML_ASSERT(buf_input != nullptr); + + // write inputs before graph execution + std::vector data(tensor_len); + for (int i = 0; i < n_inputs; i++) { + std::fill(data.begin(), data.end(), float(input_value[i])); + ggml_backend_tensor_set(input[i], data.data(), 0, ggml_nbytes(input[i])); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (n_nodes + 2)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + int64_t sum = 0; + ggml_tensor * out = nullptr; + + int i = 0; // next user input to consume + + // increments the counter on backend b, which makes the scheduler copy it there from the previous backend + auto step = [&](int b, bool with_input) { + ggml_tensor * src = out == nullptr ? consts.zero[b] : out; + + if (with_input) { + out = g.add(ggml_add(ctx_compute.get(), src, input[i]), b); + i++; + } else { + out = g.add(ggml_add(ctx_compute.get(), src, consts.one[b]), b); + sum += 1; + } + }; + + for (int lap = 0; lap < n_laps; lap++) { + for (bool with_input : { false, true }) { // test each transition with and without input + for (int a = 0; a < n_backends; a++) { + step(a, with_input); + + for (int b = 0; b < n_backends; b++) { + if (b == a) { + continue; + } + + step(b, with_input); + step(a, with_input); + } + } + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + // every node adds either the constant 1 or its drawn user input + const int64_t expected = sum + sum_inputs; + + note("%d of %d nodes take a user input, they contribute %" PRId64 " of %" PRId64, n_inputs, n_nodes, sum_inputs, expected); + + test_result ok; + if (expected >= (1 << 24)) { // the counter has to stay exact in f32 + ok = fail("expected result %" PRId64 " does not fit into the f32 mantissa, lower n_laps", expected); + } else { + ok = run_and_check(sched.get(), g, backends, {{ out, float(expected) }}, tensor_len); + } + + return ok; +} + +// Same idea as stress_test_linked_list, but with the compute graph being a directed acyclic graph (DAG). +// n_lanes independent counters run through rounds of four shapes, so that one graph covers: +// - lanes with different histories, so a misrouted copy shows up as a wrong count in a single lane +// - one split producing two values followed by two splits that each consume one of them and do not depend on each other +// - splits with no inputs at all, from lanes re-seeded out of constants that already live on the split's backend +// - splits taking one activation per lane from the previous split, one of them from an older split instead +static test_result stress_test_dag(const std::vector & backends, int n_lanes, int n_rounds, + int64_t tensor_len, bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + GGML_ASSERT(n_lanes % 2 == 0); + + // sized for the worst case + const size_t graph_size = n_lanes*(2*n_rounds + 1) + 2*n_backends; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + std::vector lane(n_lanes); + std::vector value(n_lanes); + std::vector checks; + + // every lane starts at a different value, so that a misrouted copy changes a sum instead of going unnoticed + auto seed = [&](int b, const char * prefix) { + for (int l = 0; l < n_lanes; l++) { + lane[l] = g.add(ggml_add(ctx_compute.get(), l == 0 ? consts.zero[b] : lane[l - 1], consts.one[b]), b); + value[l] = l + 1; + ggml_format_name(lane[l], "%s%d", prefix, l); + } + }; + + auto check_lanes = [&]() { + for (int l = 0; l < n_lanes; l++) { + ggml_set_output(lane[l]); + checks.push_back({ lane[l], float(value[l]) }); + } + }; + + seed(0, "seed"); + + std::vector older = lane; + std::vector value_older = value; + + for (int round = 0; round < n_rounds; round++) { + // a backend the previous node did not use, so that the round is not absorbed into the split before it + const int b = (g.backend_id.back() + 1) % n_backends; + + const std::vector prev = lane; + const std::vector value_prev = value; + + switch (round % 5) { + case 0: + for (int p = 0; p < n_lanes/2; p++) { + const int la = 2*p; + const int lb = 2*p + 1; + const int prod = (b + p) % n_backends; + const int cons = (prod + 1) % n_backends; + + // one split producing two values ... + for (int l : { la, lb }) { + lane[l] = g.add(ggml_add(ctx_compute.get(), lane[l], consts.one[prod]), prod); + value[l]++; + ggml_format_name(lane[l], "r%d_prod%d", round, l); + } + + // ... and two splits that each consume one of them, with no dependency on each other + lane[la] = g.add(ggml_add(ctx_compute.get(), lane[la], consts.one[cons]), cons); + value[la]++; + ggml_format_name(lane[la], "r%d_cons%d", round, la); + + lane[lb] = g.add(ggml_add(ctx_compute.get(), lane[lb], consts.one[prod]), prod); + value[lb]++; + ggml_format_name(lane[lb], "r%d_cons%d", round, lb); + } + break; + case 1: + check_lanes(); + seed(b, "restart"); + break; + case 2: + case 3: + for (int l = 0; l < n_lanes; l++) { + const int partner = (l + 1 + round) % n_lanes; + const bool reach_back = round >= 2 && l == round % n_lanes; + + ggml_tensor * a = reach_back ? older[l] : prev[l]; + const int64_t va = reach_back ? value_older[l] : value_prev[l]; + + lane[l] = g.add(ggml_add(ctx_compute.get(), a, prev[partner]), b); + value[l] = va + value_prev[partner]; + ggml_format_name(lane[l], "r%d_lane%d", round, l); + } + break; + case 4: + lane[0] = g.add(ggml_add(ctx_compute.get(), prev[0], consts.one[b]), b); + value[0] = value_prev[0] + 1; + ggml_format_name(lane[0], "r%d_single", round); + break; + default: + GGML_ABORT("unexpected round %d", round); + } + + older = prev; + value_older = value_prev; + } + + check_lanes(); + + test_result ok = TEST_OK; + for (const helper_check & c : checks) { + if (c.expected >= float(1 << 24)) { // the counts have to stay exact in f32 + ok = fail("expected result %.0f does not fit into the f32 mantissa, lower n_rounds", c.expected); + break; + } + } + + if (ok == TEST_OK) { + ok = run_and_check(sched.get(), g, backends, checks, tensor_len); + } + + return ok; +} + +// Created in response to https://github.com/ggml-org/llama.cpp/issues/23321 +// Currently, input copies to splits synchronize split execution. +// CPU split N+1 could overwrite output of split N if this was not copied to backend in time. +// Mechanism to test: GPU split with long sleep to clog CUDA stream / vk command queue, +// followed by CPU splits without input, provoking a race condition in the current setup. +// GPU: 100ms sleep to clog stream/queue +// CPU: produce {55} +// GPU: request copy of {55} in CUDA stream, ADD {44}; Output should be {99} +// CPU: produce {66} +// GPU: increment both {99} and {66} -> {100} and {67} +// Correct result is thus {100}, incorrect output is {111} when {55} was overwritten by {66} before the copy started. +// Note: currently only reproducible on async H2D copy (=pinned memory). +static test_result test_inputless_splits_scheduling(ggml_backend_t gpu, ggml_backend_t cpu, int64_t tensor_len, int32_t sleep_us, bool use_device_host_buft) { + + const int GPU = 0; + const int CPU = 1; + + const std::vector backends = { gpu, cpu }; + + const size_t graph_size = 64; + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_static = { + /*.mem_size =*/ 4*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + + ggml_context_ptr ctx_cpu(ggml_init(params_static)); + + ggml_tensor * zero_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_cpu, "zero_cpu"); + + ggml_tensor * val55_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val55_cpu, "val55_cpu"); + + ggml_tensor * val66_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val66_cpu, "val66_cpu"); + + ggml_backend_buffer_ptr buf_cpu(ggml_backend_alloc_ctx_tensors(ctx_cpu.get(), cpu)); + GGML_ASSERT(buf_cpu != nullptr); + + ggml_context_ptr ctx_gpu(ggml_init(params_static)); + + ggml_tensor * zero_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_gpu, "zero_gpu"); + + ggml_tensor * one_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(one_gpu, "one_gpu"); + + ggml_tensor * val44_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val44_gpu, "val44_gpu"); + + ggml_backend_buffer_ptr buf_gpu(ggml_backend_alloc_ctx_tensors(ctx_gpu.get(), gpu)); + GGML_ASSERT(buf_gpu != nullptr); + + std::vector data(tensor_len); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(zero_cpu, data.data(), 0, ggml_nbytes(zero_cpu)); + ggml_backend_tensor_set(zero_gpu, data.data(), 0, ggml_nbytes(zero_gpu)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(one_gpu, data.data(), 0, ggml_nbytes(one_gpu)); + + std::fill(data.begin(), data.end(), 44.0f); + ggml_backend_tensor_set(val44_gpu, data.data(), 0, ggml_nbytes(val44_gpu)); + + std::fill(data.begin(), data.end(), 55.0f); + ggml_backend_tensor_set(val55_cpu, data.data(), 0, ggml_nbytes(val55_cpu)); + + std::fill(data.begin(), data.end(), 66.0f); + ggml_backend_tensor_set(val66_cpu, data.data(), 0, ggml_nbytes(val66_cpu)); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + // GPU: add then sleep - occupies the GPU while later splits run + ggml_tensor * delayed = g.add(ggml_add(ctx_compute.get(), zero_gpu, one_gpu), GPU); + ggml_set_name(delayed, "to_delay"); + delayed = g.add(ggml_sleep(ctx_compute.get(), delayed, sleep_us), GPU); + ggml_set_name(delayed, "delayed"); + + // CPU: 0 + 55 -> 55 + ggml_tensor * v55 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val55_cpu), CPU); + ggml_set_name(v55, "v55"); + + // GPU: 55 + 44 -> 99 + ggml_tensor * v99 = g.add(ggml_add(ctx_compute.get(), v55, val44_gpu), GPU); + ggml_set_name(v99, "v99"); + + // CPU: 0 + 66 -> 66 + ggml_tensor * v66 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val66_cpu), CPU); + ggml_set_name(v66, "v66"); + + // GPU: increment both of the previous split outputs + ggml_tensor * out99 = g.add(ggml_add(ctx_compute.get(), v99, one_gpu), GPU); + ggml_set_name(out99, "out99"); + + ggml_tensor * out66 = g.add(ggml_add(ctx_compute.get(), v66, one_gpu), GPU); + ggml_set_name(out66, "out66"); + + ggml_set_output(delayed); + ggml_set_output(out99); + ggml_set_output(out66); + + const test_result ok = run_and_check(sched.get(), g, backends, { + { delayed, 1.0f }, + { out99, 100.0f }, + { out66, 67.0f }, + }, tensor_len); + + // the race needs the allocator to reuse the memory of the first CPU split for the second one + note("v55 and v66 %s (v55=%p v66=%p)", v55->data == v66->data ? "alias" : "do not alias", v55->data, v66->data); + + return ok; +} + +// Test that all async backends transmit their activations to the following async backend correctly. No user inputs tested. +static test_result test_chain_all_backends(const std::vector & backends, int64_t tensor_len, int32_t sleep_us, + bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + std::vector seq; + + auto push = [&](int b) { + if (seq.empty() || seq.back() != b) { + seq.push_back(b); + } + }; + + for (int i = 0; i < n_backends; i++) { + for (int j = 0; j < n_backends; j++) { + if (i != j) { + push(i); + push(j); + } + } + } + + const size_t n_nodes = seq.size(); + const size_t n_sleeps = sleep_us > 0 ? n_nodes : 0; // one sleep per split + const size_t graph_size = n_nodes + n_sleeps + n_backends + 1; // see sched->hash_set FIXME, one "one" per backend plus the "zero" that starts the chain + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = nullptr; + for (size_t k = 0; k < n_nodes; k++) { + const int b = seq[k]; + + out = g.add(ggml_add(ctx_compute.get(), k == 0 ? consts.zero[b] : out, consts.one[b]), b); + + // the sleep keeps the backend busy, so that the next one has to wait for this split + if (sleep_us > 0) { + out = g.add(ggml_sleep(ctx_compute.get(), out, sleep_us), b); + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(n_nodes) }}, tensor_len); + + return ok; +} + +// Tests data transfer between all combinations of backend pairs +// The receiving split takes one activation from the sender plus n_inputs user inputs +static test_result test_pair_user_inputs(const std::vector & backends, int b_send, int b_recv, int64_t tensor_len, + int n_inputs, bool inputs_on_sender, bool parallel, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft, parallel); + + // placing the inputs on the sender makes the receiving split copy all of them, placing them on the + // receiver leaves the activation as its only input + const int b_inputs = inputs_on_sender ? b_send : b_recv; + + ggml_init_params params_inputs = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_inputs(ggml_init(params_inputs)); + + std::vector inputs; + for (int k = 0; k < n_inputs; k++) { + ggml_tensor * in = ggml_new_tensor_1d(ctx_inputs.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(in, "in%d", k); + ggml_set_input(in); + inputs.push_back(in); + } + + ggml_backend_buffer_ptr buf_inputs(ggml_backend_alloc_ctx_tensors(ctx_inputs.get(), backends[b_inputs])); + GGML_ASSERT(buf_inputs != nullptr); + + std::vector data(tensor_len); + std::fill(data.begin(), data.end(), 1.0f); + for (ggml_tensor * in : inputs) { + ggml_backend_tensor_set(in, data.data(), 0, ggml_nbytes(in)); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), consts.zero[b_send], consts.one[b_send]), b_send); + + for (ggml_tensor * in : inputs) { + out = g.add(ggml_add(ctx_compute.get(), out, in), b_recv); + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(1 + n_inputs) }}, tensor_len); + + for (ggml_tensor * in : inputs) { + if (ok != TEST_OK) { + break; + } + ggml_backend_tensor_get(in, data.data(), 0, ggml_nbytes(in)); + for (int64_t i = 0; i < tensor_len; i++) { + if (data[i] != 1.0f) { + ok = fail("%s[%" PRId64 "] = %f after compute, expected 1.000000 - the input was modified", ggml_get_name(in), i, data[i]); + break; + } + } + } + + return ok; +} + +// Tests Y-shaped scheduling: two parallel lanes merging into 1. Lane A and B, merging into a single split. +// The lanes join in a final split on backend_a that receives one activation from each of the two backend_b splits. +static test_result test_y_shaped_graph(const std::vector & backends, int backend_a, int backend_b, int64_t tensor_len, + int32_t sleep_us, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * seed_a = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_a, "seed_a"); + + // only lane a sleeps, so that lane b is scheduled while it is still running + if (sleep_us > 0) { + seed_a = g.add(ggml_sleep(ctx_compute.get(), seed_a, sleep_us), backend_a); + ggml_set_name(seed_a, "seed_a_delayed"); + } + + ggml_tensor * lane_a = g.add(ggml_add(ctx_compute.get(), seed_a, consts.one[backend_b]), backend_b); + ggml_set_name(lane_a, "lane_a"); + + if (sleep_us > 0) { + lane_a = g.add(ggml_sleep(ctx_compute.get(), lane_a, sleep_us), backend_b); + ggml_set_name(lane_a, "lane_a_delayed"); + } + + ggml_tensor * seed_b = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_b, "seed_b"); + + ggml_tensor * lane_b = g.add(ggml_add(ctx_compute.get(), seed_b, consts.one[backend_b]), backend_b); + ggml_set_name(lane_b, "lane_b"); + + // neither lane ends on backend_a, so both activations are inputs of the last split + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), lane_a, lane_b), backend_a); + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, 4.0f }}, tensor_len); + + return ok; +} + +static const char * dev_type_name(enum ggml_backend_dev_type type) { + switch (type) { + case GGML_BACKEND_DEVICE_TYPE_CPU: return "CPU"; + case GGML_BACKEND_DEVICE_TYPE_GPU: return "GPU"; + case GGML_BACKEND_DEVICE_TYPE_IGPU: return "IGPU"; + case GGML_BACKEND_DEVICE_TYPE_ACCEL: return "ACCEL"; + case GGML_BACKEND_DEVICE_TYPE_META: return "META"; + } + return "UNKNOWN"; +} + +static bool initialize_backends(std::vector & backends) { + + // cf. GGML_SCHED_MAX_BACKENDS + const size_t max_backends = 16; + + for (size_t i = 0; i < ggml_backend_dev_count() && backends.size() + 1 < max_backends; i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + log_maybe("device %2zu: %-10s %-5s (%s)\n", i, ggml_backend_dev_name(dev), + dev_type_name(ggml_backend_dev_type(dev)), ggml_backend_dev_description(dev)); + + const enum ggml_backend_dev_type type = ggml_backend_dev_type(dev); + // Exclude ACCEL devices as they run in tandem with the CPU backend and only implement matmul, the tests here require ADD + if (type == GGML_BACKEND_DEVICE_TYPE_CPU || type == GGML_BACKEND_DEVICE_TYPE_ACCEL) { + continue; + } + + ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr); + if (backend == nullptr) { + printf("failed to initialize %s, skipping it\n", ggml_backend_dev_name(dev)); + continue; + } + + backends.emplace_back(backend); + } + + if (backends.empty()) { + printf("no non-CPU backend found, skipping\n"); + return false; + } + + // ggml_backend_sched_new requires the CPU backend to be the last one + backends.emplace_back(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + GGML_ASSERT(backends.back() != nullptr); + + for (const ggml_backend_ptr & backend : backends) { + ggml_backend_dev_t dev = ggml_backend_get_device(backend.get()); + + log_maybe("backend: %-10s host_buft = %d (%s)\n", ggml_backend_name(backend.get()), + ggml_backend_dev_host_buffer_type(dev) != nullptr, ggml_backend_dev_description(dev)); + } + log_maybe("\n"); + return true; +} + + +int main(int argc, char ** argv) { + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { + print_log = true; + } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + printf("Usage: %s [-v|--verbose]\n", argv[0]); + return 0; + } else { + fprintf(stderr, "unknown argument: %s\n", argv[i]); + fprintf(stderr, "Usage: %s [-v|--verbose]\n", argv[0]); + return 1; + } + } + + ggml_backend_load_all(); + + std::vector backends; + + // nothing to test with synchronous CPU backend only + if (!initialize_backends(backends)) { + return 0; + } + + // the tests only borrow the backends, the ownership stays with this vector + std::vector backend_ptrs; + for (const ggml_backend_ptr & backend : backends) { + backend_ptrs.push_back(backend.get()); + } + + ggml_backend_t cpu = backend_ptrs.back(); + const size_t n_non_cpu_backends = backend_ptrs.size() - 1; + + // Test cases for single backends against CPU backend + for (size_t b_id = 0; b_id < n_non_cpu_backends; b_id++) { + ggml_backend_t backend = backend_ptrs[b_id]; + const char * name_backend = ggml_backend_name(backend); + + for (bool use_device_host_buft : { false, true }) { + // without a host buffer type this case is a duplicate of the pageable one + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend)) == nullptr) { + continue; + } + + log_maybe("=== Backend: %s, CPU sched buft: %s ===\n\n", name_backend, use_device_host_buft ? "device_host" : "pageable"); + + for (int32_t sleep_us : {50, 60, 70, 80, 400, 500, 600, 700, 1000, 10000}) { + for (int tensor_len : { 2, 2048, 4096, 8192, 1600}) { + case_begin("test_inputless_splits_scheduling %-8s sleep_us = %6d, tensor_len = %4d", name_backend, sleep_us, tensor_len); + case_end(test_inputless_splits_scheduling(backend, cpu, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + } + } + + // Test cases for all present backend subsets + for (bool use_device_host_buft : { false, true }) { + // create_test_scheduler takes the host buffer type from the first backend + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend_ptrs[0])) == nullptr) { + continue; + } + + log_maybe("=== all backends, CPU sched buft: %s ===\n\n", use_device_host_buft ? "device_host" : "pageable"); + + for (int n_lanes : { 8, 16 }) { + for (int n_rounds : { 5, 13, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_dag n_lanes = %2d, n_rounds = %2d, tensor_len = %4d", n_lanes, n_rounds, tensor_len); + case_end(stress_test_dag(backend_ptrs, n_lanes, n_rounds, tensor_len, use_device_host_buft)); + } + } + } + + log_maybe("\n"); + + for (int tensor_len : { 2, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_chain_all_backends sleep_us = %4d, tensor_len = %4d", sleep_us, tensor_len); + case_end(test_chain_all_backends(backend_ptrs, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + + for (int n_laps : { 1, 4, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_linked_list n_laps = %3d, tensor_len = %4d", n_laps, tensor_len); + case_end(stress_test_linked_list(backend_ptrs, n_laps, tensor_len, use_device_host_buft)); + } + } + + log_maybe("\n"); + + // every ordered pair of backends is the sender and the receiver of a copy + for (size_t backend_a = 0; backend_a < backend_ptrs.size(); backend_a++) { + for (size_t backend_b = 0; backend_b < backend_ptrs.size(); backend_b++) { + if (backend_a == backend_b) { + continue; + } + + const char * name_a = ggml_backend_name(backend_ptrs[backend_a]); + const char * name_b = ggml_backend_name(backend_ptrs[backend_b]); + + for (bool inputs_on_sender : { false, true }) { + for (bool parallel : { false, true }) { + for (int tensor_len : { 1, 4096 }) { + case_begin("test_pair_user_inputs %-8s -> %-8s inputs on %-8s parallel = %d, tensor_len = %4d", + name_a, name_b, inputs_on_sender ? "sender" : "receiver", parallel, tensor_len); + case_end(test_pair_user_inputs(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, + /*n_inputs =*/ 4, inputs_on_sender, parallel, use_device_host_buft)); + } + } + } + + for (int tensor_len : { 1, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_y_shaped %-8s -> %-8s sleep_us = %4d, tensor_len = %4d", name_a, name_b, sleep_us, tensor_len); + case_end(test_y_shaped_graph(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, sleep_us, use_device_host_buft)); + } + } + } + } + + log_maybe("\n"); + } + + if (print_log || n_ok + n_skip != n_test) { + printf("%d/%d tests passed", n_ok, n_test); + if (n_skip > 0) { + printf(", %d skipped", n_skip); + } + printf("\n"); + } + + return n_ok + n_skip == n_test ? 0 : 1; +} diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 9685bc277789..ed617939d2ea 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -170,6 +170,40 @@ static bool test_tensor_n(ggml_backend_buffer_type_t buft) { } } + { + std::vector batch; + ggml_backend_buffer_ptr scatter_buf = alloc_tensors(ctx.get(), buft, { 64 }, batch); + if (!scatter_buf) { + return false; + } + batch.resize(128, batch[0]); + uint8_t input[32], expected[256], out[256]; + for (size_t i = 0; i < sizeof(input); i++) { + input[i] = (uint8_t) (i + 1); + } + std::vector offsets(batch.size()), sizes(batch.size(), 1), data_offsets(batch.size()); + for (bool overlap : { false, true }) { + memset(expected, 0, sizeof(expected)); + ggml_backend_tensor_set(batch[0], expected, 0, sizeof(expected)); + for (size_t i = 0; i < batch.size(); i++) { + offsets[i] = 2*((i*5) % batch.size()) + 1; + data_offsets[i] = i % sizeof(input); + } + // Repeated sources are valid; overlapping destinations must retain copy order. + if (overlap) { + offsets.back() = offsets.front(); + } + for (size_t i = 0; i < batch.size(); i++) { + expected[offsets[i]] = input[data_offsets[i]]; + } + ggml_backend_tensor_set_n(batch.data(), input, offsets.data(), sizes.data(), data_offsets.data(), batch.size()); + ggml_backend_tensor_get(batch[0], out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + } + return true; } diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index f10404e8c28a..90a32abc72cf 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -496,16 +496,22 @@ 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_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE) { std::vector pattern; pattern.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { pattern.push_back(il % 2); } ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); - if (arch == LLM_ARCH_FLINT) { + if (arch == LLM_ARCH_FLINT || arch == LLM_ARCH_DOMYN_EDGE) { ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, pattern); } + if (arch == LLM_ARCH_DOMYN_EDGE) { + // SWA (rope) layers use a smaller head dim than the full-attention (nope) layers + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT_SWA, n_embd_head/2); + } } else if (arch == LLM_ARCH_LFM3) { ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector({0, 0, 1})); ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); diff --git a/tests/test-sleep.cpp b/tests/test-sleep.cpp new file mode 100644 index 000000000000..bd836c33870a --- /dev/null +++ b/tests/test-sleep.cpp @@ -0,0 +1,154 @@ +// Tests for GGML_OP_SLEEP, on every backend that supports it. Three properties are checked: +// - the op only delays: input = output +// - the op does not return early: a chain of n sleeps must take at least n*us +// Only a lower bound is asserted for the duration. A busy-wait cannot finish early, so that bound is +// deterministic, whereas an upper bound would be flaky on a loaded machine. +// Known limitation: Vulkan does not specify the tick rate of the shader clock, see ggml_vk_sleep. A driver +// whose clock runs slower than assumed could undershoot the request and fail this bound. + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include + +enum test_result { + TEST_OK, + TEST_FAIL, + TEST_SKIP, +}; + +static test_result test_sleep(ggml_backend_t backend, ggml_type type, int64_t ne, int32_t us, int n_nodes) { + const size_t graph_size = n_nodes + 16; + + ggml_init_params params_static = { + /*.mem_size =*/ ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_static(ggml_init(params_static)); + + ggml_tensor * x = ggml_new_tensor_1d(ctx_static.get(), type, ne); + ggml_set_name(x, "x"); + ggml_set_input(x); + + ggml_init_params params_compute = { + /*.mem_size =*/ n_nodes*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + ggml_cgraph * gf = ggml_new_graph_custom(ctx_compute.get(), graph_size, false); + + ggml_tensor * out = x; + for (int i = 0; i < n_nodes; i++) { + out = ggml_sleep(ctx_compute.get(), out, us); + } + ggml_set_name(out, "out"); + ggml_build_forward_expand(gf, out); + + // the backends log to stdout while computing, so the result line is only printed once it is complete + char desc[128]; + snprintf(desc, sizeof(desc), " %-6s %-4s ne=%-9" PRId64 " us=%-7d n_nodes=%d ", + ggml_backend_name(backend), ggml_type_name(type), ne, us, n_nodes); + + test_result result = TEST_OK; + + if (!ggml_backend_supports_op(backend, out)) { + printf("%snot supported\n", desc); + result = TEST_SKIP; + } else { + ggml_backend_buffer_ptr buf_static(ggml_backend_alloc_ctx_tensors(ctx_static.get(), backend)); + + // random bytes rather than random floats, so that bit patterns a value-wise copy could + // mangle, such as NaNs and denormals, are covered as well + std::vector data_in(ggml_nbytes(x)); + std::mt19937 rng(1234); + for (size_t i = 0; i < data_in.size(); i++) { + data_in[i] = rng() & 0xFF; + } + ggml_backend_tensor_set(x, data_in.data(), 0, data_in.size()); + + ggml_gallocr_ptr galloc(ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend))); + ggml_gallocr_alloc_graph(galloc.get(), gf); + + // warm up, so that one-time costs such as lazy CUDA module loading are not timed + ggml_backend_graph_compute(backend, gf); + + const int64_t t_start_us = ggml_time_us(); + const ggml_status status = ggml_backend_graph_compute(backend, gf); + const int64_t t_us = ggml_time_us() - t_start_us; + + std::vector data_out(ggml_nbytes(out)); + ggml_backend_tensor_get(out, data_out.data(), 0, data_out.size()); + + const int64_t t_min_us = (int64_t) n_nodes * us; + + const bool ok_status = status == GGML_STATUS_SUCCESS; + const bool ok_alias = out->data == x->data; + const bool ok_data = memcmp(data_in.data(), data_out.data(), data_in.size()) == 0; + const bool ok_time = t_us >= t_min_us; + + printf("%selapsed=%7" PRId64 " us (>= %6" PRId64 ") alias: %-4s data: %-4s time: %s\n", + desc, t_us, t_min_us, ok_alias ? "OK" : "FAIL", ok_data ? "OK" : "FAIL", ok_time ? "OK" : "FAIL"); + + if (!ok_status) { + printf(" compute failed: %s\n", ggml_status_to_string(status)); + } + + result = ok_status && ok_alias && ok_data && ok_time ? TEST_OK : TEST_FAIL; + } + + return result; +} + +int main() { + ggml_time_init(); + ggml_backend_load_all(); + + int n_ok = 0; + int n_fail = 0; + int n_skip = 0; + + for (size_t i = 0; i < ggml_backend_dev_count(); i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + + ggml_backend_ptr backend(ggml_backend_dev_init(dev, nullptr)); + if (backend == nullptr) { + printf(" failed to initialize %s\n", ggml_backend_dev_name(dev)); + n_fail++; + continue; + } + + // a zero duration must still be a valid no-op, longer ones are checked against the clock, + // and the last case verifies that a chain of sleeps accumulates instead of collapsing into one + const struct { + ggml_type type; + int64_t ne; + int32_t us; + int n_nodes; + } cases[] = { + { GGML_TYPE_F32, 1, 0, 1 }, + { GGML_TYPE_F32, 4096, 10000, 1 }, + { GGML_TYPE_F16, 1024, 10000, 1 }, + { GGML_TYPE_F32, 1 << 20, 5000, 4 }, + }; + + for (const auto & c : cases) { + switch (test_sleep(backend.get(), c.type, c.ne, c.us, c.n_nodes)) { + case TEST_OK: n_ok++; break; + case TEST_FAIL: n_fail++; break; + case TEST_SKIP: n_skip++; break; + } + } + } + + printf("%d passed, %d failed, %d skipped\n", n_ok, n_fail, n_skip); + + return n_fail > 0; +} diff --git a/tests/test-tokenizer-random.py b/tests/test-tokenizer-random.py index 7f5ea3f45684..4b4fbdf75510 100644 --- a/tests/test-tokenizer-random.py +++ b/tests/test-tokenizer-random.py @@ -80,6 +80,7 @@ def __init__(self, libllama: LibLlama, path_model: str, mparams={}, cparams={}): raise RuntimeError("error: failed to load model '%s'" % path_model) if isinstance(cparams, dict): cparams = libllama.context_default_params(**cparams) + self.vocab = self.lib.llama_model_get_vocab(self.model) self.ctx = self.lib.llama_init_from_model(self.model, cparams) if not self.ctx: raise RuntimeError("error: failed to create context for model '%s'" % path_model) @@ -98,10 +99,10 @@ def free(self): def tokenize(self, text: str, add_special: bool = False, parse_special: bool = False) -> list[int]: encoded_text: bytes = text.encode("utf-8") - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) while num < 0 and len(self.token_ids) < (16 << 20): self.token_ids = self.ffi.new("llama_token[]", -2 * num) - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) return list(self.token_ids[0:num]) def detokenize(self, ids: list[int], remove_special: bool = False, unparse_special: bool = False) -> str: @@ -109,10 +110,10 @@ def detokenize(self, ids: list[int], remove_special: bool = False, unparse_speci self.token_ids = self.ffi.new("llama_token[]", 2 * len(ids)) for i, id in enumerate(ids): self.token_ids[i] = id - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) while num < 0 and len(self.text_buff) < (16 << 20): self.text_buff = self.ffi.new("uint8_t[]", -2 * num) - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) return str(self.ffi.buffer(self.text_buff, num), encoding="utf-8", errors="replace") # replace errors with '\uFFFD' # pyright: ignore[reportArgumentType] diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index 1101d267ad01..511e01f93223 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -644,6 +644,7 @@ static void mtmd_owned_llama_set_tensor_data(ggml_tensor * t, void * user_data) return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0; }; const bool optional = ends_with("scale") || ends_with(".bias") || name == "dense_2.weight" || + name == "cls.output.weight" || // Qwen3 reranking head, unused by YuE2 NAR name == "rope_freqs.weight" || // granite, voxcpm2 residual LM name == "token_embd.weight" || name == "output.weight"; // inputs are embedding rows, outputs are hidden states if (!optional || t->type != GGML_TYPE_F32) { diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 8b794bac2baa..5eea78715b38 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -359,6 +359,8 @@ struct server_slot { return false; } + const int64_t t_start = ggml_time_us(); + const size_t cur_size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t cur_size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; @@ -380,6 +382,8 @@ struct server_slot { return false; } + SLT_TRC(*this, "prompt cache save took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0); + return true; } diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index 5f8aa5c33e2c..9f977934828f 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -208,6 +208,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok if (it_best != states.end()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + const int64_t t_start = ggml_time_us(); + { auto & data = it_best->data.main; @@ -252,6 +254,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok prompt = std::move(it_best->prompt); states.erase(it_best); + + SRV_TRC("slot %d: prompt cache restore took %.2f ms\n", id_slot, (ggml_time_us() - t_start) / 1000.0); } return true; diff --git a/ui/apps/chat/demo/fixtures/traces.ts b/ui/apps/chat/demo/fixtures/traces.ts index cc7ed8979a95..dc766458e478 100644 --- a/ui/apps/chat/demo/fixtures/traces.ts +++ b/ui/apps/chat/demo/fixtures/traces.ts @@ -301,9 +301,39 @@ function agenticDebugging(): Trace { return trace; } +/** A reply with a diagram, for diagram preview demos. */ +function diagrams(): Trace { + const trace = new Trace('How a request flows through llama-server'); + + trace.user('Can you draw how a chat request flows through llama-server?'); + trace.assistant( + [ + 'Here is the path a request takes:', + '', + '```mermaid', + 'flowchart LR', + ' U[Browser] -->|POST /v1/chat/completions| S(llama-server)', + ' S --> Q{Slot free?}', + ' Q -->|yes| P[Prompt processing]', + ' Q -->|no| W[Queue]', + ' W --> P', + ' P --> G[Sample token]', + ' G -->|more| G', + ' G -->|SSE tokens| U', + ' click S href "https://github.com/ggml-org/llama.cpp" "llama.cpp on GitHub" _blank', + '```', + '', + 'Requests wait in the queue until a slot is free, then tokens stream back as they are sampled.' + ].join('\n') + ); + + return trace; +} + /** Built-in traces, by name. */ export const DEMO_TRACES: Record Trace> = { 'agentic-debugging': agenticDebugging, + diagrams, 'long-chat': longChat }; diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json index 11778042c5ce..ef7891ba3e38 100644 --- a/ui/apps/chat/package-lock.json +++ b/ui/apps/chat/package-lock.json @@ -51,8 +51,8 @@ "dompurify": "3.4.17", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", - "eslint-plugin-perfectionist": "^5.10.1", - "eslint-plugin-simple-import-sort": "^14.0.0", + "eslint-plugin-perfectionist": "5.13.0", + "eslint-plugin-simple-import-sort": "14.0.0", "eslint-plugin-storybook": "10.6.6", "eslint-plugin-svelte": "3.24.1", "fflate": "0.8.3", @@ -60,9 +60,9 @@ "highlight.js": "11.11.1", "http-server": "14.1.1", "mdsvex": "0.12.7", - "mermaid": "11.17.2", "mode-watcher": "1.1.0", "pdfjs-dist": "5.4.54", + "pele": "1.13.0", "playwright": "1.56.1", "prettier": "3.8.3", "prettier-plugin-svelte": "4.1.0", @@ -107,20 +107,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@antfu/install-pkg": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@antfu/install-pkg/-/install-pkg-2.1.0.tgz", - "integrity": "sha512-sdg9NxU3zR4Mnawfbc/x6GB5Wf17WYud5qOuEuxXjaKpYpMkISSJEjItGebXJ2bQ4DIcly4NYH23mtkGJjvKUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "package-manager-detector": "^1.8.0", - "tinyexec": "^1.3.1" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -220,13 +206,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@braintree/sanitize-url": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz", - "integrity": "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==", - "dev": true, - "license": "MIT" - }, "node_modules/@cacheable/memory": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", @@ -258,13 +237,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@chevrotain/types": { - "version": "11.1.2", - "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.1.2.tgz", - "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==", - "dev": true, - "license": "Apache-2.0" - }, "node_modules/@chromatic-com/storybook": { "version": "5.5.1", "resolved": "https://registry.npmjs.org/@chromatic-com/storybook/-/storybook-5.5.1.tgz", @@ -1190,25 +1162,6 @@ "url": "https://github.com/sponsors/nzakas" } }, - "node_modules/@iconify/types": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@iconify/types/-/types-2.0.0.tgz", - "integrity": "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@iconify/utils": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/@iconify/utils/-/utils-3.1.7.tgz", - "integrity": "sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@antfu/install-pkg": "^2.0.1", - "@iconify/types": "^2.0.0", - "import-meta-resolve": "^4.2.0" - } - }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -1984,16 +1937,6 @@ "react": ">=16" } }, - "node_modules/@mermaid-js/parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@mermaid-js/parser/-/parser-1.2.1.tgz", - "integrity": "sha512-n12NohV3mrUyUL2o93IgG/ifeW9FTyeJn3zDxkhwa8MJ9Fxg3HQMlA3RiGmD/3UnJvheztkjjQAjA2T4LmUcpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@chevrotain/types": "~11.1.2" - } - }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.32.1", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz", @@ -4640,290 +4583,6 @@ "assertion-error": "^2.0.1" } }, - "node_modules/@types/d3": { - "version": "7.4.3", - "resolved": "https://registry.npmjs.org/@types/d3/-/d3-7.4.3.tgz", - "integrity": "sha512-lZXZ9ckh5R8uiFVt8ogUNf+pIrK4EsWrx2Np75WvF/eTpJ0FMHNhjXk8CKEx/+gpHbNQyJWehbFaTvqmHWB3ww==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-array": "*", - "@types/d3-axis": "*", - "@types/d3-brush": "*", - "@types/d3-chord": "*", - "@types/d3-color": "*", - "@types/d3-contour": "*", - "@types/d3-delaunay": "*", - "@types/d3-dispatch": "*", - "@types/d3-drag": "*", - "@types/d3-dsv": "*", - "@types/d3-ease": "*", - "@types/d3-fetch": "*", - "@types/d3-force": "*", - "@types/d3-format": "*", - "@types/d3-geo": "*", - "@types/d3-hierarchy": "*", - "@types/d3-interpolate": "*", - "@types/d3-path": "*", - "@types/d3-polygon": "*", - "@types/d3-quadtree": "*", - "@types/d3-random": "*", - "@types/d3-scale": "*", - "@types/d3-scale-chromatic": "*", - "@types/d3-selection": "*", - "@types/d3-shape": "*", - "@types/d3-time": "*", - "@types/d3-time-format": "*", - "@types/d3-timer": "*", - "@types/d3-transition": "*", - "@types/d3-zoom": "*" - } - }, - "node_modules/@types/d3-array": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", - "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-axis": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@types/d3-axis/-/d3-axis-3.0.6.tgz", - "integrity": "sha512-pYeijfZuBd87T0hGn0FO1vQ/cgLk6E1ALJjfkC0oJ8cbwkZl3TpgS8bVBLZN+2jjGgg38epgxb2zmoGtSfvgMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-brush": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@types/d3-brush/-/d3-brush-3.0.6.tgz", - "integrity": "sha512-nH60IZNNxEcrh6L1ZSMNA28rj27ut/2ZmI3r96Zd+1jrZD++zD3LsMIjWlvg4AYrHn/Pqz4CF3veCxGjtbqt7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-chord": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@types/d3-chord/-/d3-chord-3.0.6.tgz", - "integrity": "sha512-LFYWWd8nwfwEmTZG9PfQxd17HbNPksHBiJHaKuY1XeqscXacsS2tyoo6OdRsjf+NQYeB6XrNL3a25E3gH69lcg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-color": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", - "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-contour": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@types/d3-contour/-/d3-contour-3.0.6.tgz", - "integrity": "sha512-BjzLgXGnCWjUSYGfH1cpdo41/hgdWETu4YxpezoztawmqsvCeep+8QGfiY6YbDvfgHz/DkjeIkkZVJavB4a3rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-array": "*", - "@types/geojson": "*" - } - }, - "node_modules/@types/d3-delaunay": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.4.tgz", - "integrity": "sha512-ZMaSKu4THYCU6sV64Lhg6qjf1orxBthaC161plr5KuPHo3CNm8DTHiLw/5Eq2b6TsNP0W0iJrUOFscY6Q450Hw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-dispatch": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@types/d3-dispatch/-/d3-dispatch-3.0.7.tgz", - "integrity": "sha512-5o9OIAdKkhN1QItV2oqaE5KMIiXAvDWBDPrD85e58Qlz1c1kI/J0NcqbEG88CoTwJrYe7ntUCVfeUl2UJKbWgA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-drag": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@types/d3-drag/-/d3-drag-3.0.7.tgz", - "integrity": "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-dsv": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@types/d3-dsv/-/d3-dsv-3.0.7.tgz", - "integrity": "sha512-n6QBF9/+XASqcKK6waudgL0pf/S5XHPPI8APyMLLUHd8NqouBGLsU8MgtO7NINGtPBtk9Kko/W4ea0oAspwh9g==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-ease": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", - "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-fetch": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/@types/d3-fetch/-/d3-fetch-3.0.7.tgz", - "integrity": "sha512-fTAfNmxSb9SOWNB9IoG5c8Hg6R+AzUHDRlsXsDZsNp6sxAEOP0tkP3gKkNSO/qmHPoBFTxNrjDprVHDQDvo5aA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-dsv": "*" - } - }, - "node_modules/@types/d3-force": { - "version": "3.0.10", - "resolved": "https://registry.npmjs.org/@types/d3-force/-/d3-force-3.0.10.tgz", - "integrity": "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-format": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.4.tgz", - "integrity": "sha512-fALi2aI6shfg7vM5KiR1wNJnZ7r6UuggVqtDA+xiEdPZQwy/trcQaHnwShLuLdta2rTymCNpxYTiMZX/e09F4g==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-geo": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@types/d3-geo/-/d3-geo-3.1.1.tgz", - "integrity": "sha512-65Emv9fQiQQqphLlRkuQ5ypPsOmWPhtBGCMv61JDPEPMvsx+gzhGf74yw1a78xFKPj6zw4AgQICJoQv0vK9M2w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/geojson": "*" - } - }, - "node_modules/@types/d3-hierarchy": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/@types/d3-hierarchy/-/d3-hierarchy-3.1.7.tgz", - "integrity": "sha512-tJFtNoYBtRtkNysX1Xq4sxtjK8YgoWUNpIiUee0/jHGRwqvzYxkq0hGVbbOGSz+JgFxxRu4K8nb3YpG3CMARtg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-interpolate": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", - "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-color": "*" - } - }, - "node_modules/@types/d3-path": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", - "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-polygon": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-polygon/-/d3-polygon-3.0.2.tgz", - "integrity": "sha512-ZuWOtMaHCkN9xoeEMr1ubW2nGWsp4nIql+OPQRstu4ypeZ+zk3YKqQT0CXVe/PYqrKpZAi+J9mTs05TKwjXSRA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-quadtree": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/@types/d3-quadtree/-/d3-quadtree-3.0.6.tgz", - "integrity": "sha512-oUzyO1/Zm6rsxKRHA1vH0NEDG58HrT5icx/azi9MF1TWdtttWl0UIUsjEQBBh+SIkrpd21ZjEv7ptxWys1ncsg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-random": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-random/-/d3-random-3.0.4.tgz", - "integrity": "sha512-UHYId5WTCx4L4YNel7NU00XUXXgvgpgZOvp10PuvsQENjMDXhh2RyFc0KBjO7B45ne4Ha1yVH7ii0vnzKkuzWA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-scale": { - "version": "4.0.9", - "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", - "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-time": "*" - } - }, - "node_modules/@types/d3-scale-chromatic": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz", - "integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-selection": { - "version": "3.0.12", - "resolved": "https://registry.npmjs.org/@types/d3-selection/-/d3-selection-3.0.12.tgz", - "integrity": "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-shape": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.2.0.tgz", - "integrity": "sha512-kVd74ta9eof3eJOvbNd1vGKS/XERRyQbT26Og63hIsvDO84cjD5gEOhsXf26w3FSoNlPVz84DOFcKv/oou+fMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-path": "*" - } - }, - "node_modules/@types/d3-time": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", - "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-time-format": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-4.0.3.tgz", - "integrity": "sha512-5xg9rC+wWL8kdDj153qZcsJ0FWiFt0J5RB6LYUNZjwSnesfblqrI/bJ1wBdJ8OQfncgbJG5+2F+qfqnqyzYxyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-timer": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", - "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/d3-transition": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/@types/d3-transition/-/d3-transition-3.0.9.tgz", - "integrity": "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-selection": "*" - } - }, - "node_modules/@types/d3-zoom": { - "version": "3.0.9", - "resolved": "https://registry.npmjs.org/@types/d3-zoom/-/d3-zoom-3.0.9.tgz", - "integrity": "sha512-0sE1406XBYJGiqD3AusTl9ZqC//2mIXix51tbom25gDCA8ri4xnSZg28CaSE8Srl6FClqABUKfsn0qghgdepMA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/d3-interpolate": "*", - "@types/d3-selection": "*" - } - }, "node_modules/@types/debug": { "version": "4.1.13", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", @@ -4955,13 +4614,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/geojson": { - "version": "7946.0.16", - "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", - "integrity": "sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/hast": { "version": "3.0.5", "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", @@ -5296,17 +4948,6 @@ "dev": true, "license": "ISC" }, - "node_modules/@upsetjs/venn.js": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@upsetjs/venn.js/-/venn.js-2.0.0.tgz", - "integrity": "sha512-WbBhLrooyePuQ1VZxrJjtLvTc4NVfpOyKx0sKqioq9bX1C1m7Jgykkn8gLrtwumBioXIqam8DLxp88Adbue6Hw==", - "dev": true, - "license": "MIT", - "optionalDependencies": { - "d3-selection": "^3.0.0", - "d3-transition": "^3.0.1" - } - }, "node_modules/@valibot/to-json-schema": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@valibot/to-json-schema/-/to-json-schema-1.8.0.tgz", @@ -6162,16 +5803,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - } - }, "node_modules/consola": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", @@ -6265,16 +5896,6 @@ "node": ">= 0.4.0" } }, - "node_modules/cose-base": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz", - "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==", - "dev": true, - "license": "MIT", - "dependencies": { - "layout-base": "^1.0.0" - } - }, "node_modules/crelt": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", @@ -6325,642 +5946,80 @@ "license": "MIT", "peer": true }, - "node_modules/cytoscape": { - "version": "3.34.4", - "resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.34.4.tgz", - "integrity": "sha512-msY99tMY8iWTg+sIPGfSqDcPNOt4xcj+v/K/7qUFaCUxxlqnMkUYLBjRUzn9W5CU/R2hrmtJa5+UtovrEM2ctg==", + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, "engines": { - "node": ">=0.10" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/cytoscape-cose-bilkent": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz", - "integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==", + "node_modules/decode-bmp": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/decode-bmp/-/decode-bmp-0.2.1.tgz", + "integrity": "sha512-NiOaGe+GN0KJqi2STf24hfMkFitDUaIoUU3eKvP/wAbLe8o6FuW5n/x7MHPR0HKvBokp6MQY/j7w8lewEeVCIA==", "dev": true, "license": "MIT", "dependencies": { - "cose-base": "^1.0.0" + "@canvas/image-data": "^1.0.0", + "to-data-view": "^1.1.0" }, - "peerDependencies": { - "cytoscape": "^3.2.0" + "engines": { + "node": ">=8.6.0" } }, - "node_modules/cytoscape-fcose": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/cytoscape-fcose/-/cytoscape-fcose-2.2.0.tgz", - "integrity": "sha512-ki1/VuRIHFCzxWNrsshHYPs6L7TvLu3DL+TyIGEsRcvVERmxokbf5Gdk7mFxZnTdiGtnA4cfSmjZJMviqSuZrQ==", + "node_modules/decode-ico": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/decode-ico/-/decode-ico-0.4.1.tgz", + "integrity": "sha512-69NZfbKIzux1vBOd31al3XnMnH+2mqDhEgLdpygErm4d60N+UwA5Sq5WFjmEDQzumgB9fElojGwWG0vybVfFmA==", "dev": true, "license": "MIT", "dependencies": { - "cose-base": "^2.2.0" + "@canvas/image-data": "^1.0.0", + "decode-bmp": "^0.2.0", + "to-data-view": "^1.1.0" }, - "peerDependencies": { - "cytoscape": "^3.2.0" + "engines": { + "node": ">=8.6" } }, - "node_modules/cytoscape-fcose/node_modules/cose-base": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/cose-base/-/cose-base-2.2.0.tgz", - "integrity": "sha512-AzlgcsCbUMymkADOJtQm3wO9S3ltPfYOFD5033keQn9NJzIbtnZj+UdBJe7DYml/8TdbtHJW3j58SOnKhWY/5g==", + "node_modules/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", "dev": true, "license": "MIT", "dependencies": { - "layout-base": "^2.0.0" - } - }, - "node_modules/cytoscape-fcose/node_modules/layout-base": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-2.0.1.tgz", - "integrity": "sha512-dp3s92+uNI1hWIpPGH3jK2kxE2lMjdXdr+DH8ynZHpd6PUlH6x6cbuXnoMmiNumznqaNO31xu9e79F0uuZ0JFg==", - "dev": true, - "license": "MIT" - }, - "node_modules/d3": { - "version": "7.9.2", - "resolved": "https://registry.npmjs.org/d3/-/d3-7.9.2.tgz", - "integrity": "sha512-ZKb/mONPVKzaO5UlcWcwN8bS4ezvQaYu+bsou+XgNABdGC800kwH651ADTbbTxMPHW13UlvbQafdmJQDk1w7Mg==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-array": "^3.2.5", - "d3-axis": "^3.0.1", - "d3-brush": "^3.0.1", - "d3-chord": "^3.0.2", - "d3-color": "^3.1.1", - "d3-contour": "^4.0.3", - "d3-delaunay": "^6.0.6", - "d3-dispatch": "^3.0.2", - "d3-drag": "^3.0.1", - "d3-dsv": "^3.0.2", - "d3-ease": "^3.0.2", - "d3-fetch": "^3.0.2", - "d3-force": "^3.0.1", - "d3-format": "^3.1.3", - "d3-geo": "^3.1.2", - "d3-hierarchy": "^3.1.3", - "d3-interpolate": "^3.0.2", - "d3-path": "^3.1.1", - "d3-polygon": "^3.0.2", - "d3-quadtree": "^3.0.2", - "d3-random": "^3.0.2", - "d3-scale": "^4.0.3", - "d3-scale-chromatic": "^3.1.1", - "d3-selection": "^3.0.1", - "d3-shape": "^3.2.1", - "d3-time": "^3.1.1", - "d3-time-format": "^4.1.1", - "d3-timer": "^3.0.2", - "d3-transition": "^3.0.2", - "d3-zoom": "^3.0.1" + "character-entities": "^2.0.0" }, - "engines": { - "node": ">=12" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/d3-array": { - "version": "3.2.5", - "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.5.tgz", - "integrity": "sha512-Th8qGXoBalmWsstpkuhmBuTsBQIFqYOJtjlBvNVvBfJ8E3uYusBUwUR8HU20U0qKKQkgCvKyR1YjiozWadk5QA==", + "node_modules/dedent": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", "dev": true, - "license": "ISC", - "dependencies": { - "internmap": "1 - 2" + "license": "MIT", + "peerDependencies": { + "babel-plugin-macros": "^3.1.0" }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-axis": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.1.tgz", - "integrity": "sha512-E5QCXfaf/uJZEHHiqoWRq+bQEm2PzoVFv2rDC7CZ3wwI0MjfMW3w83J3ubobG4IJj3lShAI5eiPJhOu/8wHofA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-brush": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.1.tgz", - "integrity": "sha512-L5Glqa/Gb7LU3ndIOMtA5mDzlJ0aXKp5ELP2X09ctWF23jO7+faIUVDbmaIi+D6k3EemXFWn1F3lkfguExoVhA==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-drag": "2 - 3", - "d3-interpolate": "1 - 3", - "d3-selection": "3", - "d3-transition": "3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-chord": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.2.tgz", - "integrity": "sha512-cGmADo5M2PTi3ewJZ2lcE32eURd4JmHtQ5JwRIUcas5L1SXqufG9yPyjWp8fW0gRi7aZi9bgbZPFZO1eyZ+1CQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-path": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-color": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.1.tgz", - "integrity": "sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-contour": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.3.tgz", - "integrity": "sha512-5DYURc8KwXPOhSUBblU0P9rVcArsSPxPOxsfO0Eud0s28oU0sB2e80aRHRL9AZW3usT8ikFKyIHpHHLNWLdRVA==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-array": "^3.2.4" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-delaunay": { - "version": "6.0.6", - "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.6.tgz", - "integrity": "sha512-DMQIEvSJhZCB6pwedcXaAlQ+MeKU5LlM2XakKtc73b/VM+RBiI1SRXycOEOKg2jsKj4zZ9F0KGYG6nCGwwWu/g==", - "dev": true, - "license": "ISC", - "dependencies": { - "delaunator": "5" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-dispatch": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.2.tgz", - "integrity": "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-drag": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.1.tgz", - "integrity": "sha512-OWeoayCq8J69hUIjvL+Mb6Q6Oaj/fyHV5XaXByEUAG+JUjIfTGDnk3qGpcXrD3VmQ3BSV96fcbM6fqq7C0tbPA==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-selection": "3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-dsv": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.2.tgz", - "integrity": "sha512-FUnXhX7I4/AXyRCZzwfZTDGSq8PGZ4oR0tiCBqNGOZMsDrQ+6sIWNQnBzcCGhzJKZ6uCvCezTwflUqI209RRiQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "commander": "7", - "iconv-lite": "0.6", - "rw": "1" - }, - "bin": { - "csv2json": "bin/dsv2json.js", - "csv2tsv": "bin/dsv2dsv.js", - "dsv2dsv": "bin/dsv2dsv.js", - "dsv2json": "bin/dsv2json.js", - "json2csv": "bin/json2dsv.js", - "json2dsv": "bin/json2dsv.js", - "json2tsv": "bin/json2dsv.js", - "tsv2csv": "bin/dsv2dsv.js", - "tsv2json": "bin/dsv2json.js" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-dsv/node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/d3-ease": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.2.tgz", - "integrity": "sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-fetch": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.2.tgz", - "integrity": "sha512-1wGF62bgjMRbF6mqbD+6rRWBL2hwWVYQjFO2UP3Wm1nIAvJZKaQxXM5caVY7athoCa8wIq9lCf7g44lPWFk50g==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-dsv": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-force": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.1.tgz", - "integrity": "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-quadtree": "1 - 3", - "d3-timer": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-format": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.3.tgz", - "integrity": "sha512-+F+/49swqmGuQJmSKnVMIDH/QkEFV5li9QRj0xm/KhyAUBv099O5PrvpQFxBp24PYph17Mnvt9mjKQV0ii0nMA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-geo": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.2.tgz", - "integrity": "sha512-5R8ZgDQorIxmauv7R6gpE/ndz+Z0qAZssigq0aXFdvPHdY41RqtW02jrRUQAL724NdPABYXo1+gQEGBBr7uKNg==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-array": "2.5.0 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-hierarchy": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.3.tgz", - "integrity": "sha512-GRajN5ZcnEwYFWqqdzhG1qJ3+fDg6WWzk47TJg7ePY7yvYAgRfD2r1mUx+wviBOWuCwamCUzjwMSdato43jbGA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-interpolate": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.2.tgz", - "integrity": "sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-path": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.1.tgz", - "integrity": "sha512-jsbgV8zIT38ReB9O7X7gcLndTQRONSqNNd+oGIaTBdUug4r5jFmp0N6RY9R5GWbdUDucn0qoTGyfjapT4tDhcg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-polygon": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.2.tgz", - "integrity": "sha512-WAUvPudGU1Dn4mDPfb6+JnnbeVEV53hG/BoT+bxts6AkZsOpTEiV1jHYX+2vtwCICNFG9Wxv8QS+eW1zE/Dwfg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-quadtree": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.2.tgz", - "integrity": "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-random": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.2.tgz", - "integrity": "sha512-PxJi9LNV+7mulaYO77nd+oGurXGL1fhedXjHnB3pWLUcqDnQtF4VASoqnQGHgoXLByVdv5QJ/2kfwkGn5HTS8g==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-sankey": { - "version": "0.12.3", - "resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz", - "integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "d3-array": "1 - 2", - "d3-shape": "^1.2.0" - } - }, - "node_modules/d3-sankey/node_modules/d3-array": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz", - "integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "internmap": "^1.0.0" - } - }, - "node_modules/d3-sankey/node_modules/d3-path": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz", - "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/d3-sankey/node_modules/d3-shape": { - "version": "1.3.7", - "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz", - "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "d3-path": "1" - } - }, - "node_modules/d3-sankey/node_modules/internmap": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz", - "integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==", - "dev": true, - "license": "ISC" - }, - "node_modules/d3-scale": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.3.tgz", - "integrity": "sha512-66cWobCNzcMvlfoaDHCxuIv9TBUWG1BLOWdv9kHHFuCr1JdqAWPvTmsaEYDD5NRMyWZ5+7u0GqiCDfMXMqh3hg==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-array": "2.10.0 - 3", - "d3-format": "1 - 3", - "d3-interpolate": "1.2.0 - 3", - "d3-time": "2.1.1 - 3", - "d3-time-format": "2 - 4" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-scale-chromatic": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.1.tgz", - "integrity": "sha512-lA5gfN2yMvmChubmptnDiBfeGpHD7Yb1EbvCz0TZE0WHXhyR6W2allPuhKtzV5ILQRqeOdefF0qYtERReLUBDg==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3", - "d3-interpolate": "1 - 3", - "d3-scale": "1 - 4" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-selection": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.1.tgz", - "integrity": "sha512-ODSf35vqCrlCfp7hrm0eZjvOosSXSYLjqvIlhMBV9q9VOx7EBJG6pc+uXBswEZNJgCGJ+qnKYcWutbZDIxe/Xg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-shape": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.1.tgz", - "integrity": "sha512-dm2o+lbKdzg9tY7GEag/dB9hcbodLfwkE/DkvqbELJXaMz0yKzWWhZqhbI7CKubukA7HnRyz0avdtvi7EPxPvw==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-path": "^3.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-time": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.1.tgz", - "integrity": "sha512-Ze7rjrhMzdeulh0/hjcfFj7XLAHOfowtEMfsoG6DU866HPynQNW7Wfen6hzXcqKTv8XzxvF6Hzr5XD6bMHr2ug==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-array": "2 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-time-format": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.1.tgz", - "integrity": "sha512-22XaqjyCjpqgda20erhsOjGmC3vvYwTNYniKAd45W5UWLDF43moeOuV9qYpRqobIlsnK0UhnKZjUUJm3VgORUA==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-time": "1 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-timer": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.2.tgz", - "integrity": "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/d3-transition": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.2.tgz", - "integrity": "sha512-RcjCsdFgyFoDB+QXLC5m60ZkTN0k9zH+ovoLlTdJnDS1AbfbcuowiM4pCKSTOclNibS4f4J4cbv2m7O7y8NTOQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-color": "1 - 3", - "d3-dispatch": "1 - 3", - "d3-ease": "1 - 3", - "d3-interpolate": "1 - 3", - "d3-timer": "1 - 3" - }, - "engines": { - "node": ">=12" - }, - "peerDependencies": { - "d3-selection": "2 - 3" - } - }, - "node_modules/d3-zoom": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.1.tgz", - "integrity": "sha512-kfjD3BDQu/FOatpZ6JdMSyIoDwTxIpI29ySTI2J5ZlDaH1WbuJGQJ2Q9oJkWTEZEW98j6idezoomSD3Cn2zwiw==", - "dev": true, - "license": "ISC", - "dependencies": { - "d3-dispatch": "1 - 3", - "d3-drag": "2 - 3", - "d3-interpolate": "1 - 3", - "d3-selection": "2 - 3", - "d3-transition": "2 - 3" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/dagre-d3-es": { - "version": "7.0.14", - "resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.14.tgz", - "integrity": "sha512-P4rFMVq9ESWqmOgK+dlXvOtLwYg0i7u0HBGJER0LZDJT2VHIPAMZ/riPxqJceWMStH5+E61QxFra9kIS3AqdMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "d3": "^7.9.0", - "lodash-es": "^4.17.21" - } - }, - "node_modules/dayjs": { - "version": "1.11.23", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz", - "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decode-bmp": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/decode-bmp/-/decode-bmp-0.2.1.tgz", - "integrity": "sha512-NiOaGe+GN0KJqi2STf24hfMkFitDUaIoUU3eKvP/wAbLe8o6FuW5n/x7MHPR0HKvBokp6MQY/j7w8lewEeVCIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@canvas/image-data": "^1.0.0", - "to-data-view": "^1.1.0" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/decode-ico": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/decode-ico/-/decode-ico-0.4.1.tgz", - "integrity": "sha512-69NZfbKIzux1vBOd31al3XnMnH+2mqDhEgLdpygErm4d60N+UwA5Sq5WFjmEDQzumgB9fElojGwWG0vybVfFmA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@canvas/image-data": "^1.0.0", - "decode-bmp": "^0.2.0", - "to-data-view": "^1.1.0" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/decode-named-character-reference": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", - "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "character-entities": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/dedent": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", - "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } + "peerDependenciesMeta": { + "babel-plugin-macros": { + "optional": true + } } }, "node_modules/dedent-js": { @@ -7047,16 +6106,6 @@ "dev": true, "license": "MIT" }, - "node_modules/delaunator": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz", - "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "robust-predicates": "^3.0.2" - } - }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -7848,16 +6897,6 @@ ], "license": "BSD-3-Clause" }, - "node_modules/fastdom": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/fastdom/-/fastdom-1.0.12.tgz", - "integrity": "sha512-LB+xjSTEbjHE1cWsxu+tN2Xqr1kpi+V9aADI7sVM5ZMaXyYGPHULQMzpJMYqOTULK/73pUkWVzzObFRBkPr+hg==", - "dev": true, - "license": "MIT", - "dependencies": { - "strictdom": "^1.0.1" - } - }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -8102,13 +7141,6 @@ "dev": true, "license": "ISC" }, - "node_modules/hachure-fill": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz", - "integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==", - "dev": true, - "license": "MIT" - }, "node_modules/has-flag": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", @@ -8519,17 +7551,6 @@ "dev": true, "license": "MIT" }, - "node_modules/import-meta-resolve": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/import-meta-resolve/-/import-meta-resolve-4.2.0.tgz", - "integrity": "sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, "node_modules/imurmurhash": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", @@ -8564,16 +7585,6 @@ "dev": true, "license": "MIT" }, - "node_modules/internmap": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", - "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, "node_modules/ip-address": { "version": "10.7.6", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", @@ -8856,12 +7867,6 @@ "@keyv/serialize": "^1.1.1" } }, - "node_modules/khroma": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/khroma/-/khroma-2.1.0.tgz", - "integrity": "sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==", - "dev": true - }, "node_modules/known-css-properties": { "version": "0.37.0", "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz", @@ -8869,13 +7874,6 @@ "dev": true, "license": "MIT" }, - "node_modules/layout-base": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz", - "integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==", - "dev": true, - "license": "MIT" - }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", @@ -9196,13 +8194,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lodash-es": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz", - "integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==", - "dev": true, - "license": "MIT" - }, "node_modules/longest-streak": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/longest-streak/-/longest-streak-3.1.0.tgz", @@ -9296,19 +8287,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/marked": { - "version": "16.4.2", - "resolved": "https://registry.npmjs.org/marked/-/marked-16.4.2.tgz", - "integrity": "sha512-TI3V8YYWvkVf3KJe1dRkpnjs68JUPyEa5vjKrp1XEEJUAOaQc+Qj+L1qWbPd0SJuAdQkFU0h73sXXqwDYxsiDA==", - "dev": true, - "license": "MIT", - "bin": { - "marked": "bin/marked.js" - }, - "engines": { - "node": ">= 20" - } - }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -9687,37 +8665,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/mermaid": { - "version": "11.17.2", - "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-11.17.2.tgz", - "integrity": "sha512-V6K3C8EBdEsPFZXSKMJe6ppQOENxuHARr9GvHX4hh47lAbhMRD9qf4oEK7LoaRQxULMa80/qt5gHO73aCleBBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@braintree/sanitize-url": "^7.1.2", - "@iconify/utils": "^3.0.2", - "@mermaid-js/parser": "^1.2.1", - "@types/d3": "^7.4.3", - "@upsetjs/venn.js": "^2.0.0", - "cytoscape": "^3.34.0", - "cytoscape-cose-bilkent": "^4.1.0", - "cytoscape-fcose": "^2.2.0", - "d3": "^7.9.0", - "d3-sankey": "^0.12.3", - "dagre-d3-es": "7.0.14", - "dayjs": "^1.11.21", - "dompurify": "^3.3.3", - "es-toolkit": "^1.45.1", - "fastdom": "1.0.12", - "katex": "^0.16.47", - "khroma": "^2.1.0", - "marked": "^16.3.0", - "roughjs": "^4.6.6", - "stylis": "^4.3.6", - "ts-dedent": "^2.2.0", - "uuid": "^11.1.0 || ^12 || ^13 || ^14.0.0" - } - }, "node_modules/micromark": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.3.tgz", @@ -10803,13 +9750,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/package-manager-detector": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", - "integrity": "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==", - "dev": true, - "license": "MIT" - }, "node_modules/parse5": { "version": "8.1.1", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", @@ -10833,13 +9773,6 @@ "node": ">= 0.8" } }, - "node_modules/path-data-parser": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz", - "integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w==", - "dev": true, - "license": "MIT" - }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -10901,6 +9834,16 @@ "@napi-rs/canvas": "^0.1.74" } }, + "node_modules/pele": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/pele/-/pele-1.13.0.tgz", + "integrity": "sha512-Ie8UKY9x00MsuR3jO6AzUwzK2Z6MIV3Tf4EDdITiuk8Uaz8K7g0R082WqsqNaSU8DdgkrRvZThzhit83mi/uiw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -10973,24 +9916,6 @@ "node": ">=14.19.0" } }, - "node_modules/points-on-curve": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz", - "integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==", - "dev": true, - "license": "MIT" - }, - "node_modules/points-on-path": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz", - "integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-data-parser": "0.1.0", - "points-on-curve": "0.2.0" - } - }, "node_modules/portfinder": { "version": "1.0.38", "resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.38.tgz", @@ -11713,13 +10638,6 @@ "dev": true, "license": "MIT" }, - "node_modules/robust-predicates": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.3.tgz", - "integrity": "sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==", - "dev": true, - "license": "Unlicense" - }, "node_modules/rolldown": { "version": "1.2.18", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", @@ -11764,19 +10682,6 @@ "url": "https://github.com/sponsors/oxc-project" } }, - "node_modules/roughjs": { - "version": "4.6.6", - "resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz", - "integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "hachure-fill": "^0.5.2", - "path-data-parser": "^0.1.0", - "points-on-curve": "^0.2.0", - "points-on-path": "^0.2.1" - } - }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", @@ -11823,13 +10728,6 @@ "svelte": "^5.7.0" } }, - "node_modules/rw": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz", - "integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==", - "dev": true, - "license": "BSD-3-Clause" - }, "node_modules/sade": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", @@ -12273,13 +11171,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/strictdom": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/strictdom/-/strictdom-1.0.1.tgz", - "integrity": "sha512-cEmp9QeXXRmjj/rVp9oyiqcvyocWab/HaoN4+bwFeZ7QzykJD6L3yD4v12K1x0tHpqRqVpJevN3gW7kyM39Bqg==", - "dev": true, - "license": "MIT" - }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -12354,13 +11245,6 @@ "inline-style-parser": "0.2.7" } }, - "node_modules/stylis": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.4.0.tgz", - "integrity": "sha512-5Z9ZpRzfuH6l/UAvCPAPUo3665Nk2wLaZU3x+TLHKVzIz33+sbJqbtrYoC3KD4/uVOr2Zp+L0LySezP9OHV9yA==", - "dev": true, - "license": "MIT" - }, "node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index b7716287ceb5..bc3f0d3315d1 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -110,8 +110,8 @@ "dompurify": "3.4.17", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", - "eslint-plugin-perfectionist": "^5.10.1", - "eslint-plugin-simple-import-sort": "^14.0.0", + "eslint-plugin-perfectionist": "5.13.0", + "eslint-plugin-simple-import-sort": "14.0.0", "eslint-plugin-storybook": "10.6.6", "eslint-plugin-svelte": "3.24.1", "fflate": "0.8.3", @@ -120,9 +120,9 @@ "http-server": "14.1.1", "@ggml-org/llama-brand": "0.1.0", "mdsvex": "0.12.7", - "mermaid": "11.17.2", "mode-watcher": "1.1.0", "pdfjs-dist": "5.4.54", + "pele": "1.13.0", "playwright": "1.56.1", "prettier": "3.8.3", "prettier-plugin-svelte": "4.1.0", diff --git a/ui/apps/chat/scripts/vite-plugin-nerdamer.ts b/ui/apps/chat/scripts/vite-plugin-nerdamer.ts index 84e463c6d764..c1551eb5aca8 100644 --- a/ui/apps/chat/scripts/vite-plugin-nerdamer.ts +++ b/ui/apps/chat/scripts/vite-plugin-nerdamer.ts @@ -10,7 +10,9 @@ const RESOLVED_ID = '\0' + VIRTUAL_ID; /** * Bundle the vendored nerdamer-prime source into a minified IIFE string, - * exposed as the `virtual:nerdamer` module. Flags mirror the upstream + * loaded through the `virtual:nerdamer` module. In the client build it is + * its own file, fetched on first use, so it stays out of the app bundle. + * Flags mirror the upstream * build (esbuild --bundle --minify --format=iife --global-name=nerdamer), * so only human readable source lives in the repo and minification is a * build artifact. Vendored under src/lib/vendors/, upstream snapshot: @@ -41,7 +43,13 @@ export function nerdamerPlugin(): Plugin { bundled = result.outputFiles[0].text; } - return `export default ${JSON.stringify(bundled)};`; + if (this.environment.mode === 'build' && this.environment.name === 'client') { + const ref = this.emitFile({ name: 'nerdamer.js', source: bundled, type: 'asset' }); + + return `export default () => fetch(import.meta.ROLLUP_FILE_URL_${ref}).then((res) => res.text());`; + } + + return `export default async () => ${JSON.stringify(bundled)};`; }, name: 'llamacpp:nerdamer', resolveId(id) { diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index 4c7fd90160a3..cca440844162 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -356,8 +356,22 @@ } } -.mermaidTooltip { - display: none !important; +/* + * Mermaid diagrams are drawn by Pele, which reads its colors from these. They sit on :root + * so the svg also inherits them inside the preview dialog's shadow root, and follow the theme. + */ +:root { + --pele-bg: var(--code-background); + --pele-fg: var(--code-foreground); + --pele-muted: var(--muted-foreground); + --pele-line: var(--muted-foreground); + --pele-surface: var(--background); + --pele-surface-alt: var(--muted); + --pele-border: var(--border); + --pele-accent: var(--primary); + --pele-critical: var(--destructive); + --pele-error: var(--destructive); + --pele-radius: calc(var(--radius) - 4px); } /* diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index 987c5a350cac..d71a8da5d891 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -2,7 +2,6 @@ import { Button } from '@ggml-org/llama-ui/ui/button'; import { SkipForward, Square } from '@lucide/svelte'; import { - ChatFormActionReasoning, ChatFormActionRecord, ChatFormActionsAdd, ChatFormActionSubmit, @@ -149,12 +148,12 @@ {/if} {#if showModelSelector} - - + {/if} diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte index ab3c5ffecba5..0edd8cbcde15 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte @@ -625,7 +625,7 @@ if ((hasRenderedBlocks || hasUnstableBlock) && containerRef) { setupCodeBlockActions(); setupImageErrorHandlers(); - renderMermaidDiagrams(containerRef, mode.current === ColorMode.DARK); + renderMermaidDiagrams(containerRef); renderSvgDiagrams(containerRef); } }); diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css index 49aee0e04c72..49e04bf0c6a2 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css @@ -626,10 +626,24 @@ div.markdown-user-content :global(.table-wrapper) { /* Hide mermaid code text until rendered - prevents flash */ .markdown-content :global(pre.mermaid:not([data-mermaid-rendered])), -.markdown-content :global(pre.mermaid[data-mermaid-rendered]:not(:has(svg))) { +.markdown-content :global(pre.mermaid[data-mermaid-rendered]:not(:has(svg, .mermaid-error))) { display: none; } +/* A diagram Pele can't draw shows why, with the line it stopped at */ +.markdown-content :global(.mermaid-error) { + max-width: 100%; + padding: 1rem; + color: var(--destructive); + font-family: var(--font-mono); + font-size: 0.8125rem; + /* the caret line under the source must line up character by character */ + font-variant-ligatures: none; + text-align: left; + white-space: pre-wrap; + cursor: default; +} + /* Hide svg source until rendered - prevents flash. A rendered-but-unsanitized block (oversized source) keeps its raw text visible as a safe fallback. */ .markdown-content :global(pre.svg-block:not([data-svg-rendered])) { diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts index 4bb7e44b3db9..ec3e35dd9d5f 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-diagrams.ts @@ -7,9 +7,15 @@ import { DIAGRAM_VIEW_RENDERED, DIAGRAM_VIEW_SOURCE, MERMAID_BLOCK_CLASS, + MERMAID_ERROR_CLASS, + MERMAID_ID_ATTR, MERMAID_RENDERED_ATTR, + MERMAID_SCROLL_CONTAINER_CLASS, + MERMAID_SVG_PADDING_X_REM, MERMAID_SYNTAX_ATTR, MERMAID_WRAPPER_CLASS, + PELE_SVG_CLASS, + PELE_THEME_VARIABLES, SVG, TOGGLE_SOURCE_BTN_CLASS } from '#lib/constants/index.ts'; @@ -19,11 +25,37 @@ import { mountSvgShadow } from '#lib/utils/svg-shadow.ts'; export type DiagramAction = { copy: string } | { previewSvg: string }; +// The width a diagram can take in its block: the scroll container's content box, less the +// svg's own horizontal padding. Undefined when the block isn't laid out (detached, hidden). +function diagramWidth(node: HTMLElement): number | undefined { + const scroll = node.closest(`.${MERMAID_SCROLL_CONTAINER_CLASS}`); + + if (!scroll?.clientWidth) return undefined; + + const box = getComputedStyle(scroll); + const rem = parseFloat(getComputedStyle(document.documentElement).fontSize); + const width = + scroll.clientWidth - + parseFloat(box.paddingLeft) - + parseFloat(box.paddingRight) - + MERMAID_SVG_PADDING_X_REM * rem; + + return width > 0 ? width : undefined; +} + +// Pele wraps a node with a `click ... href` directive in a link. Diagrams come from model +// output, so they stay inert, as they were under Mermaid's strict security level: each link +// gives way to its children. The preview dialog and the downloaded file copy this svg. +function unwrapLinks(root: HTMLElement) { + for (const link of root.querySelectorAll('a')) link.replaceWith(...link.childNodes); +} + /** - * Renders the mermaid diagrams in `container` that haven't been rendered yet. - * Marks nodes immediately to prevent duplicate renders during streaming. + * Renders the mermaid diagrams in `container` that haven't been rendered yet, with Pele. + * Marks nodes immediately to prevent duplicate renders during streaming. Colors come + * from the `--pele-*` variables in app.css, so a diagram follows the theme without a redraw. */ -export async function renderMermaidDiagrams(container: HTMLElement, isDark: boolean) { +export async function renderMermaidDiagrams(container: HTMLElement) { const nodes = container.querySelectorAll( `pre.${MERMAID_BLOCK_CLASS}:not([${MERMAID_RENDERED_ATTR}])` ); @@ -34,32 +66,57 @@ export async function renderMermaidDiagrams(container: HTMLElement, isDark: bool // This avoids needing a guard that would block node discovery. nodes.forEach((node) => node.setAttribute(MERMAID_RENDERED_ATTR, BooleanString.TRUE)); - // lazy load the mermaid dependecy only when needed to reduce bundle size. - const { default: mermaid } = await import('mermaid'); - - mermaid.initialize({ - flowchart: { - htmlLabels: true, - useMaxWidth: false - }, - gantt: { - useMaxWidth: false - }, - securityLevel: 'strict', - sequence: { - useMaxWidth: false - }, - startOnLoad: false, - theme: isDark ? 'dark' : 'default' - }); + const { render } = await import('pele'); + + // Pele measures labels with the font it is given, so wait until the page font is in + await document.fonts?.ready; + + for (const node of nodes) { + const source = node.getAttribute(MERMAID_SYNTAX_ATTR) ?? node.textContent ?? ''; + const id = node.getAttribute(MERMAID_ID_ATTR); + + try { + const { svg } = render(source, { + fontFamily: getComputedStyle(node).fontFamily, + idPrefix: id ? id.replace(/[^\w-]/g, '_') : undefined, + // narrow blocks (phones) may turn a left-to-right diagram top-to-bottom + maxWidth: diagramWidth(node) + }); + + node.innerHTML = svg; + unwrapLinks(node); + } catch (error) { + // the message quotes the diagram source, so it goes in as text + const message = document.createElement('div'); - try { - await mermaid.run({ nodes: Array.from(nodes) as unknown as NodeListOf }); - } catch (error) { - console.error('Failed to render mermaid diagram:', error); + message.className = MERMAID_ERROR_CLASS; + message.textContent = error instanceof Error ? error.message : String(error); + node.replaceChildren(message); + } } } +/** + * A Pele diagram takes its colors from the page's `--pele-*` variables. Writes their current + * values into the svg, so a downloaded file keeps the colors it had on screen. Any other svg + * comes back unchanged. + */ +export function withThemeColors(svgHtml: string): string { + const svg = new DOMParser().parseFromString(svgHtml, 'image/svg+xml').documentElement; + + if (!(svg instanceof SVGElement) || !svg.classList.contains(PELE_SVG_CLASS)) return svgHtml; + + const theme = getComputedStyle(document.documentElement); + + for (const name of PELE_THEME_VARIABLES) { + const value = theme.getPropertyValue(name).trim(); + + if (value) svg.style.setProperty(name, value); + } + + return new XMLSerializer().serializeToString(svg); +} + /** * Renders the svg diagrams in `container` that haven't been rendered yet. * Sanitizes the source before injecting and marks each node so it renders once. diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts index d7c4feac6b86..aed4b93e50d0 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-processor.ts @@ -13,6 +13,7 @@ import { rehypeEnhanceMermaidBlocks } from './plugins/rehype/enhance-mermaid-blo import { rehypeEnhanceSvgBlocks } from './plugins/rehype/enhance-svg-blocks'; import { rehypeEnhanceTables } from './plugins/rehype/enhance-tables'; import { rehypeFileBadge } from './plugins/rehype/file-badge'; +import { rehypeLazyKatex } from './plugins/rehype/lazy-katex'; import { rehypeMermaidPre } from './plugins/rehype/mermaid-pre'; import { rehypeRtlSupport } from './plugins/rehype/rehype-rtl-support'; import { rehypeResolveAttachmentImages } from './plugins/rehype/resolve-attachment-images'; @@ -25,7 +26,6 @@ import type { Root as HastRoot } from 'hast'; import { all as lowlightAll } from 'lowlight'; import type { Root as MdastRoot } from 'mdast'; import rehypeHighlight from 'rehype-highlight'; -import rehypeKatex from 'rehype-katex'; import rehypeStringify from 'rehype-stringify'; import { remark } from 'remark'; import remarkBreaks from 'remark-breaks'; @@ -71,7 +71,7 @@ function buildPipeline({ proc = proc.use(remarkRehype, allowHtml ? { allowDangerousHtml: true } : undefined); if (!disableMath) { - proc = proc.use(rehypeKatex); // Render math using KaTeX + proc = proc.use(rehypeLazyKatex); // Render math using KaTeX, loaded on the first message with math } const pipeline = proc diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-katex.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-katex.ts new file mode 100644 index 000000000000..e94a36bf4a6f --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/plugins/rehype/lazy-katex.ts @@ -0,0 +1,56 @@ +/** + * Rehype plugin that renders math with rehype-katex, loading KaTeX only when a message has math. + * + * remark-math marks math as elements with a `language-math`, `math-inline` or `math-display` + * class; a tree without one is left alone, so a chat without math never downloads KaTeX. + */ + +import type { Element, Root } from 'hast'; +import type { Plugin, Transformer } from 'unified'; +import { visit } from 'unist-util-visit'; + +const MATH_CLASSES = ['language-math', 'math-inline', 'math-display']; + +let katexLoading: Promise> | undefined; +let katexTransformer: Transformer | undefined; + +function hasMath(tree: Root): boolean { + let found = false; + + visit(tree, 'element', (node: Element) => { + const className = node.properties?.className; + + if (Array.isArray(className) && className.some((c) => MATH_CLASSES.includes(String(c)))) { + found = true; + + return false; + } + }); + + return found; +} + +// synchronous when there is no math or KaTeX has loaded, so only the first message with math +// waits for it, and every other one renders in the same pass as before +export const rehypeLazyKatex: Plugin<[], Root> = () => { + return (tree, file) => { + if (!hasMath(tree)) return; + + // rehype-katex changes the tree in place + if (katexTransformer) { + katexTransformer(tree, file, () => {}); + + return; + } + + katexLoading ??= import('rehype-katex').then(({ default: rehypeKatex }) => { + katexTransformer = rehypeKatex() as Transformer; + + return katexTransformer; + }); + + return katexLoading.then((transform) => { + transform(tree, file, () => {}); + }); + }; +}; diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-block-widget.ts b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-block-widget.ts index 6deae1d3c6a8..66bdd3a83e3e 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-block-widget.ts +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/markdown-block-widget.ts @@ -12,14 +12,12 @@ import { import { getMarkdownProcessor } from '#lib/components/app/content/MarkdownContent/markdown-processor.ts'; import { getCodeInfoFromTarget } from '#lib/components/app/content/MarkdownContent/markdown-utils.ts'; import { MERMAID_BLOCK_CLASS } from '#lib/constants/index.ts'; -import { ColorMode } from '#lib/enums/index.ts'; import { copyCodeToClipboard, copyToClipboard, preprocessLaTeX, splitGluedClosingCodeFences } from '#lib/utils/index.ts'; -import { mode } from 'mode-watcher'; export interface MarkdownBlockWidgetOptions { onPreviewCode?: (code: string, language: string) => void; @@ -311,9 +309,7 @@ export class MarkdownBlockWidget extends WidgetType { // mermaid draws asynchronously and changes the block's height when done if (dom.querySelector(`pre.${MERMAID_BLOCK_CLASS}`)) { - void renderMermaidDiagrams(dom, mode.current === ColorMode.DARK).then(() => - this.measure(dom, view, key) - ); + void renderMermaidDiagrams(dom).then(() => this.measure(dom, view, key)); } } } diff --git a/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte b/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte index d981f67d1ed9..9348025817d7 100644 --- a/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MermaidPreview.svelte @@ -1,7 +1,16 @@ + + +
-
zoomBy(DIAGRAM_ZOOM_FACTOR)} + onZoomOut={() => zoomBy(1 / DIAGRAM_ZOOM_FACTOR)} + scale={view.scale} {svgHtml} />
diff --git a/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte index 5c0e03021bcb..18f96c5294cc 100644 --- a/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MermaidPreviewControls.svelte @@ -3,6 +3,7 @@ import RotateCcwIcon from '@lucide/svelte/icons/rotate-ccw'; import ZoomInIcon from '@lucide/svelte/icons/zoom-in'; import ZoomOutIcon from '@lucide/svelte/icons/zoom-out'; + import { withThemeColors } from '#lib/components/app/content/MarkdownContent/markdown-diagrams.ts'; import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; interface Props { @@ -18,7 +19,7 @@ function downloadSvg() { if (!svgHtml) return; - const blob = new Blob([svgHtml], { type: 'image/svg+xml' }); + const blob = new Blob([withThemeColors(svgHtml)], { type: 'image/svg+xml' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); @@ -30,7 +31,7 @@
+ {/each} +
+ +
+{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte new file mode 100644 index 000000000000..fabc65c5425c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/ModelsSelectorReasoningBadge.svelte @@ -0,0 +1,34 @@ + + + +{#if reasoning.isOff} + + +{:else if reasoning.currentEffort !== ReasoningEffort.DEFAULT} + + + + Reasoning {REASONING_EFFORT_LABELS[reasoning.currentEffort]} + +{/if} diff --git a/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte index 4bfccbc91d7e..bc652d811dba 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/DropdownMenuSearchable.svelte @@ -18,10 +18,18 @@ searchClass?: string; children: Snippet; /** - * Optional sticky footer: it sticks to the bottom of DropdownMenu.Content's own - * scrollport, which must stay the scroll container (overflow-y-auto + max-height). + * Optional footer. By default it sticks to the bottom of the parent's scrollport + * (overflow-y-auto + max-height), see `scrollport`. */ footer?: Snippet; + /** + * Scroll the header and the list in a box of their own, with the footer under it + * instead of sticking. For a parent that scales as it opens (a dropdown's zoom-in): + * WebKit pins a bottom-sticky element against the scaled box, so the footer would + * ride up the list until the animation ends. The parent is then a flex column that + * does not scroll itself (flex flex-col overflow-hidden + max-height). + */ + scrollport?: boolean; } let { @@ -34,6 +42,7 @@ onSearchChange, onSearchKeyDown, placeholder = 'Search...', + scrollport = false, searchClass = '', searchValue = $bindable('') }: Props = $props(); @@ -42,32 +51,42 @@ let stickyHeaderHeight = $state(0); -
- -
+{#snippet body()} +
+ +
+ +
+ +
+ {@render children()} -
- -
- {@render children()} + {#if isEmpty} +
{emptyMessage}
+ {/if} +
+
+{/snippet} - {#if isEmpty} -
{emptyMessage}
- {/if} +{#if scrollport} +
+ {@render body()}
-
+{:else} + {@render body()} +{/if} {#if footer} -
+
{ if (!harnessCache[key]) { if (enabled) { - const { default: nerdamerJs } = await import('virtual:nerdamer'); + const { default: loadNerdamer } = await import('virtual:nerdamer'); - harnessCache[key] = buildSandboxHarness(nerdamerJs); + harnessCache[key] = buildSandboxHarness(await loadNerdamer()); } else { harnessCache[key] = buildSandboxHarness(''); } diff --git a/ui/apps/chat/src/lib/utils/diagram-viewport.ts b/ui/apps/chat/src/lib/utils/diagram-viewport.ts new file mode 100644 index 000000000000..a4f2fd200ec5 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/diagram-viewport.ts @@ -0,0 +1,75 @@ +// Pan and zoom for the diagram preview. The diagram sits at the top left of its viewport +// with `transform-origin: 0 0`, so a point (x, y) of the diagram shows on screen at +// (x * scale + x0, y * scale + y0), and every zoom keeps one screen point fixed. + +export interface DiagramView { + scale: number; + x: number; + y: number; +} + +export interface Size { + width: number; + height: number; +} + +export const DIAGRAM_MIN_SCALE = 0.1; +export const DIAGRAM_MAX_SCALE = 10; +// a fitted diagram may grow, but not so much that a two-node flowchart fills the screen +export const DIAGRAM_MAX_FIT_SCALE = 2; +// one click of a zoom button, or one key press +export const DIAGRAM_ZOOM_FACTOR = 1.25; + +function clampScale(scale: number): number { + return Math.min(Math.max(scale, DIAGRAM_MIN_SCALE), DIAGRAM_MAX_SCALE); +} + +/** + * Scales the view by `factor` around the viewport point (`px`, `py`): what is under that + * point stays there. The scale is clamped, and the point stays fixed at the clamped scale. + */ +export function zoomAt(view: DiagramView, factor: number, px: number, py: number): DiagramView { + const scale = clampScale(view.scale * factor); + const ratio = scale / view.scale; + + return { scale, x: px - (px - view.x) * ratio, y: py - (py - view.y) * ratio }; +} + +/** Scales the view by `factor` around the middle of the viewport. */ +export function zoomAtCenter(view: DiagramView, factor: number, viewport: Size): DiagramView { + return zoomAt(view, factor, viewport.width / 2, viewport.height / 2); +} + +/** + * The view that shows the whole diagram centered in the viewport, less `padding` on every + * side. A small diagram grows up to DIAGRAM_MAX_FIT_SCALE. + */ +export function fitView(content: Size, viewport: Size, padding = 0): DiagramView { + if (content.width <= 0 || content.height <= 0) return { scale: 1, x: 0, y: 0 }; + + const scale = clampScale( + Math.min( + (viewport.width - 2 * padding) / content.width, + (viewport.height - 2 * padding) / content.height, + DIAGRAM_MAX_FIT_SCALE + ) + ); + + return { + scale, + x: (viewport.width - content.width * scale) / 2, + y: (viewport.height - content.height * scale) / 2 + }; +} + +/** + * How much a wheel event zooms by. A trackpad pinch arrives as a wheel event with ctrlKey + * and small deltas, so it is scaled up to feel like the fingers; line and page deltas + * (mouse wheels on some systems) are turned into pixels first. + */ +export function wheelZoomFactor(event: Pick) { + const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 400 : 1; + const speed = event.ctrlKey ? 0.01 : 0.002; + + return Math.exp(-event.deltaY * unit * speed); +} diff --git a/ui/apps/chat/src/lib/utils/mcp.ts b/ui/apps/chat/src/lib/utils/mcp.ts index 75ec000c2aa3..232099e2b6ee 100644 --- a/ui/apps/chat/src/lib/utils/mcp.ts +++ b/ui/apps/chat/src/lib/utils/mcp.ts @@ -1,14 +1,12 @@ import { extractRootDomain } from './url'; -import { - AlertTriangle, - Code, - Database, - File, - FileText, - Image, - Info, - XCircle -} from '@lucide/svelte'; +import AlertTriangle from '@lucide/svelte/icons/alert-triangle'; +import Code from '@lucide/svelte/icons/code'; +import Database from '@lucide/svelte/icons/database'; +import File from '@lucide/svelte/icons/file'; +import FileText from '@lucide/svelte/icons/file-text'; +import Image from '@lucide/svelte/icons/image'; +import Info from '@lucide/svelte/icons/info'; +import XCircle from '@lucide/svelte/icons/x-circle'; import { CODE_FILE_EXTENSION_REGEX, DEFAULT_RESOURCE_FILENAME, diff --git a/ui/apps/chat/src/lib/utils/pdf-processing.ts b/ui/apps/chat/src/lib/utils/pdf-processing.ts index a67a117c7ea2..ca5074db180d 100644 --- a/ui/apps/chat/src/lib/utils/pdf-processing.ts +++ b/ui/apps/chat/src/lib/utils/pdf-processing.ts @@ -5,23 +5,23 @@ import { MimeTypeApplication, MimeTypeImage } from '#lib/enums/index.ts'; import { browser } from '$app/env'; -import * as pdfjs from 'pdfjs-dist'; +import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url'; type TextContent = { items: Array<{ str: string }>; }; -if (browser) { - // Import worker as text and create blob URL for inline bundling - import('pdfjs-dist/build/pdf.worker.min.mjs?raw') - .then((workerModule) => { - const workerBlob = new Blob([workerModule.default], { type: 'application/javascript' }); - - pdfjs.GlobalWorkerOptions.workerSrc = URL.createObjectURL(workerBlob); - }) - .catch(() => { - console.warn('Failed to load PDF.js worker, PDF processing may not work'); - }); +let pdfjsModule: Promise | undefined; + +// pdf.js and its worker are files of their own, so the app loads them only when it opens a PDF +function loadPdfjs(): Promise { + pdfjsModule ??= import('pdfjs-dist').then((pdfjs) => { + pdfjs.GlobalWorkerOptions.workerSrc = pdfWorkerUrl; + + return pdfjs; + }); + + return pdfjsModule; } /** @@ -58,7 +58,7 @@ export async function convertPDFToText(file: File): Promise { } try { - const buffer = await getFileAsBuffer(file); + const [pdfjs, buffer] = await Promise.all([loadPdfjs(), getFileAsBuffer(file)]); const pdf = await pdfjs.getDocument({ data: buffer }).promise; const numPages = pdf.numPages; const textContentPromises: Promise[] = []; @@ -96,7 +96,7 @@ export async function convertPDFToImage(file: File, scale: number = 1.5): Promis } try { - const buffer = await getFileAsBuffer(file); + const [pdfjs, buffer] = await Promise.all([loadPdfjs(), getFileAsBuffer(file)]); const doc = await pdfjs.getDocument({ data: buffer }).promise; const pages: Promise[] = []; diff --git a/ui/apps/chat/src/virtual-nerdamer.d.ts b/ui/apps/chat/src/virtual-nerdamer.d.ts index 433fb2b3bd20..19fcd36f6dc7 100644 --- a/ui/apps/chat/src/virtual-nerdamer.d.ts +++ b/ui/apps/chat/src/virtual-nerdamer.d.ts @@ -1,4 +1,4 @@ declare module 'virtual:nerdamer' { - const code: string; - export default code; + const loadNerdamer: () => Promise; + export default loadNerdamer; } diff --git a/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts b/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts new file mode 100644 index 000000000000..63e941306b97 --- /dev/null +++ b/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts @@ -0,0 +1,48 @@ +// pdf.js loads on first use, with its worker as a file of its own: extracting a PDF's text +// and drawing its pages go through that load. +import { convertPDFToImage, convertPDFToText } from '#lib/utils/pdf-processing.ts'; +import { describe, expect, it } from 'vitest'; + +/** A one-page PDF that shows `text`, with a correct cross-reference table. */ +function pdfWithText(text: string): File { + const stream = `BT /F1 24 Tf 72 720 Td (${text}) Tj ET`; + const objects = [ + '<< /Type /Catalog /Pages 2 0 R >>', + '<< /Type /Pages /Kids [3 0 R] /Count 1 >>', + '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>', + `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, + '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>' + ]; + + let body = '%PDF-1.4\n'; + + const offsets: number[] = []; + + objects.forEach((object, i) => { + offsets.push(body.length); + body += `${i + 1} 0 obj\n${object}\nendobj\n`; + }); + + const xref = body.length; + const entries = offsets.map((offset) => `${String(offset).padStart(10, '0')} 00000 n \n`); + + body += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${entries.join('')}`; + body += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`; + + return new File([body], 'hello.pdf', { type: 'application/pdf' }); +} + +describe('pdf-processing', () => { + it('extracts the text of a PDF', async () => { + const text = await convertPDFToText(pdfWithText('Hello from a PDF')); + + expect(text).toContain('Hello from a PDF'); + }); + + it('draws each page of a PDF as a PNG', async () => { + const pages = await convertPDFToImage(pdfWithText('Page one')); + + expect(pages).toHaveLength(1); + expect(pages[0]).toMatch(/^data:image\/png;base64,/); + }); +}); diff --git a/ui/apps/chat/tests/e2e/pwa.e2e.ts b/ui/apps/chat/tests/e2e/pwa.e2e.ts index 1b7636886d92..061cf5e1fd38 100644 --- a/ui/apps/chat/tests/e2e/pwa.e2e.ts +++ b/ui/apps/chat/tests/e2e/pwa.e2e.ts @@ -40,9 +40,10 @@ test.describe('PWA Service Worker', () => { const swResponse = await page.request.get(swActive!); const swContent = await swResponse.text(); - // Precache contains SvelteKit content-hashed bundle paths - expect(swContent).toMatch(/["'`]_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js["'`]/); - expect(swContent).toMatch(/["'`]_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css["'`]/); + // Precache contains SvelteKit's content-hashed entry points and CSS (a split build) + expect(swContent).toMatch(/["'`]_app\/immutable\/entry\/start\.[a-zA-Z0-9_-]+\.js["'`]/); + expect(swContent).toMatch(/["'`]_app\/immutable\/entry\/app\.[a-zA-Z0-9_-]+\.js["'`]/); + expect(swContent).toMatch(/["'`]_app\/immutable\/assets\/[a-zA-Z0-9_.-]+\.css["'`]/); expect(swContent).toMatch(/["'`]manifest\.webmanifest["'`]/); expect(swContent).toMatch(/["'`]_app\/version\.json["'`]/); }); @@ -120,16 +121,17 @@ test.describe('PWA Service Worker', () => { expect(manifest.icons.length).toBeGreaterThan(0); }); - test('index.html contains content-hashed bundle references', async ({ page }) => { + test('index.html contains content-hashed entry references', async ({ page }) => { const response = await page.request.get('/'); expect(response.ok()).toBeTruthy(); const html = await response.text(); - // SvelteKit outputs content-hashed bundle names in _app/immutable/ - expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); - expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/); - expect(html).toMatch(/import\("(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"\)/); + // a split build: SvelteKit's content-hashed entry points in _app/immutable/entry/ + expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/entry\/start\.[a-zA-Z0-9_-]+\.js"/); + expect(html).toMatch(/href="(\.\/|\/)_app\/immutable\/assets\/[a-zA-Z0-9_.-]+\.css"/); + expect(html).toMatch(/import\("(\.\/|\/)_app\/immutable\/entry\/start\.[a-zA-Z0-9_-]+\.js"\)/); + expect(html).toMatch(/import\("(\.\/|\/)_app\/immutable\/entry\/app\.[a-zA-Z0-9_-]+\.js"\)/); }); }); diff --git a/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte b/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte index a569a0643548..5cbd5697c88c 100644 --- a/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte +++ b/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte @@ -1,7 +1,9 @@ + + { + const viewport = await waitFor(() => { + const el = canvasElement.querySelector('.mermaid-preview'); + + expect(el?.querySelector('.mermaid-preview-diagram')).toBeVisible(); + + return el!; + }); + const rect = viewport.getBoundingClientRect(); + const middle = { x: rect.width / 2, y: rect.height / 2 }; + const fitted = readView(canvasElement); + // the wheel zooms around the pointer + const pointer = { x: rect.width * 0.7, y: rect.height * 0.35 }; + const underPointer = pointUnder(fitted, pointer.x, pointer.y); + + viewport.dispatchEvent( + new WheelEvent('wheel', { + bubbles: true, + cancelable: true, + clientX: rect.left + pointer.x, + clientY: rect.top + pointer.y, + deltaY: -200 + }) + ); + await waitFor(() => expect(readView(canvasElement).scale).toBeGreaterThan(fitted.scale)); + await expect(screenOf(readView(canvasElement), underPointer).x).toBeCloseTo(pointer.x, 0); + await expect(screenOf(readView(canvasElement), underPointer).y).toBeCloseTo(pointer.y, 0); + + // after a pan, the zoom buttons zoom around the middle of the viewport + const zoomed = readView(canvasElement); + const drag = (type: string, x: number, y: number) => + viewport.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + button: 0, + clientX: rect.left + x, + clientY: rect.top + y, + pointerId: 1 + }) + ); + + drag('pointerdown', 100, 100); + drag('pointermove', 260, 180); + drag('pointerup', 260, 180); + await waitFor(() => expect(readView(canvasElement).x).toBeCloseTo(zoomed.x + 160, 0)); + + const panned = readView(canvasElement); + const underMiddle = pointUnder(panned, middle.x, middle.y); + + await userEvent.click(canvasElement.querySelector('[aria-label="Zoom out"]')!); + await waitFor(() => expect(readView(canvasElement).scale).toBeLessThan(panned.scale)); + await expect(screenOf(readView(canvasElement), underMiddle).x).toBeCloseTo(middle.x, 0); + await expect(screenOf(readView(canvasElement), underMiddle).y).toBeCloseTo(middle.y, 0); + + // reset fits the diagram again + await userEvent.click(canvasElement.querySelector('[aria-label="Reset view"]')!); + await waitFor(() => expect(readView(canvasElement)).toEqual(fitted)); + await expect(canvasElement.querySelector('.mermaid-preview-zoom-label')?.textContent).toBe( + `${Math.round(fitted.scale * 100)}%` + ); + }} +> +
+ +
+
+ + { + // fitting shrinks a diagram wider than the screen so all of it shows + await waitFor(() => expect(readView(canvasElement).scale).toBeLessThan(1)); + }} +> +
+ +
+
+ + +
+ +
+
+ + +
+ +
+
diff --git a/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte b/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte new file mode 100644 index 000000000000..a49b14304698 --- /dev/null +++ b/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte @@ -0,0 +1,41 @@ + + + + + { + const content = await waitFor(() => { + const el = document.querySelector('[data-slot="dialog-content"]'); + + expect(el?.querySelector('.mermaid-preview')).not.toBeNull(); + + return el!; + }); + const rect = content.getBoundingClientRect(); + + await expect(rect.left).toBe(0); + await expect(rect.top).toBe(0); + await expect(rect.width).toBeCloseTo(window.innerWidth, 0); + await expect(rect.height).toBeCloseTo(window.innerHeight, 0); + }} +> + + diff --git a/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts b/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts new file mode 100644 index 000000000000..bb1e2f39f84b --- /dev/null +++ b/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts @@ -0,0 +1,57 @@ +// Mermaid blocks of several diagram types, and one that can't be drawn. The flowchart's +// click directives must leave it inert. +const fence = '```'; + +export const MERMAID_DIAGRAMS_MD = String.raw` +How a request reaches the model: + +${fence}mermaid +flowchart LR + U[Browser] -->|POST /v1/chat/completions| S(llama-server) + S --> Q{Slot free?} + Q -->|yes| D[Decode] + Q -->|no| W[Queue] + W --> D + D -->|SSE tokens| U + click S href "https://github.com/ggml-org/llama.cpp" "llama.cpp on GitHub" _blank + click D call alert(1) +${fence} + +The same exchange over time: + +${fence}mermaid +sequenceDiagram + participant C as Llama Chat + participant S as llama-server + C->>S: POST /v1/chat/completions + S-->>C: data: {"choices":[...]} + S-->>C: data: [DONE] + Note over C,S: the stream ends with DONE +${fence} + +A slot's life: + +${fence}mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Processing: prompt + Processing --> Generating: prompt evaluated + Generating --> Idle: stop or limit +${fence} + +Where the time goes: + +${fence}mermaid +pie title Time per request + "Prompt processing" : 35 + "Token generation" : 60 + "Sampling" : 5 +${fence} + +A diagram with a mistake in it: + +${fence}mermaid +flowchart LR + A --> +${fence} +`; diff --git a/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts b/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts new file mode 100644 index 000000000000..136d28d69cff --- /dev/null +++ b/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts @@ -0,0 +1,30 @@ +// Diagrams drawn with Pele, as renderMermaidDiagrams() draws them, for the preview stories +import { render } from 'pele'; + +export const FLOWCHART_SVG = render(`flowchart LR + U[Browser] -->|POST /v1/chat/completions| S(llama-server) + S --> Q{Slot free?} + Q -->|yes| D[Decode] + Q -->|no| W[Queue] + W --> D + D -->|SSE tokens| U`).svg; + +// wider than any screen, so fitting it shrinks it +export const PIPELINE_SVG = render(`flowchart LR + A[Download GGUF] --> B[Read metadata] --> C[Load tensors] --> D[Build graph] + D --> E[Tokenize prompt] --> F[Prompt processing] --> G[Sample token] + G --> H[Detokenize] --> I[Stream to client] --> J{Stop?} + J -->|no| G + J -->|yes| K[Free slot]`).svg; + +// small enough that fitting it grows it, up to the fit cap +export const SMALL_SVG = render(`flowchart TD + A[Prompt] --> B[Answer]`).svg; + +export const SEQUENCE_SVG = render(`sequenceDiagram + participant C as Llama Chat + participant S as llama-server + C->>S: POST /v1/chat/completions + S-->>C: data: {"choices":[...]} + S-->>C: data: [DONE] + Note over C,S: the stream ends with DONE`).svg; diff --git a/ui/apps/chat/tests/unit/diagram-viewport.test.ts b/ui/apps/chat/tests/unit/diagram-viewport.test.ts new file mode 100644 index 000000000000..cace3f1fee8f --- /dev/null +++ b/ui/apps/chat/tests/unit/diagram-viewport.test.ts @@ -0,0 +1,111 @@ +import { + DIAGRAM_MAX_FIT_SCALE, + DIAGRAM_MAX_SCALE, + DIAGRAM_MIN_SCALE, + type DiagramView, + fitView, + wheelZoomFactor, + zoomAt, + zoomAtCenter +} from '#lib/utils/diagram-viewport.ts'; +import { describe, expect, it } from 'vitest'; + +// where the diagram point (x, y) shows on screen +function onScreen(view: DiagramView, x: number, y: number) { + return { x: x * view.scale + view.x, y: y * view.scale + view.y }; +} + +// the diagram point under the screen point (x, y) +function underScreen(view: DiagramView, x: number, y: number) { + return { x: (x - view.x) / view.scale, y: (y - view.y) / view.scale }; +} + +describe('zoomAt', () => { + it('keeps the diagram point under the zoom point in place', () => { + const view = { scale: 1.5, x: -120, y: 40 }; + const under = underScreen(view, 300, 200); + const zoomed = zoomAt(view, 2, 300, 200); + + expect(zoomed.scale).toBe(3); + expect(onScreen(zoomed, under.x, under.y).x).toBeCloseTo(300); + expect(onScreen(zoomed, under.x, under.y).y).toBeCloseTo(200); + }); + + it('clamps the scale and still keeps the point in place', () => { + const view = { scale: 8, x: 10, y: 10 }; + const under = underScreen(view, 50, 60); + const zoomed = zoomAt(view, 4, 50, 60); + + expect(zoomed.scale).toBe(DIAGRAM_MAX_SCALE); + expect(onScreen(zoomed, under.x, under.y).x).toBeCloseTo(50); + expect(zoomAt({ scale: 0.2, x: 0, y: 0 }, 0.1, 0, 0).scale).toBe(DIAGRAM_MIN_SCALE); + }); +}); + +describe('zoomAtCenter', () => { + it('zooms around the middle of the viewport after a pan, not the diagram origin', () => { + const viewport = { height: 600, width: 800 }; + // zoomed in and panned away from where the diagram started + const panned = { scale: 2, x: -500, y: -300 }; + const under = underScreen(panned, 400, 300); + const out = zoomAtCenter(panned, 0.5, viewport); + + expect(out.scale).toBe(1); + expect(onScreen(out, under.x, under.y).x).toBeCloseTo(400); + expect(onScreen(out, under.x, under.y).y).toBeCloseTo(300); + }); + + it('zooming in and out again returns to the same view', () => { + const viewport = { height: 600, width: 800 }; + const view = { scale: 1.3, x: 25, y: -70 }; + const back = zoomAtCenter(zoomAtCenter(view, 1.25, viewport), 1 / 1.25, viewport); + + expect(back.scale).toBeCloseTo(view.scale); + expect(back.x).toBeCloseTo(view.x); + expect(back.y).toBeCloseTo(view.y); + }); +}); + +describe('fitView', () => { + it('shrinks a large diagram to fit and centers it', () => { + const view = fitView({ height: 500, width: 2000 }, { height: 800, width: 1000 }, 50); + + expect(view.scale).toBeCloseTo(0.45); + expect(view.x).toBeCloseTo(50); + expect(view.y).toBeCloseTo((800 - 500 * 0.45) / 2); + }); + + it('grows a small diagram no more than the fit cap', () => { + expect(fitView({ height: 50, width: 100 }, { height: 800, width: 1000 }).scale).toBe( + DIAGRAM_MAX_FIT_SCALE + ); + }); + + it('leaves an unmeasured diagram at its own size', () => { + expect(fitView({ height: 0, width: 0 }, { height: 800, width: 1000 })).toEqual({ + scale: 1, + x: 0, + y: 0 + }); + }); +}); + +describe('wheelZoomFactor', () => { + it('zooms in on a wheel up and out on a wheel down', () => { + expect(wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: -100 })).toBeGreaterThan(1); + expect(wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: 100 })).toBeLessThan(1); + }); + + it('a wheel step up and back down cancel out', () => { + const up = wheelZoomFactor({ ctrlKey: false, deltaMode: 1, deltaY: -3 }); + const down = wheelZoomFactor({ ctrlKey: false, deltaMode: 1, deltaY: 3 }); + + expect(up * down).toBeCloseTo(1); + }); + + it('a trackpad pinch zooms faster per pixel than a wheel', () => { + expect(wheelZoomFactor({ ctrlKey: true, deltaMode: 0, deltaY: -10 })).toBeGreaterThan( + wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: -10 }) + ); + }); +}); diff --git a/ui/apps/chat/tests/unit/lazy-katex.test.ts b/ui/apps/chat/tests/unit/lazy-katex.test.ts new file mode 100644 index 000000000000..0cfc57eb0fe7 --- /dev/null +++ b/ui/apps/chat/tests/unit/lazy-katex.test.ts @@ -0,0 +1,32 @@ +import { rehypeLazyKatex } from '#lib/components/app/content/MarkdownContent/plugins/rehype/lazy-katex.ts'; +import type { Root } from 'hast'; +import rehypeStringify from 'rehype-stringify'; +import { remark } from 'remark'; +import remarkMath from 'remark-math'; +import remarkRehype from 'remark-rehype'; +import { describe, expect, it } from 'vitest'; + +const processor = remark() + .use(remarkMath) + .use(remarkRehype) + .use(rehypeLazyKatex) + .use(rehypeStringify); + +async function render(markdown: string): Promise { + return processor.stringify((await processor.run(processor.parse(markdown))) as Root); +} + +describe('rehypeLazyKatex', () => { + it('renders inline and display math with KaTeX', async () => { + const html = await render('Area $\\pi r^2$\n\n$$\nE = mc^2\n$$'); + + expect(html.match(/class="katex"/g)).toHaveLength(2); + expect(html).toContain('katex-display'); + }); + + it('leaves a message without math as it is, in the same pass', () => { + const tree = processor.runSync(processor.parse('Just *text* and `code`')) as Root; + + expect(processor.stringify(tree)).toBe('

Just text and code

'); + }); +}); diff --git a/ui/apps/chat/tests/unit/pwa.spec.ts b/ui/apps/chat/tests/unit/pwa.spec.ts index a8f147df5bfd..ef655a28a234 100644 --- a/ui/apps/chat/tests/unit/pwa.spec.ts +++ b/ui/apps/chat/tests/unit/pwa.spec.ts @@ -38,24 +38,23 @@ describe('PWA Build Output', () => { ).toBeTruthy(); }); - it('SvelteKit bundle.js exists in _app/immutable/', () => { - // SvelteKit generates hashed bundle names in _app/immutable/ - const appDir = resolve(DIST_DIR, '_app', 'immutable'); + it('SvelteKit entry start.js and app.js exist in _app/immutable/entry/', () => { + // a split build: hashed entry points in _app/immutable/entry/, the rest in chunks/ and nodes/ + const entryDir = resolve(DIST_DIR, '_app', 'immutable', 'entry'); - expect(existsSync(appDir), '_app/immutable/ not found').toBeTruthy(); - const files = readdirSync(appDir).filter((f) => f.startsWith('bundle.') && f.endsWith('.js')); + expect(existsSync(entryDir), '_app/immutable/entry/ not found').toBeTruthy(); + const files = readdirSync(entryDir); - expect(files.length).toBeGreaterThan(0); + expect(files.some((f) => /^start\.[a-zA-Z0-9_-]+\.js$/.test(f))).toBe(true); + expect(files.some((f) => /^app\.[a-zA-Z0-9_-]+\.js$/.test(f))).toBe(true); }); - it('SvelteKit bundle.css exists in _app/immutable/assets/', () => { - // SvelteKit generates hashed CSS bundles in _app/immutable/assets/ + it('SvelteKit CSS exists in _app/immutable/assets/', () => { + // SvelteKit generates hashed CSS files in _app/immutable/assets/ const cssDir = resolve(DIST_DIR, '_app', 'immutable', 'assets'); expect(existsSync(cssDir), '_app/immutable/assets/ not found').toBeTruthy(); - const files = readdirSync(cssDir).filter( - (f) => f.startsWith('bundle.') && f.endsWith('.css') - ); + const files = readdirSync(cssDir).filter((f) => f.endsWith('.css')); expect(files.length).toBeGreaterThan(0); }); @@ -81,12 +80,15 @@ describe('PWA Build Output', () => { }); describe('Service worker content', () => { - it('precache contains SvelteKit bundle.js with content hash', () => { - expect(swContent).toMatch(/["'`]_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js["'`]/); - }); + it('precache contains every file in _app/immutable/, so lazily loaded chunks work offline', () => { + const immutableDir = resolve(DIST_DIR, '_app', 'immutable'); + const files = readdirSync(immutableDir, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => resolve(entry.parentPath, entry.name).slice(resolve(DIST_DIR).length + 1)); + + expect(files.length).toBeGreaterThan(0); - it('precache contains SvelteKit bundle.css with content hash', () => { - expect(swContent).toMatch(/["'`]_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css["'`]/); + for (const file of files) expect(swContent).toContain(file); }); it('precache contains the app shell, _app/version.json and manifest.webmanifest', () => { @@ -119,23 +121,27 @@ describe('PWA Build Output', () => { }); describe('index.html content', () => { - it('has modulepreload link for SvelteKit bundle with content hash', () => { + it('has modulepreload link for the SvelteKit entry with content hash', () => { expect(indexContent).toBeTruthy(); - // SvelteKit generates hashed bundle names in _app/immutable/ - expect(indexContent).toMatch(/href="(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"/); + expect(indexContent).toMatch( + /href="(\.\/|\/)_app\/immutable\/entry\/start\.[a-zA-Z0-9_-]+\.js"/ + ); }); - it('has stylesheet link for SvelteKit bundle.css with content hash', () => { + it('has stylesheet link for SvelteKit CSS with content hash', () => { expect(indexContent).toBeTruthy(); expect(indexContent).toMatch( - /href="(\.\/|\/)_app\/immutable\/assets\/bundle\.[a-zA-Z0-9_-]+\.css"/ + /href="(\.\/|\/)_app\/immutable\/assets\/[a-zA-Z0-9_.-]+\.[a-zA-Z0-9_-]+\.css"/ ); }); - it('has dynamic import for SvelteKit bundle with content hash', () => { + it('has dynamic imports for the SvelteKit entry with content hash', () => { expect(indexContent).toBeTruthy(); expect(indexContent).toMatch( - /import\("(\.\/|\/)_app\/immutable\/bundle\.[a-zA-Z0-9_-]+\.js"\)/ + /import\("(\.\/|\/)_app\/immutable\/entry\/start\.[a-zA-Z0-9_-]+\.js"\)/ + ); + expect(indexContent).toMatch( + /import\("(\.\/|\/)_app\/immutable\/entry\/app\.[a-zA-Z0-9_-]+\.js"\)/ ); }); diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json index 4d4c701d3ec8..574b1ab6acc9 100644 --- a/ui/apps/chat/tsconfig.json +++ b/ui/apps/chat/tsconfig.json @@ -28,6 +28,8 @@ "highlight.js/*": ["./node_modules/highlight.js/*"], "@ggml-org/llama-brand": ["./node_modules/@ggml-org/llama-brand"], "@ggml-org/llama-brand/*": ["./node_modules/@ggml-org/llama-brand/*"], + "lowlight": ["./node_modules/lowlight"], + "lowlight/*": ["./node_modules/lowlight/*"], "mode-watcher": ["./node_modules/mode-watcher"], "mode-watcher/*": ["./node_modules/mode-watcher/*"], "svelte": ["./node_modules/svelte"], diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts index cf88572a9c2f..e88c853dacff 100644 --- a/ui/apps/chat/vite.config.ts +++ b/ui/apps/chat/vite.config.ts @@ -55,7 +55,7 @@ export default defineConfig(({ mode }) => { strict: true }), extensions: ['.svelte', '.svx'], - output: { bundleStrategy: 'single' }, + output: { bundleStrategy: 'split' }, paths: { relative: true }, // Consult https://svelte.dev/docs/kit/integrations // for more information about preprocessors diff --git a/ui/lib/ui/package-lock.json b/ui/lib/ui/package-lock.json index 4df54efee682..133cb2bd3cfb 100644 --- a/ui/lib/ui/package-lock.json +++ b/ui/lib/ui/package-lock.json @@ -10,13 +10,14 @@ "license": "MIT", "dependencies": { "@ggml-org/llama-brand": "0.1.0", - "@internationalized/date": "^3.12.4", + "@internationalized/date": "3.12.4", "@lucide/svelte": "1.46.0", "bits-ui": "2.18.1", - "clsx": "^2.1.1", - "highlight.js": "^11.11.1", - "tailwind-merge": "^3.7.0", - "tailwind-variants": "^3.3.1", + "clsx": "2.1.1", + "highlight.js": "11.11.1", + "lowlight": "3.3.0", + "tailwind-merge": "3.7.0", + "tailwind-variants": "3.3.1", "vaul-svelte": "1.0.0-next.7" }, "devDependencies": { @@ -27,28 +28,28 @@ "@storybook/addon-svelte-csf": "5.1.6", "@storybook/addon-vitest": "10.6.6", "@storybook/sveltekit": "10.6.6", - "@sveltejs/adapter-auto": "^8.0.0", - "@sveltejs/kit": "^3.0.0", - "@sveltejs/package": "^2.5.8", - "@sveltejs/vite-plugin-svelte": "^7.2.0", - "@tailwindcss/vite": "^4.3.3", - "@types/node": "^24", + "@sveltejs/adapter-auto": "8.0.0", + "@sveltejs/kit": "3.2.0", + "@sveltejs/package": "2.5.8", + "@sveltejs/vite-plugin-svelte": "7.3.1", + "@tailwindcss/vite": "4.3.3", + "@types/node": "24.19.2", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-v8": "5.0.5", "mdsvex": "0.12.7", - "mode-watcher": "^1.1.0", - "playwright": "^1.60.0", - "publint": "^0.3.21", + "mode-watcher": "1.1.0", + "playwright": "1.64.1", + "publint": "0.3.25", "storybook": "10.6.6", - "svelte": "^5.57.1", - "svelte-check": "^4.6.0", - "tailwindcss": "^4.3.3", + "svelte": "5.57.3", + "svelte-check": "4.7.7", + "tailwindcss": "4.3.3", "tw-animate-css": "1.4.0", - "typescript": "^6.0.3", + "typescript": "6.0.3", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", - "vitest-browser-svelte": "^2.1.1" + "vitest-browser-svelte": "2.2.1" }, "peerDependencies": { "mode-watcher": "^1.1.0", @@ -3578,6 +3579,15 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/hast": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.5.tgz", + "integrity": "sha512-rp/ezSWaD1m44dPKICGhiskI13nVr7qTloFwDa/IYkhhf5nzwP+zIQcIJh3WIFSBOy/H1PzB40jPjMDksN4F+g==", + "license": "MIT", + "dependencies": { + "@types/unist": "*" + } + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -3616,7 +3626,6 @@ "version": "2.0.11", "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz", "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==", - "dev": true, "license": "MIT" }, "node_modules/@valibot/to-json-schema": { @@ -4707,6 +4716,19 @@ "dev": true, "license": "MIT" }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/dom-accessibility-api": { "version": "0.5.16", "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", @@ -5329,6 +5351,21 @@ "dev": true, "license": "MIT" }, + "node_modules/lowlight": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-3.3.0.tgz", + "integrity": "sha512-0JNhgFoPvP6U6lE/UdVsSq99tn6DhjjpAj5MxG49ewd2mOBVtwWYIT8ClyABhq198aXXODMU6Ox8DrGy/CpTZQ==", + "license": "MIT", + "dependencies": { + "@types/hast": "^3.0.0", + "devlop": "^1.0.0", + "highlight.js": "~11.11.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/lz-string": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", @@ -6149,9 +6186,9 @@ } }, "node_modules/svelte": { - "version": "5.57.2", - "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.2.tgz", - "integrity": "sha512-1YiPCAXT0Ct6g1vOMmSLa0Nsc3QRMvtDF32ihgglGVrugIuIK38RyDiFNXVDhtQ81TJjSO57NdMw6DyYLqSGDQ==", + "version": "5.57.3", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz", + "integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==", "dev": true, "license": "MIT", "dependencies": { diff --git a/ui/lib/ui/package.json b/ui/lib/ui/package.json index 85fc6ac04337..6706dbaeed89 100644 --- a/ui/lib/ui/package.json +++ b/ui/lib/ui/package.json @@ -86,28 +86,28 @@ "@storybook/addon-svelte-csf": "5.1.6", "@storybook/addon-vitest": "10.6.6", "@storybook/sveltekit": "10.6.6", - "@sveltejs/adapter-auto": "^8.0.0", - "@sveltejs/kit": "^3.0.0", - "@sveltejs/package": "^2.5.8", - "@sveltejs/vite-plugin-svelte": "^7.2.0", - "@tailwindcss/vite": "^4.3.3", - "@types/node": "^24", + "@sveltejs/adapter-auto": "8.0.0", + "@sveltejs/kit": "3.2.0", + "@sveltejs/package": "2.5.8", + "@sveltejs/vite-plugin-svelte": "7.3.1", + "@tailwindcss/vite": "4.3.3", + "@types/node": "24.19.2", "@vitest/browser-playwright": "5.0.5", "@vitest/coverage-v8": "5.0.5", "mdsvex": "0.12.7", - "mode-watcher": "^1.1.0", - "playwright": "^1.60.0", - "publint": "^0.3.21", + "mode-watcher": "1.1.0", + "playwright": "1.64.1", + "publint": "0.3.25", "storybook": "10.6.6", - "svelte": "^5.57.1", - "svelte-check": "^4.6.0", - "tailwindcss": "^4.3.3", + "svelte": "5.57.3", + "svelte-check": "4.7.7", + "tailwindcss": "4.3.3", "tw-animate-css": "1.4.0", - "typescript": "^6.0.3", + "typescript": "6.0.3", "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0", "vite-plus": "1.3.0", "vitest": "5.0.5", - "vitest-browser-svelte": "^2.1.1" + "vitest-browser-svelte": "2.2.1" }, "peerDependencies": { "mode-watcher": "^1.1.0", @@ -120,14 +120,15 @@ "vitest": "5.0.5" }, "dependencies": { - "@internationalized/date": "^3.12.4", + "@internationalized/date": "3.12.4", "@lucide/svelte": "1.46.0", "bits-ui": "2.18.1", - "clsx": "^2.1.1", - "highlight.js": "^11.11.1", + "clsx": "2.1.1", + "highlight.js": "11.11.1", + "lowlight": "3.3.0", "@ggml-org/llama-brand": "0.1.0", - "tailwind-merge": "^3.7.0", - "tailwind-variants": "^3.3.1", + "tailwind-merge": "3.7.0", + "tailwind-variants": "3.3.1", "vaul-svelte": "1.0.0-next.7" } } diff --git a/ui/lib/ui/src/lib/models/constants.ts b/ui/lib/ui/src/lib/models/constants.ts index 2f8899e9c76c..ebfbf84ae727 100644 --- a/ui/lib/ui/src/lib/models/constants.ts +++ b/ui/lib/ui/src/lib/models/constants.ts @@ -2,13 +2,11 @@ // models-discover-download and model-compatibility). import { ModelCapability, ModelModality } from './enums.js'; import type { ModelModalities } from './types.js'; -import { - Eye as VisionIcon, - Lightbulb as ReasoningIcon, - Mic as AudioIcon, - Video as VideoIcon, - Wrench as ToolUseIcon -} from '@lucide/svelte'; +import VisionIcon from '@lucide/svelte/icons/eye'; +import ReasoningIcon from '@lucide/svelte/icons/lightbulb'; +import AudioIcon from '@lucide/svelte/icons/mic'; +import VideoIcon from '@lucide/svelte/icons/video'; +import ToolUseIcon from '@lucide/svelte/icons/wrench'; import type { Component } from 'svelte'; /** Neutral model badge: params, quantization, tags. */ diff --git a/ui/lib/ui/src/lib/utils/code.ts b/ui/lib/ui/src/lib/utils/code.ts index ca368f3527d0..f8c5ba5fc788 100644 --- a/ui/lib/ui/src/lib/utils/code.ts +++ b/ui/lib/ui/src/lib/utils/code.ts @@ -1,7 +1,11 @@ // highlightCode and its helpers, from ui/apps/chat's utils/code.ts (only what SyntaxHighlightedCode uses) import { CODE_BLOCK } from "../constants"; -import hljs from "highlight.js"; +import hljs from "highlight.js/lib/core"; import bash from "highlight.js/lib/languages/bash"; +import { all as languages } from "lowlight"; + +// reuse lowlight's language modules: the full `highlight.js` entry bundles a second, CommonJS copy of every language +for (const [name, language] of Object.entries(languages)) hljs.registerLanguage(name, language); // highlight.js's bash marks strings, variables and keywords but leaves a command's name and its flags plain, so a // command (`curl -H … -d …`) reads as one colour. Mark them too: the name as a built-in, the flags as attributes.