From ce16fff2ad1d1ddfb39365fedfb4fcfd6db178f1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 18 Jul 2026 04:55:29 +0000 Subject: [PATCH 001/115] Add TML Inkling architecture Hybrid attention model: 55 sliding-window plus 11 global layers, banded content-dependent relative position bias instead of RoPE, per-layer short convolution state, fine-grained MoE (256 experts top-6 plus 2 shared), attention log-scaling past 128K, 1M context. Includes the GGML_OP_FLASH_ATTN_EXT_BANDED operator (CPU and CUDA, fused into the MMA flash attention kernel with an fp16 accumulator overflow guard), HF to GGUF conversion, chat template with typed content block parsing (interleaved thinking, narration and tool calls), mmproj vision and audio support, and backend op tests at production shapes. --- common/chat-peg-parser.cpp | 26 +- common/chat-peg-parser.h | 12 +- common/chat.cpp | 127 +++++ conversion/__init__.py | 2 + conversion/base.py | 31 ++ conversion/inkling.py | 350 +++++++++++++ ggml/include/ggml-rpc.h | 4 +- ggml/include/ggml.h | 20 +- ggml/src/ggml-backend-meta.cpp | 13 + ggml/src/ggml-cpu/ggml-cpu.c | 3 + ggml/src/ggml-cpu/ops.cpp | 44 +- ggml/src/ggml-cuda/argsort.cu | 28 +- ggml/src/ggml-cuda/fattn-banded.cu | 247 +++++++++ ggml/src/ggml-cuda/fattn-banded.cuh | 7 + ggml/src/ggml-cuda/fattn-common.cuh | 17 +- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 112 ++++- ggml/src/ggml-cuda/fattn.cu | 10 +- ggml/src/ggml-cuda/ggml-cuda.cu | 68 ++- ggml/src/ggml-cuda/mmf.cuh | 8 +- ggml/src/ggml-cuda/mmq.cuh | 12 +- ggml/src/ggml-cuda/mmvf.cu | 4 +- ggml/src/ggml-cuda/mmvq.cu | 4 +- ggml/src/ggml-cuda/pad.cu | 2 +- ggml/src/ggml-cuda/ssm-conv.cu | 28 +- ggml/src/ggml-rpc/ggml-rpc.cpp | 1 + ggml/src/ggml.c | 59 ++- gguf-py/gguf/constants.py | 50 ++ gguf-py/gguf/tensor_mapping.py | 49 ++ models/templates/Inkling.jinja | 514 +++++++++++++++++++ src/llama-arch.cpp | 35 ++ src/llama-arch.h | 24 + src/llama-graph.cpp | 8 +- src/llama-graph.h | 3 +- src/llama-hparams.cpp | 5 + src/llama-hparams.h | 11 + src/llama-kv-cache.cpp | 97 ++++ src/llama-kv-cache.h | 13 +- src/llama-model-saver.cpp | 1 + src/llama-model.cpp | 6 +- src/llama-model.h | 9 + src/llama-quant.cpp | 10 + src/llama-vocab.cpp | 10 + src/llama-vocab.h | 1 + src/models/inkling.cpp | 666 +++++++++++++++++++++++++ src/models/models.h | 13 + tests/CMakeLists.txt | 8 + tests/test-backend-ops.cpp | 114 ++++- tests/test-chat.cpp | 79 +++ tests/test-flash-attn-bias.cpp | 525 +++++++++++++++++++ tests/test-flash-attn-generic-hash.cpp | 142 ++++++ tests/test-llama-archs.cpp | 3 + tools/mtmd/CMakeLists.txt | 1 + tools/mtmd/clip-impl.h | 9 + tools/mtmd/clip-model.h | 13 +- tools/mtmd/clip.cpp | 62 ++- tools/mtmd/models/inkling.cpp | 106 ++++ tools/mtmd/models/models.h | 11 + tools/mtmd/mtmd-audio.cpp | 71 +++ tools/mtmd/mtmd-audio.h | 10 + tools/mtmd/mtmd-image.cpp | 195 +++++++- tools/mtmd/mtmd-image.h | 20 + tools/mtmd/mtmd.cpp | 37 +- 62 files changed, 4048 insertions(+), 122 deletions(-) create mode 100644 conversion/inkling.py create mode 100644 ggml/src/ggml-cuda/fattn-banded.cu create mode 100644 ggml/src/ggml-cuda/fattn-banded.cuh create mode 100644 models/templates/Inkling.jinja create mode 100644 src/models/inkling.cpp create mode 100644 tests/test-flash-attn-bias.cpp create mode 100644 tests/test-flash-attn-generic-hash.cpp create mode 100644 tools/mtmd/models/inkling.cpp diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp index a309f02765b7..52829b7c4b20 100644 --- a/common/chat-peg-parser.cpp +++ b/common/chat-peg-parser.cpp @@ -594,7 +594,8 @@ common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key( const std::string & args_key, const std::string & effective_args_key, const std::string & call_id_key, - const std::string & gen_call_id_key) { + const std::string & gen_call_id_key, + bool require_object_args) { auto tool_choices = choice(); @@ -631,10 +632,10 @@ common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key( // Arguments — either wrapped in args_key or parsed directly common_peg_parser args_parser = eps(); if (args_key.empty()) { - args_parser = tool_args(schema(json(), "tool-" + name + "-schema", params)); + args_parser = tool_args(schema(require_object_args ? json_object() : json(), "tool-" + name + "-schema", params)); } else { args_parser = literal("\"" + effective_args_key + "\"") + space() + literal(":") + space() + - tool_args(schema(json(), "tool-" + name + "-schema", params)); + tool_args(schema(require_object_args ? json_object() : json(), "tool-" + name + "-schema", params)); } inner_fields.push_back(args_parser); @@ -673,7 +674,8 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys( const std::string & effective_name_key, const std::string & effective_args_key, const std::string & call_id_key, - const std::string & gen_call_id_key) { + const std::string & gen_call_id_key, + bool require_object_args) { auto tool_choices = choice(); @@ -695,7 +697,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys( auto nested_name = literal("\"" + nested_name_field + "\"") + space() + literal(":") + space() + atomic(literal("\"") + tool_name(literal(name)) + literal("\"")); auto nested_args = literal("\"" + nested_args_field + "\"") + space() + literal(":") + space() + - tool_args(schema(json(), "tool-" + name + "-schema", params)); + tool_args(schema(require_object_args ? json_object() : json(), "tool-" + name + "-schema", params)); auto nested_object = literal("{") + space() + nested_name + space() + literal(",") + space() + @@ -747,7 +749,8 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys( const std::string & call_id_key, const std::string & gen_call_id_key, const std::vector & parameters_order, - bool accept_openai_wrapper) { + bool accept_openai_wrapper, + bool require_object_args) { auto tool_choices = choice(); auto name_key_parser = literal("\"" + effective_name_key + "\""); @@ -764,7 +767,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys( auto tool_name_ = name_key_parser + space() + literal(":") + space() + atomic(literal("\"") + tool_name(literal(name)) + literal("\"")); auto tool_args_ = args_key_parser + space() + literal(":") + space() + - tool_args(schema(json(), "tool-" + name + "-schema", params)); + tool_args(schema(require_object_args ? json_object() : json(), "tool-" + name + "-schema", params)); // Build ID parsers if keys are provided common_peg_parser id_parser = eps(); @@ -879,7 +882,8 @@ common_peg_parser common_chat_peg_builder::standard_json_tools( const std::string & call_id_key, const std::string & gen_call_id_key, const std::vector & parameters_order, - bool accept_openai_wrapper) { + bool accept_openai_wrapper, + bool require_object_args) { if (!tools.is_array() || tools.empty()) { return eps(); } @@ -890,14 +894,14 @@ common_peg_parser common_chat_peg_builder::standard_json_tools( // Dispatch to the appropriate builder based on the JSON layout mode common_peg_parser tool_choices = eps(); if (function_is_key) { - tool_choices = build_json_tools_function_is_key(tools, args_key, effective_args_key, call_id_key, gen_call_id_key); + tool_choices = build_json_tools_function_is_key(tools, args_key, effective_args_key, call_id_key, gen_call_id_key, require_object_args); } else { auto name_spec = parse_key_spec(effective_name_key); auto args_spec = parse_key_spec(effective_args_key); if (!name_spec.first.empty() || !args_spec.first.empty()) { - tool_choices = build_json_tools_nested_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key); + tool_choices = build_json_tools_nested_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, require_object_args); } else { - tool_choices = build_json_tools_flat_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper); + tool_choices = build_json_tools_flat_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper, require_object_args); } } diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index b3ffd7de2dd8..a2b7cbd4d303 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -121,7 +121,8 @@ class common_chat_peg_builder : public common_peg_parser_builder { const std::string & call_id_key = "", const std::string & gen_call_id_key = "", const std::vector & parameters_order = {}, - bool accept_openai_wrapper = false); + bool accept_openai_wrapper = false, + bool require_object_args = false); // Legacy-compatible helper for building XML/tagged style tool calls // Used by tests and manual parsers @@ -145,13 +146,15 @@ class common_chat_peg_builder : public common_peg_parser_builder { const std::string & args_key, const std::string & effective_args_key, const std::string & call_id_key, - const std::string & gen_call_id_key); + const std::string & gen_call_id_key, + bool require_object_args); common_peg_parser build_json_tools_nested_keys(const nlohmann::ordered_json & tools, const std::string & effective_name_key, const std::string & effective_args_key, const std::string & call_id_key, - const std::string & gen_call_id_key); + const std::string & gen_call_id_key, + bool require_object_args); common_peg_parser build_json_tools_flat_keys(const nlohmann::ordered_json & tools, const std::string & effective_name_key, @@ -159,7 +162,8 @@ class common_chat_peg_builder : public common_peg_parser_builder { const std::string & call_id_key, const std::string & gen_call_id_key, const std::vector & parameters_order, - bool accept_openai_wrapper); + bool accept_openai_wrapper, + bool require_object_args); }; inline common_peg_arena build_chat_peg_parser( diff --git a/common/chat.cpp b/common/chat.cpp index 22d2ee4a2a11..f6cf981e75f7 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -2175,6 +2175,125 @@ static common_chat_params common_chat_params_init_cohere2moe(const common_chat_t return data; } +// Inkling / TML typed-content-block parser: <|end_message|> separates blocks within a turn, +// <|content_model_end_sampling|> is the sole end-of-generation token (mirrors sglang TmlDetector). +static common_chat_params common_chat_params_init_inkling(const common_chat_template & tmpl, + const autoparser::generation_params & inputs) { + common_chat_params data; + + const std::string MSG_MODEL = "<|message_model|>"; + const std::string MSG_USER = "<|message_user|>"; + const std::string MSG_SYSTEM = "<|message_system|>"; + const std::string MSG_TOOL = "<|message_tool|>"; + const std::string THINK = "<|content_thinking|>"; + const std::string TEXT = "<|content_text|>"; + const std::string END_MESSAGE = "<|end_message|>"; + const std::string END_SAMPLING = "<|content_model_end_sampling|>"; + const std::string INVOKE_TOOL = "<|content_invoke_tool_json|>"; + + data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs); + data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs); + data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; + data.supports_thinking = true; + data.thinking_start_tag = THINK; + data.thinking_end_tag = END_MESSAGE; + data.preserved_tokens = { + MSG_MODEL, MSG_USER, MSG_SYSTEM, MSG_TOOL, + THINK, TEXT, END_MESSAGE, END_SAMPLING, INVOKE_TOOL, + }; + + auto has_tools = inputs.tools.is_array() && !inputs.tools.empty(); + data.message_delimiters = { + { COMMON_CHAT_ROLE_ASSISTANT, MSG_MODEL }, + { COMMON_CHAT_ROLE_USER, MSG_USER }, + { COMMON_CHAT_ROLE_SYSTEM, MSG_SYSTEM }, + { COMMON_CHAT_ROLE_TOOL, MSG_TOOL }, + }; + + auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; + + if (inputs.has_continuation()) { + const auto & msg = inputs.continue_msg; + + data.generation_prompt = MSG_MODEL + THINK + msg.reasoning_content; + if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) { + data.generation_prompt += END_MESSAGE + TEXT + msg.render_content(); + } + + data.prompt += data.generation_prompt; + } + + auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + auto generation_prompt = p.literal(MSG_MODEL); + auto end = p.end(); + + // thinking block; may also reappear mid-turn (after content), so it is both an optional + // prefix and a choice inside the block loops. With reasoning_format=NONE keep it + // (markers included) inline as content + common_peg_parser reasoning_block = p.eps(); + if (extract_reasoning) { + reasoning_block = p.literal(THINK) + + p.reasoning(p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING })) + + p.optional(p.literal(END_MESSAGE)); + } else { + reasoning_block = p.content(p.literal(THINK) + + p.until_one_of({ END_MESSAGE, TEXT, END_SAMPLING }) + + p.optional(p.literal(END_MESSAGE))); + } + auto reasoning = p.optional(reasoning_block); + + // TML re-emits <|message_model|> before each content block; a turn may contain several + // text blocks (one per content part), so the block repeats and bodies concatenate. + // THINK stops the content scan so a mid-turn thinking block is never leaked as text + auto text_block = p.optional(p.literal(MSG_MODEL)) + + p.optional(p.literal(TEXT)) + + p.content(p.until_one_of({ THINK, END_MESSAGE, END_SAMPLING })) + + p.optional(p.literal(END_MESSAGE)); + auto text_content = p.one_or_more(p.choice({ reasoning_block, text_block })); + + if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) { + return generation_prompt + reasoning + text_content + + p.optional(p.literal(END_SAMPLING)) + end; + } + + // each call is its own block (role opener + bare name echo + JSON section); + // force_tool_calls=true makes the JSON section required so a pure-text answer fails the + // block cleanly; parallel calls are separate blocks, hence repeat + parallel=false + auto tool_section = p.standard_json_tools( + INVOKE_TOOL, END_MESSAGE, inputs.tools, /* parallel_tool_calls = */ false, + /* force_tool_calls = */ true, + /* name_key = */ "name", + /* args_key = */ "args", + /* array_wrapped = */ false, + /* function_is_key = */ false, + /* call_id_key = */ "", + /* gen_call_id_key = */ "", + /* parameters_order = */ {}, + /* accept_openai_wrapper = */ false, + /* require_object_args = */ true); + // the name-echo scan must stop at any block marker: a greedy until(INVOKE_TOOL) returns + // NEED_MORE_INPUT mid-stream, which choice() treats as a match and shadows the text branch + auto tool_block = p.optional(p.literal(MSG_MODEL)) + + p.until_one_of({ INVOKE_TOOL, TEXT, THINK, END_MESSAGE, END_SAMPLING }) + + tool_section; + auto tool_calls = inputs.parallel_tool_calls ? p.one_or_more(tool_block) : tool_block; + // turns may interleave narration, thinking and calls; parse block-by-block (tool block + // first) since a whole-body choice would let the text branch swallow tool blocks into + // visible content + auto mixed_body = p.one_or_more(p.choice({ tool_block, reasoning_block, text_block })); + auto body = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED + ? tool_calls + : mixed_body; + + return generation_prompt + reasoning + body + + p.optional(p.literal(END_SAMPLING)) + end; + }); + + data.parser = parser.save(); + + return data; +} + namespace workaround { static void map_developer_role_to_system(json & messages) { @@ -2592,6 +2711,14 @@ std::optional common_chat_try_specialized_template( return common_chat_params_init_cohere2moe(tmpl, params); } + // Inkling / TML: this marker combination is unique to the template + if (src.find("<|content_thinking|>") != std::string::npos && + src.find("<|content_text|>") != std::string::npos && + src.find("<|message_model|>") != std::string::npos) { + LOG_DBG("Using specialized template: Inkling\n"); + return common_chat_params_init_inkling(tmpl, params); + } + if (is_lfm2_template(src)) { LOG_DBG("Using specialized template: LFM2\n"); return common_chat_params_init_lfm2(tmpl, params, /* tool_list_tokens = */ true); diff --git a/conversion/__init__.py b/conversion/__init__.py index 465c010f667a..73da6ca5cc1d 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -109,6 +109,7 @@ "HunYuanVLForConditionalGeneration": "hunyuan", "HYV3ForCausalLM": "hunyuan", "IQuestCoderForCausalLM": "llama", + "InklingForConditionalGeneration": "inkling", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", "JAISLMHeadModel": "jais", @@ -273,6 +274,7 @@ "GraniteSpeechPlusForConditionalGeneration": "granite", "HunYuanVLForConditionalGeneration": "hunyuan", "Idefics3ForConditionalGeneration": "smolvlm", + "InklingForConditionalGeneration": "inkling", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", "KimiK25ForConditionalGeneration": "kimivl", diff --git a/conversion/base.py b/conversion/base.py index 1b85ef0a1b89..b780901887c3 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -268,8 +268,17 @@ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Call data_gen = lambda data=data_torch: LazyTorchTensor.from_eager(data) # noqa: E731 else: data_gen = lambda data=data_torch: data # noqa: E731 + # the index maps each tensor to one shard; a duplicate would silently overwrite it + if weight_map and name in weight_map and weight_map[name] != part_name: + raise ValueError( + f"tensor '{name}' found in '{part_name}' but the index assigns " + f"it to '{weight_map[name]}'; refusing to load a wrong-shard copy") if titem := self.filter_tensors((name, data_gen)): tname, tgen = titem + if tname in tensors: + raise ValueError( + f"duplicate tensor '{tname}' found in multiple model parts; " + f"refusing to silently overwrite") tensors[tname] = tgen # verify tensor name presence and identify potentially missing files @@ -537,6 +546,20 @@ def dequant_packed(w: Tensor, scale: Tensor, shape_tensor: Tensor, zero_point: T else: raise NotImplementedError(f"Quant format {quant_format!r} for method {quant_method!r} is not yet supported") elif quant_method == "modelopt": + # Stacked-expert NVFP4 checkpoints (e.g. Inkling-NVFP4) store experts as + # w13_weight/w2_weight with .scale/.scale2/.input_amax/.original_shape + # auxiliaries; the main tensors do not end in .weight, so the NVFP4 path + # below would silently skip them. Reject them with a clear error. + stacked_expert_aux = [ + n for n in self.model_tensors + if n.endswith((".scale2", ".input_amax", ".original_shape")) + ] + if stacked_expert_aux: + raise NotImplementedError( + "This checkpoint stores quantized experts in the stacked ModelOpt NVFP4 layout " + f"({len(stacked_expert_aux)} auxiliary tensors like {stacked_expert_aux[0]!r}), " + "which is not supported yet. Convert from the unquantized (BF16) checkpoint instead." + ) # Mixed-precision ModelOpt models: NVFP4 tensors are handled by # _generate_nvfp4_tensors; FP8 tensors have 1D weight_scale and # are dequantized here. k/v scale tensors are unused. @@ -1023,6 +1046,14 @@ def write_vocab(self): def write(self): self.prepare_tensors() + # zero tensors means the shards were never discovered, yet a metadata-only GGUF logs success + n_written = sum(len(shard) for shard in self.gguf_writer.tensors) + if n_written == 0: + raise ValueError( + "no tensors were written: the model shards could not be found. " + "Check that the safetensors filenames are discoverable (they must " + "start with 'model') or that model.safetensors exists." + ) self.prepare_metadata(vocab_only=False) self.gguf_writer.write_header_to_file(path=self.fname_out) self.gguf_writer.write_kv_data_to_file() diff --git a/conversion/inkling.py b/conversion/inkling.py new file mode 100644 index 000000000000..90ef65c3bdcc --- /dev/null +++ b/conversion/inkling.py @@ -0,0 +1,350 @@ +from __future__ import annotations + +from typing import Callable, Iterable, TYPE_CHECKING + +if TYPE_CHECKING: + from torch import Tensor + +from .base import MmprojModel, ModelBase, TextModel, gguf, logger + + +@ModelBase.register("InklingForConditionalGeneration") +class InklingModel(TextModel): + model_arch = gguf.MODEL_ARCH.INKLING + undo_permute = False + + _SKIP_PREFIXES = ("model.visual.", "model.audio.", "model.mtp.") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # explicit raises (not assert, stripped by python -O) guard the single supported variant + hp = self.hparams + + # normalize keys renamed by HF-port re-saved configs back to checkpoint names + if "dense_intermediate_size" not in hp and "moe_intermediate_size" in hp: + hp["dense_intermediate_size"] = hp["intermediate_size"] + hp["intermediate_size"] = hp["moe_intermediate_size"] + if "sconv_kernel_size" not in hp and "conv_kernel_size" in hp: + hp["sconv_kernel_size"] = hp["conv_kernel_size"] + if "dense_mlp_idx" not in hp and hp.get("mlp_layer_types"): + types = hp["mlp_layer_types"] + hp["dense_mlp_idx"] = next((i for i, t in enumerate(types) if t != "dense"), len(types)) + + if hp.get("gate_activation", "sigmoid") != "sigmoid": + raise NotImplementedError( + f"unsupported gate_activation {hp.get('gate_activation')!r}; only 'sigmoid' is implemented" + ) + for flag, want in ( + ("norm_after_topk", True), + ("shared_expert_sink", True), + ("use_sconv", True), + ("use_embed_norm", True), + ("use_gate_bias", True), + ("use_global_scale", True), + ): + if hp.get(flag, want) is not want: + raise NotImplementedError(f"unsupported {flag}={hp.get(flag)!r}; only {want} is implemented") + if hp.get("q_bias", False) is not False or hp.get("o_bias", False) is not False: + raise NotImplementedError("attention q_bias / o_bias are not supported") + if hp.get("final_logit_softcapping") not in (None, 0, 0.0): + raise NotImplementedError( + f"final_logit_softcapping={hp.get('final_logit_softcapping')!r} is not supported" + ) + if hp["swa_head_dim"] != hp["head_dim"]: + raise ValueError(f"swa_head_dim {hp['swa_head_dim']} must equal head_dim {hp['head_dim']}") + if hp["swa_num_attention_heads"] != hp["num_attention_heads"]: + raise ValueError( + f"swa_num_attention_heads {hp['swa_num_attention_heads']} must equal " + f"num_attention_heads {hp['num_attention_heads']}" + ) + + # context length comes from model_max_length per the design contract + if (mml := hp.get("model_max_length")) is not None: + self.hparams["max_position_embeddings"] = mml + + # checked by the base find_hparam list before the MoE "intermediate_size" + self.hparams["prefix_dense_intermediate_size"] = hp["dense_intermediate_size"] + + self._local_layer_flags = self._get_local_layer_flags() + self.hparams["num_key_value_heads"] = [ + hp["swa_num_key_value_heads"] if is_local else hp["num_key_value_heads"] + for is_local in self._local_layer_flags + ] + + def _get_local_layer_flags(self) -> list[bool]: + # local_layer_ids is authoritative; a round-tripped layer_types may be stale and must not override it + n_layer = self.hparams["num_hidden_layers"] + local_ids = self.hparams.get("local_layer_ids") + if local_ids is None: + # default: global at id % 6 == 5; omitted/null must not collapse to all-global (explicit [] does) + local_ids = [i for i in range(n_layer) if i % 6 != 5] + local_ids = set(local_ids) + return [i in local_ids for i in range(n_layer)] + + def get_vocab_base(self) -> tuple[list[str], list[int], str]: + tokens, toktypes, tokpre = super().get_vocab_base() + # dedicated pre-type: o200k-family regex that keeps combining marks attached to base letters + tokpre = "inkling" + import gguf as _gguf + n_vocab = self.hparams["vocab_size"] + n_unpadded = self.hparams.get("unpadded_vocab_size") or n_vocab + if len(tokens) != n_vocab: + raise ValueError(f"Inkling tokenizer produced {len(tokens)} entries, expected {n_vocab}") + # force-CONTROL special ids from added_tokens_decoder, else the trailing-60 convention + try: + import json as _json + import pathlib as _pl + tc = _json.loads((_pl.Path(self.dir_model) / "tokenizer_config.json").read_text()) + special_ids = sorted(int(i) for i, d in tc.get("added_tokens_decoder", {}).items() if d.get("special")) + except Exception: + special_ids = list(range(n_unpadded - 60, n_unpadded)) + for tid in special_ids: + if 0 <= tid < n_vocab: + toktypes[tid] = _gguf.TokenType.CONTROL + if any(t != _gguf.TokenType.UNUSED for t in toktypes[n_unpadded:]): + raise ValueError("real tokens found at/above unpadded_vocab_size; padded-vocab mask would hide them") + return tokens, toktypes, tokpre + + def set_vocab(self): + self._set_vocab_gpt2() + eos_id = int(self.hparams.get("eos_token_id", 200006)) + if eos_id < 199998: + # HF-port configs re-save generic bos/eos defaults; the real EOS lives at 199998+ + eos_id = 200006 + # 200006 is the SOLE end-of-generation token; <|end_message|> (200010) is an + # intra-turn block separator and must NOT be registered eot/eog + self.gguf_writer.add_eos_token_id(eos_id) + # no BOS is ever prepended; pin bos to EOS so a stale base-tokenizer bos id never surfaces + self.gguf_writer.add_bos_token_id(eos_id) + self.gguf_writer.add_add_bos_token(False) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hp = self.hparams + + self.gguf_writer.add_vocab_size(hp["vocab_size"]) + self.gguf_writer.add_expert_feed_forward_length(hp["intermediate_size"]) + self.gguf_writer.add_expert_shared_count(hp["n_shared_experts"]) + self.gguf_writer.add_expert_weights_scale(hp["route_scale"]) + self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SIGMOID) + + # sliding_window_size is canonical; explicit is-None fallback so a serialized 0 cannot bypass the mismatch check + canonical_window = hp["sliding_window_size"] + sliding_window = hp.get("sliding_window") + if sliding_window is None: + sliding_window = canonical_window + elif sliding_window != canonical_window: + raise ValueError( + f"sliding_window {sliding_window} disagrees with sliding_window_size " + f"{canonical_window!r}" + ) + if sliding_window <= 0: + raise ValueError(f"sliding_window must be positive, got {sliding_window}") + self.gguf_writer.add_sliding_window(sliding_window) + # true = local (swa) layer + self.gguf_writer.add_sliding_window_pattern(self._local_layer_flags) + + # no RoPE (arch-determined NONE); custom inkling.* keys per INKLING_DESIGN.md + arch = gguf.MODEL_ARCH_NAMES[self.model_arch] + self.gguf_writer.add_uint32(f"{arch}.d_rel", hp["d_rel"]) + self.gguf_writer.add_uint32(f"{arch}.rel_extent", hp["rel_extent"]) + self.gguf_writer.add_uint32(f"{arch}.rel_extent_swa", sliding_window) + self.gguf_writer.add_uint32(f"{arch}.shortconv_kernel", hp["sconv_kernel_size"]) + self.gguf_writer.add_uint32(f"{arch}.dense_block_count", hp["dense_mlp_idx"]) + self.gguf_writer.add_float32(f"{arch}.logit_scale_denom", hp["logits_mup_width_multiplier"]) + self.gguf_writer.add_uint32(f"{arch}.log_scaling_n_floor", int(hp.get("log_scaling_n_floor") or 0)) + self.gguf_writer.add_float32(f"{arch}.log_scaling_alpha", hp.get("log_scaling_alpha", 0.0)) + self.gguf_writer.add_uint32(f"{arch}.unpadded_vocab_size", hp["unpadded_vocab_size"]) + + logger.info(f"gguf: (inkling) swa pattern (true=local) = {self._local_layer_flags}") + logger.info(f"gguf: (inkling) unpadded_vocab_size = {hp['unpadded_vocab_size']}") + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + name, gen = item + + if name.startswith(cls._SKIP_PREFIXES): + return None + + name = name.replace("model.llm.", "model.") + # parameter has no ".weight"-style suffix in the checkpoint + name = name.replace("rel_logits_proj.proj", "rel_logits_proj.weight") + + return super().filter_tensors((name, gen)) + + @staticmethod + def _deinterleave_w13(w13: Tensor) -> tuple[Tensor, Tensor]: + # interleaved SwiGLU along the output rows: silu(z[..., ::2]) * z[..., 1::2] + gate = w13[..., 0::2, :].contiguous() + up = w13[..., 1::2, :].contiguous() + return gate, up + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # short convs: [C, 1, K] -> [C, K] (same layout as LFM2 shortconv.conv) + if name.endswith("_sconv.weight"): + data_torch = data_torch.squeeze(1) + return [(self.map_tensor_name(name), data_torch)] + + if name.endswith(".mlp.w13_dn.weight"): + assert bid is not None + gate, up = self._deinterleave_w13(data_torch) + return [ + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_GATE, bid), gate), + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_UP, bid), up), + ] + + if name.endswith(".mlp.global_scale") or name.endswith(".mlp.gate.global_scale"): + assert bid is not None + return [(self.format_tensor_name(gguf.MODEL_TENSOR.FFN_GSCALE, bid), data_torch.float())] + + if name.endswith(".mlp.gate.bias"): + assert bid is not None + return [(self.format_tensor_name(gguf.MODEL_TENSOR.FFN_EXP_PROBS_B, bid, ".bias"), data_torch.float())] + + if name.endswith(".mlp.experts.w13_weight"): + assert bid is not None + gate, up = self._deinterleave_w13(data_torch) + return [ + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_GATE_EXP, bid), gate), + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_UP_EXP, bid), up), + ] + if name.endswith(".mlp.experts.w2_weight"): + assert bid is not None + return [(self.format_tensor_name(gguf.MODEL_TENSOR.FFN_DOWN_EXP, bid), data_torch)] + + # shared experts stored stacked for mul_mat_id + if name.endswith(".mlp.shared_experts.shared_w13_weight"): + assert bid is not None + gate, up = self._deinterleave_w13(data_torch) + return [ + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_GATE_SHEXP, bid), gate), + (self.format_tensor_name(gguf.MODEL_TENSOR.FFN_UP_SHEXP, bid), up), + ] + if name.endswith(".mlp.shared_experts.shared_w2_weight"): + assert bid is not None + return [(self.format_tensor_name(gguf.MODEL_TENSOR.FFN_DOWN_SHEXP, bid), data_torch)] + + return [(self.map_tensor_name(name), data_torch)] + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int): + # used in fp32 rel-bias math; keep full precision + if new_name.endswith("attn_rel_proj.weight"): + return gguf.GGMLQuantizationType.F32 + # ggml_ssm_conv kernels are F32-only + if ".shortconv_" in new_name: + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + +@ModelBase.register("InklingForConditionalGeneration") +class InklingMmprojModel(MmprojModel): + """Export Inkling's hMLP and dMel towers as one mtmd projector.""" + + has_vision_encoder = True + has_audio_encoder = True + + _IMAGE_MEAN = [0.48145466, 0.4578275, 0.40821073] + _IMAGE_STD = [0.26862954, 0.2613026, 0.2757771] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + assert self.hparams_vision is not None + hp = self.hparams_vision + expected = { + "vision_encoder_type": "hmlp", + "patch_size": 40, + "temporal_patch_size": 2, + "n_channels": 3, + "n_layers": 4, + "decoder_dmodel": 6144, + "use_vision_norm": True, + } + for key, want in expected.items(): + got = hp.get(key, want) + if got != want: + raise NotImplementedError( + f"Inkling mmproj requires vision_config.{key}={want!r}, got {got!r}" + ) + + assert self.hparams_audio is not None + ahp = self.hparams_audio + audio_expected = { + "audio_mode": "dmel", + "decoder_dmodel": 6144, + "n_mel_bins": 80, + "mel_vocab_size": 16, + "use_audio_norm": True, + } + for key, want in audio_expected.items(): + got = ahp.get(key, want) + if got != want: + raise NotImplementedError( + f"Inkling mmproj requires audio_config.{key}={want!r}, got {got!r}" + ) + + def set_gguf_parameters(self): + hp = self.hparams_vision + assert hp is not None + + self.gguf_writer.add_file_type(self.ftype) + self.gguf_writer.add_clip_has_vision_encoder(True) + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_vision_projector_type(gguf.VisionProjectorType.INKLING) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.INKLING) + self.gguf_writer.add_vision_projection_dim(hp["decoder_dmodel"]) + + # clip.cpp requires these common fields even though hMLP is not a ViT. + self.gguf_writer.add_vision_image_size(hp["patch_size"]) + self.gguf_writer.add_vision_patch_size(hp["patch_size"]) + self.gguf_writer.add_vision_embedding_length(hp["n_channels"]) + self.gguf_writer.add_vision_feed_forward_length(0) + self.gguf_writer.add_vision_block_count(hp["n_layers"]) + self.gguf_writer.add_vision_head_count(1) + self.gguf_writer.add_vision_attention_layernorm_eps(1e-6) + self.gguf_writer.add_vision_image_mean(self._IMAGE_MEAN) + self.gguf_writer.add_vision_image_std(self._IMAGE_STD) + + ahp = self.hparams_audio + assert ahp is not None + self.gguf_writer.add_audio_projection_dim(ahp["decoder_dmodel"]) + self.gguf_writer.add_audio_embedding_length(ahp["decoder_dmodel"]) + self.gguf_writer.add_audio_feed_forward_length(0) + self.gguf_writer.add_audio_block_count(0) + self.gguf_writer.add_audio_head_count(1) + self.gguf_writer.add_audio_attention_layernorm_eps(1e-6) + self.gguf_writer.add_audio_num_mel_bins(ahp["n_mel_bins"]) + + @classmethod + def filter_tensors(cls, item): + name, gen = item + if not name.startswith(("model.visual.", "visual.", "model.audio.", "audio.")): + return None + return name, gen + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None): + del bid + if name.startswith(("model.audio.", "audio.")): + prefix = "model.audio." if name.startswith("model.audio.") else "audio." + local = name.removeprefix(prefix) + if local == "encoder.weight": + yield "a.dmel.embedding.weight", data_torch + return + if local == "final_norm.weight": + yield "a.dmel.final_norm.weight", data_torch + return + raise ValueError(f"unexpected Inkling audio tensor {name!r}") + + prefix = "model.visual." if name.startswith("model.visual.") else "visual." + local = name.removeprefix(prefix) + if local == "final_norm.weight": + yield "v.hmlp.final_norm.weight", data_torch + return + + parts = local.split(".") + if len(parts) == 3 and parts[0] == "layers" and parts[2] == "weight": + kind, sep, layer_s = parts[1].partition("_") + if sep and kind in ("linear", "norm") and layer_s.isdigit(): + yield f"v.hmlp.{int(layer_s)}.{kind}.weight", data_torch + return + + raise ValueError(f"unexpected Inkling vision tensor {name!r}") diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index 16ca33947a2e..7ca7f5fbf54e 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -8,10 +8,10 @@ extern "C" { #define RPC_PROTO_MAJOR_VERSION 4 #define RPC_PROTO_MINOR_VERSION 0 -#define RPC_PROTO_PATCH_VERSION 3 +#define RPC_PROTO_PATCH_VERSION 4 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 102, "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 35f0c44ec421..6e51f5734ee5 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -435,8 +435,9 @@ extern "C" { // precision enum ggml_prec { - GGML_PREC_DEFAULT = 0, // stored as ggml_tensor.op_params, 0 by default - GGML_PREC_F32 = 10, + GGML_PREC_DEFAULT = 0, // stored as ggml_tensor.op_params, 0 by default + GGML_PREC_F32 = 10, + GGML_PREC_F32_PEDANTIC = 11, }; // op hint @@ -558,6 +559,7 @@ extern "C" { GGML_OP_FILL, GGML_OP_FLASH_ATTN_EXT, + GGML_OP_FLASH_ATTN_EXT_BANDED, GGML_OP_FLASH_ATTN_BACK, GGML_OP_SSM_CONV, GGML_OP_SSM_SCAN, @@ -1432,6 +1434,7 @@ extern "C" { // change the precision of a matrix multiplication // set to GGML_PREC_F32 for higher precision (useful for phi-2) + // or GGML_PREC_F32_PEDANTIC to require true F32 arithmetic GGML_API void ggml_mul_mat_set_prec( struct ggml_tensor * a, enum ggml_prec prec); @@ -2426,6 +2429,19 @@ extern "C" { float max_bias, float logit_softcap); + // flash attention with an additive banded relative-position bias, applied after scale, no dense bias tensor: + // rel_logits: [rel_extent, n_head, n_batch, ne3]; rel_dist = q_idx + (n_kv - n_batch) - kv_idx + // score += rel_logits[rel_dist, head, q_idx, batch] iff 0 <= rel_dist < rel_extent + GGML_API struct ggml_tensor * ggml_flash_attn_ext_banded( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * mask, + struct ggml_tensor * rel_logits, + float scale, + int64_t rel_extent); + GGML_API void ggml_flash_attn_ext_set_prec( struct ggml_tensor * a, enum ggml_prec prec); diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index a5a3a58ad054..b397fb6ba1b8 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -753,6 +753,16 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; }; + auto handle_flash_attn_ext_banded = [&](const std::vector & src_ss) -> ggml_backend_meta_split_state { + GGML_ASSERT( src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_2); + GGML_ASSERT( src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_2); + GGML_ASSERT( src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_2); + GGML_ASSERT(tensor->src[3] == nullptr || src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + // rel_logits is [E, H, Q, B], so its head shard is axis 1. + GGML_ASSERT( src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_1); + return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; + }; + auto handle_ssm_conv = [&](const std::vector & src_ss) -> ggml_backend_meta_split_state { if (src_ss[0].axis == src_ss[1].axis) { if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_0) { @@ -964,6 +974,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_FLASH_ATTN_EXT: { split_state = handle_flash_attn_ext(src_ss); } break; + case GGML_OP_FLASH_ATTN_EXT_BANDED: { + split_state = handle_flash_attn_ext_banded(src_ss); + } break; case GGML_OP_FLASH_ATTN_BACK: { split_state = handle_generic(src_ss, /*scalar_only =*/ true); } break; diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 491316f74912..1c335b07b89e 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1998,6 +1998,7 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm ggml_compute_forward_fill(params, tensor); } break; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { ggml_compute_forward_flash_attn_ext(params, tensor); } break; @@ -2396,6 +2397,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_ARGSORT: case GGML_OP_TOP_K: case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: case GGML_OP_FLASH_ATTN_BACK: case GGML_OP_SSM_CONV: case GGML_OP_SSM_SCAN: @@ -2944,6 +2946,7 @@ struct ggml_cplan ggml_graph_plan( cur += sizeof(int32_t)*node->src[0]->ne[0]*n_tasks; } break; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { const int64_t neq2 = node->src[0]->ne[2]; // number of query heads const int64_t DK = node->src[1]->ne[0]; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 42ec809ce521..ba8e8c69bd8a 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8332,10 +8332,11 @@ template struct cmp_argsort { const float * data; bool operator()(int32_t a, int32_t b) const { + // ties must resolve to the lower id (MoE routers); std::sort is unstable if constexpr (order == GGML_SORT_ORDER_ASC) { - return data[a] < data[b]; + return data[a] < data[b] || (data[a] == data[b] && a < b); } else { - return data[a] > data[b]; + return data[a] > data[b] || (data[a] == data[b] && a < b); } } }; @@ -8404,7 +8405,8 @@ void ggml_compute_forward_argsort( struct cmp_top_k { const float * data; bool operator()(int32_t a, int32_t b) const { - return data[a] > data[b]; + // ties must resolve to the lower id so the selected set matches the CUDA backend + return data[a] > data[b] || (data[a] == data[b] && a < b); } }; @@ -8465,6 +8467,30 @@ void ggml_compute_forward_top_k( } } +static inline float ggml_flash_attn_ext_banded_load( + const ggml_tensor * rel, + int64_t iq1, + int64_t iq2, + int64_t iq3, + int64_t rel_idx) { + const char * ptr = (const char *) rel->data + + (size_t) rel_idx * rel->nb[0] + + (size_t) iq2 * rel->nb[1] + + (size_t) iq1 * rel->nb[2] + + (size_t) (iq3 % rel->ne[3]) * rel->nb[3]; + + switch (rel->type) { + case GGML_TYPE_F32: + return *(const float *) ptr; + case GGML_TYPE_F16: + return GGML_CPU_FP16_TO_FP32(*(const ggml_fp16_t *) ptr); + case GGML_TYPE_BF16: + return GGML_BF16_TO_FP32(*(const ggml_bf16_t *) ptr); + default: + GGML_ABORT("banded flash attention: unsupported rel_logits type"); + } +} + static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_compute_params * params, ggml_tensor * dst, @@ -8478,6 +8504,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_tensor * v = dst->src[2]; const ggml_tensor * mask = dst->src[3]; const ggml_tensor * sinks = dst->src[4]; + const ggml_tensor * rel = dst->src[5]; GGML_TENSOR_LOCALS(int64_t, neq, q, ne) GGML_TENSOR_LOCALS(size_t, nbq, q, nb) @@ -8606,6 +8633,14 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( s = logit_softcap*tanhf(s); } + if (rel) { + // the offset aligns a short decode Q block to the tail of K (FA4 seqlen_k - seqlen_q convention) + const int64_t rel_dist = iq1 + (nek1 - neq1) - ic; + if (rel_dist >= 0 && rel_dist < rel->ne[0]) { + s += ggml_flash_attn_ext_banded_load(rel, iq1, iq2, iq3, rel_dist); + } + } + s += mv; // apply mask const float Mold = M; @@ -9070,6 +9105,7 @@ static void ggml_compute_forward_flash_attn_ext_f16( const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; + const ggml_tensor * rel = dst->src[5]; GGML_TENSOR_LOCALS(int64_t, neq, q, ne) GGML_TENSOR_LOCALS(size_t, nbq, q, nb) @@ -9169,7 +9205,7 @@ static void ggml_compute_forward_flash_attn_ext_f16( const int64_t dr = (nr + nchunk - 1) / nchunk; static constexpr int64_t Q_TILE_SZ = ggml_fa_tile_config::Q; - bool use_tiled = !use_ref && + bool use_tiled = !use_ref && rel == nullptr && (q->type == GGML_TYPE_F32 && kv_is_f32_or_f16 && k->type == v->type && diff --git a/ggml/src/ggml-cuda/argsort.cu b/ggml/src/ggml-cuda/argsort.cu index 26af90025972..0352e6baca06 100644 --- a/ggml/src/ggml-cuda/argsort.cu +++ b/ggml/src/ggml-cuda/argsort.cu @@ -163,6 +163,22 @@ static inline __device__ void ggml_cuda_swap(T & a, T & b) { b = tmp; } +// true if ia sorts after ib; padded indices sink to the end, ties break to the lower index (matches CPU cmp_argsort) +template +static inline __device__ bool argsort_ranks_after(const float * x_row, int ia, int ib, int ncols) { + const bool a_pad = ia >= ncols; + const bool b_pad = ib >= ncols; + if (a_pad || b_pad) { + return a_pad && (!b_pad || ia > ib); + } + const float xa = x_row[ia]; + const float xb = x_row[ib]; + if (xa != xb) { + return order == GGML_SORT_ORDER_ASC ? (xa > xb) : (xa < xb); + } + return ia > ib; +} + template static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int ncols, int ncols_pad) { // bitonic sort @@ -186,19 +202,11 @@ static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int n int ixj = col ^ j; if (ixj > col) { if ((col & k) == 0) { - if (dst_row[col] >= ncols || - (dst_row[ixj] < ncols && (order == GGML_SORT_ORDER_ASC ? - x_row[dst_row[col]] > x_row[dst_row[ixj]] : - x_row[dst_row[col]] < x_row[dst_row[ixj]])) - ) { + if (argsort_ranks_after(x_row, dst_row[col], dst_row[ixj], ncols)) { ggml_cuda_swap(dst_row[col], dst_row[ixj]); } } else { - if (dst_row[ixj] >= ncols || - (dst_row[col] < ncols && (order == GGML_SORT_ORDER_ASC ? - x_row[dst_row[col]] < x_row[dst_row[ixj]] : - x_row[dst_row[col]] > x_row[dst_row[ixj]])) - ) { + if (argsort_ranks_after(x_row, dst_row[ixj], dst_row[col], ncols)) { ggml_cuda_swap(dst_row[col], dst_row[ixj]); } } diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu new file mode 100644 index 000000000000..98458ae86860 --- /dev/null +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -0,0 +1,247 @@ +#include "common.cuh" +#include "fattn-banded.cuh" +#include "fattn.cuh" + +#include + +static __device__ __forceinline__ float fattn_banded_load( + const char * ptr, const int type) { + switch (type) { + case GGML_TYPE_F32: + return *(const float *) ptr; + case GGML_TYPE_F16: + return __half2float(*(const half *) ptr); + case GGML_TYPE_BF16: { + // Read BF16 as raw bits so this kernel needs no native BF16 support; all math stays FP32. + const uint32_t bits = uint32_t(*(const uint16_t *) ptr) << 16; + return __uint_as_float(bits); + } + default: + return 0.0f; + } +} + +template +static __global__ void flash_attn_ext_banded_f32( + const char * __restrict__ q, + const char * __restrict__ k, + const char * __restrict__ v, + const char * __restrict__ mask, + const char * __restrict__ rel, + float * __restrict__ dst, + float scale, + int type_k, + int type_v, + int type_rel, + int64_t n_q, + int64_t n_kv, + int64_t n_head_q, + int64_t n_head_kv, + int64_t n_batch, + int64_t rel_extent, + int64_t mask_ne2, + int64_t mask_ne3, + uint64_t q_nb1, + uint64_t q_nb2, + uint64_t q_nb3, + uint64_t k_nb0, + uint64_t k_nb1, + uint64_t k_nb2, + uint64_t k_nb3, + uint64_t v_nb0, + uint64_t v_nb1, + uint64_t v_nb2, + uint64_t v_nb3, + uint64_t m_nb1, + uint64_t m_nb2, + uint64_t m_nb3, + uint64_t r_nb0, + uint64_t r_nb1, + uint64_t r_nb2, + uint64_t r_nb3, + int64_t rel_ne3) { + constexpr int values_per_lane = D / WARP_SIZE; + static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); + static_assert(D % WARP_SIZE == 0, "head dimension must be divisible by warp size"); + + const int lane = threadIdx.x % WARP_SIZE; + const int warp = threadIdx.x / WARP_SIZE; + const int64_t iq = int64_t(blockIdx.x) * WARPS_PER_BLOCK + warp; + const int64_t ih = blockIdx.y; + const int64_t ib = blockIdx.z; + + if (iq >= n_q || ih >= n_head_q || ib >= n_batch) { + return; + } + + const int64_t ih_kv = ih / (n_head_q / n_head_kv); + const char * q_row = q + uint64_t(iq)*q_nb1 + uint64_t(ih)*q_nb2 + uint64_t(ib)*q_nb3; + + float q_reg[values_per_lane]; + float out[values_per_lane]; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + q_reg[j] = *(const float *)(q_row + uint64_t(d)*sizeof(float)); + out[j] = 0.0f; + } + + float row_max = -INFINITY; + float row_sum = 0.0f; + const int64_t q_offset = n_kv - n_q; + + for (int64_t ik = 0; ik < n_kv; ++ik) { + const char * k_row = k + uint64_t(ik)*k_nb1 + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; + float dot = 0.0f; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + dot += q_reg[j] * fattn_banded_load(k_row + uint64_t(d)*k_nb0, type_k); + } + dot = warp_reduce_sum(dot); + + float score = dot * scale; + if (lane == 0) { + const int64_t rel_dist = iq + q_offset - ik; + if (rel_dist >= 0 && rel_dist < rel_extent) { + const char * rel_value = rel + + uint64_t(rel_dist)*r_nb0 + uint64_t(ih)*r_nb1 + + uint64_t(iq)*r_nb2 + uint64_t(ib % rel_ne3)*r_nb3; + score += fattn_banded_load(rel_value, type_rel); + } + if (mask) { + const char * mask_value = mask + uint64_t(ik)*sizeof(half) + + uint64_t(iq)*m_nb1 + uint64_t(ih % mask_ne2)*m_nb2 + + uint64_t(ib % mask_ne3)*m_nb3; + score += __half2float(*(const half *) mask_value); + } + } + score = __shfl_sync(0xffffffff, score, 0, WARP_SIZE); + + if (score == -INFINITY) { + continue; + } + + float old_scale = 1.0f; + float value_scale = 1.0f; + if (score > row_max) { + old_scale = expf(row_max - score); + row_max = score; + } else { + value_scale = expf(score - row_max); + } + + const char * v_row = v + uint64_t(ik)*v_nb1 + uint64_t(ih_kv)*v_nb2 + uint64_t(ib)*v_nb3; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + const float vv = fattn_banded_load(v_row + uint64_t(d)*v_nb0, type_v); + out[j] = out[j]*old_scale + vv*value_scale; + } + row_sum = row_sum*old_scale + value_scale; + } + + const float inv_sum = row_sum == 0.0f ? 0.0f : 1.0f/row_sum; + float * dst_row = dst + ((ib*n_q + iq)*n_head_q + ih)*D; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + dst_row[d] = out[j]*inv_sum; + } +} + +static bool fattn_banded_type_supported(ggml_type type) { + return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; +} + +bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * dst) { + GGML_UNUSED(device); +#if defined(GGML_USE_MUSA) + GGML_UNUSED(dst); + return false; +#else + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { + return false; + } + + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * m = dst->src[3]; + const ggml_tensor * rel = dst->src[5]; + if (!q || !k || !v || !rel || q->type != GGML_TYPE_F32) { + return false; + } + if (!fattn_banded_type_supported(k->type) || + !fattn_banded_type_supported(v->type) || + !fattn_banded_type_supported(rel->type)) { + return false; + } + if ((q->ne[0] != 64 && q->ne[0] != 128) || v->ne[0] != q->ne[0] || k->ne[0] != q->ne[0]) { + return false; + } + if (q->ne[2] % k->ne[2] != 0 || q->ne[2] % v->ne[2] != 0 || k->ne[2] != v->ne[2]) { + return false; + } + if (q->ne[3] != k->ne[3] || q->ne[3] != v->ne[3]) { + return false; + } + if (q->nb[0] != sizeof(float) || k->nb[0] != ggml_type_size(k->type) || + v->nb[0] != ggml_type_size(v->type) || rel->nb[0] != ggml_type_size(rel->type)) { + return false; + } + if (rel->ne[0] <= 0 || rel->ne[1] != q->ne[2] || rel->ne[2] != q->ne[1] || + (rel->ne[3] != 1 && rel->ne[3] != q->ne[3])) { + return false; + } + return !m || (m->type == GGML_TYPE_F16 && ggml_is_contiguous(m) && + q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0); +#endif +} + +void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + GGML_ASSERT(ggml_cuda_flash_attn_ext_banded_supported(ctx.device, dst)); + + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * m = dst->src[3]; + const ggml_tensor * rel = dst->src[5]; + + // route F16/BF16 K/V to the MMA kernel; keep this FP32 kernel for mixed types and strided rel + if (k->type != GGML_TYPE_F32 && v->type != GGML_TYPE_F32 && + rel->type == GGML_TYPE_F32 && ggml_is_contiguous(rel) && + // MMA ABI indexes rel by Q's batch: a singleton rel batch must take the stride-aware fallback + rel->ne[3] == q->ne[3] && rel->ne[0] <= (1 << 20)) { + ggml_cuda_flash_attn_ext(ctx, dst); + return; + } + + float scale; + memcpy(&scale, dst->op_params, sizeof(scale)); + // the tensor extent (not op_params) is authoritative after graph cloning + const int64_t rel_extent = rel->ne[0]; + + constexpr int warps_per_block = 4; + const dim3 blocks((q->ne[1] + warps_per_block - 1) / warps_per_block, q->ne[2], q->ne[3]); + const dim3 threads(warps_per_block * WARP_SIZE, 1, 1); + cudaStream_t stream = ctx.stream(); + +#define LAUNCH_BANDED(D) \ + flash_attn_ext_banded_f32<<>>( \ + (const char *) q->data, (const char *) k->data, (const char *) v->data, \ + m ? (const char *) m->data : nullptr, (const char *) rel->data, (float *) dst->data, \ + scale, k->type, v->type, rel->type, q->ne[1], k->ne[1], q->ne[2], k->ne[2], q->ne[3], \ + rel_extent, m ? m->ne[2] : 1, m ? m->ne[3] : 1, \ + q->nb[1], q->nb[2], q->nb[3], k->nb[0], k->nb[1], k->nb[2], k->nb[3], \ + v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ + m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]) + + if (q->ne[0] == 64) { + LAUNCH_BANDED(64); + } else { + LAUNCH_BANDED(128); + } +#undef LAUNCH_BANDED +} diff --git a/ggml/src/ggml-cuda/fattn-banded.cuh b/ggml/src/ggml-cuda/fattn-banded.cuh new file mode 100644 index 000000000000..bb56b8986720 --- /dev/null +++ b/ggml/src/ggml-cuda/fattn-banded.cuh @@ -0,0 +1,7 @@ +#pragma once + +#include "common.cuh" + +void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index e67cc7fdf784..b07a0122db09 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -52,7 +52,7 @@ struct ggml_cuda_flash_attn_ext_f16_extra_data { static inline ggml_cuda_flash_attn_ext_f16_extra_data ggml_cuda_flash_attn_ext_get_f16_extra_data( const ggml_tensor * dst, const bool need_f16_K, const bool need_f16_V) { - GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT || dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const ggml_tensor * K = dst->src[1]; const ggml_tensor * V = dst->src[2]; @@ -983,7 +983,8 @@ void launch_fattn( const bool V_is_K_view = V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs)); const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; + const ggml_tensor * rel = dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED ? dst->src[5] : nullptr; + const ggml_tensor * sinks = rel ? rel : dst->src[4]; ggml_tensor * KQV = dst; @@ -1192,6 +1193,13 @@ void launch_fattn( memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float)); + // banded op reuses the MMA ABI: negative max_bias tags the branch, sinks_ptr carries rel_logits, -max_bias is E + if (rel) { + GGML_ASSERT(rel->type == GGML_TYPE_F32 && ggml_is_contiguous(rel)); + GGML_ASSERT(rel->ne[0] <= (1 << 20)); // exactly representable in float + max_bias = -float(rel->ne[0]); + } + if (logit_softcap != 0.0f) { scale /= logit_softcap; } @@ -1199,8 +1207,9 @@ void launch_fattn( const uint32_t n_head = Q->ne[2]; const uint32_t n_head_log2 = 1u << uint32_t(floorf(log2f(float(n_head)))); - const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + // m0/m1 are unused for banded bias; the negative tag would otherwise blow up the exponent + const float m0 = rel ? 1.0f : powf(2.0f, -(max_bias ) / n_head_log2); + const float m1 = rel ? 1.0f : powf(2.0f, -(max_bias / 2.0f) / n_head_log2); // TODO other tensor dimensions after removal of WMMA kernel: const uint3 ne01 = init_fastdiv_values(Q->ne[1]); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 7f4cfd5511ff..f6db6a79b24a 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -535,13 +535,17 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( const half2 * const __restrict__ K_h2, const half2 * const __restrict__ V_h2, const half * const __restrict__ mask_h, + const float * const __restrict__ rel_f, float2 * const __restrict__ dstk, float2 * const __restrict__ dstk_fixup, const float scale, const float slope, const float logit_softcap, + const int rel_extent, + const int head_q0, const uint3 ne01, const int ne02, + const int ne11, const int stride_K, const int stride_V, const int stride_mask, @@ -688,10 +692,42 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( #pragma unroll for (int col = 0; col < cols_per_thread; ++col) { KQ_max_new[col] = KQ_max[col]; + // The fp16 VKQ accumulator holds the still-unnormalized sum of softmax weights times V. + // With large-magnitude V (~1e3) it overflows after a few thousand KV positions even though + // all inputs are finite. Gated on rel_f so only the banded op (whose V is that large) pays + // for it. When the per-thread partial row sum of weights gets large, force + // the running maximum up: the regular rescale below then shrinks the accumulator, row sum, + // and all further weights by 2^-8, which the final normalization cancels exactly. The bump + // reaches all threads sharing the column via the KQ_max_new warp reduction, and re-triggers + // only after the row sum regrows 256x, so the number of bumps is logarithmic in n_kv. + if (rel_f && KQ_rowsum[col] > 4.0f) { + KQ_max_new[col] += 8.0f*0.6931f; + } } float KQ_rowsum_add[cols_per_thread] = {0.0f}; if constexpr (cols_per_warp == 8) { + if (rel_f) { +#pragma unroll + for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::I) { + const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::I; +#pragma unroll + for (int l = 0; l < T_C_KQ::ne; ++l) { + const int i = i0 + T_C_KQ::get_i(l); + const int jc = (threadIdx.y / np)*T_C_KQ::J + T_C_KQ::get_j(l); + const int j = jc / ncols2; + const int c = jc % ncols2; + const int64_t q_idx = int64_t(jt)*ncols1 + j; + const int64_t kv_idx = int64_t(k_VKQ_0) + i; + const int64_t dist = q_idx + (int64_t(ne11) - ne01.z) - kv_idx; + if (q_idx < ne01.z && head_q0 + c < ne02 && kv_idx < ne11 && + dist >= 0 && dist < rel_extent) { + KQ_C[i00/(np*T_C_KQ::I)].x[l] += + rel_f[(q_idx*ne02 + head_q0 + c)*rel_extent + dist]; + } + } + } + } if (ncols2 > 1 || mask_h) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::I) { @@ -754,6 +790,27 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } } } else { // not Turing mma or T_B_KQ::I > 8 + if (rel_f) { +#pragma unroll + for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::J) { + const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::J; +#pragma unroll + for (int l = 0; l < T_C_KQ::ne; ++l) { + const int i = i0 + T_C_KQ::get_j(l); + const int jc = (threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l); + const int j = jc / ncols2; + const int c = jc % ncols2; + const int64_t q_idx = int64_t(jt)*ncols1 + j; + const int64_t kv_idx = int64_t(k_VKQ_0) + i; + const int64_t dist = q_idx + (int64_t(ne11) - ne01.z) - kv_idx; + if (q_idx < ne01.z && head_q0 + c < ne02 && kv_idx < ne11 && + dist >= 0 && dist < rel_extent) { + KQ_C[i00/(np*T_C_KQ::J)].x[l] += + rel_f[(q_idx*ne02 + head_q0 + c)*rel_extent + dist]; + } + } + } + } if (ncols2 > 1 || mask_h) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::J) { @@ -1015,8 +1072,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } } #else - GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, dstk, dstk_fixup, - scale, slope, logit_softcap, ne01, ne02, + GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, rel_f, dstk, dstk_fixup, + scale, slope, logit_softcap, rel_extent, head_q0, ne01, ne02, ne11, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, kb0); @@ -1120,11 +1177,14 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( const half2 * const __restrict__ V_h2, const half * const __restrict__ mask_h, const float * const __restrict__ sinks_f, + const float * const __restrict__ rel_f, float2 * const __restrict__ dstk, float2 * const __restrict__ dstk_fixup, const float scale, const float slope, const float logit_softcap, + const int rel_extent, + const int head_q0, const uint3 ne01, const int ne02, const int gqa_ratio, @@ -1278,8 +1338,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, + (Q_f2, K_h2, V_h2, mask_h, rel_f, dstk, dstk_fixup, scale, slope, logit_softcap, + rel_extent, head_q0, ne01, ne02, ne11, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); } constexpr bool last_iter = true; @@ -1287,8 +1347,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, + (Q_f2, K_h2, V_h2, mask_h, rel_f, dstk, dstk_fixup, scale, slope, logit_softcap, + rel_extent, head_q0, ne01, ne02, ne11, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); } else { constexpr bool oob_check = false; @@ -1298,8 +1358,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, + (Q_f2, K_h2, V_h2, mask_h, rel_f, dstk, dstk_fixup, scale, slope, logit_softcap, + rel_extent, head_q0, ne01, ne02, ne11, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); } constexpr bool last_iter = true; @@ -1307,8 +1367,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( flash_attn_ext_f16_iter - (Q_f2, K_h2, V_h2, mask_h, dstk, dstk_fixup, scale, slope, logit_softcap, - ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, + (Q_f2, K_h2, V_h2, mask_h, rel_f, dstk, dstk_fixup, scale, slope, logit_softcap, + rel_extent, head_q0, ne01, ne02, ne11, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, k_VKQ_sup); } @@ -1692,8 +1752,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( } } #else - GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, sinks_f, dstk, dstk_fixup, - scale, slope, logit_softcap, ne01, ne02, gqa_ratio, + GGML_UNUSED_VARS(Q_f2, K_h2, V_h2, mask_h, sinks_f, rel_f, dstk, dstk_fixup, + scale, slope, logit_softcap, rel_extent, head_q0, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, kb0_start, kb0_stop); NO_DEVICE_CODE; @@ -1734,6 +1794,8 @@ static __global__ void flash_attn_ext_f16( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; + const bool banded_bias = max_bias < 0.0f; + const int rel_extent = banded_bias ? int(-max_bias) : 0; // Skip unused kernel variants for faster compilation: if (use_logit_softcap && !(DKQ == 128 || DKQ == 256 || DKQ == 512)) { @@ -1819,9 +1881,12 @@ static __global__ void flash_attn_ext_f16( float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; + const float * sinks_f = sinks && !banded_bias ? (const float *) sinks + zt_Q : nullptr; + const float * rel_f = banded_bias ? + (const float *) sinks + int64_t(sequence)*ne01.z*ne02*rel_extent : nullptr; - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + const float slope = banded_bias ? 1.0f : + (ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f); if (KV_max) { kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); @@ -1830,13 +1895,13 @@ static __global__ void flash_attn_ext_f16( if (kb0_start == 0) { constexpr bool needs_fixup = false; // CUDA block is working on an entire tile. flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); + (Q_f2, K_h2, V_h2, mask_h, sinks_f, rel_f, dstk, dst_meta, scale, slope, logit_softcap, + rel_extent, zt_Q, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); } else { constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile. flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); + (Q_f2, K_h2, V_h2, mask_h, sinks_f, rel_f, dstk, dst_meta, scale, slope, logit_softcap, + rel_extent, zt_Q, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); } kbc += iter_k; @@ -1865,9 +1930,12 @@ static __global__ void flash_attn_ext_f16( float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; + const float * sinks_f = sinks && !banded_bias ? (const float *) sinks + zt_Q : nullptr; + const float * rel_f = banded_bias ? + (const float *) sinks + int64_t(sequence)*ne01.z*ne02*rel_extent : nullptr; - const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f; + const float slope = banded_bias ? 1.0f : + (ncols2 == 1 ? get_alibi_slope(max_bias, zt_Q, n_head_log2, m0, m1) : 1.0f); if (KV_max) { kb0_stop = min(kb0_stop, KV_max[sequence*iter_j + jt] / nbatch_fa); @@ -1876,8 +1944,8 @@ static __global__ void flash_attn_ext_f16( constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. constexpr bool needs_fixup = false; flash_attn_ext_f16_process_tile - (Q_f2, K_h2, V_h2, mask_h, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); + (Q_f2, K_h2, V_h2, mask_h, sinks_f, rel_f, dstk, dst_meta, scale, slope, logit_softcap, + rel_extent, zt_Q, ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_start, kb0_stop); #else GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, dst_ptr, dst_meta_ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 00ffacf29921..5d51a956d4f2 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -392,6 +392,14 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const const int cc = ggml_cuda_info().devices[device].cc; + // banded bias lives in the F16 MMA loop; F32 K/V keeps the dedicated FP32 warp kernel + if (dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED && + dst->src[5]->type == GGML_TYPE_F32 && K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && + dst->src[5]->ne[3] == Q->ne[3] && + turing_mma_available(cc) && (Q->ne[0] == 64 || Q->ne[0] == 128) && V->ne[0] == Q->ne[0]) { + return BEST_FATTN_KERNEL_MMA_F16; + } + switch (K->ne[0]) { case 40: case 64: @@ -544,7 +552,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const } size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) { - GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT(dst->op == GGML_OP_FLASH_ATTN_EXT || dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const ggml_tensor * K = dst->src[1]; const ggml_tensor * V = dst->src[2]; diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 4aaa4f367afc..0dbb38a26f2a 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -25,6 +25,7 @@ #include "ggml-cuda/diagmask.cuh" #include "ggml-cuda/diag.cuh" #include "ggml-cuda/fattn.cuh" +#include "ggml-cuda/fattn-banded.cuh" #include "ggml-cuda/fwht.cuh" #include "ggml-cuda/getrows.cuh" #include "ggml-cuda/im2col.cuh" @@ -906,7 +907,7 @@ static size_t ggml_backend_cuda_buffer_type_get_alignment(ggml_backend_buffer_ty static size_t ggml_backend_cuda_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { ggml_backend_cuda_buffer_type_context * buft_ctx = (ggml_backend_cuda_buffer_type_context *) buft->context; - size_t size = tensor->op == GGML_OP_FLASH_ATTN_EXT + size_t size = (tensor->op == GGML_OP_FLASH_ATTN_EXT || tensor->op == GGML_OP_FLASH_ATTN_EXT_BANDED) ? ggml_cuda_flash_attn_ext_get_alloc_size(buft_ctx->device, tensor) : ggml_nbytes(tensor); int64_t ne0 = tensor->ne[0]; @@ -1496,6 +1497,9 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const size_t nbd2 = dst->nb[2]; size_t nbd3 = dst->nb[3]; + const bool f32_pedantic = compute_type == GGML_TYPE_F32 && + src0->type == GGML_TYPE_F32 && ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC; + cublasComputeType_t cu_compute_type = traits::compute_type; cudaDataType_t cu_data_type = traits::data_type; cudaDataType_t cu_data_type_a = traits::data_type; @@ -1527,6 +1531,18 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const } } + if (f32_pedantic) { +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11020 + cu_compute_type = CUBLAS_COMPUTE_32F_PEDANTIC; +#else + // no pedantic compute enum here; ordinary F32 is the strongest available contract + cu_compute_type = CUBLAS_COMPUTE_32F; +#endif + } + + const auto cu_gemm_algo = f32_pedantic ? + CUBLAS_GEMM_DEFAULT : CUBLAS_GEMM_DEFAULT_TENSOR_OP; + GGML_ASSERT(ne12 % ne02 == 0); GGML_ASSERT(ne13 % ne03 == 0); @@ -1538,12 +1554,23 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const // However, for some old NVIDIA and AMD GPUs the strided/Ex GEMM is much slower, // probably because the internal kernel selection logic is suboptimal. if (compute_type == GGML_TYPE_F32 && ne12 == 1 && ne13 == 1) { - CUBLAS_CHECK( - cublasSgemm(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N, - ne01, ne11, ne10, - (const float *) alpha, (const float *) src0_ptr, s01, - (const float *) src1_ptr, s11, - (const float *) beta, (float *) dst_ptr, ne0)); + if (f32_pedantic) { + CUBLAS_CHECK( + cublasGemmEx(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N, + ne01, ne11, ne10, + alpha, src0_ptr, CUDA_R_32F, s01, + src1_ptr, CUDA_R_32F, s11, + beta, dst_ptr, CUDA_R_32F, ne0, + cu_compute_type, + cu_gemm_algo)); + } else { + CUBLAS_CHECK( + cublasSgemm(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N, + ne01, ne11, ne10, + (const float *) alpha, (const float *) src0_ptr, s01, + (const float *) src1_ptr, s11, + (const float *) beta, (float *) dst_ptr, ne0)); + } } else if (ne12 == 1 && ne13 == 1) { CUBLAS_CHECK( cublasGemmEx(ctx.cublas_handle(), CUBLAS_OP_T, CUBLAS_OP_N, @@ -1552,7 +1579,7 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const src1_ptr, cu_data_type_b, s11, beta, dst_ptr, cu_data_type, ne0, cu_compute_type, - CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + cu_gemm_algo)); } else if (r2 == 1 && r3 == 1 && is_src0_cont_2 && is_src1_cont_2) { // with a [0, 2, 1, 3] perm. and ne02==1 the matrix strides need to be determined from dim 3: const int64_t sma = ne02 == 1 ? s03 : s02; @@ -1568,7 +1595,7 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const beta, dst_ptr, cu_data_type, ne0, ne1*ne0, // strideC ne12*ne13, cu_compute_type, - CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + cu_gemm_algo)); } else { // use cublasGemmBatchedEx const int64_t ne23 = ne12*ne13; @@ -1606,7 +1633,7 @@ static void ggml_cuda_mul_mat_cublas_impl(ggml_backend_cuda_context & ctx, const beta, ( void **) (ptrs_dst.get() + 0*ne23), cu_data_type, ne0, ne23, cu_compute_type, - CUBLAS_GEMM_DEFAULT_TENSOR_OP)); + cu_gemm_algo)); } // Convert output back to F32 if needed @@ -1644,6 +1671,11 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml } } + // a scoped pedantic request overrides the process-wide compute type, for F32 weights only + if (src0->type == GGML_TYPE_F32 && ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC) { + compute_type = GGML_TYPE_F32; + } + switch (compute_type) { case GGML_TYPE_F32: ggml_cuda_mul_mat_cublas_impl(ctx, src0, src1, dst); @@ -1829,6 +1861,8 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor const int cc = ggml_cuda_info().devices[ctx.device].cc; const int warp_size = ggml_cuda_info().devices[ctx.device].warp_size; + const bool f32_pedantic = src0->type == GGML_TYPE_F32 && + ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC; if (ggml_cuda_should_use_mmvf(src0->type, cc, src0->ne, src0->nb, ne11)) { // The custom F16 vector kernel can be used over batched cuBLAS GEMM. @@ -1836,7 +1870,8 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor ggml_cuda_mul_mat_vec_f(ctx, src0, src1, nullptr, dst); return; } - if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) { + if (!f32_pedantic && ggml_cuda_should_use_mmf( + src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) { ggml_cuda_mul_mat_f(ctx, src0, src1, nullptr, dst); return; } @@ -1862,6 +1897,8 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * GGML_TENSOR_BINARY_OP_LOCALS const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + const bool f32_pedantic = src0->type == GGML_TYPE_F32 && + ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC; // [TAG_MUL_MAT_ID_CUDA_GRAPHS] if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { @@ -1886,7 +1923,8 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * return; } - if (ggml_cuda_should_use_mmf(src0->type, cc, WARP_SIZE, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { + if (!f32_pedantic && ggml_cuda_should_use_mmf( + src0->type, cc, WARP_SIZE, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { ggml_cuda_mul_mat_f(ctx, src0, src1, ids, dst); return; } @@ -1994,6 +2032,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst_slice.nb[2] = dst_slice.ne[1] * dst_slice.nb[1]; dst_slice.nb[3] = dst_slice.ne[2] * dst_slice.nb[2]; dst_slice.data = dst_data_cur; + dst_slice.op_params[0] = dst->op_params[0]; ggml_cuda_mul_mat(ctx, &src0_slice, &src1_slice, &dst_slice); CUDA_CHECK(cudaGetLastError()); @@ -2305,6 +2344,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg case GGML_OP_FLASH_ATTN_EXT: ggml_cuda_flash_attn_ext(ctx, dst); break; + case GGML_OP_FLASH_ATTN_EXT_BANDED: + ggml_cuda_flash_attn_ext_banded(ctx, dst); + break; case GGML_OP_CROSS_ENTROPY_LOSS: ggml_cuda_cross_entropy_loss(ctx, dst); break; @@ -5110,6 +5152,8 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g op->type == GGML_TYPE_F32; case GGML_OP_FLASH_ATTN_EXT: return ggml_cuda_flash_attn_ext_supported(dev_ctx->device, op); + case GGML_OP_FLASH_ATTN_EXT_BANDED: + return ggml_cuda_flash_attn_ext_banded_supported(dev_ctx->device, op); case GGML_OP_CROSS_ENTROPY_LOSS: case GGML_OP_CROSS_ENTROPY_LOSS_BACK: case GGML_OP_OPT_STEP_ADAMW: diff --git a/ggml/src/ggml-cuda/mmf.cuh b/ggml/src/ggml-cuda/mmf.cuh index d55cc1ec7b52..8b2be232ec9b 100644 --- a/ggml/src/ggml-cuda/mmf.cuh +++ b/ggml/src/ggml-cuda/mmf.cuh @@ -110,9 +110,9 @@ static __global__ void mul_mat_f( 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); + x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x)*stride_channel_x + int64_t(row0)*stride_row; + y += int64_t(sample_y) *stride_sample_y + (has_ids ? 0 : int64_t(channel_y) *stride_channel_y); + dst += int64_t(sample_dst)*stride_sample_dst + (has_ids ? 0 : int64_t(channel_dst)*stride_channel_dst); if constexpr (has_ids) { constexpr int y_stride_scale = std::is_same_v ? 1 : 2; @@ -362,7 +362,7 @@ static __global__ void mul_mat_f_ids( 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; + x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x)*stride_channel_x + int64_t(row0)*stride_row; y += int64_t(sample_y) *stride_sample_y; dst += int64_t(sample_dst)*stride_sample_dst; diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index ad3d6a5a6832..d7f22f1e759c 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -434,7 +434,7 @@ template static __device__ __forceinline_ continue; } - dst[ids_dst[j]*stride + i] = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size]; + dst[(int64_t) ids_dst[j]*stride + i] = sum[(j0/nwarps) * (I/warp_size) + i0/warp_size]; } } } @@ -475,7 +475,7 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma( continue; } - dst[ids_dst[j]*stride + i] = sum[(j0/tile_C::J + n)*tile_C::ne + l]; + dst[(int64_t) ids_dst[j]*stride + i] = sum[(j0/tile_C::J + n)*tile_C::ne + l]; } } } @@ -944,7 +944,7 @@ static __global__ void mul_mat_q( int col_high = ncols_dst; int col_diff = ncols_dst; int offset_y = wt*stride_sample_y + zt*stride_channel_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) { col_low = expert_bounds[zt + 0]; @@ -1017,7 +1017,7 @@ static __global__ void mul_mat_q( int col_high = ncols_dst; int col_diff = ncols_dst; int offset_y = wt*stride_sample_y + zt*stride_channel_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) { col_low = expert_bounds[zt + 0]; @@ -1091,7 +1091,7 @@ static __global__ void mul_mat_q( int col_high = ncols_dst; int col_diff = ncols_dst; int offset_y = wt*stride_sample_y + zt*stride_channel_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) { col_low = expert_bounds[zt + 0]; @@ -1219,7 +1219,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 + (int64_t) it*I; dst += offset_dst; const int i_max = nrows_x - it*I - 1; diff --git a/ggml/src/ggml-cuda/mmvf.cu b/ggml/src/ggml-cuda/mmvf.cu index d7dbc8b99282..bbf862b3f5d7 100644 --- a/ggml/src/ggml-cuda/mmvf.cu +++ b/ggml/src/ggml-cuda/mmvf.cu @@ -44,7 +44,7 @@ static __global__ void mul_mat_vec_f( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); - x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row*stride_row; + x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x)*stride_channel_x + int64_t(row)*stride_row; 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; if constexpr (is_multi_token_id) { @@ -81,7 +81,7 @@ static __global__ void mul_mat_vec_f( } if (use_gate) { - gate_x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row*stride_row; + gate_x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x)*stride_channel_x + int64_t(row)*stride_row; } if constexpr (has_fusion) { diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index e18ada5377d5..f62c4ebb2389 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -587,7 +587,7 @@ static __global__ void mul_mat_vec_q( float tmp_gate[ncols_dst][rows_per_cuda_block] = {{0.0f}}; const block_q8_1 * y = ((const block_q8_1 *) vy) + sample_y*stride_sample_y + channel_y*stride_channel_y; - const int kbx_offset = sample_x*stride_sample_x + channel_x*stride_channel_x + row0*stride_row_x; + const int64_t kbx_offset = int64_t(sample_x)*stride_sample_x + int64_t(channel_x)*stride_channel_x + int64_t(row0)*stride_row_x; for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { const int kby = kbx * (qk/QK8_1); // y block index that aligns with kbx @@ -739,7 +739,7 @@ static __global__ void mul_mat_vec_q_moe( const uint32_t channel_y = fastmodulo(channel_dst, nchannels_y); const block_q8_1 * y = ((const block_q8_1 *) vy) + channel_y*stride_channel_y + token_idx*stride_col_y; - const int kbx_offset = channel_x*stride_channel_x + row0*stride_row_x; + const int64_t kbx_offset = int64_t(channel_x)*stride_channel_x + int64_t(row0)*stride_row_x; // partial sum for each thread float tmp[c_rows_per_block] = {0.0f}; diff --git a/ggml/src/ggml-cuda/pad.cu b/ggml/src/ggml-cuda/pad.cu index 31cd00f77816..013bd8386e93 100644 --- a/ggml/src/ggml-cuda/pad.cu +++ b/ggml/src/ggml-cuda/pad.cu @@ -25,7 +25,7 @@ static __global__ void pad_f32(const float * src, size_t s00, size_t s01, size_t return; } - const int64_t dst_idx = i3 * (ne0 * ne1 * ne2) + i2 * (ne0 * ne1) + i1 * ne0 + i0; + const int64_t dst_idx = (int64_t) i3 * ne0 * ne1 * ne2 + (int64_t) i2 * ne0 * ne1 + (int64_t) i1 * ne0 + i0; if (!circular) { if ((i0 >= lp0 && i0 < ne0 - rp0) && (i1 >= lp1 && i1 < ne1 - rp1) && (i2 >= lp2 && i2 < ne2 - rp2) && diff --git a/ggml/src/ggml-cuda/ssm-conv.cu b/ggml/src/ggml-cuda/ssm-conv.cu index 1463169cf78b..1e09177a4172 100644 --- a/ggml/src/ggml-cuda/ssm-conv.cu +++ b/ggml/src/ggml-cuda/ssm-conv.cu @@ -5,8 +5,8 @@ template static __global__ void ssm_conv_f32(const float * src0_ptr, const float * src1_ptr, const float * bias_ptr, - const int src0_nb0, const int src0_nb1, const int src0_nb2, const int src1_nb1, - float * dst_ptr, const int dst_nb0, const int dst_nb1, const int dst_nb2, + const int64_t src0_nb0, const int64_t src0_nb1, const int64_t src0_nb2, const int64_t src1_nb1, + float * dst_ptr, const int64_t dst_nb0, const int64_t dst_nb1, const int64_t dst_nb2, const int64_t n_t) { ggml_cuda_pdl_lc(); const float * GGML_CUDA_RESTRICT src0 = src0_ptr; @@ -22,9 +22,9 @@ static __global__ void ssm_conv_f32(const float * src0_ptr, const float * src1_p const float * w_block = (const float *) ((const char *) src1 + bidy * split_d_inner * src1_nb1); float * y_block = (float *) ((char *) dst + bidx * dst_nb2 + bidy * split_d_inner * dst_nb0); - const int stride_x = src0_nb1 / sizeof(float); - const int stride_w = src1_nb1 / sizeof(float); - const int stride_y = dst_nb1 / sizeof(float); + const int64_t stride_x = src0_nb1 / sizeof(float); + const int64_t stride_w = src1_nb1 / sizeof(float); + const int64_t stride_y = dst_nb1 / sizeof(float); float x[d_conv] = { 0.0f }; float w[d_conv] = { 0.0f }; @@ -60,9 +60,9 @@ static __global__ void ssm_conv_f32(const float * src0_ptr, const float * src1_p template static __global__ void ssm_conv_long_token_f32(const float * __restrict__ src0, const float * __restrict__ src1, const float * __restrict__ bias, - const int src0_nb0, const int src0_nb1, const int src0_nb2, - const int src1_nb1, float * __restrict__ dst, const int dst_nb0, - const int dst_nb1, const int dst_nb2, const int64_t n_t) { + const int64_t src0_nb0, const int64_t src0_nb1, const int64_t src0_nb2, + const int64_t src1_nb1, float * __restrict__ dst, const int64_t dst_nb0, + const int64_t dst_nb1, const int64_t dst_nb2, const int64_t n_t) { const int tid = threadIdx.x; const int bidx = blockIdx.x; const int bidy = blockIdx.y; @@ -74,9 +74,9 @@ static __global__ void ssm_conv_long_token_f32(const float * __restrict__ src0, float * y_block = (float *) ((char *) dst + bidx * dst_nb2 + bidz * split_n_t * dst_nb1 + bidy * split_d_inner * dst_nb0); - const int stride_x = src0_nb1 / sizeof(float); - const int stride_w = src1_nb1 / sizeof(float); - const int stride_y = dst_nb1 / sizeof(float); + const int64_t stride_x = src0_nb1 / sizeof(float); + const int64_t stride_w = src1_nb1 / sizeof(float); + const int64_t stride_y = dst_nb1 / sizeof(float); const int64_t local_n_t = min(split_n_t, n_t - bidz * split_n_t); const int n_cols = d_conv - 1 + split_n_t; @@ -124,9 +124,9 @@ static __global__ void ssm_conv_long_token_f32(const float * __restrict__ src0, } template -static void ssm_conv_f32_cuda(const float * src0, const float * src1, const float * bias, const int src0_nb0, const int src0_nb1, - const int src0_nb2, const int src1_nb1, float * dst, const int dst_nb0, const int dst_nb1, - const int dst_nb2, const int64_t nc, const int64_t nr, const int64_t n_t, +static void ssm_conv_f32_cuda(const float * src0, const float * src1, const float * bias, const int64_t src0_nb0, const int64_t src0_nb1, + const int64_t src0_nb2, const int64_t src1_nb1, float * dst, const int64_t dst_nb0, const int64_t dst_nb1, + const int64_t dst_nb2, const int64_t nc, const int64_t nr, const int64_t n_t, const int64_t n_s, cudaStream_t stream) { const int threads = 128; GGML_ASSERT(nr % threads == 0); diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index d38057721834..1166178b7249 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -600,6 +600,7 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty // ops that require additional memory for fleeting data on certain backends // ref: https://github.com/ggml-org/llama.cpp/pull/15966 rpc_get |= tensor->op == GGML_OP_FLASH_ATTN_EXT; + rpc_get |= tensor->op == GGML_OP_FLASH_ATTN_EXT_BANDED; rpc_get |= tensor->op == GGML_OP_MUL_MAT_ID; if (rpc_get) { diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index a7d1fe7d94be..9c3d172a8086 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1067,6 +1067,7 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "FILL", "FLASH_ATTN_EXT", + "FLASH_ATTN_EXT_BANDED", "FLASH_ATTN_BACK", "SSM_CONV", "SSM_SCAN", @@ -1100,7 +1101,7 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "GLU", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1182,6 +1183,7 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "fill(x, c)", "flash_attn_ext(x)", + "flash_attn_ext_banded(x)", "flash_attn_back(x)", "ssm_conv(x)", "ssm_scan(x)", @@ -1215,7 +1217,7 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "glu(x)", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -5443,11 +5445,60 @@ struct ggml_tensor * ggml_flash_attn_ext( return result; } +struct ggml_tensor * ggml_flash_attn_ext_banded( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * mask, + struct ggml_tensor * rel_logits, + float scale, + int64_t rel_extent) { + GGML_ASSERT(ggml_can_mul_mat(k, q)); + GGML_ASSERT(q->type == GGML_TYPE_F32); + GGML_ASSERT(q->ne[3] == k->ne[3]); + GGML_ASSERT(q->ne[3] == v->ne[3]); + GGML_ASSERT(q->ne[2] % k->ne[2] == 0); + GGML_ASSERT(q->ne[2] % v->ne[2] == 0); + + GGML_ASSERT(rel_logits != NULL); + GGML_ASSERT(rel_logits->type == GGML_TYPE_F32 || + rel_logits->type == GGML_TYPE_F16 || + rel_logits->type == GGML_TYPE_BF16); + GGML_ASSERT(rel_extent > 0); + GGML_ASSERT(rel_logits->ne[0] == rel_extent); + GGML_ASSERT(rel_logits->ne[1] == q->ne[2]); + GGML_ASSERT(rel_logits->ne[2] == q->ne[1]); + GGML_ASSERT(rel_logits->ne[3] == 1 || rel_logits->ne[3] == q->ne[3]); + + if (mask) { + GGML_ASSERT(mask->type == GGML_TYPE_F16); + GGML_ASSERT(ggml_is_contiguous(mask)); + GGML_ASSERT(q->ne[2] % mask->ne[2] == 0); + GGML_ASSERT(q->ne[3] % mask->ne[3] == 0); + } + + int64_t ne[4] = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] }; + struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne); + + float params[] = { scale, 0.0f, 0.0f }; + ggml_set_op_params(result, params, sizeof(params)); + memcpy(result->op_params + 16, &rel_extent, sizeof(rel_extent)); + + result->op = GGML_OP_FLASH_ATTN_EXT_BANDED; + result->src[0] = q; + result->src[1] = k; + result->src[2] = v; + result->src[3] = mask; + result->src[5] = rel_logits; + + return result; +} void ggml_flash_attn_ext_set_prec( struct ggml_tensor * a, enum ggml_prec prec) { - GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT || a->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const int32_t prec_i32 = (int32_t) prec; @@ -5456,7 +5507,7 @@ void ggml_flash_attn_ext_set_prec( enum ggml_prec ggml_flash_attn_ext_get_prec( const struct ggml_tensor * a) { - GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT || a->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const int32_t prec_i32 = ggml_get_op_params_i32(a, 3); diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 63ac2ed1f5cf..71809cf21f94 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -540,6 +540,7 @@ class MODEL_ARCH(IntEnum): KIMI_LINEAR = auto() TALKIE = auto() MELLUM = auto() + INKLING = auto() class VISION_PROJECTOR_TYPE(IntEnum): @@ -763,6 +764,14 @@ class MODEL_TENSOR(IntEnum): SHORTCONV_CONV = auto() SHORTCONV_INPROJ = auto() SHORTCONV_OUTPROJ = auto() + # inkling + ATTN_R = auto() + ATTN_REL_PROJ = auto() + SHORTCONV_K = auto() + SHORTCONV_V = auto() + SHORTCONV_ATTN = auto() + SHORTCONV_MLP = auto() + FFN_GSCALE = auto() VISEXP_ATTN_QKV = auto() VISEXP_ATTN_OUT = auto() VISEXP_GATE = auto() @@ -1122,6 +1131,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KIMI_LINEAR: "kimi-linear", MODEL_ARCH.TALKIE: "talkie", MODEL_ARCH.MELLUM: "mellum", + MODEL_ARCH.INKLING: "inkling", } VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = { @@ -1343,6 +1353,13 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.SHORTCONV_CONV: "blk.{bid}.shortconv.conv", MODEL_TENSOR.SHORTCONV_INPROJ: "blk.{bid}.shortconv.in_proj", MODEL_TENSOR.SHORTCONV_OUTPROJ: "blk.{bid}.shortconv.out_proj", + MODEL_TENSOR.ATTN_R: "blk.{bid}.attn_r", # inkling + MODEL_TENSOR.ATTN_REL_PROJ: "blk.{bid}.attn_rel_proj", # inkling + MODEL_TENSOR.SHORTCONV_K: "blk.{bid}.shortconv_k", # inkling + MODEL_TENSOR.SHORTCONV_V: "blk.{bid}.shortconv_v", # inkling + MODEL_TENSOR.SHORTCONV_ATTN: "blk.{bid}.shortconv_attn", # inkling + MODEL_TENSOR.SHORTCONV_MLP: "blk.{bid}.shortconv_mlp", # inkling + MODEL_TENSOR.FFN_GSCALE: "blk.{bid}.ffn_gscale", # inkling MODEL_TENSOR.VISEXP_ATTN_QKV: "blk.{bid}.vis_attn_qkv", MODEL_TENSOR.VISEXP_ATTN_OUT: "blk.{bid}.vis_attn_output", MODEL_TENSOR.VISEXP_GATE: "blk.{bid}.vis_gate", @@ -4044,6 +4061,38 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_UP_EXP, MODEL_TENSOR.FFN_EXP_PROBS_B, ], + MODEL_ARCH.INKLING: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.TOKEN_EMBD_NORM, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_R, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_Q_NORM, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_REL_PROJ, + MODEL_TENSOR.SHORTCONV_K, + MODEL_TENSOR.SHORTCONV_V, + MODEL_TENSOR.SHORTCONV_ATTN, + MODEL_TENSOR.SHORTCONV_MLP, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_GSCALE, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_GATE_SHEXP, + MODEL_TENSOR.FFN_UP_SHEXP, + MODEL_TENSOR.FFN_DOWN_SHEXP, + ], MODEL_ARCH.SMALLTHINKER: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -4665,6 +4714,7 @@ def get_type(val: Any) -> GGUFValueType: class VisionProjectorType: + INKLING = "inkling" GEMMA3 = "gemma3" GEMMA3NV = "gemma3nv" GEMMA3NA = "gemma3na" diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index 9efb36f8a447..3fbeb2e53743 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -63,6 +63,7 @@ class TensorNameMap: "model.layers.0.pre_norm", # rwkv7 "backbone.norm", # wavtokenizer "model.embedding_norm", # lfm2 + "model.embed_norm", # inkling ), # Position embeddings @@ -86,6 +87,7 @@ class TensorNameMap: "lm_head", # llama4 "model.transformer.ff_out", # llada "head.decoder", # modern-bert + "model.unembed", # inkling ), MODEL_TENSOR.DENSE_2_OUT: ( "dense_2_out", # embeddinggemma @@ -2415,6 +2417,53 @@ class TensorNameMap: # architecture-specific block mappings arch_block_mappings_cfg: dict[MODEL_ARCH, dict[MODEL_TENSOR, tuple[str, ...]]] = { + MODEL_ARCH.INKLING: { + MODEL_TENSOR.ATTN_NORM: ( + "model.layers.{bid}.attn_norm", + ), + MODEL_TENSOR.ATTN_Q: ( + "model.layers.{bid}.attn.wq_du", + ), + MODEL_TENSOR.ATTN_K: ( + "model.layers.{bid}.attn.wk_dv", + ), + MODEL_TENSOR.ATTN_V: ( + "model.layers.{bid}.attn.wv_dv", + ), + MODEL_TENSOR.ATTN_R: ( + "model.layers.{bid}.attn.wr_du", + ), + MODEL_TENSOR.ATTN_OUT: ( + "model.layers.{bid}.attn.wo_ud", + ), + MODEL_TENSOR.ATTN_Q_NORM: ( + "model.layers.{bid}.attn.q_norm", + ), + MODEL_TENSOR.ATTN_K_NORM: ( + "model.layers.{bid}.attn.k_norm", + ), + MODEL_TENSOR.ATTN_REL_PROJ: ( + "model.layers.{bid}.attn.rel_logits_proj", + ), + MODEL_TENSOR.SHORTCONV_K: ( + "model.layers.{bid}.attn.k_sconv", + ), + MODEL_TENSOR.SHORTCONV_V: ( + "model.layers.{bid}.attn.v_sconv", + ), + MODEL_TENSOR.SHORTCONV_ATTN: ( + "model.layers.{bid}.attn_sconv", + ), + MODEL_TENSOR.SHORTCONV_MLP: ( + "model.layers.{bid}.mlp_sconv", + ), + MODEL_TENSOR.FFN_NORM: ( + "model.layers.{bid}.mlp_norm", + ), + MODEL_TENSOR.FFN_DOWN: ( + "model.layers.{bid}.mlp.w2_md", + ), + }, MODEL_ARCH.ARCTIC: { MODEL_TENSOR.FFN_NORM: ( "model.layers.{bid}.residual_layernorm", diff --git a/models/templates/Inkling.jinja b/models/templates/Inkling.jinja new file mode 100644 index 000000000000..512d92685eac --- /dev/null +++ b/models/templates/Inkling.jinja @@ -0,0 +1,514 @@ +{#- Keep Python's floating type spelling when the jinja engine compacts 1.0 to 1. -#} +{%- macro json_scalar(value) -%} + {%- set serialized = value | tojson(ensure_ascii=false, separators=(',', ':')) -%} + {%- if value is float and '.' not in serialized and 'e' not in (serialized | lower) -%} + {{- serialized -}}{{- '.0' -}} + {%- else -%} + {{- serialized -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro canonical_json(value) -%} + {%- if value is mapping -%} + {{- '{' -}} + {%- for key, item in value | dictsort(case_sensitive=true) -%} + {{- (key | string) | tojson(ensure_ascii=false, separators=(',', ':')) -}}{{- ':' -}} + {{- canonical_json(item) -}} + {%- if not loop.last -%}{{- ',' -}}{%- endif -%} + {%- endfor -%} + {{- '}' -}} + {%- elif value is sequence and value is not string -%} + {{- '[' -}} + {%- for item in value -%} + {{- canonical_json(item) -}} + {%- if not loop.last -%}{{- ',' -}}{%- endif -%} + {%- endfor -%} + {{- ']' -}} + {%- else -%} + {{- json_scalar(value) -}} + {%- endif -%} +{%- endmacro -%} + +{#- Advance across insignificant JSON whitespace. -#} +{%- macro json_skip_ws(source, state) -%} + {%- set scan = namespace(done=false) -%} + {%- for ignored in range(source | length) -%} + {%- if not scan.done and state.pos < source | length -%} + {%- set ch = source[state.pos] -%} + {%- if ch == ' ' or ch == '\t' or ch == '\r' or ch == '\n' -%} + {%- set state.pos = state.pos + 1 -%} + {%- else -%} + {%- set scan.done = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} +{%- endmacro -%} + +{#- + Decode a JSON string under Transformers, then re-encode it like json.dumps. + llama.cpp converts string arguments to objects after capability detection; + the fallback keeps engine-only parsing safe without runtime-only filters. +-#} +{%- macro json_string(source, state) -%} + {%- if lipsum is defined -%} + {%- set out = namespace(decoded='', done=false, code=0, low=0) -%} + {%- set hex_values = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15} -%} + {%- set state.pos = state.pos + 1 -%} + {%- for ignored in range(source | length) -%} + {%- if not out.done and state.pos < source | length -%} + {%- set ch = source[state.pos] -%} + {%- set state.pos = state.pos + 1 -%} + {%- if ch == '"' -%} + {%- set out.done = true -%} + {%- elif ch != '\\' -%} + {%- set out.decoded = out.decoded + ch -%} + {%- elif state.pos < source | length -%} + {%- set escape = source[state.pos] -%} + {%- set state.pos = state.pos + 1 -%} + {%- if escape == '"' -%}{%- set out.decoded = out.decoded + '"' -%} + {%- elif escape == '\\' -%}{%- set out.decoded = out.decoded + '\\' -%} + {%- elif escape == '/' -%}{%- set out.decoded = out.decoded + '/' -%} + {%- elif escape == 'b' -%}{%- set out.decoded = out.decoded + '\b' -%} + {%- elif escape == 'f' -%}{%- set out.decoded = out.decoded + '\f' -%} + {%- elif escape == 'n' -%}{%- set out.decoded = out.decoded + '\n' -%} + {%- elif escape == 'r' -%}{%- set out.decoded = out.decoded + '\r' -%} + {%- elif escape == 't' -%}{%- set out.decoded = out.decoded + '\t' -%} + {%- elif escape == 'u' -%} + {%- set out.code = 0 -%} + {%- for offset in range(4) -%} + {%- set digit = source[state.pos + offset] | lower -%} + {%- set out.code = out.code * 16 + hex_values[digit] -%} + {%- endfor -%} + {%- set state.pos = state.pos + 4 -%} + {%- if out.code >= 55296 and out.code <= 56319 and source[state.pos:state.pos + 2] == '\\u' -%} + {%- set out.low = 0 -%} + {%- for offset in range(4) -%} + {%- set digit = source[state.pos + 2 + offset] | lower -%} + {%- set out.low = out.low * 16 + hex_values[digit] -%} + {%- endfor -%} + {%- if out.low >= 56320 and out.low <= 57343 -%} + {%- set out.code = 65536 + (out.code - 55296) * 1024 + out.low - 56320 -%} + {%- set state.pos = state.pos + 6 -%} + {%- endif -%} + {%- endif -%} + {%- set out.decoded = out.decoded + ('%c' % out.code) -%} + {%- else -%} + {%- set out.decoded = out.decoded + escape -%} + {%- endif -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- set state.string_value = out.decoded -%} + {{- out.decoded | tojson(ensure_ascii=false, separators=(',', ':')) -}} + {%- else -%} + {%- set out = namespace(start=state.pos, escaped=false, done=false) -%} + {%- set state.pos = state.pos + 1 -%} + {%- for ignored in range(source | length) -%} + {%- if not out.done and state.pos < source | length -%} + {%- set ch = source[state.pos] -%} + {%- set state.pos = state.pos + 1 -%} + {%- if out.escaped -%} + {%- set out.escaped = false -%} + {%- elif ch == '\\' -%} + {%- set out.escaped = true -%} + {%- elif ch == '"' -%} + {%- set out.done = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- set state.string_value = source[out.start:state.pos] -%} + {{- source[out.start:state.pos] -}} + {%- endif -%} +{%- endmacro -%} + +{#- + Move the cursor across one complete JSON value without rendering it. Object + parsing uses the raw slice to sort members before recursively rendering them. +-#} +{%- macro json_scan_value(source, state) -%} + {{- json_skip_ws(source, state) -}} + {%- set scan = namespace(depth=0, quoted=false, escaped=false, done=false) -%} + {%- for ignored in range(source | length) -%} + {%- if not scan.done and state.pos < source | length -%} + {%- set ch = source[state.pos] -%} + {%- if scan.quoted -%} + {%- set state.pos = state.pos + 1 -%} + {%- if ch == '"' and not scan.escaped -%} + {%- set scan.quoted = false -%} + {%- elif ch == '\\' and not scan.escaped -%} + {%- set scan.escaped = true -%} + {%- else -%} + {%- set scan.escaped = false -%} + {%- endif -%} + {%- elif ch == '"' -%} + {%- set scan.quoted = true -%} + {%- set state.pos = state.pos + 1 -%} + {%- elif ch == '{' or ch == '[' -%} + {%- set scan.depth = scan.depth + 1 -%} + {%- set state.pos = state.pos + 1 -%} + {%- elif ch == '}' or ch == ']' -%} + {%- if scan.depth > 0 -%} + {%- set scan.depth = scan.depth - 1 -%} + {%- set state.pos = state.pos + 1 -%} + {%- else -%} + {%- set scan.done = true -%} + {%- endif -%} + {%- elif ch == ',' and scan.depth == 0 -%} + {%- set scan.done = true -%} + {%- else -%} + {%- set state.pos = state.pos + 1 -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} +{%- endmacro -%} + +{#- Parse and canonically render one JSON value from source at state.pos. -#} +{%- macro canonical_json_text_value(source, state) -%} + {{- json_skip_ws(source, state) -}} + {%- if state.pos >= source | length -%} + {{- '{}' -}} + {%- elif source[state.pos] == '"' -%} + {{- json_string(source, state) -}} + {%- elif source[state.pos] == '{' -%} + {%- set state.pos = state.pos + 1 -%} + {{- json_skip_ws(source, state) -}} + {%- set object_state = namespace(pairs=[], done=false) -%} + {%- if state.pos < source | length and source[state.pos] == '}' -%} + {%- set state.pos = state.pos + 1 -%} + {%- set object_state.done = true -%} + {%- endif -%} + {%- for ignored in range(source | length) -%} + {%- if not object_state.done -%} + {{- json_skip_ws(source, state) -}} + {%- set key = json_string(source, state) -%} + {%- set sort_key = state.string_value -%} + {{- json_skip_ws(source, state) -}} + {%- if state.pos < source | length and source[state.pos] == ':' -%} + {%- set state.pos = state.pos + 1 -%} + {%- endif -%} + {{- json_skip_ws(source, state) -}} + {%- set value_start = state.pos -%} + {{- json_scan_value(source, state) -}} + {#- json.loads keeps the final member when a key is duplicated. -#} + {%- set unique = namespace(pairs=[]) -%} + {%- for previous in object_state.pairs -%} + {%- if previous[0] != sort_key -%} + {%- set unique.pairs = unique.pairs + [previous] -%} + {%- endif -%} + {%- endfor -%} + {%- set object_state.pairs = unique.pairs + [[sort_key, key, source[value_start:state.pos]]] -%} + {{- json_skip_ws(source, state) -}} + {%- if state.pos < source | length and source[state.pos] == ',' -%} + {%- set state.pos = state.pos + 1 -%} + {%- else -%} + {%- if state.pos < source | length and source[state.pos] == '}' -%} + {%- set state.pos = state.pos + 1 -%} + {%- endif -%} + {%- set object_state.done = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {{- '{' -}} + {%- for pair in object_state.pairs | sort(case_sensitive=true, attribute=0) -%} + {{- pair[1] -}}{{- ':' -}} + {%- set child_state = namespace(pos=0, string_value='') -%} + {{- canonical_json_text_value(pair[2], child_state) -}} + {%- if not loop.last -%}{{- ',' -}}{%- endif -%} + {%- endfor -%} + {{- '}' -}} + {%- elif source[state.pos] == '[' -%} + {%- set state.pos = state.pos + 1 -%} + {{- '[' -}} + {{- json_skip_ws(source, state) -}} + {%- set array_state = namespace(done=false, first=true) -%} + {%- if state.pos < source | length and source[state.pos] == ']' -%} + {%- set state.pos = state.pos + 1 -%} + {%- set array_state.done = true -%} + {%- endif -%} + {%- for ignored in range(source | length) -%} + {%- if not array_state.done -%} + {%- if not array_state.first -%}{{- ',' -}}{%- endif -%} + {%- set array_state.first = false -%} + {{- canonical_json_text_value(source, state) -}} + {{- json_skip_ws(source, state) -}} + {%- if state.pos < source | length and source[state.pos] == ',' -%} + {%- set state.pos = state.pos + 1 -%} + {%- else -%} + {%- if state.pos < source | length and source[state.pos] == ']' -%} + {%- set state.pos = state.pos + 1 -%} + {%- endif -%} + {%- set array_state.done = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {{- ']' -}} + {%- else -%} + {%- set scalar = namespace(start=state.pos, done=false) -%} + {%- for ignored in range(source | length) -%} + {%- if not scalar.done and state.pos < source | length -%} + {%- set ch = source[state.pos] -%} + {%- if ch == ',' or ch == '}' or ch == ']' or ch == ' ' or ch == '\t' or ch == '\r' or ch == '\n' -%} + {%- set scalar.done = true -%} + {%- else -%} + {%- set state.pos = state.pos + 1 -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- set token = source[scalar.start:state.pos] -%} + {%- if token == 'true' or token == 'false' or token == 'null' -%} + {{- token -}} + {%- elif '.' in token or 'e' in token or 'E' in token -%} + {{- json_scalar(token | float) -}} + {%- else -%} + {{- token | int | tojson(ensure_ascii=false, separators=(',', ':')) -}} + {%- endif -%} + {%- endif -%} +{%- endmacro -%} + +{%- macro canonical_json_text(source) -%} + {%- set text = source | trim -%} + {%- if not text -%} + {{- '{}' -}} + {%- else -%} + {%- set state = namespace(pos=0, string_value='') -%} + {{- canonical_json_text_value(text, state) -}} + {%- endif -%} +{%- endmacro -%} + +{#- + OpenAI clients use either an argument mapping or a JSON-encoded object. + Non-object/empty oddities degrade to {} instead of raising. Object parsing + recursively sorts keys, keeps the last duplicate key (json.loads behavior), + decodes JSON escapes under Transformers, and preserves array order. +-#} +{%- macro canonical_arguments(arguments) -%} + {%- if arguments is mapping -%} + {{- canonical_json(arguments) -}} + {%- elif arguments is string -%} + {%- set source = arguments | trim -%} + {%- if source and source[0] == '{' -%} + {{- canonical_json_text(source) -}} + {%- else -%} + {{- '{}' -}} + {%- endif -%} + {%- else -%} + {{- '{}' -}} + {%- endif -%} +{%- endmacro -%} + +{#- + Match Python f"{float(effort):.2f}" followed by trailing-zero removal. + llama.cpp's jinja engine has no round filter; the bit table handles binary64 midpoint equality. +-#} +{%- macro reasoning_effort_text(effort) -%} + {%- set eff = effort -%} + {%- if eff is string -%} + {%- set e = eff | trim | lower -%} + {%- if e == 'none' -%}{%- set eff = 0.0 -%} + {%- elif e == 'minimal' -%}{%- set eff = 0.1 -%} + {%- elif e == 'low' -%}{%- set eff = 0.2 -%} + {%- elif e == 'medium' -%}{%- set eff = 0.7 -%} + {%- elif e == 'high' -%}{%- set eff = 0.9 -%} + {%- elif e == 'xhigh' -%}{%- set eff = 0.99 -%} + {%- elif e == 'max' -%}{%- set eff = 0.99 -%} + {%- else -%}{%- set eff = e | float(-1.0) -%} + {%- endif -%} + {%- endif -%} + {%- set value = eff | float -%} + {%- if value < 0 or value > 0.99 -%} + {{- raise_exception('Invalid reasoning_effort: ' + (effort | string) + '; expected none/minimal/low/medium/high/xhigh/max or a number in [0.0, 0.99]') -}} + {%- endif -%} + {%- if value == value | int and value >= 0 and value <= 1 -%} + {{- value | int -}} + {%- else -%} + {%- set midpoint_rounds_up = '1011011011010100100100100111000111000111100011100011111100000001111110000001111110000001111111000000' -%} + {%- set rounded = namespace(hundredths=0) -%} + {%- for lower_hundredth in range(100) -%} + {%- set boundary = (lower_hundredth + 0.5) / 100 -%} + {%- if value > boundary or (value == boundary and midpoint_rounds_up[lower_hundredth] == '1') -%} + {%- set rounded.hundredths = lower_hundredth + 1 -%} + {%- endif -%} + {%- endfor -%} + {%- if rounded.hundredths == 100 -%} + {{- '1' -}} + {%- elif rounded.hundredths == 0 -%} + {{- '0' -}} + {%- elif rounded.hundredths % 10 == 0 -%} + {{- '0.' -}}{{- (rounded.hundredths / 10) | int -}} + {%- elif rounded.hundredths < 10 -%} + {{- '0.0' -}}{{- rounded.hundredths -}} + {%- else -%} + {{- '0.' -}}{{- rounded.hundredths -}} + {%- endif -%} + {%- endif -%} +{%- endmacro -%} + +{%- macro role_token(role) -%} + {%- if role == 'user' -%}{{- '<|message_user|>' -}} + {%- elif role == 'assistant' -%}{{- '<|message_model|>' -}} + {%- elif role == 'system' or role == 'developer' -%}{{- '<|message_system|>' -}} + {%- elif role == 'tool' -%}{{- '<|message_tool|>' -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro emit_message(role, kind, content='', author_name='') -%} + {{- role_token(role) -}} + {%- if author_name -%}{{- author_name -}}{%- endif -%} + {%- if kind == 'text' -%} + {{- '<|content_text|>' -}}{{- content -}} + {%- elif kind == 'thinking' -%} + {{- '<|content_thinking|>' -}}{{- content -}} + {%- elif kind == 'xml' -%} + {{- '<|content_xml|>' -}}{{- content -}} + {%- elif kind == 'invoke_tool_json' -%} + {{- '<|content_invoke_tool_json|>' -}}{{- content -}} + {%- elif kind == 'image' -%} + {{- '<|content_image|><|image|>' -}} + {%- elif kind == 'audio' -%} + {{- '<|content_audio_input|><|audio|><|audio_end|>' -}} + {%- endif -%} + {{- '<|end_message|>' -}} +{%- endmacro -%} + +{%- set effort_value = reasoning_effort if (reasoning_effort is defined and reasoning_effort is not none) else 0.9 -%} +{%- set eff_ns = namespace(emitted=false) -%} +{%- set first_ns = namespace(idx=-1) -%} +{%- for m in messages -%} + {%- if first_ns.idx == -1 and m.get('role') not in ['system', 'developer'] -%} + {%- set first_ns.idx = loop.index0 -%} + {%- endif -%} +{%- endfor -%} + +{%- if tools is defined and tools -%} + {{- '<|message_system|>tool_declare<|content_xml|>[' -}} + {%- for tool in tools -%} + {%- set function = tool.get('function', {}) if tool.get('function', {}) is mapping else {} -%} + {%- set description = function.get('description') or '' -%} + {%- set parameters = function.get('parameters') or {} -%} + {%- set tool_type = tool.get('type', 'function') -%} + {{- '{"description":' -}}{{- canonical_json(description) -}} + {{- ',"name":' -}}{{- canonical_json(function.get('name')) -}} + {{- ',"parameters":' -}}{{- canonical_json(parameters) -}} + {{- ',"type":' -}}{{- canonical_json(tool_type) -}}{{- '}' -}} + {%- if not loop.last -%}{{- ',' -}}{%- endif -%} + {%- endfor -%} + {{- ']<|end_message|>' -}} +{%- endif -%} + +{#- Last-user boundary used only by the opt-in preserve_thinking=false mode. -#} +{%- set thinking_state = namespace(last_user_index=messages | length - 1, found_user=false) -%} +{%- for index in range(messages | length - 1, -1, -1) -%} + {%- if not thinking_state.found_user and messages[index].get('role') == 'user' -%} + {%- set thinking_state.last_user_index = index -%} + {%- set thinking_state.found_user = true -%} + {%- endif -%} +{%- endfor -%} + +{%- for message in messages -%} + {%- set message_index = loop.index0 -%} + {%- set role = message.get('role') -%} + {%- if not eff_ns.emitted and loop.index0 == first_ns.idx -%} + {{- emit_message('system', 'text', 'Thinking effort level: ' + reasoning_effort_text(effort_value)) -}} + {%- set eff_ns.emitted = true -%} + {%- endif -%} + {%- if role == 'tool' -%} + {%- set resolved = namespace(name=message.get('name') or '') -%} + {%- if not resolved.name and message.get('tool_call_id') -%} + {%- for prior in messages[:message_index] -%} + {%- if prior.get('role') == 'assistant' -%} + {%- for call in prior.get('tool_calls') or [] -%} + {%- if call.get('id') and (call.get('id') | string) == message.get('tool_call_id') -%} + {%- set prior_function = call.get('function', {}) if call.get('function', {}) is mapping else {} -%} + {%- set resolved.name = prior_function.get('name') or '' -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- set tool_content = message.get('content', '') -%} + {%- if tool_content is none -%} + {%- set tool_content = '' -%} + {%- elif tool_content is mapping or (tool_content is sequence and tool_content is not string) -%} + {%- set tool_content = canonical_json(tool_content) -%} + {%- elif tool_content is not string -%} + {%- set tool_content = canonical_json(tool_content) -%} + {%- endif -%} + {{- emit_message('tool', 'text', tool_content, resolved.name | string) -}} + {%- elif role == 'user' or role == 'assistant' or role == 'system' or role == 'developer' -%} + {%- set turn_out -%} + {%- if role == 'assistant' and message.get('reasoning_content') is string and message.get('reasoning_content') and + ((preserve_thinking is not defined) or preserve_thinking is not false or message_index > thinking_state.last_user_index) -%} + {{- emit_message('assistant', 'thinking', message.get('reasoning_content')) -}} + {%- endif -%} + + {%- set content = message.get('content', '') -%} + {#- Makes llama.cpp retain typed arrays rather than flattening them. -#} + {%- set content_probe = content[0] if content is sequence and content | length > 0 else none -%} + {%- if content is string -%} + {%- if '<__media_' in content -%} + {#- Flattened media markers: each part becomes its own message block. The runtime may + randomize the marker suffix, so split on the stable prefix and re-emit the exact + marker text; the runtime then expands it into the typed content sentinel plus the + media embedding rows. -#} + {%- for segment in content.split('<__media_') -%} + {%- if loop.first -%} + {%- if segment -%}{{- emit_message(role, 'text', segment) -}}{%- endif -%} + {%- else -%} + {%- set mparts = segment.split('>') -%} + {%- set rest = mparts[1:] | join('>') -%} + {{- role_token(role) -}}{{- '<__media_' + mparts[0] + '>' -}}{{- '<|end_message|>' -}} + {%- if rest -%}{{- emit_message(role, 'text', rest) -}}{%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- elif content -%} + {{- emit_message(role, 'text', content) -}} + {%- endif -%} + {%- elif content is sequence -%} + {%- for part in content -%} + {%- if part is string -%} + {{- emit_message(role, 'text', part) -}} + {%- elif part is mapping -%} + {%- set part_type = part.get('type') -%} + {%- if part_type is none or part_type == 'text' or part_type == 'input_text' -%} + {%- set part_text = part.get('text', '') -%} + {{- emit_message(role, 'text', part_text if part_text is string else '') -}} + {%- elif part_type == 'image' or part_type == 'input_image' or part_type == 'image_url' -%} + {{- emit_message(role, 'image') -}} + {%- elif part_type == 'audio' or part_type == 'input_audio' or part_type == 'audio_url' -%} + {{- emit_message(role, 'audio') -}} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + + {%- if role == 'assistant' -%} + {%- for call in message.get('tool_calls') or [] -%} + {%- set function = call.get('function', {}) if call.get('function', {}) is mapping else {} -%} + {%- if function.get('name') is string -%} + {%- set raw_arguments = function.get('arguments') or {} -%} + {%- set arguments_json = canonical_arguments(raw_arguments) -%} + {%- set invocation = '{"name":' + canonical_json(function.get('name')) + ',"args":' + arguments_json + '}' -%} + {{- emit_message('assistant', 'invoke_tool_json', invocation, function.get('name')) -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endset -%} + {{- turn_out -}} + {#- Close each historical model turn, but never emit a bare terminator for an + assistant message that rendered no blocks. -#} + {%- if role == 'assistant' and turn_out -%} + {{- '<|content_model_end_sampling|>' -}} + {%- endif -%} + {%- else -%} + {{- raise_exception('Unknown message role: ' + (role | string)) -}} + {%- endif -%} +{%- endfor -%} + +{%- if not eff_ns.emitted -%} + {{- emit_message('system', 'text', 'Thinking effort level: ' + reasoning_effort_text(effort_value)) -}} +{%- endif -%} + +{%- if add_generation_prompt is defined and add_generation_prompt -%} + {{- '<|message_model|>' -}} +{%- endif -%} +{#- Unsloth translation to jinja from TML's parser #} diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 72968607db80..a01bad68df92 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -141,6 +141,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KIMI_LINEAR, "kimi-linear" }, { LLM_ARCH_TALKIE, "talkie" }, { LLM_ARCH_MELLUM, "mellum" }, + { LLM_ARCH_INKLING, "inkling" }, { LLM_ARCH_UNKNOWN, "(unknown)" }, }; @@ -311,6 +312,18 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_NORM_BEFORE_RESIDUAL, "%s.norm_before_residual" }, { LLM_KV_SHORTCONV_L_CACHE, "%s.shortconv.l_cache" }, + + // inkling (private arch) + { LLM_KV_INKLING_D_REL, "%s.d_rel" }, + { LLM_KV_INKLING_REL_EXTENT, "%s.rel_extent" }, + { LLM_KV_INKLING_REL_EXTENT_SWA, "%s.rel_extent_swa" }, + { LLM_KV_INKLING_SHORTCONV_KERNEL, "%s.shortconv_kernel" }, + { LLM_KV_INKLING_DENSE_BLOCK_COUNT, "%s.dense_block_count" }, + { LLM_KV_INKLING_LOGIT_SCALE_DENOM, "%s.logit_scale_denom" }, + { LLM_KV_INKLING_LOG_SCALING_N_FLOOR, "%s.log_scaling_n_floor" }, + { LLM_KV_INKLING_LOG_SCALING_ALPHA, "%s.log_scaling_alpha" }, + { LLM_KV_INKLING_UNPADDED_VOCAB_SIZE, "%s.unpadded_vocab_size" }, + // sentence-transformers dense modules feature dims { LLM_KV_DENSE_2_FEAT_IN, "%s.dense_2_feat_in" }, { LLM_KV_DENSE_2_FEAT_OUT, "%s.dense_2_feat_out" }, @@ -583,9 +596,19 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_SHORTCONV_CONV, "blk.%d.shortconv.conv" }, { LLM_TENSOR_SHORTCONV_INPROJ, "blk.%d.shortconv.in_proj" }, { LLM_TENSOR_SHORTCONV_OUTPROJ, "blk.%d.shortconv.out_proj" }, + { LLM_TENSOR_ATTN_R, "blk.%d.attn_r" }, + { LLM_TENSOR_ATTN_REL_PROJ, "blk.%d.attn_rel_proj" }, + { LLM_TENSOR_SHORTCONV_K, "blk.%d.shortconv_k" }, + { LLM_TENSOR_SHORTCONV_V, "blk.%d.shortconv_v" }, + { LLM_TENSOR_SHORTCONV_ATTN, "blk.%d.shortconv_attn" }, + { LLM_TENSOR_SHORTCONV_MLP, "blk.%d.shortconv_mlp" }, + { LLM_TENSOR_FFN_GSCALE, "blk.%d.ffn_gscale" }, { LLM_TENSOR_FFN_GATE_CHEXPS, "blk.%d.ffn_gate_chexps" }, { LLM_TENSOR_FFN_DOWN_CHEXPS, "blk.%d.ffn_down_chexps" }, { LLM_TENSOR_FFN_UP_CHEXPS, "blk.%d.ffn_up_chexps" }, + { LLM_TENSOR_FFN_GATE_SHEXPS, "blk.%d.ffn_gate_shexp" }, + { LLM_TENSOR_FFN_DOWN_SHEXPS, "blk.%d.ffn_down_shexp" }, + { LLM_TENSOR_FFN_UP_SHEXPS, "blk.%d.ffn_up_shexp" }, { LLM_TENSOR_VISEXP_ATTN_QKV, "blk.%d.vis_attn_qkv" }, { LLM_TENSOR_VISEXP_ATTN_OUT, "blk.%d.vis_attn_output" }, { LLM_TENSOR_VISEXP_FFN_GATE, "blk.%d.vis_gate" }, @@ -780,6 +803,9 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_FFN_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, {LLM_TENSOR_FFN_GATE_UP_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, {LLM_TENSOR_FFN_DOWN_CHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, + {LLM_TENSOR_FFN_DOWN_SHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, + {LLM_TENSOR_FFN_GATE_SHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, + {LLM_TENSOR_FFN_UP_SHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, {LLM_TENSOR_FFN_GATE_CHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, {LLM_TENSOR_FFN_UP_CHEXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}}, {LLM_TENSOR_FFN_EXP_PROBS_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, @@ -821,6 +847,13 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_SHORTCONV_CONV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, {LLM_TENSOR_SHORTCONV_INPROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_SHORTCONV_OUTPROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_ATTN_R, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_ATTN_REL_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_SHORTCONV_K, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, + {LLM_TENSOR_SHORTCONV_V, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, + {LLM_TENSOR_SHORTCONV_ATTN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, + {LLM_TENSOR_SHORTCONV_MLP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, + {LLM_TENSOR_FFN_GSCALE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_VISEXP_ATTN_QKV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_VISEXP_ATTN_OUT, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_VISEXP_FFN_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, @@ -946,6 +979,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) { case LLM_ARCH_KIMI_LINEAR: case LLM_ARCH_QWEN35: case LLM_ARCH_QWEN35MOE: + case LLM_ARCH_INKLING: return true; default: return false; @@ -1001,6 +1035,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_MINIMAX_M2: case LLM_ARCH_MISTRAL4: case LLM_ARCH_KIMI_LINEAR: + case LLM_ARCH_INKLING: return false; default: return true; diff --git a/src/llama-arch.h b/src/llama-arch.h index b74d53af4a32..9d2eb4a92028 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -146,6 +146,7 @@ enum llm_arch { LLM_ARCH_MELLUM, LLM_ARCH_EAGLE3, LLM_ARCH_DFLASH, + LLM_ARCH_INKLING, LLM_ARCH_UNKNOWN, }; @@ -358,6 +359,17 @@ enum llm_kv { LLM_KV_SHORTCONV_L_CACHE, + // inkling (private arch) + LLM_KV_INKLING_D_REL, + LLM_KV_INKLING_REL_EXTENT, + LLM_KV_INKLING_REL_EXTENT_SWA, + LLM_KV_INKLING_SHORTCONV_KERNEL, + LLM_KV_INKLING_DENSE_BLOCK_COUNT, + LLM_KV_INKLING_LOGIT_SCALE_DENOM, + LLM_KV_INKLING_LOG_SCALING_N_FLOOR, + LLM_KV_INKLING_LOG_SCALING_ALPHA, + LLM_KV_INKLING_UNPADDED_VOCAB_SIZE, + LLM_KV_XIELU_ALPHA_N, LLM_KV_XIELU_ALPHA_P, LLM_KV_XIELU_BETA, @@ -425,6 +437,10 @@ enum llm_tensor { LLM_TENSOR_FFN_DOWN_CHEXPS, LLM_TENSOR_FFN_GATE_CHEXPS, LLM_TENSOR_FFN_UP_CHEXPS, + // Inkling: same GGUF names as *_SHEXP but registered as MUL_MAT_ID (3D shared-expert bank via ggml_mul_mat_id) + LLM_TENSOR_FFN_DOWN_SHEXPS, + LLM_TENSOR_FFN_GATE_SHEXPS, + LLM_TENSOR_FFN_UP_SHEXPS, LLM_TENSOR_FFN_EXP_PROBS_B, LLM_TENSOR_FFN_LATENT_DOWN, LLM_TENSOR_FFN_LATENT_UP, @@ -586,6 +602,14 @@ enum llm_tensor { LLM_TENSOR_SHORTCONV_CONV, LLM_TENSOR_SHORTCONV_INPROJ, LLM_TENSOR_SHORTCONV_OUTPROJ, + // inkling (private arch) + LLM_TENSOR_ATTN_R, + LLM_TENSOR_ATTN_REL_PROJ, + LLM_TENSOR_SHORTCONV_K, + LLM_TENSOR_SHORTCONV_V, + LLM_TENSOR_SHORTCONV_ATTN, + LLM_TENSOR_SHORTCONV_MLP, + LLM_TENSOR_FFN_GSCALE, LLM_TENSOR_VISEXP_ATTN_QKV, LLM_TENSOR_VISEXP_ATTN_OUT, LLM_TENSOR_VISEXP_FFN_GATE, diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index c8ecb0a2854c..9a390c7f26f3 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1382,9 +1382,15 @@ ggml_tensor * llm_graph_context::build_cvec( ggml_tensor * llm_graph_context::build_lora_mm( ggml_tensor * w, ggml_tensor * cur, - ggml_tensor * w_s) const { + ggml_tensor * w_s, + enum ggml_prec prec) const { ggml_tensor * res = ggml_mul_mat(ctx0, w, cur); + if (prec != GGML_PREC_DEFAULT) { + // Set precision on the base MUL_MAT before an optional scale/LoRA attachment changes the root op. + ggml_mul_mat_set_prec(res, prec); + } + if (w_s) { res = ggml_mul(ctx0, res, w_s); } diff --git a/src/llama-graph.h b/src/llama-graph.h index 7ed490ce6728..d3270a1a3469 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -954,7 +954,8 @@ struct llm_graph_context { ggml_tensor * build_lora_mm( ggml_tensor * w, ggml_tensor * cur, - ggml_tensor * w_s = nullptr) const; + ggml_tensor * w_s = nullptr, + enum ggml_prec prec = GGML_PREC_DEFAULT) const; // do mat_mul_id, while optionally apply lora and per-expert scale ggml_tensor * build_lora_mm_id( diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index 9d0683d2fec4..d0cf45f64711 100644 --- a/src/llama-hparams.cpp +++ b/src/llama-hparams.cpp @@ -181,6 +181,11 @@ uint32_t llama_hparams::n_embd_v_gqa_max() const { } uint32_t llama_hparams::n_embd_r() const { + if (n_embd_r_impl != 0) { + // explicit override (e.g. inkling: 4 packed shortconv streams per layer) + return n_embd_r_impl; + } + if (wkv_head_size != 0) { // for RWKV models return token_shift_count * n_embd; diff --git a/src/llama-hparams.h b/src/llama-hparams.h index 8be5f28f39e6..38b8640326cb 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -79,6 +79,17 @@ struct llama_hparams { uint32_t n_shortconv_l_cache = 0; + // explicit override for the rolling state size per layer (see n_embd_r()) + uint32_t n_embd_r_impl = 0; + + // inkling (private arch) + uint32_t inkling_d_rel = 0; + uint32_t inkling_rel_extent = 0; // global (non-SWA) layers + uint32_t inkling_rel_extent_swa = 0; // local (SWA) layers + uint32_t inkling_log_n_floor = 0; // 0 = log-N scaling disabled + float inkling_log_alpha = 0.0f; + uint32_t inkling_unpadded_n_vocab = 0; // 0 = no padded-vocab masking + std::array n_head_arr; std::array n_head_kv_arr; std::array n_ff_arr; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index e70583e64152..812f8293b271 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1240,6 +1240,51 @@ uint32_t llama_kv_cache::get_n_kv(const slot_info & sinfo) const { return result; } +uint32_t llama_kv_cache::get_n_kv_pos_contiguous(const slot_info & sinfo, const llama_ubatch & ubatch) const { + if (sinfo.n_stream() != 1 || ubatch.n_seqs_unq != 1 || ubatch.n_tokens == 0 || + ubatch.pos == nullptr || ubatch.n_seq_id == nullptr || + ubatch.seq_id == nullptr || ubatch.seq_id[0] == nullptr) { + return 0; + } + + const llama_seq_id seq_id = ubatch.seq_id[0][0]; + if (seq_id < 0 || (size_t) seq_id >= seq_to_stream.size()) { + return 0; + } + + const uint32_t stream = seq_to_stream[seq_id]; + if (sinfo.strm[0] < 0 || (uint32_t) sinfo.strm[0] != stream || stream >= v_cells.size()) { + return 0; + } + + const auto & cells = v_cells[stream]; + const llama_pos pos_max = cells.seq_pos_max(seq_id); + + if (pos_max < 0 || pos_max >= (llama_pos) cells.size()) { + return 0; + } + + // the banded op aligns Q to the tail of K: the ubatch must be that monotonic tail, else dense bias + if ((uint32_t) pos_max + 1 < ubatch.n_tokens) { + return 0; + } + const llama_pos pos_start = pos_max + 1 - ubatch.n_tokens; + for (uint32_t i = 0; i < ubatch.n_tokens; ++i) { + if (ubatch.pos[i] != pos_start + (llama_pos) i || + ubatch.n_seq_id[i] < 1 || ubatch.seq_id[i] == nullptr || ubatch.seq_id[i][0] != seq_id) { + return 0; + } + } + + for (llama_pos pos = 0; pos <= pos_max; ++pos) { + if (cells.is_empty(pos) || cells.pos_get(pos) != pos || !cells.seq_has(pos, seq_id)) { + return 0; + } + } + + return pos_max + 1; +} + ggml_tensor * llama_kv_cache::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const { const int32_t ikv = map_layer_ids.at(il); @@ -1779,6 +1824,39 @@ void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch } } +void llama_kv_cache::set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { + const int64_t n_tokens = ubatch->n_tokens; + + GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); + + int32_t * data = (int32_t *) dst->data; + + const int64_t n_kv = dst->ne[0]; + GGML_ASSERT(dst->ne[1] == n_tokens); + + // [n_kv, n_tokens] in GLOBAL token order (stream-major, same as the KQ mask) + for (int64_t i = 0; i < n_tokens; ++i) { + const llama_seq_id seq_id = ubatch->seq_id[i][0]; + + const auto & cells = v_cells[seq_to_stream[seq_id]]; + + const llama_pos p1 = ubatch->pos[i]; + + for (int64_t j = 0; j < n_kv; ++j) { + // use the ACTUAL absolute position in the KV cell; physical slot order is not monotonic + int32_t rel = (int32_t) extent; // zero-bias column + if (!cells.is_empty(j)) { + const llama_pos d = p1 - cells.pos_get(j); + if (d >= 0 && d < (llama_pos) extent) { + rel = (int32_t) d; + } + } + + data[i*n_kv + j] = (int32_t) (i*(extent + 1)) + rel; + } + } +} + void llama_kv_cache::set_input_k_rot(ggml_tensor * dst) const { GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer)); @@ -2567,6 +2645,21 @@ uint32_t llama_kv_cache_context::get_n_kv() const { return n_kv; } +uint32_t llama_kv_cache_context::get_n_kv_pos_contiguous() const { + // Full-cache and update contexts do not carry a concrete ubatch/slot pair. + if (ubatches.empty() || sinfos.empty() || i_cur >= ubatches.size() || i_cur >= sinfos.size()) { + // reserve context: report the whole cache as position-contiguous so the worst-case graph + // is the banded path; reserving the dense fallback is unallocatable at large n_ctx + if (kv != nullptr && lctx == nullptr && kv->get_n_stream() == 1) { + return n_kv; + } + return 0; + } + + const uint32_t result = kv->get_n_kv_pos_contiguous(sinfos[i_cur], ubatches[i_cur]); + return result <= (uint32_t) n_kv ? result : 0; +} + ggml_type llama_kv_cache_context::type_k() const { return kv->type_k(); } @@ -2627,6 +2720,10 @@ void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama kv->set_input_pos_bucket(dst, ubatch); } +void llama_kv_cache_context::set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { + kv->set_input_pos_rel_flat(dst, ubatch, extent); +} + void llama_kv_cache_context::set_input_k_rot(ggml_tensor * dst) const { kv->set_input_k_rot(dst); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 531d99dbdec1..08248f17c73f 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -170,6 +170,9 @@ class llama_kv_cache : public llama_memory_i { uint32_t get_n_kv(const slot_info & sinfo) const; + // active cell count when position p lives in physical cell p; 0 for any non-contiguous layout + uint32_t get_n_kv_pos_contiguous(const slot_info & sinfo, const llama_ubatch & ubatch) const; + // get views of the current state of the cache ggml_tensor * get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const; ggml_tensor * get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const; @@ -214,6 +217,10 @@ class llama_kv_cache : public llama_memory_i { void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + // inkling: fill dst I32 [n_kv, n_tokens] with flat rel-bias gather indices, + // idx(i, j) = i*(extent + 1) + rel; empty/out-of-band cells map to the zero-bias column `extent` + void set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_k_rot(ggml_tensor * dst) const; void set_input_v_rot(ggml_tensor * dst) const; @@ -363,6 +370,7 @@ class llama_kv_cache_context : public llama_memory_context_i { // uint32_t get_n_kv() const; + uint32_t get_n_kv_pos_contiguous() const; ggml_type type_k() const; ggml_type type_v() const; @@ -395,6 +403,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_kq_mask (ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + void set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // inkling void set_input_k_rot(ggml_tensor * dst) const; void set_input_v_rot(ggml_tensor * dst) const; @@ -402,8 +411,8 @@ class llama_kv_cache_context : public llama_memory_context_i { private: llama_memory_status status; - llama_kv_cache * kv; - llama_context * lctx; + llama_kv_cache * kv = nullptr; + llama_context * lctx = nullptr; // // update context diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index a3928523ba8d..0d39901abf71 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -28,6 +28,7 @@ bool llama_model_saver_supports_arch(llm_arch arch) { case LLM_ARCH_MIMO2: case LLM_ARCH_STEP35: case LLM_ARCH_MELLUM: + case LLM_ARCH_INKLING: return false; default: return true; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 4c10e4126f62..b7c36ca95b36 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -304,6 +304,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_kimi_linear(params); case LLM_ARCH_STEP35: return new llama_model_step35(params); + case LLM_ARCH_INKLING: + return new llama_model_inkling(params); default: throw std::runtime_error(std::string("unsupported model architecture: '") + llm_arch_name(arch) + "'"); } @@ -2102,7 +2104,8 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, // layer filters, so pick the right one here llama_memory_hybrid::layer_filter_cb filter_attn = nullptr; llama_memory_hybrid::layer_filter_cb filter_recr = nullptr; - if (arch == LLM_ARCH_FALCON_H1) { + if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING) { + // all layers have both an attention KV cache and a recurrent (conv) state filter_attn = [&](uint32_t) { return true; }; filter_recr = [&](uint32_t) { return true; }; } else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { @@ -2444,6 +2447,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_NEMOTRON_H: case LLM_ARCH_NEMOTRON_H_MOE: case LLM_ARCH_KIMI_LINEAR: + case LLM_ARCH_INKLING: return LLAMA_ROPE_TYPE_NONE; // use what we call a normal RoPE, operating on pairs of consecutive head values diff --git a/src/llama-model.h b/src/llama-model.h index 45b054cedf1d..57c7caf37ddb 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -525,6 +525,15 @@ struct llama_layer { struct llama_layer_shortconv shortconv; struct llama_layer_nextn nextn; + + // inkling (private arch) + struct ggml_tensor * wr = nullptr; // attn_r [n_embd, n_head*d_rel] + struct ggml_tensor * attn_rel_proj = nullptr; // [rel_extent, d_rel] (checkpoint [d_rel, E] orientation) + struct ggml_tensor * shortconv_k = nullptr; // [K, kvw] + struct ggml_tensor * shortconv_v = nullptr; // [K, kvw] + struct ggml_tensor * shortconv_attn = nullptr; // [K, n_embd] + struct ggml_tensor * shortconv_mlp = nullptr; // [K, n_embd] + struct ggml_tensor * ffn_gscale = nullptr; // F32 [1] }; struct llama_device { diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index b66759b27760..94b30f9ac57c 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -322,6 +322,16 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name.find("ssm_conv1d") == std::string::npos; quantize &= name.find("shortconv.conv.weight") == std::string::npos; + // keep Inkling's shortconv kernels and rel-proj table unquantized; arch-gated so the + // name substrings cannot hit another architecture + if (arch == LLM_ARCH_INKLING) { + quantize &= name.find("shortconv_k.weight") == std::string::npos; + quantize &= name.find("shortconv_v.weight") == std::string::npos; + quantize &= name.find("shortconv_attn.weight") == std::string::npos; + quantize &= name.find("shortconv_mlp.weight") == std::string::npos; + quantize &= name.find("attn_rel_proj.weight") == std::string::npos; + } + // do not quantize RWKV's small yet 2D weights quantize &= name.find("time_mix_first.weight") == std::string::npos; quantize &= name.find("time_mix_w0.weight") == std::string::npos; diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index fdd447147d43..3197843e002d 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -433,6 +433,12 @@ struct llm_tokenizer_bpe : llm_tokenizer { "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))*((?=[\\p{L}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}])([^a-z]))+((?=[\\p{L}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; + case LLAMA_VOCAB_PRE_TYPE_INKLING: + // o200k-family with \p{M} in the letter classes; own pre-type so GPT4O / MINIMAX_M2 stay unchanged + regex_exprs = { + "[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}\\p{M}])([^a-z]))*((?=[\\p{L}\\p{M}])([^A-Z]))+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?((?=[\\p{L}\\p{M}])([^a-z]))+((?=[\\p{L}\\p{M}])([^A-Z]))*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + }; + break; case LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI: // Same lookaheads as GPT4O but with \p{M} added so combining marks // (diacritics) attach to their base letters. Avoids excessive @@ -2286,6 +2292,10 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "talkie") { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O; clean_spaces = false; + } else if ( + tokenizer_pre == "inkling") { + pre_type = LLAMA_VOCAB_PRE_TYPE_INKLING; + clean_spaces = false; } else if ( tokenizer_pre == "granite-embed-multi-97m") { pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 707cd4bac4bf..be5d77b53ad7 100644 --- a/src/llama-vocab.h +++ b/src/llama-vocab.h @@ -64,6 +64,7 @@ enum llama_vocab_pre_type { LLAMA_VOCAB_PRE_TYPE_WHITESPACE = 53, LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI = 54, LLAMA_VOCAB_PRE_TYPE_MELLUM2 = 55, + LLAMA_VOCAB_PRE_TYPE_INKLING = 56, }; struct LLM_KV; diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp new file mode 100644 index 000000000000..f83930c6976a --- /dev/null +++ b/src/models/inkling.cpp @@ -0,0 +1,666 @@ +// Inkling (PRIVATE arch): hybrid iSWA attention + per-layer packed shortconv state; see INKLING_DESIGN.md. + +#include "models.h" + +#include "../llama-kv-cache-iswa.h" +#include "../llama-kv-cache.h" +#include "../llama-memory-hybrid-iswa.h" +#include "../llama-memory-recurrent.h" + +#include + +void llama_model_inkling::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_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false); + + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; // visible iff pos_q - pos_k < n_swa (includes self) + ml.get_key_or_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl, hparams.n_layer()); + + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + hparams.is_recr_impl[il] = 1; + } + + ml.get_key(LLM_KV_INKLING_D_REL, hparams.inkling_d_rel); + ml.get_key(LLM_KV_INKLING_REL_EXTENT, hparams.inkling_rel_extent); + ml.get_key(LLM_KV_INKLING_REL_EXTENT_SWA, hparams.inkling_rel_extent_swa); + ml.get_key(LLM_KV_INKLING_SHORTCONV_KERNEL, hparams.n_shortconv_l_cache); + ml.get_key(LLM_KV_INKLING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead); + + float logit_scale_denom = 0.0f; + ml.get_key(LLM_KV_INKLING_LOGIT_SCALE_DENOM, logit_scale_denom); + GGML_ASSERT(logit_scale_denom != 0.0f); + hparams.f_logit_scale = 1.0f / logit_scale_denom; + + ml.get_key(LLM_KV_INKLING_LOG_SCALING_N_FLOOR, hparams.inkling_log_n_floor, false); + ml.get_key(LLM_KV_INKLING_LOG_SCALING_ALPHA, hparams.inkling_log_alpha, false); + ml.get_key(LLM_KV_INKLING_UNPADDED_VOCAB_SIZE, hparams.inkling_unpadded_n_vocab, false); + + GGML_ASSERT(hparams.n_shortconv_l_cache > 1); + GGML_ASSERT(hparams.inkling_d_rel > 0); + GGML_ASSERT(hparams.inkling_rel_extent > 0 && hparams.inkling_rel_extent_swa > 0); + + // uniform state per cell: 4 packed streams [k | v | attn | mlp] of last K-1 columns, k/v sized for the widest layer + const uint32_t d_conv = hparams.n_shortconv_l_cache - 1; + hparams.n_embd_r_impl = d_conv * (hparams.n_embd_k_gqa_max() + hparams.n_embd_v_gqa_max() + 2*hparams.n_embd); + + type = LLM_TYPE_UNKNOWN; +} + +void llama_model_inkling::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t head_dim = hparams.n_embd_head_k(); + const int64_t d_rel = hparams.inkling_d_rel; + const int64_t K = hparams.n_shortconv_l_cache; + const int64_t n_ff_exp = hparams.n_ff_exp; + const int64_t n_shexp = hparams.n_expert_shared; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight", 0), {n_embd}, 0); // bid 0: compute on the first layer's device + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, 0); + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + const int64_t n_head_kv_i = hparams.n_head_kv(i); + const int64_t kvw = n_head_kv_i * head_dim; + const int64_t rel_extent = hparams.is_swa(i) ? hparams.inkling_rel_extent_swa : hparams.inkling_rel_extent; + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + + layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_head*head_dim}, 0); + layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, kvw}, 0); + layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, kvw}, 0); + layer.wr = create_tensor(tn(LLM_TENSOR_ATTN_R, "weight", i), {n_embd, n_head*d_rel}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head*head_dim, n_embd}, 0); + + layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {head_dim}, 0); + layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {head_dim}, 0); + + // stored in checkpoint orientation [d_rel, E] -> gguf ne = [E, d_rel] + layer.attn_rel_proj = create_tensor(tn(LLM_TENSOR_ATTN_REL_PROJ, "weight", i), {rel_extent, d_rel}, 0); + + layer.shortconv_k = create_tensor(tn(LLM_TENSOR_SHORTCONV_K, "weight", i), {K, kvw}, 0); + layer.shortconv_v = create_tensor(tn(LLM_TENSOR_SHORTCONV_V, "weight", i), {K, kvw}, 0); + layer.shortconv_attn = create_tensor(tn(LLM_TENSOR_SHORTCONV_ATTN, "weight", i), {K, n_embd}, 0); + layer.shortconv_mlp = create_tensor(tn(LLM_TENSOR_SHORTCONV_MLP, "weight", i), {K, n_embd}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gscale = create_tensor(tn(LLM_TENSOR_FFN_GSCALE, "weight", i), {1}, 0); + + if (i < (int) hparams.n_layer_dense_lead) { + const int64_t n_ff_i = hparams.n_ff(i); + + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff_i}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff_i}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff_i, n_embd}, 0); + } else { + GGML_ASSERT(n_expert > 0 && n_expert_used > 0 && n_shexp > 0); + + // gate holds n_expert + n_shexp rows (incl. shared-expert sink logits) + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert + n_shexp}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); + + // shared experts stacked as an n_shexp bank, registered MUL_MAT_ID so the loader picks a mul_mat_id-capable buffer + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXPS, "weight", i), {n_embd, n_ff_exp, n_shexp}, 0); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXPS, "weight", i), {n_embd, n_ff_exp, n_shexp}, 0); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXPS, "weight", i), {n_ff_exp, n_embd, n_shexp}, 0); + } + } +} + +class llm_graph_input_inkling : public llm_graph_input_i { +public: + llm_graph_input_inkling( + const llama_hparams & hparams, + const llama_memory_hybrid_iswa_context * mctx) : + hparams(hparams), + mctx(mctx) {} + virtual ~llm_graph_input_inkling() = default; + + void set_input(const llama_ubatch * ubatch) override { + if (tau) { + GGML_ASSERT(ggml_backend_buffer_is_host(tau->buffer)); + float * data = (float *) tau->data; + + const float n_floor = (float) hparams.inkling_log_n_floor; + const float alpha = hparams.inkling_log_alpha; + + for (int64_t i = 0; i < (int64_t) ubatch->n_tokens; ++i) { + const float eff = (float) (ubatch->pos[i] + 1) / n_floor; + data[i] = 1.0f + alpha*logf(std::max(eff, 1.0f)); + } + } + + if (rel_idx) { + mctx->get_attn()->get_base()->set_input_pos_rel_flat(rel_idx, ubatch, hparams.inkling_rel_extent); + } + + if (rel_idx_swa) { + mctx->get_attn()->get_swa()->set_input_pos_rel_flat(rel_idx_swa, ubatch, hparams.inkling_rel_extent_swa); + } + + if (vocab_mask) { + GGML_ASSERT(ggml_backend_buffer_is_host(vocab_mask->buffer)); + float * data = (float *) vocab_mask->data; + + const int64_t n_vocab = vocab_mask->ne[0]; + const int64_t n_unpadded = hparams.inkling_unpadded_n_vocab; + + for (int64_t id = 0; id < n_vocab; ++id) { + data[id] = id < n_unpadded ? 0.0f : -INFINITY; + } + } + + if (shexp_idx) { + GGML_ASSERT(ggml_backend_buffer_is_host(shexp_idx->buffer)); + int32_t * data = (int32_t *) shexp_idx->data; + + const int64_t n_shexp = shexp_idx->ne[0]; + const int64_t n_tokens = shexp_idx->ne[1]; + + for (int64_t j = 0; j < n_tokens; ++j) { + for (int64_t s = 0; s < n_shexp; ++s) { + data[j*n_shexp + s] = (int32_t) s; + } + } + } + } + + ggml_tensor * tau = nullptr; // F32 [1, 1, n_tokens] + ggml_tensor * rel_idx = nullptr; // I32 [n_kv_base, n_tokens] + ggml_tensor * rel_idx_swa = nullptr; // I32 [n_kv_swa, n_tokens] + ggml_tensor * vocab_mask = nullptr; // F32 [n_vocab] + ggml_tensor * shexp_idx = nullptr; // I32 [n_shexp, n_tokens], constant 0..n_shexp-1 + + const llama_hparams hparams; + + const llama_memory_hybrid_iswa_context * mctx; +}; + +std::unique_ptr llama_model_inkling::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(*this, params); +} + +llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_params & params) : + llm_graph_context(params) { + + const int64_t head_dim = hparams.n_embd_head_k(); + const int64_t d_rel = hparams.inkling_d_rel; + const int64_t d_conv = hparams.n_shortconv_l_cache - 1; + const int64_t n_embd_r = hparams.n_embd_r(); + const int64_t kw_max = hparams.n_embd_k_gqa_max(); + const int64_t vw_max = hparams.n_embd_v_gqa_max(); + + // packed conv-state stream offsets within one cell: [k | v | attn | mlp] + const int64_t off_k = 0; + const int64_t off_v = d_conv*kw_max; + const int64_t off_attn = d_conv*(kw_max + vw_max); + const int64_t off_mlp = d_conv*(kw_max + vw_max + n_embd); + + const auto * mctx_hyb = static_cast(mctx); + const auto * mctx_recr = mctx_hyb->get_recr(); + const auto * mctx_attn = mctx_hyb->get_attn(); + + const uint32_t kv_head = mctx_recr->get_head(); + + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + GGML_ASSERT(n_seqs != 0); + GGML_ASSERT(ubatch.equal_seqs()); + GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs); + + const uint32_t n_kv_flash_base = cparams.flash_attn ? mctx_attn->get_base()->get_n_kv_pos_contiguous() : 0; + const uint32_t n_kv_flash_swa = cparams.flash_attn ? mctx_attn->get_swa ()->get_n_kv_pos_contiguous() : 0; + + bool has_global = false; + bool needs_rel_idx_local = false; + bool needs_rel_idx_global = false; + + const auto banded_cache_type_supported = [](ggml_type type) { + return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; + }; + + const auto use_banded_flash = [&](int il) { + const auto * cache = hparams.is_swa(il) ? mctx_attn->get_swa() : mctx_attn->get_base(); + const uint32_t n_kv_flash = hparams.is_swa(il) ? n_kv_flash_swa : n_kv_flash_base; + + // get_n_kv_pos_contiguous() is 0 for multi-sequence ubatches; the reserve context reports full n_kv + return cparams.flash_attn && + n_kv_flash > 0 && + (head_dim == 64 || head_dim == 128) && + hparams.n_embd_head_v(il) == head_dim && + hparams.n_head(il) % hparams.n_head_kv(il) == 0 && + banded_cache_type_supported(cache->type_k()) && + banded_cache_type_supported(cache->type_v()); + }; + + for (int il = 0; il < n_layer; ++il) { + if (hparams.is_swa(il)) { + needs_rel_idx_local |= !use_banded_flash(il); + } else { + has_global = true; + needs_rel_idx_global |= !use_banded_flash(il); + } + } + + auto inp = std::make_unique(hparams, mctx_hyb); + + if (hparams.inkling_log_n_floor > 0 && has_global) { + inp->tau = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, 1, 1, n_tokens); + ggml_set_input(inp->tau); + ggml_set_name(inp->tau, "inkling_tau"); + } + + if (needs_rel_idx_global) { + const int64_t n_kv = mctx_attn->get_base()->get_n_kv(); + inp->rel_idx = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens); + ggml_set_input(inp->rel_idx); + ggml_set_name(inp->rel_idx, "inkling_rel_idx"); + } + + if (needs_rel_idx_local) { + const int64_t n_kv_swa = mctx_attn->get_swa()->get_n_kv(); + inp->rel_idx_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv_swa, n_tokens); + ggml_set_input(inp->rel_idx_swa); + ggml_set_name(inp->rel_idx_swa, "inkling_rel_idx_swa"); + } + + const int64_t n_vocab = model.vocab.n_tokens(); + if (!cparams.embeddings && hparams.inkling_unpadded_n_vocab > 0 && (int64_t) hparams.inkling_unpadded_n_vocab < n_vocab) { + inp->vocab_mask = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_vocab); + ggml_set_input(inp->vocab_mask); + ggml_set_name(inp->vocab_mask, "inkling_vocab_mask"); + } + + // shared experts go through mul_mat_id: 2D views into a repacked/quantized 3D bank are invalid + if (hparams.n_expert_shared > 0 && (uint32_t) n_layer > hparams.n_layer_dense_lead) { + inp->shexp_idx = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, hparams.n_expert_shared, n_tokens); + ggml_set_input(inp->shexp_idx); + ggml_set_name(inp->shexp_idx, "inkling_shexp_idx"); + } + + ggml_tensor * tau = inp->tau; + ggml_tensor * rel_idx = inp->rel_idx; + ggml_tensor * rel_idx_swa = inp->rel_idx_swa; + ggml_tensor * vocab_mask = inp->vocab_mask; + ggml_tensor * shexp_idx = inp->shexp_idx; + + res->add_input(std::move(inp)); + + auto * inp_hybrid = build_inp_mem_hybrid_iswa(); + + // shared by the 4 stream sub-views; build_rs must run exactly once per layer (it zero-inits fresh states) + ggml_tensor * conv_rs_cur = nullptr; + + // sconv(x) = x + causal_depthwise_conv1d(x); rolling state = last K-1 inputs + auto build_sconv = [&](ggml_tensor * x2d, ggml_tensor * kernel, int64_t off, int il) -> ggml_tensor * { + const int64_t w = x2d->ne[0]; + + ggml_tensor * x3 = ggml_reshape_3d(ctx0, x2d, w, n_seq_tokens, n_seqs); + ggml_tensor * xt = ggml_transpose(ctx0, x3); // time-major for the conv + + ggml_tensor * conv_state = mctx_recr->get_r_l(il); + ggml_tensor * conv_rs = conv_rs_cur; // {n_embd_r, n_seqs} + GGML_ASSERT(conv_rs != nullptr); + + const size_t sz = ggml_element_size(conv_rs); + + // this stream's slice of the packed state + ggml_tensor * state = ggml_view_3d(ctx0, conv_rs, d_conv, w, n_seqs, + d_conv*sz, conv_rs->nb[1], off*sz); + + ggml_tensor * sx = ggml_concat(ctx0, state, xt, 0); // {d_conv + n_seq_tokens, w, n_seqs} + + // write the last d_conv time columns back into the cache + ggml_tensor * new_state = ggml_view_3d(ctx0, sx, d_conv, w, n_seqs, + sx->nb[1], sx->nb[2], (sx->ne[0] - d_conv)*sx->nb[0]); + ggml_tensor * state_dst = ggml_view_3d(ctx0, conv_state, d_conv, w, n_seqs, + d_conv*sz, n_embd_r*sz, (kv_head*n_embd_r + off)*sz); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst)); + + ggml_tensor * conv_out = ggml_ssm_conv(ctx0, sx, kernel); // {w, n_seq_tokens, n_seqs} + + ggml_tensor * y = ggml_add(ctx0, x3, conv_out); // built-in residual, no activation + + return ggml_reshape_2d(ctx0, y, w, n_seq_tokens*n_seqs); + }; + + auto build_attn_block = [&](ggml_tensor * cur, int il) -> ggml_tensor * { + const auto & layer = model.layers[il]; + + const bool is_swa = hparams.is_swa(il); + const int64_t n_head_kv = hparams.n_head_kv(il); + const int64_t rel_extent = is_swa ? hparams.inkling_rel_extent_swa : hparams.inkling_rel_extent; + + ggml_tensor * q = build_lora_mm(layer.wq, cur); + ggml_tensor * k = build_lora_mm(layer.wk, cur); + ggml_tensor * v = build_lora_mm(layer.wv, cur); + ggml_tensor * r = build_lora_mm(layer.wr, cur); + cb(q, "inkling_attn_q", il); + cb(k, "inkling_attn_k", il); + cb(v, "inkling_attn_v", il); + cb(r, "inkling_attn_r", il); + + // k/v short convs on the flat projections, before the head reshape + k = build_sconv(k, layer.shortconv_k, off_k, il); + v = build_sconv(v, layer.shortconv_v, off_v, il); + cb(k, "inkling_attn_k_sconv", il); + cb(v, "inkling_attn_v_sconv", il); + + q = ggml_reshape_3d(ctx0, q, head_dim, n_head, n_tokens); + k = ggml_reshape_3d(ctx0, k, head_dim, n_head_kv, n_tokens); + v = ggml_reshape_3d(ctx0, v, head_dim, n_head_kv, n_tokens); + + q = build_norm(q, layer.attn_q_norm, NULL, LLM_NORM_RMS, il); + k = build_norm(k, layer.attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(q, "inkling_attn_q_norm", il); + cb(k, "inkling_attn_k_norm", il); + + // log-N tau on global layers only, after q_norm + if (tau && !is_swa) { + q = ggml_mul(ctx0, q, tau); + } + + // relative position bias + ggml_tensor * r2 = ggml_reshape_2d(ctx0, r, d_rel, n_head*n_tokens); + + // proj stored [E, d_rel]; transpose so ggml_mul_mat contracts over d_rel + ggml_tensor * proj = ggml_cont(ctx0, ggml_transpose(ctx0, layer.attn_rel_proj)); // {d_rel, E} + + ggml_tensor * rel = ggml_mul_mat(ctx0, proj, r2); // {E, n_head*n_tokens} + ggml_mul_mat_set_prec(rel, GGML_PREC_F32_PEDANTIC); + rel = ggml_reshape_3d(ctx0, rel, rel_extent, n_head, n_tokens); + + if (tau && !is_swa) { + rel = ggml_mul(ctx0, rel, tau); + } + cb(rel, "inkling_rel_logits", il); + + auto * inp_attn = inp_hybrid->get_attn(); + const int64_t n_stream = (is_swa ? inp_attn->get_kq_mask_swa() : inp_attn->get_kq_mask())->ne[3]; + GGML_ASSERT(n_tokens % n_stream == 0); + + if (use_banded_flash(il)) { + GGML_ASSERT(q->type == GGML_TYPE_F32); + auto * k_rot = is_swa ? inp_attn->self_k_rot_swa : inp_attn->self_k_rot; + auto * v_rot = is_swa ? inp_attn->self_v_rot_swa : inp_attn->self_v_rot; + + if (k_rot) { + q = llama_mul_mat_hadamard(ctx0, q, k_rot); + k = llama_mul_mat_hadamard(ctx0, k, k_rot); + } + if (v_rot) { + v = llama_mul_mat_hadamard(ctx0, v, v_rot); + } + + ggml_build_forward_expand(gf, q); + ggml_build_forward_expand(gf, k); + ggml_build_forward_expand(gf, v); + + const auto * cache = is_swa ? inp_attn->mctx->get_swa() : inp_attn->mctx->get_base(); + const auto & k_idxs = is_swa ? inp_attn->get_k_idxs_swa() : inp_attn->get_k_idxs(); + const auto & v_idxs = is_swa ? inp_attn->get_v_idxs_swa() : inp_attn->get_v_idxs(); + + ggml_build_forward_expand(gf, cache->cpy_k(ctx0, k, k_idxs, il)); + ggml_build_forward_expand(gf, cache->cpy_v(ctx0, v, v_idxs, il)); + + ggml_tensor * q_fa = ggml_view_4d(ctx0, q, + q->ne[0], q->ne[1], q->ne[2]/n_stream, n_stream, + q->nb[1], q->nb[2], q->nb[3]/n_stream, 0); + ggml_tensor * k_fa = cache->get_k(ctx0, il); + ggml_tensor * v_fa = cache->get_v(ctx0, il); + + const int64_t n_kv_flash = is_swa ? n_kv_flash_swa : n_kv_flash_base; + GGML_ASSERT(n_stream == 1 && n_kv_flash <= k_fa->ne[2]); + + k_fa = ggml_view_4d(ctx0, k_fa, + k_fa->ne[0], k_fa->ne[1], n_kv_flash, k_fa->ne[3], + k_fa->nb[1], k_fa->nb[2], k_fa->nb[3], 0); + + const bool v_trans = v_fa->nb[1] > v_fa->nb[2]; + if (v_trans) { + GGML_ASSERT(n_kv_flash <= v_fa->ne[0]); + v_fa = ggml_view_4d(ctx0, v_fa, + n_kv_flash, v_fa->ne[1], v_fa->ne[2], v_fa->ne[3], + v_fa->nb[1], v_fa->nb[2], v_fa->nb[3], 0); + } else { + GGML_ASSERT(n_kv_flash <= v_fa->ne[2]); + v_fa = ggml_view_4d(ctx0, v_fa, + v_fa->ne[0], v_fa->ne[1], n_kv_flash, v_fa->ne[3], + v_fa->nb[1], v_fa->nb[2], v_fa->nb[3], 0); + } + + q_fa = ggml_permute(ctx0, q_fa, 0, 2, 1, 3); + k_fa = ggml_permute(ctx0, k_fa, 0, 2, 1, 3); + v_fa = ggml_permute(ctx0, v_fa, 0, 2, 1, 3); + + if (v_trans) { + v_fa = ggml_transpose(ctx0, v_fa); + } + if (k_fa->type == GGML_TYPE_F32) { + k_fa = ggml_cast(ctx0, k_fa, GGML_TYPE_F16); + } + if (v_fa->type == GGML_TYPE_F32) { + v_fa = ggml_cast(ctx0, v_fa, GGML_TYPE_F16); + } + + ggml_tensor * rel_fa = ggml_reshape_4d(ctx0, rel, + rel_extent, n_head, n_tokens/n_stream, n_stream); + ggml_tensor * mask = is_swa ? inp_attn->get_kq_mask_swa() : inp_attn->get_kq_mask(); + mask = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, + n_kv_flash, mask->ne[1], mask->ne[2], mask->ne[3], + mask->nb[1], mask->nb[2], mask->nb[3], 0)); + + cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, mask, rel_fa, + 1.0f/float(head_dim), rel_extent); + ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32); + res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); + + cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); + ggml_build_forward_expand(gf, cur); + cb(cur, "kqv_out", il); + + if (v_rot) { + cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); + } + cur = build_lora_mm(layer.wo, cur); + } else { + // soft_max_ext scales kq + kq_b jointly: fold 1/head_dim into q to keep the bias unscaled + q = ggml_scale(ctx0, q, 1.0f/float(head_dim)); + + // zero column at index E is gathered by out-of-band / empty-cell indices + rel = ggml_pad(ctx0, rel, 1, 0, 0, 0); // {E+1, n_head, n_tokens} + rel = ggml_cont(ctx0, ggml_permute(ctx0, rel, 1, 0, 2, 3)); // {n_head, E+1, n_tokens} + rel = ggml_reshape_2d(ctx0, rel, n_head, (rel_extent + 1)*n_tokens); + + ggml_tensor * idx = is_swa ? rel_idx_swa : rel_idx; // {n_kv, n_tokens} + GGML_ASSERT(idx != nullptr); + const int64_t n_kv = idx->ne[0]; + + ggml_tensor * idx1 = ggml_reshape_1d(ctx0, idx, n_kv*n_tokens); + + ggml_tensor * kq_b = ggml_get_rows(ctx0, rel, idx1); // {n_head, n_kv*n_tokens} + kq_b = ggml_reshape_3d(ctx0, kq_b, n_head, n_kv, n_tokens); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); // {n_kv, n_tokens, n_head} + cb(kq_b, "inkling_kq_b", il); + + // streamed kq is [n_kv, n_tokens/n_stream, n_head, n_stream], tokens stream-major: view kq_b to match (same trick as the KQ mask) + if (n_stream > 1) { + kq_b = ggml_view_4d(ctx0, kq_b, n_kv, n_tokens/n_stream, n_head, n_stream, + kq_b->nb[1], + kq_b->nb[2], + (n_tokens/n_stream)*kq_b->nb[1], + 0); + } + + cur = build_attn(inp_attn, + layer.wo, NULL, NULL, + q, k, v, kq_b, nullptr, nullptr, 1.0f, il); + } + cb(cur, "inkling_attn_o", il); + + return cur; + }; + + auto build_dense_ffn = [&](ggml_tensor * cur, int il) -> ggml_tensor * { + cur = build_ffn(cur, + model.layers[il].ffn_up, NULL, NULL, + model.layers[il].ffn_gate, NULL, NULL, + model.layers[il].ffn_down, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + cur = ggml_mul(ctx0, cur, model.layers[il].ffn_gscale); + cb(cur, "inkling_dense_ffn_out", il); + return cur; + }; + + // custom MoE routing (not expressible via build_moe_ffn): select by top-k(sigmoid(logits) + bias), weight by softmax(logsigmoid(raw logits)) * scales + auto build_moe = [&](ggml_tensor * cur, int il) -> ggml_tensor * { + const auto & layer = model.layers[il]; + + const int64_t n_shexp = hparams.n_expert_shared; + + ggml_tensor * logits = build_lora_mm( + layer.ffn_gate_inp, cur, nullptr, GGML_PREC_F32_PEDANTIC); // {n_expert + n_shexp, n_tokens} + cb(logits, "inkling_moe_logits", il); + + const size_t lsz = ggml_element_size(logits); + + ggml_tensor * routed = ggml_cont(ctx0, ggml_view_2d(ctx0, logits, n_expert, n_tokens, logits->nb[1], 0)); + ggml_tensor * shared_logits = ggml_view_2d(ctx0, logits, n_shexp, n_tokens, logits->nb[1], n_expert*lsz); + + // bias affects selection only, not the weights + ggml_tensor * scores = ggml_sigmoid(ctx0, routed); + scores = ggml_add(ctx0, scores, layer.ffn_exp_probs_b); + cb(scores, "inkling_moe_scores", il); + + ggml_tensor * selected = ggml_argsort_top_k(ctx0, scores, n_expert_used); // I32 {n_expert_used, n_tokens} + cb(selected, "inkling_moe_topk", il); + + // weights use the raw top-k logits, not the biased scores + ggml_tensor * routed3 = ggml_reshape_3d(ctx0, routed, 1, n_expert, n_tokens); + ggml_tensor * topk_logits = ggml_get_rows(ctx0, routed3, selected); // {1, n_expert_used, n_tokens} + topk_logits = ggml_reshape_2d(ctx0, topk_logits, n_expert_used, n_tokens); + + ggml_tensor * all_logits = ggml_concat(ctx0, topk_logits, shared_logits, 0); // {n_expert_used + n_shexp, n_tokens} + + // logsigmoid(x) = -softplus(-x) + ggml_tensor * w = ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, all_logits))); + w = ggml_soft_max(ctx0, w); + w = ggml_scale(ctx0, w, hparams.expert_weights_scale); + w = ggml_mul(ctx0, w, layer.ffn_gscale); // gate global_scale (F32 [1]) + cb(w, "inkling_moe_weights", il); + + const size_t wsz = ggml_element_size(w); + + ggml_tensor * weights = ggml_cont(ctx0, ggml_view_2d(ctx0, w, n_expert_used, n_tokens, w->nb[1], 0)); + weights = ggml_reshape_3d(ctx0, weights, 1, n_expert_used, n_tokens); + + ggml_tensor * xr = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); + ggml_tensor * gate = build_lora_mm_id(layer.ffn_gate_exps, xr, selected); // {n_ff_exp, n_expert_used, n_tokens} + ggml_tensor * up = build_lora_mm_id(layer.ffn_up_exps, xr, selected); + ggml_tensor * h = ggml_swiglu_split(ctx0, gate, up); + + ggml_tensor * experts = build_lora_mm_id(layer.ffn_down_exps, h, selected); // {n_embd, n_expert_used, n_tokens} + experts = ggml_mul(ctx0, experts, weights); + + ggml_tensor * moe_out = nullptr; + for (int64_t i = 0; i < n_expert_used; ++i) { + ggml_tensor * e = ggml_view_2d(ctx0, experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1]); + moe_out = moe_out ? ggml_add(ctx0, moe_out, e) : e; + } + + // shared experts: mul_mat_id with constant ids (never 2D-view a quantized/repacked weight) + GGML_ASSERT(shexp_idx != nullptr); + ggml_tensor * gs = build_lora_mm_id(layer.ffn_gate_shexp, xr, shexp_idx); // {n_ff_exp, n_shexp, n_tokens} + ggml_tensor * us = build_lora_mm_id(layer.ffn_up_shexp, xr, shexp_idx); + ggml_tensor * hs = ggml_swiglu_split(ctx0, gs, us); + + // gammas (last n_shexp weight rows) must scale hs BEFORE the down-proj to match reference rounding in bf16/quant + ggml_tensor * gammas = ggml_cont(ctx0, ggml_view_2d(ctx0, w, n_shexp, n_tokens, w->nb[1], n_expert_used*wsz)); + hs = ggml_mul(ctx0, hs, ggml_reshape_3d(ctx0, gammas, 1, n_shexp, n_tokens)); + ggml_tensor * ds = build_lora_mm_id(layer.ffn_down_shexp, hs, shexp_idx); // {n_embd, n_shexp, n_tokens} + + for (int64_t s = 0; s < n_shexp; ++s) { + ggml_tensor * e = ggml_view_2d(ctx0, ds, n_embd, n_tokens, ds->nb[2], s*ds->nb[1]); + moe_out = ggml_add(ctx0, moe_out, e); + } + cb(moe_out, "inkling_moe_out", il); + + return moe_out; + }; + + ggml_tensor * cur = build_inp_embd(model.tok_embd); + // mtmd embd rows arrive pre-normalized; embed_norm applies to text token lookups only + if (ubatch.token) { + cur = build_norm(cur, model.tok_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "inkling_embd_norm", -1); + } else { + cb(cur, "inkling_mm_embd", -1); + } + + ggml_build_forward_expand(gf, cur); + + for (int il = 0; il < n_layer; ++il) { + conv_rs_cur = build_rs(inp_hybrid->get_recr(), mctx_recr->get_r_l(il), n_embd_r, n_seqs); + + // h += attn_sconv(attn(attn_norm(h))) + ggml_tensor * attn_in = build_norm(cur, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(attn_in, "inkling_attn_norm", il); + ggml_tensor * attn_out = build_attn_block(attn_in, il); + attn_out = build_sconv(attn_out, model.layers[il].shortconv_attn, off_attn, il); + cb(attn_out, "inkling_attn_sconv", il); + + cur = ggml_add(ctx0, cur, attn_out); + + // h += mlp_sconv(mlp(mlp_norm(h))) + ggml_tensor * ffn_in = build_norm(cur, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(ffn_in, "inkling_ffn_norm", il); + ggml_tensor * ffn_out = il < (int) hparams.n_layer_dense_lead ? + build_dense_ffn(ffn_in, il) : build_moe(ffn_in, il); + ffn_out = build_sconv(ffn_out, model.layers[il].shortconv_mlp, off_mlp, il); + cb(ffn_out, "inkling_ffn_sconv", il); + + cur = ggml_add(ctx0, cur, ffn_out); + + cur = build_cvec(cur, il); + cb(cur, "l_out", il); + } + + // conv states need every layer to see ALL tokens, so trim outputs only after the full stack + ggml_tensor * inp_out_ids = build_inp_out_ids(); + if (inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + + cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + + if (!cparams.embeddings) { + cur = ggml_scale(ctx0, cur, hparams.f_logit_scale); + cur = build_lora_mm( + model.output, cur, nullptr, + model.output->type == GGML_TYPE_F32 ? GGML_PREC_F32_PEDANTIC : GGML_PREC_DEFAULT); + + // padded vocab rows get -inf so samplers never emit a padded id + if (vocab_mask) { + cur = ggml_add(ctx0, cur, vocab_mask); + } + cb(cur, "result_output", -1); + res->t_logits = cur; + } + + ggml_build_forward_expand(gf, cur); +} diff --git a/src/models/models.h b/src/models/models.h index a86ae05aae6b..d13c04c57fca 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -1835,6 +1835,19 @@ struct llama_model_lfm2moe : public llama_model_base { }; +struct llama_model_inkling : public llama_model_base { + llama_model_inkling(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; + + struct graph : public llm_graph_context { + graph(const llama_model & model, const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + + struct llama_model_smallthinker : public llama_model_base { llama_model_smallthinker(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7a93b19a0765..8fda15806815 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -265,6 +265,14 @@ if (NOT LLAMA_SANITIZE_ADDRESS AND NOT GGML_SCHED_NO_REALLOC) endif() llama_build_and_test(test-backend-ops.cpp) +add_executable(test-flash-attn-bias test-flash-attn-bias.cpp) +target_link_libraries(test-flash-attn-bias PRIVATE ggml) +add_test(NAME test-flash-attn-bias COMMAND test-flash-attn-bias) + +add_executable(test-flash-attn-generic-hash test-flash-attn-generic-hash.cpp) +target_link_libraries(test-flash-attn-generic-hash PRIVATE ggml) +add_test(NAME test-flash-attn-generic-hash COMMAND test-flash-attn-generic-hash) + llama_build_and_test(test-model-load-cancel.cpp LABEL "model") llama_build_and_test(test-autorelease.cpp LABEL "model") llama_build_and_test(test-backend-sampler.cpp LABEL "model") diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index e3553c5e9ca1..243d2aaeef73 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -6912,6 +6912,101 @@ struct test_flash_attn_ext : public test_case { } }; +// GGML_OP_FLASH_ATTN_EXT_BANDED +struct test_flash_attn_ext_banded : public test_case { + const int64_t d; + const int64_t n_head; + const int64_t n_head_kv; + const int64_t n_q; + const int64_t n_kv; + const int64_t rel_extent; + const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent + const ggml_type kv_type; + const ggml_type rel_type; + const bool strided; + + std::string vars() override { + return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); + } + + double max_nmse_err() override { + if (kv_type == GGML_TYPE_F32 && rel_type == GGML_TYPE_F32) { + return 2e-6; + } + // fp16 VKQ accumulation error grows with the KV length (plus periodic accumulator + // rescales guarding against fp16 overflow) + return n_kv > 8192 ? 1e-3 : 5e-4; + } + + uint64_t op_flops(ggml_tensor * t) override { + GGML_UNUSED(t); + return 4*n_head*n_q*n_kv*d; + } + + test_flash_attn_ext_banded( + int64_t d, int64_t n_head, int64_t n_head_kv, + int64_t n_q, int64_t n_kv, int64_t rel_extent, + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false) + : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), + rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + ggml_tensor * k; + ggml_tensor * v; + ggml_tensor * r; + if (strided) { + // gaps between rows/heads force the kernels to use the 64-bit byte strides + ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); + k = ggml_view_4d(ctx, kb, d, n_kv, n_head_kv, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0); + v = ggml_view_4d(ctx, vb, d, n_kv, n_head_kv, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0); + r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); + } else { + k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); + } + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + + ggml_tensor * m = nullptr; + if (mask_kind != 0) { + m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); + ggml_set_name(m, "m"); + } + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); + ggml_flash_attn_ext_set_prec(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + std::vector data(n_q*n_kv); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < n_kv; ++ik) { + const int64_t rel_dist = iq + (n_kv - n_q) - ik; + const bool visible = rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent); + data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (strcmp(t->name, "rel_logits") == 0) { + // A larger range makes rel_dist = E versus E-1 mistakes immediately visible. + init_tensor_uniform(t, -1.0f, 1.0f); + } else { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + // GGML_OP_CROSS_ENTROPY_LOSS struct test_cross_entropy_loss : public test_case { const ggml_type type; @@ -7491,6 +7586,7 @@ struct test_generic_op : public test_case { case GGML_OP_RWKV_WKV7: return 5e-3; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { // Scale error with kv length to account for accumulating floating point error const int64_t kv = sources[1].ne[1]; @@ -7514,7 +7610,7 @@ struct test_generic_op : public test_case { } // FLASH_ATTN_EXT: src[3] is the KQ mask - if (op == GGML_OP_FLASH_ATTN_EXT && i == 3) { + if ((op == GGML_OP_FLASH_ATTN_EXT || op == GGML_OP_FLASH_ATTN_EXT_BANDED) && i == 3) { init_tensor_kq_mask(t); continue; } @@ -9542,6 +9638,22 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext(64, 128, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_Q1_0)); test_cases.emplace_back(new test_flash_attn_ext(128, 64, 4, {1, 1}, 64, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q1_0, GGML_TYPE_F16)); + // banded score-bias coverage: band edges, masks, decode offset, GQA, head sizes, table types + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 2, 1, 8, 8, 8, 1, GGML_TYPE_F32, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 16, 16, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16)); + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 1, 64, 8, 1, GGML_TYPE_F32, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 1, 64, 64, 512, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 17, 33, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, true)); + // production-scale n_kv straddling the observed ~16.4-16.9K garbage threshold + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16896, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 17024, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 17024, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 32768, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_cross_entropy_loss (GGML_TYPE_F32, { 10, 5, 4, 3})); test_cases.emplace_back(new test_cross_entropy_loss (GGML_TYPE_F32, {30000, 1, 1, 1})); test_cases.emplace_back(new test_cross_entropy_loss_back(GGML_TYPE_F32, { 10, 5, 4, 3})); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 93685ec8ff42..1b8ed9b1de02 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -2909,6 +2909,85 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .run(); } + { + // Inkling / TML typed content blocks: <|end_message|> separates blocks, <|content_model_end_sampling|> ends the turn. + auto tst = peg_tester("models/templates/Inkling.jinja", detailed_debug); + + // reasoning + visible answer + tst.test("<|content_thinking|>I'm\nthinking<|end_message|>" + "<|message_model|><|content_text|>Hello, world!\nWhat's up?<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .expect(message_assist_thoughts) + .run(); + + // Visible answer only (reasoning_effort=0 -> no thinking block). + tst.test("<|content_text|>Hello, world!\nWhat's up?<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .expect(message_assist) + .run(); + + // Empty thinking block, then the answer. + tst.test("<|content_thinking|><|end_message|>" + "<|message_model|><|content_text|>Hello, world!\nWhat's up?<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .expect(message_assist) + .run(); + + // single tool call with reasoning; the bare tool-name echo and role opener are dropped + tst.test("<|content_thinking|>I'm\nthinking<|end_message|>" + "<|message_model|>special_function<|content_invoke_tool_json|>" + "{\"name\":\"special_function\",\"args\":{\"arg1\":1}}<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ special_function_tool }) + .expect(message_with_reasoning_and_tool_call("I'm\nthinking", "special_function", "{\"arg1\": 1}")) + .run(); + + // Tool call, no reasoning. + tst.test("<|message_model|>special_function<|content_invoke_tool_json|>" + "{\"name\":\"special_function\",\"args\":{\"arg1\":1}}<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ special_function_tool }) + .expect(message_assist_call) + .run(); + + // regression: the tool branch must not swallow a pure-text answer + tst.test("<|content_thinking|>I'm\nthinking<|end_message|>" + "<|message_model|><|content_text|>Hello, world!\nWhat's up?<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ special_function_tool }) + .expect(message_assist_thoughts) + .run(); + + // tools available, content only, no thinking (reasoning_effort=0 leak scenario) + tst.test("<|content_text|>Hello, world!\nWhat's up?<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ special_function_tool }) + .expect(message_assist) + .run(); + + // parallel tool calls are separate marker-wrapped blocks + tst.test("<|message_model|>special_function<|content_invoke_tool_json|>" + "{\"name\":\"special_function\",\"args\":{\"arg1\":1}}<|end_message|>" + "<|message_model|>python<|content_invoke_tool_json|>" + "{\"name\":\"python\",\"args\":{\"code\":\"print('hey')\"}}<|end_message|>" + "<|content_model_end_sampling|>") + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .parallel_tool_calls(true) + .tools({ special_function_tool, python_tool }) + .expect_tool_calls({ + { "special_function", R"({"arg1": 1})", "" }, + { "python", "{\"code\": \"print('hey')\"}", "" }, + }) + .run(); + } + { // Google Gemma 2 2B - does not support tool calling auto tst = peg_tester("models/templates/google-gemma-2-2b-it.jinja"); diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp new file mode 100644 index 000000000000..94232b32dbcb --- /dev/null +++ b/tests/test-flash-attn-bias.cpp @@ -0,0 +1,525 @@ +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct bias_test_config { + const char * name; + int64_t d; + int64_t nq; + int64_t nkv; + int64_t hq; + int64_t hkv; + int64_t extent; + ggml_type type; + bool use_mask; + bool sliding; + int64_t n_batch = 1; + int64_t rel_batch = 1; + bool strided_rel = false; +}; + +struct test_data { + std::vector q; + std::vector k; + std::vector v; + std::vector rel; + std::vector mask; + std::vector k_typed; + std::vector v_typed; + std::vector rel_typed; + std::vector k_rounded; + std::vector v_rounded; + std::vector rel_rounded; + std::vector dense_bias; +}; + +struct run_result { + std::vector output; + size_t allocated_bytes; + double ms; +}; + +static std::vector convert_type(ggml_type type, const std::vector & src, std::vector & rounded) { + rounded.resize(src.size()); + if (type == GGML_TYPE_F32) { + rounded = src; + std::vector bytes(src.size()*sizeof(float)); + memcpy(bytes.data(), src.data(), bytes.size()); + return bytes; + } + if (type == GGML_TYPE_F16) { + std::vector tmp(src.size()); + ggml_fp32_to_fp16_row(src.data(), tmp.data(), src.size()); + ggml_fp16_to_fp32_row(tmp.data(), rounded.data(), src.size()); + std::vector bytes(tmp.size()*sizeof(tmp[0])); + memcpy(bytes.data(), tmp.data(), bytes.size()); + return bytes; + } + GGML_ASSERT(type == GGML_TYPE_BF16); + std::vector tmp(src.size()); + ggml_fp32_to_bf16_row_ref(src.data(), tmp.data(), src.size()); + ggml_bf16_to_fp32_row(tmp.data(), rounded.data(), src.size()); + std::vector bytes(tmp.size()*sizeof(tmp[0])); + memcpy(bytes.data(), tmp.data(), bytes.size()); + return bytes; +} + +static test_data make_data(const bias_test_config & c) { + test_data data; + data.q.resize(c.d*c.nq*c.hq*c.n_batch); + data.k.resize(c.d*c.nkv*c.hkv*c.n_batch); + data.v.resize(c.d*c.nkv*c.hkv*c.n_batch); + data.rel.resize(c.extent*c.hq*c.nq*c.rel_batch); + data.mask.resize(c.nkv*c.nq); + + for (size_t i = 0; i < data.q.size(); ++i) { + data.q[i] = 0.20f*std::sin(float(i)*0.017f + 0.13f); + } + for (size_t i = 0; i < data.k.size(); ++i) { + data.k[i] = 0.25f*std::cos(float(i)*0.013f - 0.29f); + data.v[i] = 0.30f*std::sin(float(i)*0.019f + 0.71f); + } + for (int64_t ib = 0; ib < c.rel_batch; ++ib) { + for (int64_t iq = 0; iq < c.nq; ++iq) { + for (int64_t ih = 0; ih < c.hq; ++ih) { + for (int64_t ie = 0; ie < c.extent; ++ie) { + const size_t idx = ((ib*c.nq + iq)*c.hq + ih)*c.extent + ie; + data.rel[idx] = 0.75f*std::sin(float(idx)*0.007f + float(ie)*0.021f + 0.31f); + } + } + } + } + for (int64_t iq = 0; iq < c.nq; ++iq) { + for (int64_t ik = 0; ik < c.nkv; ++ik) { + const int64_t dist = iq + (c.nkv - c.nq) - ik; + const bool visible = !c.use_mask || (dist >= 0 && (!c.sliding || dist < c.extent)); + data.mask[iq*c.nkv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + + data.k_typed = convert_type(c.type, data.k, data.k_rounded); + data.v_typed = convert_type(c.type, data.v, data.v_rounded); + data.rel_typed = convert_type(GGML_TYPE_F32, data.rel, data.rel_rounded); + + data.dense_bias.assign(c.nkv*c.nq*c.hq*c.n_batch, 0.0f); + for (int64_t ib = 0; ib < c.n_batch; ++ib) { + const int64_t irb = ib % c.rel_batch; + for (int64_t ih = 0; ih < c.hq; ++ih) { + for (int64_t iq = 0; iq < c.nq; ++iq) { + for (int64_t ik = 0; ik < c.nkv; ++ik) { + const int64_t dist = iq + (c.nkv - c.nq) - ik; + if (dist >= 0 && dist < c.extent) { + data.dense_bias[((ib*c.hq + ih)*c.nq + iq)*c.nkv + ik] = + data.rel_rounded[((irb*c.nq + iq)*c.hq + ih)*c.extent + dist]; + } + } + } + } + } + return data; +} + +static run_result run_graph( + ggml_backend_t backend, + const bias_test_config & c, + const test_data & data, + bool dense, + int repeats) { + ggml_init_params params = { + /* .mem_size = */ ggml_tensor_overhead()*64 + ggml_graph_overhead_custom(64, false), + /* .mem_base = */ nullptr, + /* .no_alloc = */ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + GGML_ASSERT(ctx); + + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.d, c.nq, c.hq, c.n_batch); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), c.type, c.d, c.nkv, c.hkv, c.n_batch); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), c.type, c.d, c.nkv, c.hkv, c.n_batch); + ggml_tensor * r_storage = nullptr; + ggml_tensor * r; + if (c.strided_rel) { + r_storage = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, + 2*c.extent, c.hq, c.nq, c.rel_batch); + r = ggml_view_4d(ctx.get(), r_storage, c.extent, c.hq, c.nq, c.rel_batch, + r_storage->nb[1], r_storage->nb[2], r_storage->nb[3], 0); + } else { + r = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, + c.extent, c.hq, c.nq, c.rel_batch); + } + ggml_tensor * m = c.use_mask ? ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, c.nkv, c.nq, 1, 1) : nullptr; + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + if (m) { + ggml_set_name(m, "mask"); + } + + ggml_tensor * out; + ggml_tensor * bias = nullptr; + if (!dense) { + out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, m, r, 1.0f/float(c.d), c.extent); + } else { + bias = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.nkv, c.nq, c.hq, c.n_batch); + ggml_set_name(bias, "dense_bias"); + ggml_tensor * scores = ggml_mul_mat(ctx.get(), k, q); + ggml_mul_mat_set_prec(scores, GGML_PREC_F32); + scores = ggml_scale(ctx.get(), scores, 1.0f/float(c.d)); + scores = ggml_add(ctx.get(), scores, bias); + scores = ggml_soft_max_ext(ctx.get(), scores, m, 1.0f, 0.0f); + ggml_tensor * vt = ggml_cont(ctx.get(), ggml_transpose(ctx.get(), v)); + out = ggml_mul_mat(ctx.get(), vt, scores); + ggml_mul_mat_set_prec(out, GGML_PREC_F32); + out = ggml_cont(ctx.get(), ggml_permute(ctx.get(), out, 0, 2, 1, 3)); + } + ggml_set_name(out, dense ? "out_dense" : "out_flash"); + + GGML_ASSERT(ggml_backend_supports_op(backend, out)); + ggml_backend_buffer_ptr buffer(ggml_backend_alloc_ctx_tensors(ctx.get(), backend)); + GGML_ASSERT(buffer); + + ggml_backend_tensor_set(q, data.q.data(), 0, data.q.size()*sizeof(float)); + ggml_backend_tensor_set(k, data.k_typed.data(), 0, data.k_typed.size()); + ggml_backend_tensor_set(v, data.v_typed.data(), 0, data.v_typed.size()); + if (r_storage) { + std::vector physical(2*c.extent*c.hq*c.nq*c.rel_batch, 0.0f); + for (int64_t ib = 0; ib < c.rel_batch; ++ib) { + for (int64_t iq = 0; iq < c.nq; ++iq) { + for (int64_t ih = 0; ih < c.hq; ++ih) { + const size_t logical = ((ib*c.nq + iq)*c.hq + ih)*c.extent; + const size_t storage = ((ib*c.nq + iq)*c.hq + ih)*(2*c.extent); + memcpy(physical.data() + storage, data.rel_rounded.data() + logical, + c.extent*sizeof(float)); + } + } + } + ggml_backend_tensor_set(r_storage, physical.data(), 0, physical.size()*sizeof(float)); + } else { + ggml_backend_tensor_set(r, data.rel_typed.data(), 0, data.rel_typed.size()); + } + if (m) { + ggml_backend_tensor_set(m, data.mask.data(), 0, data.mask.size()*sizeof(data.mask[0])); + } + if (bias) { + ggml_backend_tensor_set(bias, data.dense_bias.data(), 0, data.dense_bias.size()*sizeof(float)); + } + + ggml_cgraph * graph = ggml_new_graph_custom(ctx.get(), 64, false); + ggml_build_forward_expand(graph, out); + GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); + ggml_backend_synchronize(backend); + + const int64_t start = ggml_time_us(); + for (int i = 0; i < repeats; ++i) { + GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); + } + ggml_backend_synchronize(backend); + const int64_t elapsed = ggml_time_us() - start; + + run_result result; + result.output.resize(ggml_nelements(out)); + ggml_backend_tensor_get(out, result.output.data(), 0, result.output.size()*sizeof(float)); + result.allocated_bytes = ggml_backend_buffer_get_size(buffer.get()); + result.ms = double(elapsed)/1000.0/repeats; + return result; +} + +static std::vector naive_materialized(const bias_test_config & c, const test_data & data) { + const int64_t nrows = c.n_batch*c.hq*c.nq; + std::vector scores(nrows*c.nkv); + std::vector output(c.d*c.hq*c.nq*c.n_batch, 0.0f); + std::atomic next_row(0); + const unsigned nt = std::max(1u, std::thread::hardware_concurrency()); + std::vector workers; + workers.reserve(nt); + + for (unsigned it = 0; it < nt; ++it) { + workers.emplace_back([&]() { + while (true) { + const int64_t row = next_row.fetch_add(1); + if (row >= nrows) { + break; + } + const int64_t ib = row / (c.hq*c.nq); + const int64_t ih = (row / c.nq) % c.hq; + const int64_t iq = row % c.nq; + const int64_t ihkv = ih / (c.hq/c.hkv); + float row_max = -INFINITY; + for (int64_t ik = 0; ik < c.nkv; ++ik) { + float dot = 0.0f; + for (int64_t id = 0; id < c.d; ++id) { + dot += data.q[((ib*c.hq + ih)*c.nq + iq)*c.d + id] * + data.k_rounded[((ib*c.hkv + ihkv)*c.nkv + ik)*c.d + id]; + } + const float mask = ggml_fp16_to_fp32(data.mask[iq*c.nkv + ik]); + const float score = dot/float(c.d) + data.dense_bias[row*c.nkv + ik] + mask; + scores[row*c.nkv + ik] = score; + row_max = std::max(row_max, score); + } + float sum = 0.0f; + for (int64_t ik = 0; ik < c.nkv; ++ik) { + const float p = std::exp(scores[row*c.nkv + ik] - row_max); + scores[row*c.nkv + ik] = p; + sum += p; + } + for (int64_t ik = 0; ik < c.nkv; ++ik) { + const float p = scores[row*c.nkv + ik]/sum; + for (int64_t id = 0; id < c.d; ++id) { + output[((ib*c.nq + iq)*c.hq + ih)*c.d + id] += + p*data.v_rounded[((ib*c.hkv + ihkv)*c.nkv + ik)*c.d + id]; + } + } + } + }); + } + for (auto & worker : workers) { + worker.join(); + } + return output; +} + +static void error_stats(const std::vector & got, const std::vector & ref, + double & max_abs, double & mean_abs, double & max_rel, double & mean_rel, double & rmse) { + double sq = 0.0; + double abs_sum = 0.0; + double rel_sum = 0.0; + max_abs = 0.0; + max_rel = 0.0; + for (size_t i = 0; i < got.size(); ++i) { + const double ae = std::abs(double(got[i]) - ref[i]); + const double re = ae/std::max(1e-5, std::abs(double(ref[i]))); + max_abs = std::max(max_abs, ae); + max_rel = std::max(max_rel, re); + abs_sum += ae; + rel_sum += re; + sq += ae*ae; + } + mean_abs = abs_sum/got.size(); + mean_rel = rel_sum/got.size(); + rmse = std::sqrt(sq/got.size()); +} + +static void overflow_arithmetic_self_test() { + // mirrors the scalar-path offset math; exact offset checked at 128 bits, lands past 2^31 + const uint64_t nb0 = sizeof(float); + const uint64_t nb1 = 1024*nb0; + const uint64_t nb2 = 64*nb1; + const uint64_t nb3 = 131072*nb2; + const uint64_t dist = 1023, head = 63, query = 131071, batch = 3; + const uint64_t offset = dist*nb0 + head*nb1 + query*nb2 + batch*nb3; + __extension__ typedef unsigned __int128 uint128_t; + const uint128_t exact = uint128_t(dist)*nb0 + uint128_t(head)*nb1 + + uint128_t(query)*nb2 + uint128_t(batch)*nb3; + GGML_ASSERT(exact <= UINT64_MAX && offset == (uint64_t) exact && offset > INT32_MAX); + + const int64_t nq = int64_t(1) << 40; + const int64_t nkv = nq + 8192; + const int64_t iq = nq - 1; + const int64_t ik = nkv - 1024; + const int64_t rel_dist = iq + (nkv - nq) - ik; + GGML_ASSERT(rel_dist == 1023); + printf("overflow_check offset=%llu (>INT32_MAX) large_T=%lld rel_dist=%lld PASS\n", + (unsigned long long) offset, (long long) nq, (long long) rel_dist); +} + +static bool overflow_kernel_test(ggml_backend_t backend, const char * backend_kind) { + // rel-logits row for query 1 sits beyond INT32_MAX; only two small logical rows are touched + const bias_test_config c = { + "overflow_kernel_stride", 64, 2, 2, 2, 1, 8, GGML_TYPE_F32, true, false, + }; + test_data data = make_data(c); + const uint64_t rel_nb2 = (UINT64_C(1) << 31) + 4096; + const size_t rel_row_bytes = c.extent*c.hq*sizeof(float); + const uint64_t storage_bytes = rel_nb2 + rel_row_bytes; + + ggml_init_params params = { + /* .mem_size = */ ggml_tensor_overhead()*32 + ggml_graph_overhead_custom(32, false), + /* .mem_base = */ nullptr, + /* .no_alloc = */ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + GGML_ASSERT(ctx); + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.d, c.nq, c.hq, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.d, c.nkv, c.hkv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.d, c.nkv, c.hkv, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, c.nkv, c.nq, 1, 1); + ggml_tensor * r_storage = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_F32, + (storage_bytes + sizeof(float) - 1)/sizeof(float)); + ggml_tensor * r = ggml_view_4d(ctx.get(), r_storage, c.extent, c.hq, c.nq, 1, + c.extent*sizeof(float), rel_nb2, rel_nb2*c.nq, 0); + ggml_tensor * out = ggml_flash_attn_ext_banded( + ctx.get(), q, k, v, m, r, 1.0f/float(c.d), c.extent); + ggml_backend_buffer_ptr buffer(ggml_backend_alloc_ctx_tensors(ctx.get(), backend)); + GGML_ASSERT(buffer); + + ggml_backend_tensor_set(q, data.q.data(), 0, data.q.size()*sizeof(float)); + ggml_backend_tensor_set(k, data.k_typed.data(), 0, data.k_typed.size()); + ggml_backend_tensor_set(v, data.v_typed.data(), 0, data.v_typed.size()); + ggml_backend_tensor_set(m, data.mask.data(), 0, data.mask.size()*sizeof(data.mask[0])); + ggml_backend_tensor_set(r_storage, data.rel_typed.data(), 0, rel_row_bytes); + ggml_backend_tensor_set(r_storage, data.rel_typed.data() + rel_row_bytes, rel_nb2, rel_row_bytes); + + ggml_cgraph * graph = ggml_new_graph_custom(ctx.get(), 32, false); + ggml_build_forward_expand(graph, out); + GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); + ggml_backend_synchronize(backend); + std::vector got(ggml_nelements(out)); + ggml_backend_tensor_get(out, got.data(), 0, got.size()*sizeof(float)); + const std::vector ref = naive_materialized(c, data); + double max_abs, mean_abs, max_rel, mean_rel, rmse; + error_stats(got, ref, max_abs, mean_abs, max_rel, mean_rel, rmse); + const bool pass = max_abs <= 2e-5; + printf("overflow_kernel backend=%s rel_query_stride=%llu allocated_bytes=%zu " + "naive_max_abs=%.9g naive_mean_abs=%.9g naive_max_rel=%.9g naive_mean_rel=%.9g naive_rmse=%.9g %s\n", + backend_kind, (unsigned long long) rel_nb2, ggml_backend_buffer_get_size(buffer.get()), + max_abs, mean_abs, max_rel, mean_rel, rmse, pass ? "PASS" : "FAIL"); + return pass; +} + +int main(int argc, char ** argv) { + std::string backend_kind = argc > 1 ? argv[1] : "cpu"; + std::string suite = argc > 2 ? argv[2] : "small"; + int repeats = argc > 3 ? std::max(1, atoi(argv[3])) : 1; + + overflow_arithmetic_self_test(); + ggml_backend_load_all(); + ggml_backend_dev_t chosen = nullptr; + const enum ggml_backend_dev_type wanted = backend_kind == "cuda" ? + GGML_BACKEND_DEVICE_TYPE_GPU : GGML_BACKEND_DEVICE_TYPE_CPU; + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + if (ggml_backend_dev_type(dev) == wanted) { + chosen = dev; + break; + } + } + GGML_ASSERT(chosen); + ggml_backend_ptr backend(ggml_backend_dev_init(chosen, nullptr)); + GGML_ASSERT(backend); + + if (suite == "overflow") { + return overflow_kernel_test(backend.get(), backend_kind.c_str()) ? 0 : 1; + } + + if (suite == "perf") { + const std::vector perf_cases = { + {"prefill_t1024", 64, 1024, 1024, 8, 2, 512, GGML_TYPE_F16, true, false}, + {"prefill_t2048", 64, 2048, 2048, 8, 2, 512, GGML_TYPE_F16, true, false}, + {"prefill_t4096", 64, 4096, 4096, 8, 2, 512, GGML_TYPE_F16, true, false}, + {"decode_8k", 128, 1, 8192, 8, 1, 1024, GGML_TYPE_F16, true, false}, + {"heads64_gqa", 64, 1024, 1024, 64, 8, 512, GGML_TYPE_F16, true, false}, + }; + printf("backend=%s suite=perf device=%s repeats=%d\n", backend_kind.c_str(), + ggml_backend_dev_description(chosen), repeats); + for (const bias_test_config & c : perf_cases) { + test_data data = make_data(c); + const run_result flash = run_graph(backend.get(), c, data, false, repeats); + const run_result dense = run_graph(backend.get(), c, data, true, repeats); + printf("%s type=%s D=%lld nq=%lld nkv=%lld hq=%lld hkv=%lld E=%lld " + "flash_ms=%.6f dense_ms=%.6f speedup=%.6f flash_bytes=%zu dense_bytes=%zu memory_ratio=%.6f\n", + c.name, ggml_type_name(c.type), (long long)c.d, (long long)c.nq, + (long long)c.nkv, (long long)c.hq, (long long)c.hkv, (long long)c.extent, + flash.ms, dense.ms, dense.ms/flash.ms, flash.allocated_bytes, + dense.allocated_bytes, double(dense.allocated_bytes)/flash.allocated_bytes); + } + return 0; + } + + if (suite == "memory") { + const std::vector memory_cases = { + {"memory_t1024", 64, 1024, 1024, 8, 2, 512, GGML_TYPE_F16, false, false}, + {"memory_t2048", 64, 2048, 2048, 8, 2, 512, GGML_TYPE_F16, false, false}, + {"memory_t4096", 64, 4096, 4096, 8, 2, 512, GGML_TYPE_F16, false, false}, + }; + printf("backend=%s suite=memory device=%s\n", backend_kind.c_str(), + ggml_backend_dev_description(chosen)); + for (const bias_test_config & c : memory_cases) { + test_data data = make_data(c); + const run_result flash = run_graph(backend.get(), c, data, false, 1); + const run_result dense = run_graph(backend.get(), c, data, true, 1); + double max_abs, mean_abs, max_rel, mean_rel, rmse; + error_stats(flash.output, dense.output, max_abs, mean_abs, max_rel, mean_rel, rmse); + printf("%s T=%lld flash_bytes=%zu dense_bytes=%zu memory_ratio=%.6f " + "dense_max_abs=%.9g dense_mean_abs=%.9g PASS\n", + c.name, (long long)c.nq, flash.allocated_bytes, dense.allocated_bytes, + double(dense.allocated_bytes)/flash.allocated_bytes, max_abs, mean_abs); + } + return 0; + } + + std::vector configs; + if (suite == "small") { + configs = { + {"edge_e8_f32", 64, 16, 16, 2, 1, 8, GGML_TYPE_F32, true, false}, + {"gqa_d128_f16", 128, 16, 16, 8, 2, 8, GGML_TYPE_F16, true, false}, + {"sliding_bf16", 64, 64, 64, 8, 2, 8, GGML_TYPE_BF16, true, true }, + {"decode_offset", 64, 1, 513, 8, 2, 8, GGML_TYPE_F32, true, false}, + {"extent_512_edge", 64, 64, 64, 8, 1, 512, GGML_TYPE_F16, true, false}, + {"strided_rel_f16", 64, 17, 33, 8, 2, 8, GGML_TYPE_F16, true, false, 1, 1, true}, + {"batch_distinct", 64, 16, 16, 8, 2, 8, GGML_TYPE_F16, true, false, 2, 2, false}, + {"batch_broadcast", 64, 16, 16, 8, 2, 8, GGML_TYPE_F16, true, false, 2, 1, false}, + {"heads64_gqa4", 64, 16, 16, 64, 16, 8, GGML_TYPE_F16, true, false}, + {"heads64_gqa8", 64, 16, 16, 64, 8, 8, GGML_TYPE_F16, true, false}, + }; + } else if (suite == "medium") { + configs = { + {"medium_f32_e512", 64, 1024, 1024, 8, 2, 512, GGML_TYPE_F32, true, false}, + {"medium_f16_e1024", 128, 1024, 1024, 8, 2, 1024, GGML_TYPE_F16, true, false}, + {"medium_bf16_local", 64, 2048, 2048, 8, 2, 512, GGML_TYPE_BF16, true, true }, + {"decode_8k_e1024", 128, 1, 8192, 8, 1, 1024, GGML_TYPE_F16, true, false}, + }; + } else if (suite == "hard") { + configs = { + {"heads64_gqa", 64, 1024, 1024, 64, 8, 512, GGML_TYPE_F16, true, false}, + }; + } else { + fprintf(stderr, "unknown suite: %s (expected small, medium, hard, perf, memory, or overflow)\n", + suite.c_str()); + return 2; + } + + bool ok = true; + printf("backend=%s suite=%s device=%s\n", backend_kind.c_str(), suite.c_str(), ggml_backend_dev_description(chosen)); + for (const bias_test_config & c : configs) { + test_data data = make_data(c); + run_result flash = run_graph(backend.get(), c, data, false, repeats); + run_result dense = run_graph(backend.get(), c, data, true, repeats); + // always compare to an independently materialized oracle (O(T^2), test-only) + const std::vector naive = naive_materialized(c, data); + + double abs_dense, mean_abs_dense, rel_dense, mean_rel_dense, rmse_dense; + error_stats(flash.output, dense.output, abs_dense, mean_abs_dense, rel_dense, mean_rel_dense, rmse_dense); + double abs_naive = 0.0, mean_abs_naive = 0.0, rel_naive = 0.0, mean_rel_naive = 0.0, rmse_naive = 0.0; + error_stats(flash.output, naive, abs_naive, mean_abs_naive, rel_naive, mean_rel_naive, rmse_naive); + const double tol = c.type == GGML_TYPE_F32 ? 2e-5 : 2e-3; + const bool pass = abs_naive <= tol; + ok = ok && pass; + printf("%s type=%s D=%lld nq=%lld nkv=%lld hq=%lld hkv=%lld E=%lld mask=%d sliding=%d " + "batch=%lld rel_batch=%lld strided_rel=%d " + "dense_max_abs=%.9g dense_mean_abs=%.9g dense_max_rel=%.9g dense_mean_rel=%.9g dense_rmse=%.9g " + "naive_max_abs=%.9g naive_mean_abs=%.9g naive_max_rel=%.9g naive_mean_rel=%.9g naive_rmse=%.9g " + "flash_ms=%.4f dense_ms=%.4f speedup=%.4f " + "flash_bytes=%zu dense_bytes=%zu memory_ratio=%.4f %s\n", + c.name, ggml_type_name(c.type), (long long)c.d, (long long)c.nq, (long long)c.nkv, + (long long)c.hq, (long long)c.hkv, (long long)c.extent, c.use_mask, c.sliding, + (long long)c.n_batch, (long long)c.rel_batch, c.strided_rel, + abs_dense, mean_abs_dense, rel_dense, mean_rel_dense, rmse_dense, + abs_naive, mean_abs_naive, rel_naive, mean_rel_naive, rmse_naive, + flash.ms, dense.ms, dense.ms/flash.ms, + flash.allocated_bytes, dense.allocated_bytes, double(dense.allocated_bytes)/flash.allocated_bytes, + pass ? "PASS" : "FAIL"); + } + return ok ? 0 : 1; +} diff --git a/tests/test-flash-attn-generic-hash.cpp b/tests/test-flash-attn-generic-hash.cpp new file mode 100644 index 000000000000..4e3aca44ffab --- /dev/null +++ b/tests/test-flash-attn-generic-hash.cpp @@ -0,0 +1,142 @@ +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" + +#include +#include +#include +#include +#include +#include + +// Deterministic FLASH_ATTN_EXT probe; banded-API-free so the same source builds on base and final trees. +int main(int argc, char ** argv) { + const std::string backend_kind = argc > 1 ? argv[1] : "cpu"; + const std::string output_path = argc > 2 ? argv[2] : ""; + + ggml_backend_load_all(); + const enum ggml_backend_dev_type wanted = backend_kind == "cuda" ? + GGML_BACKEND_DEVICE_TYPE_GPU : GGML_BACKEND_DEVICE_TYPE_CPU; + ggml_backend_dev_t chosen = nullptr; + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + if (ggml_backend_dev_type(dev) == wanted) { + chosen = dev; + break; + } + } + if (!chosen) { + fprintf(stderr, "requested backend is unavailable: %s\n", backend_kind.c_str()); + return 2; + } + ggml_backend_t backend = ggml_backend_dev_init(chosen, nullptr); + if (!backend) { + return 2; + } + + constexpr int64_t d = 64; + constexpr int64_t nq = 33; + constexpr int64_t nkv = 47; + constexpr int64_t hq = 8; + constexpr int64_t hkv = 2; + ggml_init_params params = { + /* .mem_size = */ ggml_tensor_overhead()*16 + ggml_graph_overhead_custom(16, false), + /* .mem_base = */ nullptr, + /* .no_alloc = */ true, + }; + ggml_context * ctx = ggml_init(params); + if (!ctx) { + ggml_backend_free(backend); + return 2; + } + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, nq, hq, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, d, nkv, hkv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, d, nkv, hkv, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, nkv, nq, 1, 1); + ggml_tensor * out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/float(d), 0.0f, 0.0f); + ggml_flash_attn_ext_set_prec(out, GGML_PREC_F32); + if (!ggml_backend_supports_op(backend, out)) { + fprintf(stderr, "ordinary flash attention is unsupported on %s\n", + ggml_backend_dev_description(chosen)); + ggml_free(ctx); + ggml_backend_free(backend); + return 2; + } + + ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (!buffer) { + ggml_free(ctx); + ggml_backend_free(backend); + return 2; + } + + std::vector q_data(ggml_nelements(q)); + std::vector k_f32(ggml_nelements(k)); + std::vector v_f32(ggml_nelements(v)); + std::vector k_data(k_f32.size()); + std::vector v_data(v_f32.size()); + std::vector mask(ggml_nelements(m)); + for (size_t i = 0; i < q_data.size(); ++i) { + q_data[i] = 0.20f*std::sin(0.017f*float(i) + 0.11f); + } + for (size_t i = 0; i < k_f32.size(); ++i) { + k_f32[i] = 0.23f*std::cos(0.013f*float(i) - 0.29f); + v_f32[i] = 0.31f*std::sin(0.019f*float(i) + 0.71f); + } + ggml_fp32_to_fp16_row(k_f32.data(), k_data.data(), k_data.size()); + ggml_fp32_to_fp16_row(v_f32.data(), v_data.data(), v_data.size()); + for (int64_t iq = 0; iq < nq; ++iq) { + for (int64_t ik = 0; ik < nkv; ++ik) { + const int64_t dist = iq + (nkv - nq) - ik; + mask[iq*nkv + ik] = ggml_fp32_to_fp16(dist >= 0 && dist < 29 ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(q, q_data.data(), 0, q_data.size()*sizeof(q_data[0])); + ggml_backend_tensor_set(k, k_data.data(), 0, k_data.size()*sizeof(k_data[0])); + ggml_backend_tensor_set(v, v_data.data(), 0, v_data.size()*sizeof(v_data[0])); + ggml_backend_tensor_set(m, mask.data(), 0, mask.size()*sizeof(mask[0])); + + ggml_cgraph * graph = ggml_new_graph_custom(ctx, 16, false); + ggml_build_forward_expand(graph, out); + const ggml_status status = ggml_backend_graph_compute(backend, graph); + ggml_backend_synchronize(backend); + if (status != GGML_STATUS_SUCCESS) { + fprintf(stderr, "graph failed with status %d\n", int(status)); + ggml_backend_buffer_free(buffer); + ggml_free(ctx); + ggml_backend_free(backend); + return 1; + } + + std::vector result(ggml_nelements(out)); + ggml_backend_tensor_get(out, result.data(), 0, result.size()*sizeof(result[0])); + uint64_t fnv = UINT64_C(1469598103934665603); + const uint8_t * bytes = reinterpret_cast(result.data()); + for (size_t i = 0; i < result.size()*sizeof(result[0]); ++i) { + fnv ^= bytes[i]; + fnv *= UINT64_C(1099511628211); + } + if (!output_path.empty()) { + FILE * fp = fopen(output_path.c_str(), "wb"); + if (!fp || fwrite(result.data(), sizeof(result[0]), result.size(), fp) != result.size()) { + fprintf(stderr, "failed to write %s\n", output_path.c_str()); + if (fp) { + fclose(fp); + } + ggml_backend_buffer_free(buffer); + ggml_free(ctx); + ggml_backend_free(backend); + return 1; + } + fclose(fp); + } + printf("generic_hash backend=%s device=%s bytes=%zu fnv1a64=%016llx\n", + backend_kind.c_str(), ggml_backend_dev_description(chosen), + result.size()*sizeof(result[0]), (unsigned long long) fnv); + + ggml_backend_buffer_free(buffer); + ggml_free(ctx); + ggml_backend_free(backend); + return 0; +} diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 57d33a627d5d..9ada66a242fa 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -418,6 +418,9 @@ static bool arch_supported(const llm_arch arch) { if (arch == LLM_ARCH_DEEPSEEK4) { return false; } + if (arch == LLM_ARCH_INKLING) { + return false; // TODO fixture params for the arch-specific hparams (d_rel, rel_extent, shortconv, logit_scale_denom) + } // FIXME some models are segfaulting with WebGPU: #ifdef GGML_USE_WEBGPU diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index ea684d9f156d..12ff725e37ca 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -31,6 +31,7 @@ add_library(mtmd models/granite4-vision.cpp models/hunyuanvl.cpp models/internvl.cpp + models/inkling.cpp models/kimivl.cpp models/kimik25.cpp models/nemotron-v2-vl.cpp diff --git a/tools/mtmd/clip-impl.h b/tools/mtmd/clip-impl.h index 5b413681f040..c874a2c7c99c 100644 --- a/tools/mtmd/clip-impl.h +++ b/tools/mtmd/clip-impl.h @@ -258,6 +258,13 @@ #define TN_A_FFN_POST_NORM "%s.blk.%d.ffn_post_norm.%s" #define TN_A_FFN_POST_NORM_1 "%s.blk.%d.ffn_post_norm_1.%s" +// Inkling hMLP vision and dMel audio towers. +#define TN_INKLING_HMLP_LINEAR "v.hmlp.%d.linear.weight" +#define TN_INKLING_HMLP_NORM "v.hmlp.%d.norm.weight" +#define TN_INKLING_HMLP_FINAL_NORM "v.hmlp.final_norm.weight" +#define TN_INKLING_DMEL_EMBD "a.dmel.embedding.weight" +#define TN_INKLING_DMEL_FINAL_NORM "a.dmel.final_norm.weight" + // mobilenetv5 (gemma3n) definitions #define TN_MNV5_STEM_CONV "v.conv_stem.conv.weight" #define TN_MNV5_STEM_BIAS "v.conv_stem.conv.bias" @@ -320,6 +327,7 @@ struct clip_ctx; enum projector_type { + PROJECTOR_TYPE_INKLING, PROJECTOR_TYPE_MLP, PROJECTOR_TYPE_MLP_NORM, PROJECTOR_TYPE_LDP, @@ -375,6 +383,7 @@ enum projector_type { }; static std::map PROJECTOR_TYPE_NAMES = { + { PROJECTOR_TYPE_INKLING, "inkling" }, { PROJECTOR_TYPE_MLP, "mlp" }, { PROJECTOR_TYPE_LDP, "ldp" }, { PROJECTOR_TYPE_LDPV2, "ldpv2"}, diff --git a/tools/mtmd/clip-model.h b/tools/mtmd/clip-model.h index 6d4336c4010b..9b5cb09a8f6f 100644 --- a/tools/mtmd/clip-model.h +++ b/tools/mtmd/clip-model.h @@ -33,7 +33,7 @@ enum resize_algo { RESIZE_ALGO_BILINEAR, // stretch to target resolution RESIZE_ALGO_BICUBIC, // center-crop when aspect ratio doesn't match RESIZE_ALGO_BICUBIC_PILLOW, - // RESIZE_ALGO_LANCZOS, // TODO + RESIZE_ALGO_LANCZOS, }; // Padding style for img_tool::resize @@ -347,6 +347,11 @@ struct qf_block { std::vector qf_proj_layers; }; +struct inkling_hmlp_layer { + ggml_tensor * linear_w = nullptr; + ggml_tensor * norm_w = nullptr; +}; + struct clip_model { clip_modality modality = CLIP_MODALITY_VISION; projector_type proj_type = PROJECTOR_TYPE_MLP; @@ -361,6 +366,12 @@ struct clip_model { ggml_tensor * norm_embd_w = nullptr; ggml_tensor * norm_embd_b = nullptr; + // Inkling towers (neither uses standard transformer blocks). + std::vector inkling_hmlp_layers; + ggml_tensor * inkling_hmlp_final_norm_w = nullptr; + ggml_tensor * inkling_dmel_embd_w = nullptr; + ggml_tensor * inkling_dmel_final_norm_w = nullptr; + // "indexed" patch embedding norms ggml_tensor * patch_norm_1_w = nullptr; ggml_tensor * patch_norm_1_b = nullptr; diff --git a/tools/mtmd/clip.cpp b/tools/mtmd/clip.cpp index b8866506493e..dbd07081bf73 100644 --- a/tools/mtmd/clip.cpp +++ b/tools/mtmd/clip.cpp @@ -869,6 +869,10 @@ static std::unique_ptr clip_get_graph_builder(clip_ctx * ctx, const std::unique_ptr builder; switch (ctx->proj_type()) { + case PROJECTOR_TYPE_INKLING: + { + builder = std::make_unique(ctx, img); + } break; case PROJECTOR_TYPE_GEMMA3: case PROJECTOR_TYPE_IDEFICS3: case PROJECTOR_TYPE_LFM2: @@ -1277,6 +1281,21 @@ struct clip_model_loader { // model-specific params switch (model.proj_type) { + case PROJECTOR_TYPE_INKLING: + { + if (is_vision) { + hparams.image_resize_algo = RESIZE_ALGO_BICUBIC_PILLOW; + hparams.image_resize_pad = PAD_NONE; + hparams.warmup_image_size = hparams.patch_size; + } else { + hparams.audio_chunk_len = 0; + hparams.audio_sample_rate = 16000; + hparams.audio_n_fft = 1600; + hparams.audio_window_len = 1600; + hparams.audio_hop_len = 800; + hparams.warmup_audio_size = 4; + } + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_LDP: @@ -1856,7 +1875,8 @@ struct clip_model_loader { model.position_embeddings = get_tensor(string_format(TN_POS_EMBD, prefix), false); const bool has_standard_layers = ( - model.proj_type != PROJECTOR_TYPE_GEMMA3NV); + model.proj_type != PROJECTOR_TYPE_GEMMA3NV && + model.proj_type != PROJECTOR_TYPE_INKLING); // layers const int n_layers_to_load = has_standard_layers ? hparams.n_layer : 0; @@ -1942,6 +1962,23 @@ struct clip_model_loader { switch (model.proj_type) { + case PROJECTOR_TYPE_INKLING: + { + if (model.modality == CLIP_MODALITY_VISION) { + model.inkling_hmlp_layers.resize(hparams.n_layer); + for (int il = 0; il < hparams.n_layer; ++il) { + auto & layer = model.inkling_hmlp_layers[il]; + layer.linear_w = get_tensor(string_format(TN_INKLING_HMLP_LINEAR, il)); + layer.norm_w = il + 1 < hparams.n_layer + ? get_tensor(string_format(TN_INKLING_HMLP_NORM, il)) + : nullptr; + } + model.inkling_hmlp_final_norm_w = get_tensor(TN_INKLING_HMLP_FINAL_NORM); + } else { + model.inkling_dmel_embd_w = get_tensor(TN_INKLING_DMEL_EMBD); + model.inkling_dmel_final_norm_w = get_tensor(TN_INKLING_DMEL_FINAL_NORM); + } + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: { @@ -2906,6 +2943,11 @@ struct clip_model_loader { LOG_INF("%s: warmup with audio size = %d\n", __func__, hparams.warmup_audio_size); } batch.entries.push_back(img); + // One logical Inkling vision patch always contains two adjacent temporal slices (including warmup reserve). + if (ctx_clip.model.modality == CLIP_MODALITY_VISION && + ctx_clip.model.proj_type == PROJECTOR_TYPE_INKLING) { + batch.entries.push_back(img); + } return batch; } @@ -3303,6 +3345,16 @@ int clip_n_output_tokens(const clip_ctx * ctx, const clip_image_f32 * img) { projector_type proj = ctx->proj_type(); switch (proj) { + case PROJECTOR_TYPE_INKLING: + { + if (ctx->model.modality == CLIP_MODALITY_AUDIO) { + // One dMel row is one soft audio token. + n_patches = img->nx(); + } else { + // Batch entries are temporal slices; each pair emits one token. + n_patches = 1; + } + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_JANUS_PRO: @@ -3675,6 +3727,10 @@ bool clip_image_batch_encode(clip_ctx * ctx, int n_threads, const clip_image_f32 // set input per projector switch (ctx->model.proj_type) { + case PROJECTOR_TYPE_INKLING: + { + // inp_raw is the only graph input. + } break; case PROJECTOR_TYPE_MINICPMV: { // inspired from siglip: @@ -4551,6 +4607,10 @@ bool clip_image_batch_encode(clip_ctx * ctx, int n_threads, const clip_image_f32 int clip_n_mmproj_embd(const struct clip_ctx * ctx) { switch (ctx->model.proj_type) { + case PROJECTOR_TYPE_INKLING: + return ctx->model.modality == CLIP_MODALITY_AUDIO + ? ctx->model.inkling_dmel_final_norm_w->ne[0] + : ctx->model.inkling_hmlp_final_norm_w->ne[0]; case PROJECTOR_TYPE_LDP: return ctx->model.mm_model_block_1_block_2_1_b->ne[0]; case PROJECTOR_TYPE_LDPV2: diff --git a/tools/mtmd/models/inkling.cpp b/tools/mtmd/models/inkling.cpp new file mode 100644 index 000000000000..c072f66a2c40 --- /dev/null +++ b/tools/mtmd/models/inkling.cpp @@ -0,0 +1,106 @@ +#include "models.h" + +ggml_tensor * clip_graph_inkling::build_mm(ggml_tensor * w, ggml_tensor * x) const { + ggml_tensor * cur = ggml_mul_mat(ctx0, w, x); + ggml_mul_mat_set_prec(cur, GGML_PREC_F32); + return cur; +} + +// fold square neighborhoods from W/H into channels; folded order is [h_fold, w_fold, C] +static ggml_tensor * inkling_fold_spatial( + ggml_context * ctx0, + ggml_tensor * cur, + int scale) { + GGML_ASSERT(scale > 0); + GGML_ASSERT(cur->ne[1] % scale == 0); + GGML_ASSERT(cur->ne[2] % scale == 0); + + const int64_t c = cur->ne[0]; + const int64_t w = cur->ne[1]; + const int64_t h = cur->ne[2]; + const int64_t b = cur->ne[3]; + + cur = ggml_reshape_4d(ctx0, cur, c * scale, w / scale, h, b); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3)); + cur = ggml_reshape_4d(ctx0, cur, c * scale * scale, h / scale, w / scale, b); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3)); + return cur; +} + +ggml_cgraph * clip_graph_inkling::build() { + return model.modality == CLIP_MODALITY_AUDIO ? build_audio() : build_vision(); +} + +ggml_cgraph * clip_graph_inkling::build_vision() { + static constexpr int temporal_patch_size = 2; + static constexpr int spatial_folds[] = {5, 2, 4}; + + GGML_ASSERT(img.nx() == 40 && img.ny() == 40); + GGML_ASSERT(n_batch > 0 && n_batch % temporal_patch_size == 0); + GGML_ASSERT(model.inkling_hmlp_layers.size() == 4); + GGML_ASSERT(model.inkling_hmlp_final_norm_w); + + // Raw input is [W,H,RGB,temporal*patch]. Put RGB on ne[0]. + ggml_tensor * cur = build_inp_raw(3); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 1, 2, 0, 3)); + + for (int il = 0; il < 3; ++il) { + cur = inkling_fold_spatial(ctx0, cur, spatial_folds[il]); + const int64_t w = cur->ne[1]; + const int64_t h = cur->ne[2]; + const int64_t b = cur->ne[3]; + + cur = ggml_reshape_2d(ctx0, cur, cur->ne[0], w * h * b); + cur = build_mm(model.inkling_hmlp_layers[il].linear_w, cur); + cur = build_norm(cur, model.inkling_hmlp_layers[il].norm_w, + nullptr, NORM_TYPE_RMS, eps, il); + cur = ggml_gelu_erf(ctx0, cur); + cur = ggml_reshape_4d(ctx0, cur, cur->ne[0], w, h, b); + } + + GGML_ASSERT(cur->ne[1] == 1 && cur->ne[2] == 1); + const int64_t n_patches = n_batch / temporal_patch_size; + cur = ggml_reshape_2d(ctx0, cur, cur->ne[0] * temporal_patch_size, n_patches); + cur = build_mm(model.inkling_hmlp_layers[3].linear_w, cur); + cur = build_norm(cur, model.inkling_hmlp_final_norm_w, + nullptr, NORM_TYPE_RMS, eps, 3); + + // Batched mtmd convention: one token in ne[1], patch count in ne[2]. + cur = ggml_reshape_3d(ctx0, cur, cur->ne[0], 1, n_patches); + ggml_build_forward_expand(gf, cur); + return gf; +} + +ggml_cgraph * clip_graph_inkling::build_audio() { + static constexpr int n_mels = 80; + static constexpr int mel_vocab_size = 16; + static constexpr int n_embd = 6144; + + GGML_ASSERT(img.ny() == n_mels); + GGML_ASSERT(model.inkling_dmel_embd_w); + GGML_ASSERT(model.inkling_dmel_final_norm_w); + GGML_ASSERT(model.inkling_dmel_embd_w->ne[0] == n_embd); + GGML_ASSERT(model.inkling_dmel_embd_w->ne[1] == n_mels * mel_vocab_size); + + const int64_t n_tokens = img.nx(); + // mtmd audio storage is mel-major and represented as [token, mel]. + ggml_tensor * bins = build_inp_raw(1); + bins = ggml_cont(ctx0, ggml_transpose(ctx0, bins)); + ggml_tensor * offsets = ggml_arange(ctx0, 0, n_mels, 1); + offsets = ggml_scale(ctx0, offsets, mel_vocab_size); + offsets = ggml_reshape_2d(ctx0, offsets, n_mels, 1); + ggml_tensor * indices = ggml_cast(ctx0, ggml_add(ctx0, bins, offsets), GGML_TYPE_I32); + + indices = ggml_reshape_1d(ctx0, indices, n_mels * n_tokens); + ggml_tensor * cur = ggml_get_rows(ctx0, model.inkling_dmel_embd_w, indices); + cur = ggml_reshape_3d(ctx0, cur, n_embd, n_mels, n_tokens); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 1, 0, 2, 3)); + cur = ggml_sum_rows(ctx0, cur); + cur = ggml_cont(ctx0, ggml_permute(ctx0, cur, 1, 0, 2, 3)); + cur = ggml_reshape_2d(ctx0, cur, n_embd, n_tokens); + cur = build_norm(cur, model.inkling_dmel_final_norm_w, + nullptr, NORM_TYPE_RMS, eps, -1); + + ggml_build_forward_expand(gf, cur); + return gf; +} diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index 5f1493fa603e..e50785e525bf 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -12,6 +12,17 @@ struct clip_graph_siglip : clip_graph { ggml_cgraph * build() override; }; +struct clip_graph_inkling : clip_graph { + clip_graph_inkling(clip_ctx * ctx, const clip_image_f32 & img) : clip_graph(ctx, img) {} + ggml_cgraph * build() override; + ggml_tensor * build_mm(ggml_tensor * w, ggml_tensor * x) const override; + bool support_batch() const override { return true; } + +private: + ggml_cgraph * build_vision(); + ggml_cgraph * build_audio(); +}; + struct clip_graph_gemma4v : clip_graph { clip_graph_gemma4v(clip_ctx * ctx, const clip_image_f32 & img) : clip_graph(ctx, img) {} ggml_cgraph * build() override; diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index b72fd067a508..7d6cc83961d8 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -283,6 +283,7 @@ struct filter_params { bool norm_per_feature = false; bool use_magnitude = false; // |X| instead of |X|^2 float mel_floor = 5.960464477539063e-08f; + float power_floor = 0.0f; // clamp |X|^2 to this before sqrt (0 = disabled) }; static void log_mel_spectrogram_worker_thread(int ith, @@ -327,6 +328,7 @@ static void log_mel_spectrogram_worker_thread(int ith, // Calculate modulus^2 (power) or modulus (magnitude) for (int j = 0; j < n_fft_bins; j++) { float power = (fft_out[2 * j + 0] * fft_out[2 * j + 0] + fft_out[2 * j + 1] * fft_out[2 * j + 1]); + power = std::max(power, params.power_floor); fft_out[j] = params.use_magnitude ? sqrtf(power) : power; } @@ -537,6 +539,75 @@ static bool log_mel_spectrogram( return true; } +void mtmd_audio_preprocessor_inkling::initialize() { + GGML_ASSERT(hparams.n_mel_bins == 80); + GGML_ASSERT(hparams.audio_n_fft == 1600); + cache.fill_sin_cos_table(hparams.audio_n_fft); + cache.fill_hann_window(hparams.audio_window_len, true); + cache.fill_mel_filterbank_matrix( + hparams.n_mel_bins, hparams.audio_n_fft, hparams.audio_sample_rate, + 0.0f, -1.0f, true, 1.0f, false); +} + +bool mtmd_audio_preprocessor_inkling::preprocess( + const float * samples, + size_t n_samples, + std::vector & output) { + if (n_samples == 0) { + return false; + } + GGML_ASSERT(hparams.audio_hop_len == 800); + GGML_ASSERT(hparams.audio_window_len == 1600); + GGML_ASSERT(!cache.filters.data.empty()); + + // Reference behavior: left pad by n_fft-hop, then right pad to a whole hop. + const size_t left_pad = static_cast(hparams.audio_n_fft - hparams.audio_hop_len); + const size_t right_pad = + (static_cast(hparams.audio_hop_len) - n_samples % hparams.audio_hop_len) + % hparams.audio_hop_len; + std::vector padded(left_pad + n_samples + right_pad, 0.0f); + std::copy(samples, samples + n_samples, padded.begin() + left_pad); + + filter_params params; + params.n_mel = hparams.n_mel_bins; + params.n_fft_bins = 1 + hparams.audio_n_fft / 2; + params.hann_window_size = hparams.audio_window_len; + params.hop_length = hparams.audio_hop_len; + params.sample_rate = hparams.audio_sample_rate; + params.no_padding = true; + params.use_natural_log = false; + params.use_magnitude = true; + params.mel_floor = 1e-10f; + params.power_floor = 1e-10f; // reference clamps |X|^2 before sqrt + + mtmd_audio_mel dmel; + if (!log_mel_spectrogram( + padded.data(), static_cast(padded.size()), 4, + params, cache, dmel)) { + return false; + } + dmel.n_len_org = static_cast(n_samples); + + // nearest of 16 float64 centers over [-7,2]; strict '<' keeps the lower bin on midpoints (torch.argmin) + for (float & value_f32 : dmel.data) { + const double value = std::max(-7.0, std::min(2.0, static_cast(value_f32))); + int best = 0; + double best_dist = INFINITY; + for (int bin = 0; bin < 16; ++bin) { + const double center = -7.0 + 9.0 * static_cast(bin) / 15.0; + const double dist = std::abs(value - center); + if (dist < best_dist) { + best = bin; + best_dist = dist; + } + } + value_f32 = static_cast(best); + } + + output.push_back(std::move(dmel)); + return true; +} + // // mtmd_audio_preprocessor_whisper // diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index ad96bd847cfc..29613d11146c 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -69,6 +69,16 @@ struct mtmd_audio_preprocessor_whisper : mtmd_audio_preprocessor { mtmd_audio_cache cache; }; +// Inkling dMel: 100 ms Slaney-mel magnitude windows at a 50 ms hop, quantized to 16 bins. +struct mtmd_audio_preprocessor_inkling : mtmd_audio_preprocessor { + mtmd_audio_preprocessor_inkling(const clip_ctx * ctx) : mtmd_audio_preprocessor(ctx) {} + void initialize() override; + bool preprocess(const float * samples, size_t n_samples, std::vector & output) override; + +private: + mtmd_audio_cache cache; +}; + struct mtmd_audio_preprocessor_conformer : mtmd_audio_preprocessor { mtmd_audio_preprocessor_conformer(const clip_ctx * ctx) : mtmd_audio_preprocessor(ctx) {} void initialize() override; diff --git a/tools/mtmd/mtmd-image.cpp b/tools/mtmd/mtmd-image.cpp index 36cd463b20eb..e58c79882a73 100644 --- a/tools/mtmd/mtmd-image.cpp +++ b/tools/mtmd/mtmd-image.cpp @@ -68,6 +68,9 @@ struct img_tool { case RESIZE_ALGO_BICUBIC_PILLOW: resize_bicubic_pillow(src, dst, target_resolution.width, target_resolution.height); break; + case RESIZE_ALGO_LANCZOS: + resize_lanczos_pillow(src, dst, target_resolution.width, target_resolution.height); + break; default: throw std::runtime_error("Unsupported resize algorithm"); } @@ -97,6 +100,9 @@ struct img_tool { case RESIZE_ALGO_BICUBIC_PILLOW: resize_bicubic_pillow(src, resized_image, new_width, new_height); break; + case RESIZE_ALGO_LANCZOS: + resize_lanczos_pillow(src, resized_image, new_width, new_height); + break; default: throw std::runtime_error("Unsupported resize algorithm"); } @@ -345,6 +351,19 @@ struct img_tool { // 2. Pre-computes normalized filter coefficients for each output pixel // 3. Applies convolution using fixed-point integer arithmetic for performance static bool resize_bicubic_pillow(const clip_image_u8 & img, clip_image_u8 & dst, int target_width, int target_height) { + return resize_pillow(img, dst, target_width, target_height, false); + } + + static bool resize_lanczos_pillow(const clip_image_u8 & img, clip_image_u8 & dst, int target_width, int target_height) { + return resize_pillow(img, dst, target_width, target_height, true); + } + + static bool resize_pillow( + const clip_image_u8 & img, + clip_image_u8 & dst, + int target_width, + int target_height, + bool use_lanczos) { // Fixed-point precision: 22 bits = 32 (int32_t) - 8 (uint8_t pixels) - 2 (headroom for accumulation) // This allows encoding fractional weights as integers: weight * 2^22 const int PRECISION_BITS = 32 - 8 - 2; @@ -352,7 +371,21 @@ struct img_tool { // Bicubic filter function with a = -0.5 (Note that GGML/PyTorch takes a = -0.75) // Returns filter weight for distance x from pixel center // Support: [-2, 2], meaning the filter influences pixels within 2 units of distance - auto bicubic_filter = [](double x) -> double { + auto resample_filter = [use_lanczos](double x) -> double { + if (use_lanczos) { + if (-3.0 <= x && x < 3.0) { + auto sinc = [](double value) { + if (value == 0.0) { + return 1.0; + } + const double pix = value * 3.141592653589793238462643383279502884; + return std::sin(pix) / pix; + }; + return sinc(x) * sinc(x / 3.0); + } + return 0.0; + } + constexpr double a = -0.5; if (x < 0.0) { x = -x; @@ -367,7 +400,7 @@ struct img_tool { }; // Filter support radius: bicubic extends 2 pixels in each direction - constexpr double filter_support = 2.0; + const double filter_support = use_lanczos ? 3.0 : 2.0; // Clipping function for 8-bit values auto clip8 = [](int val) -> uint8_t { @@ -434,7 +467,7 @@ struct img_tool { // Compute filter weights for each contributing input pixel for (x = 0; x < xmax; x++) { // Distance from input pixel center to output pixel center in input space - double w = bicubic_filter((x + xmin - center + 0.5) * ss); + double w = resample_filter((x + xmin - center + 0.5) * ss); pre_weights[xx * ksize + x] = w; ww += w; // Accumulate for normalization } @@ -463,6 +496,12 @@ struct img_tool { const double fxp_scale = std::ldexp(1.0, PRECISION_BITS); // 1.0 * 2^PRECISION_BITS for (int i = 0; i < outSize * ksize; i++) { + if (use_lanczos) { + // Pillow adds +/- 0.5 then truncates toward zero; std::round would round twice + const double rounded = pre_weights[i] * fxp_scale + (pre_weights[i] < 0 ? -0.5 : 0.5); + weights[i] = static_cast(rounded); + continue; + } double tmp_val = pre_weights[i] * fxp_scale; if (pre_weights[i] < 0) { tmp_val -= 0.5; @@ -606,6 +645,82 @@ struct img_tool { } }; +mtmd_inkling_image_preproc_out mtmd_image_preprocess_inkling( + const clip_image_u8 & img, + resize_algo algo) { + constexpr int patch_size = 40; + constexpr int temporal_patch_size = 2; + constexpr int max_upscaled_long_edge = 2048; + constexpr double rescale_image_frac = 2.0; + constexpr float image_mean[3] = { 0.48145466f, 0.4578275f, 0.40821073f }; + constexpr float image_std[3] = { 0.26862954f, 0.26130258f, 0.27577711f }; + + mtmd_inkling_image_preproc_out output; + output.source_size = img.get_size(); + GGML_ASSERT(output.source_size.width > 0 && output.source_size.height > 0); + GGML_ASSERT(!img.is_placeholder()); + + const int long_edge = std::max(output.source_size.width, output.source_size.height); + const double target_long_edge = std::min( + static_cast(long_edge) * rescale_image_frac, + static_cast(std::max(max_upscaled_long_edge, long_edge))); + const double ratio = target_long_edge / long_edge; + const auto scaled = [ratio](int size) { + // The reference explicitly requests half-up rounding for positive sizes. + return std::max(1, static_cast(std::floor(size * ratio + 0.5))); + }; + output.resized_size = { + scaled(output.source_size.width), + scaled(output.source_size.height), + }; + + clip_image_u8 resized; + img_tool::resize(img, resized, output.resized_size, algo, PAD_NONE); + output.resized_rgb = resized.get_ro_buf(); + + output.patch_rows = (output.resized_size.height + patch_size - 1) / patch_size; + // Inkling always appends a right-hand patch, even at exact multiples of 40 + output.patch_cols = output.resized_size.width / patch_size + 1; + const size_t n_patches = static_cast(output.patch_rows) * output.patch_cols; + const size_t values_per_patch = static_cast(temporal_patch_size) * + patch_size * patch_size * 3; + output.pixel_values_bthwc.resize(n_patches * values_per_patch); + + // preserve torchvision's fused (raw - mean*255)/(std*255) order (raw=-1 for padding) for ulp parity + float mean_255[3]; + float std_255[3]; + for (int c = 0; c < 3; ++c) { + mean_255[c] = image_mean[c] * 255.0f; + std_255[c] = image_std[c] * 255.0f; + } + + for (int py = 0; py < output.patch_rows; ++py) { + for (int px = 0; px < output.patch_cols; ++px) { + const size_t patch_index = static_cast(py) * output.patch_cols + px; + for (int t = 0; t < temporal_patch_size; ++t) { + for (int y = 0; y < patch_size; ++y) { + const int iy = py * patch_size + y; + for (int x = 0; x < patch_size; ++x) { + const int ix = px * patch_size + x; + const bool in_image = iy < output.resized_size.height && ix < output.resized_size.width; + const std::array rgb = in_image + ? resized.get_pixel(ix, iy) + : std::array{ 0, 0, 0 }; + for (int c = 0; c < 3; ++c) { + const float raw = in_image ? static_cast(rgb[c]) : -1.0f; + const size_t offset = (((((patch_index * temporal_patch_size + t) * + patch_size + y) * patch_size + x) * 3) + c); + output.pixel_values_bthwc[offset] = (raw - mean_255[c]) / std_255[c]; + } + } + } + } + } + } + + return output; +} + // // mtmd_image_preprocessor_llava_uhd @@ -885,6 +1000,80 @@ mtmd_image_preproc_out mtmd_image_preprocessor_fixed_size::preprocess(const clip return output; } +// Inkling hMLP patches +mtmd_image_preproc_out mtmd_image_preprocessor_inkling::preprocess(const clip_image_u8 & img) { + GGML_ASSERT(hparams.patch_size == 40); + constexpr int temporal_patch_size = 2; + constexpr float rescale_frac = 2.0f; + constexpr int rescale_max_long_edge = 2048; + + const auto original = img.get_size(); + const int long_edge = std::max(original.width, original.height); + const float target_long = std::min( + static_cast(long_edge) * rescale_frac, + static_cast(std::max(long_edge, rescale_max_long_edge))); + const float ratio = long_edge > 0 ? target_long / long_edge : 1.0f; + const clip_image_size scaled_size { + std::max(1, static_cast(std::floor(original.width * ratio + 0.5f))), + std::max(1, static_cast(std::floor(original.height * ratio + 0.5f))), + }; + + clip_image_u8 scaled; + // The reference processor resizes with Pillow Lanczos (radius 3). + img_tool::resize(img, scaled, scaled_size, RESIZE_ALGO_LANCZOS, PAD_NONE); + + const int p = hparams.patch_size; + const int nph = (scaled_size.height + p - 1) / p; + // The extra right column is intentional, including exact multiples of 40. + const int npw = scaled_size.width / p + 1; + + const float pad_raw = -1.0f / 255.0f; + // the reference materializes normalized patches as bf16; round through bf16 for bit-parity + const auto bf16_round = [](float v) { + return ggml_bf16_to_fp32(ggml_fp32_to_bf16(v)); + }; + float pad_norm[3]; + for (int c = 0; c < 3; ++c) { + pad_norm[c] = bf16_round((pad_raw - hparams.image_mean[c]) / hparams.image_std[c]); + } + + mtmd_image_preproc_out output; + output.entries.reserve(static_cast(nph) * npw * temporal_patch_size); + for (int py = 0; py < nph; ++py) { + for (int px = 0; px < npw; ++px) { + std::vector data(static_cast(p) * p * 3); + for (int y = 0; y < p; ++y) { + const int iy = py * p + y; + for (int x = 0; x < p; ++x) { + const int ix = px * p + x; + const size_t off = static_cast(y * p + x) * 3; + if (iy < scaled_size.height && ix < scaled_size.width && !scaled.is_placeholder()) { + const auto rgb = scaled.get_pixel(ix, iy); + for (int c = 0; c < 3; ++c) { + const float raw = static_cast(rgb[c]) / 255.0f; + data[off + c] = bf16_round((raw - hparams.image_mean[c]) / hparams.image_std[c]); + } + } else { + for (int c = 0; c < 3; ++c) { + data[off + c] = pad_norm[c]; + } + } + } + } + + for (int t = 0; t < temporal_patch_size; ++t) { + clip_image_f32 patch; + patch.set_size({p, p}, scaled.is_placeholder(), false); + if (!scaled.is_placeholder()) { + patch.cpy_buf(data); + } + output.entries.push_back(std::move(patch)); + } + } + } + return output; +} + // // mtmd_image_preprocessor_dyn_size // diff --git a/tools/mtmd/mtmd-image.h b/tools/mtmd/mtmd-image.h index 115cba51e8f4..044d72f61375 100644 --- a/tools/mtmd/mtmd-image.h +++ b/tools/mtmd/mtmd-image.h @@ -26,6 +26,20 @@ struct mtmd_image_preproc_out { } }; +// Inkling hMLP preprocessing; pixel_values_bthwc is row-major BTHWC [n_patches, 2, 40, 40, 3]. +struct mtmd_inkling_image_preproc_out { + clip_image_size source_size; + clip_image_size resized_size; + int patch_rows = 0; + int patch_cols = 0; + std::vector resized_rgb; + std::vector pixel_values_bthwc; +}; + +mtmd_inkling_image_preproc_out mtmd_image_preprocess_inkling( + const clip_image_u8 & img, + resize_algo algo = RESIZE_ALGO_LANCZOS); + // base class, models must inherit from this class struct mtmd_image_preprocessor { const clip_hparams & hparams; @@ -115,6 +129,12 @@ struct mtmd_image_preprocessor_fixed_size : mtmd_image_preprocessor { mtmd_image_preproc_out preprocess(const clip_image_u8 & img) override; }; +// Inkling: split an image into 40x40 hMLP patches, each duplicated across a fixed temporal dimension of two. +struct mtmd_image_preprocessor_inkling : mtmd_image_preprocessor { + mtmd_image_preprocessor_inkling(const clip_ctx * ctx) : mtmd_image_preprocessor(ctx) {} + mtmd_image_preproc_out preprocess(const clip_image_u8 & img) override; +}; + // resize image to multiple of patch_size*n_merge, while preserving aspect ratio // if image_resize_pad is true, the resized image will be padded, otherwise it will be either stretched or center-cropped depending on image_resize_pad // this is used by models with native support for dynamic image size, for example: Qwen-VL, Pixtral, Kimi-VL, etc diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index e10ccf186b14..3e81e44143fa 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -393,6 +393,12 @@ struct mtmd_context { projector_type proj = clip_get_projector_type(ctx_v); switch (proj) { + case PROJECTOR_TYPE_INKLING: + { + // renderer opens each image part with <|content_image|>; block framing comes from the template + img_beg = "<|content_image|>"; + image_preproc = std::make_unique(ctx_v); + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_LDP: @@ -663,6 +669,13 @@ struct mtmd_context { // set preprocessor switch (proj) { + case PROJECTOR_TYPE_INKLING: + { + // <|content_audio_input|> ... <|audio_end|>, matching the renderer's audio framing + aud_beg = "<|content_audio_input|>"; + aud_end = "<|audio_end|>"; + audio_preproc = std::make_unique(ctx_a); + } break; case PROJECTOR_TYPE_QWEN2A: case PROJECTOR_TYPE_QWEN25O: { @@ -1179,23 +1192,35 @@ struct mtmd_tokenizer { } size_t n_tokens = 0; - for (auto & e : preproc_out.entries) { - n_tokens += clip_n_output_tokens(ctx->ctx_v, &e); - if (clip_model_n_temporal_merge(ctx->ctx_v) == 2) { - // [QWEN_VIDEO] pair input is merged to the same embd, so only count as one image - break; + if (ctx->proj_type_v() == PROJECTOR_TYPE_INKLING) { + GGML_ASSERT(preproc_out.entries.size() % 2 == 0); + n_tokens = preproc_out.entries.size() / 2; + } else { + for (auto & e : preproc_out.entries) { + n_tokens += clip_n_output_tokens(ctx->ctx_v, &e); + if (clip_model_n_temporal_merge(ctx->ctx_v) == 2) { + // [QWEN_VIDEO] pair input is merged to the same embd, so only count as one image + break; + } } } mtmd_image_tokens_ptr image_tokens(new mtmd_image_tokens); // [QWEN_VIDEO] improve this in the future - image_tokens->n_temporal_merge = clip_model_n_temporal_merge(ctx->ctx_v); + // Inkling's pair is internal to each patch; it must not merge consecutive user bitmaps as video frames. + image_tokens->n_temporal_merge = ctx->proj_type_v() == PROJECTOR_TYPE_INKLING + ? 2 + : clip_model_n_temporal_merge(ctx->ctx_v); if (mtmd_decode_use_mrope(ctx)) { // for Qwen2VL, we need this information for M-RoPE decoding positions image_tokens->nx = clip_n_output_tokens_x(ctx->ctx_v, &preproc_out.entries[0]); image_tokens->ny = clip_n_output_tokens_y(ctx->ctx_v, &preproc_out.entries[0]); + } else if (ctx->proj_type_v() == PROJECTOR_TYPE_INKLING) { + // n_tokens() multiplies 1x1 by the number of temporal groups. + image_tokens->nx = 1; + image_tokens->ny = 1; } else { // other models, we only need the total number of tokens image_tokens->nx = n_tokens; From d8f87500a3dfab0933cf49bfa5d447e83662d3f1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 26 Jul 2026 11:55:01 +0000 Subject: [PATCH 002/115] inkling : adapt to the renamed thinking_end_tags chat API Upstream 910196f6b renamed common_chat_params::thinking_end_tag to thinking_end_tags and changed it from std::string to a vector, so data.thinking_end_tag = END_MESSAGE no longer compiles. --- common/chat.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/chat.cpp b/common/chat.cpp index 5dd8fd8979bd..c589675e52ec 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -2291,7 +2291,7 @@ static common_chat_params common_chat_params_init_inkling(const common_chat_temp data.format = COMMON_CHAT_FORMAT_PEG_NATIVE; data.supports_thinking = true; data.thinking_start_tag = THINK; - data.thinking_end_tag = END_MESSAGE; + data.thinking_end_tags = {END_MESSAGE}; data.preserved_tokens = { MSG_MODEL, MSG_USER, MSG_SYSTEM, MSG_TOOL, THINK, TEXT, END_MESSAGE, END_SAMPLING, INVOKE_TOOL, From d69b7e606af7f59d9e81c5c81a5c7ce0dad197e1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 30 Jul 2026 22:12:57 +0000 Subject: [PATCH 003/115] Fix mmproj decoder width for Inkling Small --- conversion/inkling.py | 7 +++++-- tools/mtmd/models/inkling.cpp | 5 +++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/conversion/inkling.py b/conversion/inkling.py index 90ef65c3bdcc..5d53ff6d914e 100644 --- a/conversion/inkling.py +++ b/conversion/inkling.py @@ -256,7 +256,6 @@ def __init__(self, *args, **kwargs): "temporal_patch_size": 2, "n_channels": 3, "n_layers": 4, - "decoder_dmodel": 6144, "use_vision_norm": True, } for key, want in expected.items(): @@ -265,12 +264,14 @@ def __init__(self, *args, **kwargs): raise NotImplementedError( f"Inkling mmproj requires vision_config.{key}={want!r}, got {got!r}" ) + # decoder_dmodel is the text model width, it varies per checkpoint + if not hp.get("decoder_dmodel"): + raise NotImplementedError("Inkling mmproj requires vision_config.decoder_dmodel") assert self.hparams_audio is not None ahp = self.hparams_audio audio_expected = { "audio_mode": "dmel", - "decoder_dmodel": 6144, "n_mel_bins": 80, "mel_vocab_size": 16, "use_audio_norm": True, @@ -281,6 +282,8 @@ def __init__(self, *args, **kwargs): raise NotImplementedError( f"Inkling mmproj requires audio_config.{key}={want!r}, got {got!r}" ) + if not ahp.get("decoder_dmodel"): + raise NotImplementedError("Inkling mmproj requires audio_config.decoder_dmodel") def set_gguf_parameters(self): hp = self.hparams_vision diff --git a/tools/mtmd/models/inkling.cpp b/tools/mtmd/models/inkling.cpp index c072f66a2c40..325fddde8a21 100644 --- a/tools/mtmd/models/inkling.cpp +++ b/tools/mtmd/models/inkling.cpp @@ -74,14 +74,15 @@ ggml_cgraph * clip_graph_inkling::build_vision() { ggml_cgraph * clip_graph_inkling::build_audio() { static constexpr int n_mels = 80; static constexpr int mel_vocab_size = 16; - static constexpr int n_embd = 6144; GGML_ASSERT(img.ny() == n_mels); GGML_ASSERT(model.inkling_dmel_embd_w); GGML_ASSERT(model.inkling_dmel_final_norm_w); - GGML_ASSERT(model.inkling_dmel_embd_w->ne[0] == n_embd); GGML_ASSERT(model.inkling_dmel_embd_w->ne[1] == n_mels * mel_vocab_size); + // decoder width varies per checkpoint + const int64_t n_embd = model.inkling_dmel_embd_w->ne[0]; + const int64_t n_tokens = img.nx(); // mtmd audio storage is mel-major and represented as [token, mel]. ggml_tensor * bins = build_inp_raw(1); From 02142bbc33d477880a89dc5854a2c611d36e3494 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 2 Aug 2026 05:28:28 +0000 Subject: [PATCH 004/115] Fix some GitHub Issues --- ggml/src/ggml-cpu/ops.cpp | 9 ++++--- ggml/src/ggml-cuda/fattn-banded.cu | 14 +++++++---- ggml/src/ggml-cuda/fattn.cu | 38 ++++++++++++++++++++++++---- ggml/src/ggml-cuda/fattn.cuh | 2 ++ src/llama-vocab.cpp | 1 + tests/test-flash-attn-bias.cpp | 40 ++++++++++++++++++++++++------ 6 files changed, 84 insertions(+), 20 deletions(-) diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index ba8e8c69bd8a..9c38aadf45a1 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8571,6 +8571,9 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( ggml_vec_dot_t const kq_vec_dot = ggml_get_type_traits_cpu(k->type)->vec_dot; ggml_to_float_t const v_to_float = ggml_get_type_traits(v->type)->to_float; + // the banded op saturates an unnormalized FP16 VKQ accumulator, keep it in FP32 + const bool vkq_f16 = v->type == GGML_TYPE_F16 && rel == nullptr; + GGML_ASSERT(( q_to_vec_dot) && "fattn: unsupported K-type"); GGML_ASSERT((v->type == GGML_TYPE_F32 || v_to_float ) && "fattn: unsupported V-type"); @@ -8593,7 +8596,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( ggml_fp16_t * VKQ16 = (ggml_fp16_t *) (VKQ32 + 1*DV); // (temporary) FP16 VKQ accumulator ggml_fp16_t * Q_q = (ggml_fp16_t *) (VKQ32 + 2*DV); // (temporary) buffer for Q converted to quantized/FP16 - if (v->type == GGML_TYPE_F16) { + if (vkq_f16) { memset(VKQ16, 0, DV*sizeof(ggml_fp16_t)); } else { memset(VKQ32, 0, DV*sizeof(float)); @@ -8650,7 +8653,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3)); - if (v->type == GGML_TYPE_F16) { + if (vkq_f16) { if (s > M) { // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f M = s; @@ -8691,7 +8694,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( S = S*ms + vs; // scale and increment sum with partial sum } - if (v->type == GGML_TYPE_F16) { + if (vkq_f16) { for (int64_t d = 0; d < DV; ++d) { VKQ32[d] = GGML_CPU_FP16_TO_FP32(VKQ16[d]); } diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 98458ae86860..175760f2314e 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -91,6 +91,13 @@ static __global__ void flash_attn_ext_banded_f32( const int64_t q_offset = n_kv - n_q; for (int64_t ik = 0; ik < n_kv; ++ik) { + // skip masked positions before touching K/V + if (mask && __half2float(*(const half *) (mask + uint64_t(ik)*sizeof(half) + + uint64_t(iq)*m_nb1 + uint64_t(ih % mask_ne2)*m_nb2 + + uint64_t(ib % mask_ne3)*m_nb3)) == -INFINITY) { + continue; + } + const char * k_row = k + uint64_t(ik)*k_nb1 + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; float dot = 0.0f; #pragma unroll @@ -208,11 +215,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso const ggml_tensor * m = dst->src[3]; const ggml_tensor * rel = dst->src[5]; - // route F16/BF16 K/V to the MMA kernel; keep this FP32 kernel for mixed types and strided rel - if (k->type != GGML_TYPE_F32 && v->type != GGML_TYPE_F32 && - rel->type == GGML_TYPE_F32 && ggml_is_contiguous(rel) && - // MMA ABI indexes rel by Q's batch: a singleton rel batch must take the stride-aware fallback - rel->ne[3] == q->ne[3] && rel->ne[0] <= (1 << 20)) { + // only the MMA kernel reads src[5]; delegating otherwise drops the bias + if (ggml_cuda_flash_attn_ext_banded_use_mma(ctx.device, dst)) { ggml_cuda_flash_attn_ext(ctx, dst); return; } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 43849b9cec22..699940c41490 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -355,6 +355,38 @@ static bool ggml_cuda_fattn_kv_type_supported(ggml_type type) { } } +// The MMA kernel is the only one that reads src[5], so both call sites must agree on this. +bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor * dst) { + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { + return false; + } + + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + const ggml_tensor * rel = dst->src[5]; + + if (!Q || !K || !V || !rel) { + return false; + } + + // the MMA ABI indexes rel linearly and by Q's batch + if (rel->type != GGML_TYPE_F32 || !ggml_is_contiguous(rel) || + rel->ne[3] != Q->ne[3] || rel->ne[0] > (1 << 20)) { + return false; + } + + if (K->type == GGML_TYPE_F32 || V->type == GGML_TYPE_F32) { + return false; + } + + if ((Q->ne[0] != 64 && Q->ne[0] != 128) || V->ne[0] != Q->ne[0]) { + return false; + } + + return turing_mma_available(ggml_cuda_info().devices[device].cc); +} + static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const ggml_tensor * dst) { #ifndef FLASH_ATTN_AVAILABLE GGML_UNUSED(device); GGML_UNUSED(dst); @@ -390,11 +422,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const const int cc = ggml_cuda_info().devices[device].cc; - // banded bias lives in the F16 MMA loop; F32 K/V keeps the dedicated FP32 warp kernel - if (dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED && - dst->src[5]->type == GGML_TYPE_F32 && K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 && - dst->src[5]->ne[3] == Q->ne[3] && - turing_mma_available(cc) && (Q->ne[0] == 64 || Q->ne[0] == 128) && V->ne[0] == Q->ne[0]) { + if (ggml_cuda_flash_attn_ext_banded_use_mma(device, dst)) { return BEST_FATTN_KERNEL_MMA_F16; } diff --git a/ggml/src/ggml-cuda/fattn.cuh b/ggml/src/ggml-cuda/fattn.cuh index f9a7e15fbd62..b26f2f03bebc 100644 --- a/ggml/src/ggml-cuda/fattn.cuh +++ b/ggml/src/ggml-cuda/fattn.cuh @@ -4,4 +4,6 @@ void ggml_cuda_flash_attn_ext(ggml_backend_cuda_context & ctx, ggml_tensor * dst bool ggml_cuda_flash_attn_ext_supported(int device, const ggml_tensor * dst); +bool ggml_cuda_flash_attn_ext_banded_use_mma(int device, const ggml_tensor * dst); + size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst); diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 9b828d0c48eb..31831aaf110a 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2827,6 +2827,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { || t.first == "<|tool_response>" // gemma4 || t.first == "<|end▁of▁sentence|>" // deepseek-ocr || t.first == "[e~[" // minimax-m2/m3 + || t.first == "<|content_model_end_sampling|>" // inkling ) { special_eog_ids.insert(t.second); if ((attr & LLAMA_TOKEN_ATTR_CONTROL) == 0) { diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index 94232b32dbcb..4e842e1d119c 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -27,6 +27,8 @@ struct bias_test_config { int64_t n_batch = 1; int64_t rel_batch = 1; bool strided_rel = false; + float v_scale = 1.0f; // v = v_scale*(sin + v_bias) + float v_bias = 0.0f; }; struct test_data { @@ -88,7 +90,7 @@ static test_data make_data(const bias_test_config & c) { } for (size_t i = 0; i < data.k.size(); ++i) { data.k[i] = 0.25f*std::cos(float(i)*0.013f - 0.29f); - data.v[i] = 0.30f*std::sin(float(i)*0.019f + 0.71f); + data.v[i] = c.v_scale*(0.30f*std::sin(float(i)*0.019f + 0.71f) + c.v_bias); } for (int64_t ib = 0; ib < c.rel_batch; ++ib) { for (int64_t iq = 0; iq < c.nq; ++iq) { @@ -311,18 +313,40 @@ static void error_stats(const std::vector & got, const std::vector rmse = std::sqrt(sq/got.size()); } +// MSVC has no __int128, so check the reference value in uint64_t instead +static bool mul_checked(uint64_t a, uint64_t b, uint64_t & out) { + if (a != 0 && b > UINT64_MAX/a) { + return false; + } + out = a*b; + return true; +} + +static bool add_checked(uint64_t a, uint64_t b, uint64_t & out) { + if (a > UINT64_MAX - b) { + return false; + } + out = a + b; + return true; +} + static void overflow_arithmetic_self_test() { - // mirrors the scalar-path offset math; exact offset checked at 128 bits, lands past 2^31 + // mirrors the scalar-path offset math; the offset lands past 2^31 const uint64_t nb0 = sizeof(float); const uint64_t nb1 = 1024*nb0; const uint64_t nb2 = 64*nb1; const uint64_t nb3 = 131072*nb2; const uint64_t dist = 1023, head = 63, query = 131071, batch = 3; const uint64_t offset = dist*nb0 + head*nb1 + query*nb2 + batch*nb3; - __extension__ typedef unsigned __int128 uint128_t; - const uint128_t exact = uint128_t(dist)*nb0 + uint128_t(head)*nb1 + - uint128_t(query)*nb2 + uint128_t(batch)*nb3; - GGML_ASSERT(exact <= UINT64_MAX && offset == (uint64_t) exact && offset > INT32_MAX); + + const uint64_t terms[4][2] = {{dist, nb0}, {head, nb1}, {query, nb2}, {batch, nb3}}; + uint64_t exact = 0; + for (const auto & term : terms) { + uint64_t prod = 0; + GGML_ASSERT(mul_checked(term[0], term[1], prod)); + GGML_ASSERT(add_checked(exact, prod, exact)); + } + GGML_ASSERT(offset == exact && offset > INT32_MAX); const int64_t nq = int64_t(1) << 40; const int64_t nkv = nq + 8192; @@ -479,6 +503,8 @@ int main(int argc, char ** argv) { {"medium_f16_e1024", 128, 1024, 1024, 8, 2, 1024, GGML_TYPE_F16, true, false}, {"medium_bf16_local", 64, 2048, 2048, 8, 2, 512, GGML_TYPE_BF16, true, true }, {"decode_8k_e1024", 128, 1, 8192, 8, 1, 1024, GGML_TYPE_F16, true, false}, + // large single-signed V: saturates an FP16 VKQ accumulator, row turns into inf + {"large_v_16k", 128, 16, 16384, 8, 1, 1024, GGML_TYPE_F16, true, false, 1, 1, false, 512.0f, 1.0f}, }; } else if (suite == "hard") { configs = { @@ -503,7 +529,7 @@ int main(int argc, char ** argv) { error_stats(flash.output, dense.output, abs_dense, mean_abs_dense, rel_dense, mean_rel_dense, rmse_dense); double abs_naive = 0.0, mean_abs_naive = 0.0, rel_naive = 0.0, mean_rel_naive = 0.0, rmse_naive = 0.0; error_stats(flash.output, naive, abs_naive, mean_abs_naive, rel_naive, mean_rel_naive, rmse_naive); - const double tol = c.type == GGML_TYPE_F32 ? 2e-5 : 2e-3; + const double tol = (c.type == GGML_TYPE_F32 ? 2e-5 : 2e-3)*std::max(1.0f, c.v_scale); const bool pass = abs_naive <= tol; ok = ok && pass; printf("%s type=%s D=%lld nq=%lld nkv=%lld hq=%lld hkv=%lld E=%lld mask=%d sliding=%d " From 68b15cfde7119ad99922bad0b20379651b9b42a7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 6 Aug 2026 03:32:46 +0000 Subject: [PATCH 005/115] Fix quantized V cache issue --- src/llama-context.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 19cca7df1e9d..1197fe6a013c 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3562,6 +3562,13 @@ llama_context * llama_init_from_model( return nullptr; } + // quantized V forces the dense path, which transposes V - invalid for a block-quantized tensor + if (model->arch == LLM_ARCH_INKLING && ggml_is_quantized(params.type_v)) { + LLAMA_LOG_ERROR("%s: model does not support a quantized V cache (%s)\n", + __func__, ggml_type_name(params.type_v)); + return nullptr; + } + if (ggml_is_quantized(params.type_v) && params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_ENABLED) { if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO) { LLAMA_LOG_INFO("%s: enabling flash_attn since it is required for quantized V cache\n", __func__); From e2404ddadd38081f59da9542244170ec0705083e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 10 Aug 2026 10:26:33 +0000 Subject: [PATCH 006/115] Fix merge conflicts --- tools/mtmd/clip.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tools/mtmd/clip.cpp b/tools/mtmd/clip.cpp index 45db39d3ab12..521beeb7873a 100644 --- a/tools/mtmd/clip.cpp +++ b/tools/mtmd/clip.cpp @@ -4242,10 +4242,6 @@ bool clip_encode(struct clip_ctx * ctx, struct clip_encode_params * params) { // set input per projector switch (ctx->model.proj_type) { - case PROJECTOR_TYPE_INKLING: - { - // inp_raw is the only graph input. - } break; case PROJECTOR_TYPE_MINICPMV: { // inspired from siglip: @@ -4773,6 +4769,7 @@ bool clip_encode(struct clip_ctx * ctx, struct clip_encode_params * params) { case PROJECTOR_TYPE_GEMMA3: case PROJECTOR_TYPE_GEMMA3NV: case PROJECTOR_TYPE_IDEFICS3: + case PROJECTOR_TYPE_INKLING: // inp_raw is the only graph input case PROJECTOR_TYPE_INTERNVL: case PROJECTOR_TYPE_NEMOTRON_V2_VL: case PROJECTOR_TYPE_QWEN2A: From fe45c899aa52aafd6a1f880c80f74d2d7f1f9047 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Fri, 4 Sep 2026 09:16:03 +0000 Subject: [PATCH 007/115] mtmd: mark the Inkling preprocessors const to match the base class --- tools/mtmd/mtmd-audio.cpp | 2 +- tools/mtmd/mtmd-audio.h | 2 +- tools/mtmd/mtmd-image.cpp | 2 +- tools/mtmd/mtmd-image.h | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index 4d84102e5014..ebdc39cf01aa 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -552,7 +552,7 @@ void mtmd_audio_preprocessor_inkling::initialize() { bool mtmd_audio_preprocessor_inkling::preprocess( const float * samples, size_t n_samples, - std::vector & output) { + std::vector & output) const { if (n_samples == 0) { return false; } diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index a3c527ee9b9d..984b475d8e9e 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -73,7 +73,7 @@ struct mtmd_audio_preprocessor_whisper : mtmd_audio_preprocessor { struct mtmd_audio_preprocessor_inkling : mtmd_audio_preprocessor { mtmd_audio_preprocessor_inkling(const clip_ctx * ctx) : mtmd_audio_preprocessor(ctx) {} void initialize() override; - bool preprocess(const float * samples, size_t n_samples, std::vector & output) override; + bool preprocess(const float * samples, size_t n_samples, std::vector & output) const override; private: mtmd_audio_cache cache; diff --git a/tools/mtmd/mtmd-image.cpp b/tools/mtmd/mtmd-image.cpp index 2f0b1e0ca20a..8901eb87e9c9 100644 --- a/tools/mtmd/mtmd-image.cpp +++ b/tools/mtmd/mtmd-image.cpp @@ -836,7 +836,7 @@ mtmd_image_preproc_out mtmd_image_preprocessor_fixed_size::preprocess(const clip } // Inkling hMLP patches -mtmd_image_preproc_out mtmd_image_preprocessor_inkling::preprocess(const clip_image_u8 & img) { +mtmd_image_preproc_out mtmd_image_preprocessor_inkling::preprocess(const clip_image_u8 & img) const { GGML_ASSERT(hparams.patch_size == 40); constexpr int temporal_patch_size = 2; constexpr float rescale_frac = 2.0f; diff --git a/tools/mtmd/mtmd-image.h b/tools/mtmd/mtmd-image.h index b2508c1bbc0b..39ec62b193a2 100644 --- a/tools/mtmd/mtmd-image.h +++ b/tools/mtmd/mtmd-image.h @@ -132,7 +132,7 @@ struct mtmd_image_preprocessor_fixed_size : mtmd_image_preprocessor { // Inkling: split an image into 40x40 hMLP patches, each duplicated across a fixed temporal dimension of two. struct mtmd_image_preprocessor_inkling : mtmd_image_preprocessor { mtmd_image_preprocessor_inkling(const clip_ctx * ctx) : mtmd_image_preprocessor(ctx) {} - mtmd_image_preproc_out preprocess(const clip_image_u8 & img) override; + mtmd_image_preproc_out preprocess(const clip_image_u8 & img) const override; }; // resize image to multiple of patch_size*n_merge, while preserving aspect ratio From 36df1bf409c8b257689321a971a66973ee817ee1 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Fri, 4 Sep 2026 09:59:28 +0000 Subject: [PATCH 008/115] tests: give inkling its arch fixture so test-llama-archs stops skipping it --- tests/test-llama-archs.cpp | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 2b7fe87a0c5e..d87882201678 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -341,6 +341,21 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe) { ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, std::vector({0.0f, 4.0f})); ms.add_kv(LLM_KV_SWIGLU_CLAMP_SHEXP, std::vector({0.0f, 5.0f})); } + if (arch == LLM_ARCH_INKLING) { + // Read unconditionally by llama_model_inkling::load_arch_hparams, which + // then GGML_ASSERTs shortconv_kernel > 1, d_rel > 0, both rel extents > 0 + // and logit_scale_denom != 0, so none of these can be left out. + ms.add_kv(LLM_KV_INKLING_D_REL, uint32_t(16)); + ms.add_kv(LLM_KV_INKLING_REL_EXTENT, uint32_t(8)); + ms.add_kv(LLM_KV_INKLING_REL_EXTENT_SWA, uint32_t(4)); + ms.add_kv(LLM_KV_INKLING_SHORTCONV_KERNEL, uint32_t(3)); + ms.add_kv(LLM_KV_INKLING_DENSE_BLOCK_COUNT, uint32_t(1)); + ms.add_kv(LLM_KV_INKLING_LOGIT_SCALE_DENOM, 16.0f); + ms.add_kv(LLM_KV_INKLING_LOG_SCALING_N_FLOOR, uint32_t(n_ctx)); + ms.add_kv(LLM_KV_INKLING_LOG_SCALING_ALPHA, 0.0f); + ms.add_kv(LLM_KV_INKLING_UNPADDED_VOCAB_SIZE, n_vocab); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + } ms.add_kv(LLM_KV_WKV_HEAD_SIZE, n_embd/n_head); ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(3)); ms.add_kv(LLM_KV_RESIDUAL_SCALE, 3.5565588200778455f); @@ -446,6 +461,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_QWEN3NEXT: case LLM_ARCH_QWEN3VLMOE: case LLM_ARCH_QWEN35MOE: + case LLM_ARCH_INKLING: case LLM_ARCH_QWEN4EXP: case LLM_ARCH_PHIMOE: case LLM_ARCH_DBRX: @@ -541,9 +557,6 @@ static bool arch_supported(const llm_arch arch) { if (arch == LLM_ARCH_DEEPSEEK2OCR) { return false; } - if (arch == LLM_ARCH_INKLING) { - return false; // TODO fixture params for the arch-specific hparams (d_rel, rel_extent, shortconv, logit_scale_denom) - } // FIXME: these hit scheduler/view-backed-output issues with WebGPU on CI. #ifdef GGML_USE_WEBGPU if (arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_QWEN4EXP) { From 946fc11d1afb1e6cd316e853f1b23487754a74b9 Mon Sep 17 00:00:00 2001 From: danielhanchen Date: Wed, 9 Sep 2026 06:49:07 +0000 Subject: [PATCH 009/115] inkling: move to ggml_prec_set_acc, teach the backends about GGML_PREC_F32_PEDANTIC Every caller of the deprecated ggml_mul_mat_set_prec / ggml_flash_attn_ext_set_prec now uses ggml_prec_set_acc (the macOS prebuilt leg builds with LLAMA_FATAL_WARNINGS, so the deprecation would be fatal there), and ggml_prec_set_acc accepts GGML_OP_FLASH_ATTN_EXT_BANDED. With the enum ranked, the CUDA cuBLAS compute-type gate and the CPU, spacemit and Vulkan flash-attention accumulator checks compare by rank instead of equality with GGML_PREC_F32, so a pedantic request never falls through to a lower-precision path. The CUDA mul_mat_id slice carries the acc and src precision slots, and ggml_cuda_mul_mat_id_needs_sync applies the same pedantic gate as ggml_cuda_mul_mat_id so a pedantic F32 expert matmul cannot trip its assertion. --- ggml/src/ggml-cpu/ops.cpp | 1 + ggml/src/ggml-cpu/spacemit/ime.cpp | 2 +- ggml/src/ggml-cuda/ggml-cuda.cu | 16 +++++++++++++--- ggml/src/ggml-impl.h | 5 +++++ ggml/src/ggml-vulkan/ggml-vulkan.cpp | 4 +++- ggml/src/ggml.c | 1 + src/llama-graph.cpp | 4 ++-- src/llama-graph.h | 2 +- src/models/inkling.cpp | 6 +++--- tests/test-backend-ops.cpp | 2 +- tests/test-flash-attn-bias.cpp | 4 ++-- tests/test-flash-attn-generic-hash.cpp | 2 +- tools/mtmd/models/inkling.cpp | 2 +- 13 files changed, 35 insertions(+), 16 deletions(-) diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 5ba9f69db930..2c78f7923be8 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -9389,6 +9389,7 @@ void ggml_compute_forward_flash_attn_ext( ggml_tensor * dst) { switch (dst->op_params[3]) { case GGML_PREC_DEFAULT: + case GGML_PREC_F32_PEDANTIC: case GGML_PREC_F32: { // uses F32 accumulators diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp index 29d683270e51..ba53ed1cc852 100644 --- a/ggml/src/ggml-cpu/spacemit/ime.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime.cpp @@ -1165,7 +1165,7 @@ class tensor_traits_common : public tensor_traits_base { const int64_t DK = nek0; const int64_t DV = nev0; - const bool supported_prec = (dst->op_params[3] == GGML_PREC_F32 || dst->op_params[3] == GGML_PREC_DEFAULT); + const bool supported_prec = (dst->op_params[3] == GGML_PREC_F32 || dst->op_params[3] == GGML_PREC_F32_PEDANTIC || dst->op_params[3] == GGML_PREC_DEFAULT); const bool supported_types = (q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16); const bool supported_shape = (DK > 0 && DK <= 128 && DV > 0 && DV <= 128); const bool supported_vlen = (__riscv_vlenb() == 128); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 7915072dfa57..56e398a66d09 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -1653,7 +1653,9 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml } else if (compute_type == GGML_TYPE_F16 && !fast_fp16_hardware_available(ggml_cuda_info().devices[ctx.device].cc)) { compute_type = GGML_TYPE_F32; } - if (dst->op_params[0] == GGML_PREC_F32) { + // [TAG_GGML_PREC] any acc rank at least as strict as F32 (F32, F32_PEDANTIC) forces F32 compute + const ggml_prec prec_acc = ggml_prec(dst->op_params[0]); + if (prec_acc != GGML_PREC_UNDEFINED && prec_acc <= GGML_PREC_F32) { compute_type = GGML_TYPE_F32; } @@ -1675,7 +1677,7 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml } // a scoped pedantic request overrides the process-wide compute type, for F32 weights only - if (src0->type == GGML_TYPE_F32 && ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC) { + if (src0->type == GGML_TYPE_F32 && prec_acc == GGML_PREC_F32_PEDANTIC) { compute_type = GGML_TYPE_F32; } @@ -1909,6 +1911,10 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; + // same gate as ggml_cuda_mul_mat_id: a pedantic F32 request never takes the mmf path + const bool f32_pedantic = src0->type == GGML_TYPE_F32 && + ggml_prec(dst->op_params[0]) == GGML_PREC_F32_PEDANTIC; + if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { return true; } @@ -1927,7 +1933,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return false; } - if (ggml_cuda_should_use_mmf(src0->type, cc, WARP_SIZE, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { + if (!f32_pedantic && ggml_cuda_should_use_mmf(src0->type, cc, WARP_SIZE, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { return false; } @@ -2080,7 +2086,11 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst_slice.nb[2] = dst_slice.ne[1] * dst_slice.nb[1]; dst_slice.nb[3] = dst_slice.ne[2] * dst_slice.nb[2]; dst_slice.data = dst_data_cur; + // [TAG_GGML_PREC] the slice stands in for dst: carry acc (0) and src precision (2, 3). + // Not op_params[1], the op hint, which describes the unsliced operands. dst_slice.op_params[0] = dst->op_params[0]; + dst_slice.op_params[2] = dst->op_params[2]; + dst_slice.op_params[3] = dst->op_params[3]; ggml_cuda_mul_mat(ctx, &src0_slice, &src1_slice, &dst_slice); CUDA_CHECK(cudaGetLastError()); diff --git a/ggml/src/ggml-impl.h b/ggml/src/ggml-impl.h index ae26e0c23b46..49d3d6241025 100644 --- a/ggml/src/ggml-impl.h +++ b/ggml/src/ggml-impl.h @@ -172,6 +172,11 @@ static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t // 1 - hint // 2 - src0 precision // 3 - src1 precision +// +// - GGML_OP_FLASH_ATTN_EXT +// - GGML_OP_FLASH_ATTN_EXT_BANDED +// 0..2 - scale, max_bias, logit_softcap (f32) +// 3 - acc static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) { assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t)); ((int32_t *)(tensor->op_params))[i] = value; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index b3a7cb6ab6ac..42e79233eb68 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -11392,7 +11392,9 @@ static void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx uint32_t workgroups_y = (uint32_t)neq2; uint32_t workgroups_z = (uint32_t)neq3; - const bool f32acc = !ctx->device->fp16 || dst->op_params[3] == GGML_PREC_F32 || k->type == GGML_TYPE_BF16; + const ggml_prec fa_prec = ggml_prec(dst->op_params[3]); + const bool f32acc = !ctx->device->fp16 || k->type == GGML_TYPE_BF16 || + (fa_prec != GGML_PREC_UNDEFINED && fa_prec <= GGML_PREC_F32); // dequant K/V once into an f16 scratch, reordered KV layout so FA can read without a stride auto is_dense_kv_cache = [](const ggml_tensor * t) { diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 2bfff3c9a080..43c0b5d6f633 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -3293,6 +3293,7 @@ bool ggml_prec_set_acc( } break; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { const int32_t prec_i32 = (int32_t) prec; ggml_set_op_params_i32(a, 3, prec_i32); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index fbc9633c6880..3909546e10e3 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1518,9 +1518,9 @@ ggml_tensor * llm_graph_context::build_lora_mm( enum ggml_prec prec) const { ggml_tensor * res = ggml_mul_mat(ctx0, w, cur); - if (prec != GGML_PREC_DEFAULT) { + if (prec != GGML_PREC_UNDEFINED) { // Set precision on the base MUL_MAT before an optional scale/LoRA attachment changes the root op. - ggml_mul_mat_set_prec(res, prec); + ggml_prec_set_acc(res, prec); } if (w_s) { diff --git a/src/llama-graph.h b/src/llama-graph.h index fa1f7701f430..f79a274c9112 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1054,7 +1054,7 @@ struct llm_graph_context { ggml_tensor * w, ggml_tensor * cur, ggml_tensor * w_s = nullptr, - enum ggml_prec prec = GGML_PREC_DEFAULT) const; + enum ggml_prec prec = GGML_PREC_UNDEFINED) const; // do mat_mul_id, while optionally apply lora and per-expert scale ggml_tensor * build_lora_mm_id( diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 8a70208ba805..0a2ecb628378 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -380,7 +380,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * proj = ggml_cont(ctx0, ggml_transpose(ctx0, layer.attn_rel_proj)); // {d_rel, E} ggml_tensor * rel = ggml_mul_mat(ctx0, proj, r2); // {E, n_head*n_tokens} - ggml_mul_mat_set_prec(rel, GGML_PREC_F32_PEDANTIC); + ggml_prec_set_acc(rel, GGML_PREC_F32_PEDANTIC); rel = ggml_reshape_3d(ctx0, rel, rel_extent, n_head, n_tokens); if (tau && !is_swa) { @@ -465,7 +465,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, mask, rel_fa, 1.0f/float(head_dim), rel_extent); - ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32); + ggml_prec_set_acc(cur, GGML_PREC_F32); res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); @@ -652,7 +652,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par cur = ggml_scale(ctx0, cur, hparams.f_logit_scale); cur = build_lora_mm( model.output, cur, nullptr, - model.output->type == GGML_TYPE_F32 ? GGML_PREC_F32_PEDANTIC : GGML_PREC_DEFAULT); + model.output->type == GGML_TYPE_F32 ? GGML_PREC_F32_PEDANTIC : GGML_PREC_UNDEFINED); // padded vocab rows get -inf so samplers never emit a padded id if (vocab_mask) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index bc03df997e2c..f4e85f2b47ea 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -7783,7 +7783,7 @@ struct test_flash_attn_ext_banded : public test_case { } ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); - ggml_flash_attn_ext_set_prec(out, GGML_PREC_F32); + ggml_prec_set_acc(out, GGML_PREC_F32); ggml_set_name(out, "out"); return out; } diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index 4e842e1d119c..ae0724f0999e 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -177,13 +177,13 @@ static run_result run_graph( bias = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.nkv, c.nq, c.hq, c.n_batch); ggml_set_name(bias, "dense_bias"); ggml_tensor * scores = ggml_mul_mat(ctx.get(), k, q); - ggml_mul_mat_set_prec(scores, GGML_PREC_F32); + ggml_prec_set_acc(scores, GGML_PREC_F32); scores = ggml_scale(ctx.get(), scores, 1.0f/float(c.d)); scores = ggml_add(ctx.get(), scores, bias); scores = ggml_soft_max_ext(ctx.get(), scores, m, 1.0f, 0.0f); ggml_tensor * vt = ggml_cont(ctx.get(), ggml_transpose(ctx.get(), v)); out = ggml_mul_mat(ctx.get(), vt, scores); - ggml_mul_mat_set_prec(out, GGML_PREC_F32); + ggml_prec_set_acc(out, GGML_PREC_F32); out = ggml_cont(ctx.get(), ggml_permute(ctx.get(), out, 0, 2, 1, 3)); } ggml_set_name(out, dense ? "out_dense" : "out_flash"); diff --git a/tests/test-flash-attn-generic-hash.cpp b/tests/test-flash-attn-generic-hash.cpp index 4e3aca44ffab..e7f256d8af1e 100644 --- a/tests/test-flash-attn-generic-hash.cpp +++ b/tests/test-flash-attn-generic-hash.cpp @@ -55,7 +55,7 @@ int main(int argc, char ** argv) { ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, d, nkv, hkv, 1); ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, nkv, nq, 1, 1); ggml_tensor * out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/float(d), 0.0f, 0.0f); - ggml_flash_attn_ext_set_prec(out, GGML_PREC_F32); + ggml_prec_set_acc(out, GGML_PREC_F32); if (!ggml_backend_supports_op(backend, out)) { fprintf(stderr, "ordinary flash attention is unsupported on %s\n", ggml_backend_dev_description(chosen)); diff --git a/tools/mtmd/models/inkling.cpp b/tools/mtmd/models/inkling.cpp index 325fddde8a21..3c6799cef1a6 100644 --- a/tools/mtmd/models/inkling.cpp +++ b/tools/mtmd/models/inkling.cpp @@ -2,7 +2,7 @@ ggml_tensor * clip_graph_inkling::build_mm(ggml_tensor * w, ggml_tensor * x) const { ggml_tensor * cur = ggml_mul_mat(ctx0, w, x); - ggml_mul_mat_set_prec(cur, GGML_PREC_F32); + ggml_prec_set_acc(cur, GGML_PREC_F32); return cur; } From eeac951be2038fc27e89613d8d1158c31d97d732 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 14 Nov 2026 06:05:56 -0800 Subject: [PATCH 010/115] inkling : give the conv state, memory filter and rel-pos input their own lines Inkling shared its n_embd_r() check, the FALCON_H1 hybrid-memory branch and the kv-cache context declaration with the line any new hybrid architecture also edits, so every such PR (Inkling 2 in #32217 among them) conflicts with this one. Move each into its own block; behaviour is unchanged (RWKV never sets n_embd_r_impl, and the Inkling branch is the FALCON_H1 body). --- src/llama-hparams.cpp | 9 +++++---- src/llama-kv-cache.h | 3 ++- src/llama-model.cpp | 5 ++++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/llama-hparams.cpp b/src/llama-hparams.cpp index 6f9767d05422..876bb979dbc2 100644 --- a/src/llama-hparams.cpp +++ b/src/llama-hparams.cpp @@ -206,15 +206,16 @@ uint32_t llama_hparams::n_embd_v_gqa_max() const { } uint32_t llama_hparams::n_embd_r() const { - if (n_embd_r_impl != 0) { - return n_embd_r_impl; - } - if (wkv_head_size != 0) { // for RWKV models return token_shift_count * n_embd; } + if (n_embd_r_impl != 0) { + // for Inkling (attention conv state set by the model) + return n_embd_r_impl; + } + if (n_shortconv_l_cache != 0) { // for LFM2 models return n_embd * (n_shortconv_l_cache - 1); diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 32356277e259..0af7bedeaa9f 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -460,11 +460,12 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; - void set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // inkling // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; + void set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // inkling + private: llama_memory_status status; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index e88bf8318c62..cca89764661b 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -3321,7 +3321,10 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, filter_idx = [&](uint32_t il) { return il < hparams.n_layer() && !hparams.is_recr(il) && hparams.is_indexer_full(il); }; - } else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING) { + } else if (arch == LLM_ARCH_FALCON_H1) { + filter_attn = [&](uint32_t) { return true; }; + filter_recr = [&](uint32_t) { return true; }; + } else if (arch == LLM_ARCH_INKLING) { // all layers have both an attention KV cache and a recurrent (conv) state filter_attn = [&](uint32_t) { return true; }; filter_recr = [&](uint32_t) { return true; }; From e2a52601a0301910e9d57cccd3d34297a48baedd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 19 Nov 2026 11:04:12 -0800 Subject: [PATCH 011/115] CUDA: use ggml_cuda_shfl in the banded FA kernel Upstream #31617 enabled HIP's native warp sync builtins, which require a 64-bit lane mask, so the raw __shfl_sync(0xffffffff, ...) no longer compiles for ROCm. ggml_cuda_shfl passes GGML_CUDA_FULL_THREAD_MASK (0xffffffff on CUDA, 64-bit on HIP); CUDA codegen is unchanged. --- ggml/src/ggml-cuda/fattn-banded.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index c0a67a2914ac..99687a16d64c 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -122,7 +122,7 @@ static __global__ void flash_attn_ext_banded_f32( score += __half2float(*(const half *) mask_value); } } - score = __shfl_sync(0xffffffff, score, 0, WARP_SIZE); + score = ggml_cuda_shfl(score, 0, WARP_SIZE); if (score == -INFINITY) { continue; From 7980f5ca43ec7a52ecfa9c807aac6394f66c13f2 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 20 Nov 2026 02:24:11 -0800 Subject: [PATCH 012/115] model : chunk the Inkling 2 relative-bias attention over query rows Inkling 2 builds a dense relative-position bias of n_kv x n_ubatch x n_head elements per attention layer and adds it to the KQ mask. For Inkling-2-Small (48 heads) that passes 2^32 elements from about 175K tokens of context at the default ubatch of 512 (44K at -ub 2048), and the add aborts with GGML_ASSERT(s2 <= UINT32_MAX). The compute buffer also grows with it. When the bias of one call would exceed 2^29 elements for a full cache, attend in equal chunks of query rows (whole 64-row tiles, at most 64 chunks) and concatenate the outputs. The first chunk stores K and V, the distances and the F32 mask are copied to the device once per graph and each chunk views its rows. Below the budget the graph is unchanged. --- src/llama-graph.cpp | 12 +++++-- src/llama-graph.h | 9 +++-- src/llama-kv-cache.cpp | 4 +++ src/llama-kv-cache.h | 1 + src/models/inkling2.cpp | 75 ++++++++++++++++++++++++++++++++++++----- 5 files changed, 89 insertions(+), 12 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 269b920fb8e3..0556b06b5d61 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -4489,7 +4489,8 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * kq_b, ggml_tensor * sinks, float kq_scale, - int il) const { + int il, + int64_t i_row) const { const bool is_swa = hparams.is_swa(il); auto * inp_attn = inp->get_attn(); @@ -4502,7 +4503,14 @@ ggml_tensor * llm_graph_context::build_attn( // 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) { + if (kq_b->ne[1] != kq_mask->ne[1]) { + ggml_tensor *& dev = inp->self_kq_mask_dev[is_swa]; + if (!dev) { + dev = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_view_4d(ctx0, dev, dev->ne[0], kq_b->ne[1], dev->ne[2], dev->ne[3], + dev->nb[1], dev->nb[2], dev->nb[3], i_row*dev->nb[1]); + } else 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); diff --git a/src/llama-graph.h b/src/llama-graph.h index b5956ead9120..fcde13d3e55f 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -808,6 +808,10 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + // [base, swa] device copies, made once per graph when attention is chunked over query rows + ggml_tensor * self_rel_pos_dev[2] = { nullptr, nullptr }; + ggml_tensor * self_kq_mask_dev[2] = { nullptr, nullptr }; + const uint32_t extent; const uint32_t extent_swa; @@ -1550,10 +1554,11 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * kq_b, // [n_kv, n_rows, n_head_q, n_stream] ggml_tensor * sinks, // [n_head_q] float kq_scale, - int il) const; + int il, + int64_t i_row = 0) const; // first mask row of q_cur and kq_b // // pooling diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 5dd0e5f02861..c419883ec1ee 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -3055,6 +3055,10 @@ uint32_t llama_kv_cache_context::get_n_kv() const { return n_kv; } +uint32_t llama_kv_cache_context::get_size() const { + return kv->get_size(); +} + uint32_t llama_kv_cache_context::get_n_kv_rows() const { return n_kv_rows; } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc41d5..e99934b8b2f8 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -419,6 +419,7 @@ class llama_kv_cache_context : public llama_memory_context_i { uint32_t get_n_kv() const; uint32_t get_n_kv_rows() const; + uint32_t get_size() const; ggml_type type_k() const; ggml_type type_v() const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 3ba20ffe83d4..fbb09aa54c20 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -1,6 +1,13 @@ #include "models.h" #include "../llama-memory-hybrid-iswa.h" +#include +#include + +// max elements of the dense relative bias per attention call, and max chunks per layer +static constexpr int64_t n_kq_bias_max = int64_t(1) << 29; +static constexpr int64_t n_kq_chunk_max = 64; + void llama_model_inkling2::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_QK_CLIP, hparams.f_qk_clip); @@ -329,16 +336,68 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ 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); + // the dense bias is n_kv x n_tokens x n_head: past the budget, attend in chunks of query rows + const int64_t n_seq_tokens = n_tokens/n_stream; + // sized for a full cache so the chunking does not change while it fills + const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); + int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), + (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); + if (n_rows_max < n_seq_tokens) { + // equal chunks of whole 64-row tiles + const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; + n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); + } + // rows [r0, r0 + nr) of every stream along dim d + auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { + int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; + ne[d] = nr; + return ggml_cont(ctx0, ggml_view_4d(ctx0, t, ne[0], ne[1], ne[2], ne[3], t->nb[1], t->nb[2], t->nb[3], r0*t->nb[d])); + }; + std::vector outs; + for (int64_t r0 = 0; r0 < n_seq_tokens; r0 += n_rows_max) { + const int64_t nr = std::min(n_rows_max, n_seq_tokens - r0); + const bool all = nr == n_seq_tokens; + ggml_tensor * q_c = Qcur; + ggml_tensor * kq_b = nullptr; + if (all) { + kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, nr, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + } else { + q_c = ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_seq_tokens, n_stream), 2, r0, nr), + n_embd_head, n_head, nr*n_stream); + ggml_tensor * table_c = ggml_reshape_4d(ctx0, table, table->ne[0], table->ne[1], n_seq_tokens, n_stream); + table_c = ggml_view_4d(ctx0, table_c, table_c->ne[0], table_c->ne[1], nr, n_stream, + table_c->nb[1], table_c->nb[2], table_c->nb[3], r0*table_c->nb[2]); + ggml_tensor *& rel_pos_dev = inp->self_rel_pos_dev[is_swa]; + if (!rel_pos_dev) { + rel_pos_dev = ggml_cont(ctx0, rel_pos); + } + ggml_tensor * rel_pos_c = ggml_view_3d(ctx0, rel_pos_dev, n_kv, nr, n_stream, + rel_pos_dev->nb[1], n_seq_tokens*rel_pos_dev->nb[1], r0*rel_pos_dev->nb[1]); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, ggml_get_rows(ctx0, table_c, rel_pos_c), 2, 0, 1, 3)); + } + cb(kq_b, "kq_b", il); + + // only the first chunk stores K and V + ggml_tensor * out = build_attn(inp, + nullptr, nullptr, nullptr, + q_c, r0 == 0 ? Kcur : nullptr, r0 == 0 ? Vcur : nullptr, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il, r0); + outs.push_back(all ? out : ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream)); + } + while (outs.size() > 1) { + std::vector next; + for (size_t c = 0; c + 1 < outs.size(); c += 2) { + next.push_back(ggml_concat(ctx0, outs[c], outs[c + 1], 1)); + } + if (outs.size() % 2) { + next.push_back(outs.back()); + } + outs = std::move(next); + } + cur = n_rows_max >= n_seq_tokens ? outs[0] : ggml_reshape_2d(ctx0, outs[0], outs[0]->ne[0], n_tokens); 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); From 7c3655ce79c063626b8e4781a002b72a1c280155 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 20 Nov 2026 02:26:57 -0800 Subject: [PATCH 013/115] model : banded flash attention for the Inkling 2 relative bias With flash attention on and a position-contiguous cache, Inkling 2 now passes the relative logits inside the extent to ggml_flash_attn_ext_banded and the sink logit as per-query sinks, instead of building a dense per-head mask of n_kv x n_ubatch x n_head elements. Other caches, quantized K/V, devices without the op and ubatches of up to 32 tokens keep the chunked dense path. The rel-pos input refuses graph reuse when the banded cell count changes. ggml: FLASH_ATTN_EXT_BANDED takes per-query sinks [n_head, n_q, n_seq] on CPU and CUDA, with a split-KV decode kernel and a tensor-core prefill kernel on CUDA. test-backend-ops covers the sinks and Inkling-2-Small shapes. --- ggml/src/ggml-cpu/ops.cpp | 3 +- ggml/src/ggml-cuda/fattn-banded.cu | 889 +++++++++++++++++++++++++++++ ggml/src/ggml-cuda/fattn.cu | 5 + ggml/src/ggml.c | 4 +- src/llama-graph.cpp | 5 + src/llama-graph.h | 4 + src/models/inkling2.cpp | 218 +++++-- tests/test-backend-ops.cpp | 51 ++ 8 files changed, 1114 insertions(+), 65 deletions(-) diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index da509d0da432..d1f7a55aac62 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -9026,7 +9026,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( // sinks - apply only on the first kv-chunk if (sinks && ic_start == 0) { - const float s = ((float *)((char *) sinks->data))[h]; + const float s = *(const float *)((const char *) sinks->data + h*sinks->nb[0] + + (sinks->ne[1] > 1 ? iq1*sinks->nb[1] : 0) + (sinks->ne[2] > 1 ? iq3*sinks->nb[2] : 0)); float ms = 1.0f; float vs = 1.0f; diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 99687a16d64c..4995319167ca 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1,7 +1,9 @@ #include "common.cuh" +#include "convert.cuh" #include "fattn-banded.cuh" #include "fattn.cuh" +#include #include static __device__ __forceinline__ float fattn_banded_load( @@ -55,6 +57,9 @@ static __global__ void flash_attn_ext_banded_f32( uint64_t m_nb1, uint64_t m_nb2, uint64_t m_nb3, + const float * __restrict__ sinks, + int64_t sinks_s1, + int64_t sinks_s2, uint64_t r_nb0, uint64_t r_nb1, uint64_t r_nb2, @@ -147,6 +152,22 @@ static __global__ void flash_attn_ext_banded_f32( row_sum = row_sum*old_scale + value_scale; } + // attention sink: an extra logit with a zero value + if (sinks) { + const float sink = sinks[ih + iq*sinks_s1 + ib*sinks_s2]; + if (sink > row_max) { + const float old_scale = expf(row_max - sink); +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + out[j] *= old_scale; + } + row_sum = row_sum*old_scale + 1.0f; + row_max = sink; + } else { + row_sum += expf(sink - row_max); + } + } + const float inv_sum = row_sum == 0.0f ? 0.0f : 1.0f/row_sum; float * dst_row = dst + ((ib*n_q + iq)*n_head_q + ih)*D; #pragma unroll @@ -156,6 +177,663 @@ static __global__ void flash_attn_ext_banded_f32( } } +template +static __global__ void flash_attn_ext_banded_f32_split( + const char * __restrict__ q, + const char * __restrict__ k, + const char * __restrict__ v, + const char * __restrict__ mask, + const char * __restrict__ rel, + float * __restrict__ part, + float scale, + int type_k, + int type_v, + int type_rel, + int64_t n_q, + int64_t n_kv, + int64_t n_head_q, + int64_t n_head_kv, + int64_t n_chunks, + int64_t chunk, + int64_t rel_extent, + int64_t mask_ne2, + int64_t mask_ne3, + uint64_t q_nb1, + uint64_t q_nb2, + uint64_t q_nb3, + uint64_t k_nb0, + uint64_t k_nb1, + uint64_t k_nb2, + uint64_t k_nb3, + uint64_t v_nb0, + uint64_t v_nb1, + uint64_t v_nb2, + uint64_t v_nb3, + uint64_t m_nb1, + uint64_t m_nb2, + uint64_t m_nb3, + uint64_t r_nb0, + uint64_t r_nb1, + uint64_t r_nb2, + uint64_t r_nb3, + int64_t rel_ne3) { + constexpr int values_per_lane = D / WARP_SIZE; + static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); + + const int lane = threadIdx.x % WARP_SIZE; + const int warp = threadIdx.x / WARP_SIZE; + const int64_t ic = blockIdx.x; + const int64_t ih = blockIdx.y; + const int64_t iq = int64_t(blockIdx.z) % n_q; + const int64_t ib = int64_t(blockIdx.z) / n_q; + + const int64_t ih_kv = ih / (n_head_q / n_head_kv); + const char * q_row = q + uint64_t(iq)*q_nb1 + uint64_t(ih)*q_nb2 + uint64_t(ib)*q_nb3; + + float q_reg[values_per_lane]; + float out[values_per_lane]; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + q_reg[j] = *(const float *)(q_row + uint64_t(d)*sizeof(float)); + out[j] = 0.0f; + } + + float row_max = -INFINITY; + float row_sum = 0.0f; + const int64_t q_offset = n_kv - n_q; + const int64_t ik0 = ic*chunk; + const int64_t ik1 = ik0 + chunk < n_kv ? ik0 + chunk : n_kv; + + for (int64_t ik = ik0 + warp; ik < ik1; ik += NW) { + if (mask && __half2float(*(const half *) (mask + uint64_t(ik)*sizeof(half) + + uint64_t(iq)*m_nb1 + uint64_t(ih % mask_ne2)*m_nb2 + + uint64_t(ib % mask_ne3)*m_nb3)) == -INFINITY) { + continue; + } + + const char * k_row = k + uint64_t(ik)*k_nb1 + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; + float dot = 0.0f; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + dot += q_reg[j] * fattn_banded_load(k_row + uint64_t(d)*k_nb0, type_k); + } + dot = warp_reduce_sum(dot); + + float score = dot * scale; + if (lane == 0) { + const int64_t rel_dist = iq + q_offset - ik; + if (rel_dist >= 0 && rel_dist < rel_extent) { + const char * rel_value = rel + + uint64_t(rel_dist)*r_nb0 + uint64_t(ih)*r_nb1 + + uint64_t(iq)*r_nb2 + uint64_t(ib % rel_ne3)*r_nb3; + score += fattn_banded_load(rel_value, type_rel); + } + if (mask) { + const char * mask_value = mask + uint64_t(ik)*sizeof(half) + + uint64_t(iq)*m_nb1 + uint64_t(ih % mask_ne2)*m_nb2 + + uint64_t(ib % mask_ne3)*m_nb3; + score += __half2float(*(const half *) mask_value); + } + } + score = ggml_cuda_shfl(score, 0, WARP_SIZE); + + if (score == -INFINITY) { + continue; + } + + float old_scale = 1.0f; + float value_scale = 1.0f; + if (score > row_max) { + old_scale = expf(row_max - score); + row_max = score; + } else { + value_scale = expf(score - row_max); + } + + const char * v_row = v + uint64_t(ik)*v_nb1 + uint64_t(ih_kv)*v_nb2 + uint64_t(ib)*v_nb3; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + const int d = lane + j*WARP_SIZE; + const float vv = fattn_banded_load(v_row + uint64_t(d)*v_nb0, type_v); + out[j] = out[j]*old_scale + vv*value_scale; + } + row_sum = row_sum*old_scale + value_scale; + } + + __shared__ float s_max[NW]; + __shared__ float s_sum[NW]; + __shared__ float s_out[NW][D]; + if (lane == 0) { + s_max[warp] = row_max; + s_sum[warp] = row_sum; + } +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + s_out[warp][lane + j*WARP_SIZE] = out[j]; + } + __syncthreads(); + + if (warp == 0) { + float m = -INFINITY; +#pragma unroll + for (int w = 0; w < NW; ++w) { + m = fmaxf(m, s_max[w]); + } + float acc[values_per_lane]; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + acc[j] = 0.0f; + } + float sum = 0.0f; + if (m != -INFINITY) { +#pragma unroll + for (int w = 0; w < NW; ++w) { + if (s_max[w] == -INFINITY) { + continue; + } + const float f = expf(s_max[w] - m); + sum += s_sum[w]*f; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + acc[j] += s_out[w][lane + j*WARP_SIZE]*f; + } + } + } + float * p = part + ((((ib*n_q + iq)*n_head_q + ih)*n_chunks) + ic)*(D + 2); + if (lane == 0) { + p[0] = m; + p[1] = sum; + } +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + p[2 + lane + j*WARP_SIZE] = acc[j]; + } + } +} + +template +static __global__ void flash_attn_ext_banded_f32_merge( + const float * __restrict__ part, + float * __restrict__ dst, + int64_t n_rows, + int64_t n_head_q, + int64_t n_q, + int64_t n_chunks, + const float * __restrict__ sinks, + int64_t sinks_s1, + int64_t sinks_s2) { + constexpr int values_per_lane = D / WARP_SIZE; + const int lane = threadIdx.x % WARP_SIZE; + const int64_t row = int64_t(blockIdx.x)*(blockDim.x/WARP_SIZE) + threadIdx.x/WARP_SIZE; + if (row >= n_rows) { + return; + } + const int64_t ih = row % n_head_q; + const int64_t iq = (row / n_head_q) % n_q; + const int64_t ib = row / (n_head_q*n_q); + const float * p = part + row*n_chunks*(D + 2); + + float m = -INFINITY; + for (int64_t c = 0; c < n_chunks; ++c) { + m = fmaxf(m, p[c*(D + 2)]); + } + float out[values_per_lane]; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + out[j] = 0.0f; + } + float row_sum = 0.0f; + if (m != -INFINITY) { + for (int64_t c = 0; c < n_chunks; ++c) { + const float * pc = p + c*(D + 2); + if (pc[0] == -INFINITY) { + continue; + } + const float f = expf(pc[0] - m); + row_sum += pc[1]*f; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + out[j] += pc[2 + lane + j*WARP_SIZE]*f; + } + } + } + float row_max = m; + + if (sinks) { + const float sink = sinks[ih + iq*sinks_s1 + ib*sinks_s2]; + if (sink > row_max) { + const float old_scale = expf(row_max - sink); +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + out[j] *= old_scale; + } + row_sum = row_sum*old_scale + 1.0f; + row_max = sink; + } else { + row_sum += expf(sink - row_max); + } + } + + const float inv_sum = row_sum == 0.0f ? 0.0f : 1.0f/row_sum; + float * dst_row = dst + row*D; +#pragma unroll + for (int j = 0; j < values_per_lane; ++j) { + dst_row[lane + j*WARP_SIZE] = out[j]*inv_sum; + } +} + +#if defined(TURING_MMA_AVAILABLE) +#define FATTN_BANDED_MMA_AVAILABLE +#endif + +static constexpr int fattn_banded_mma_bk = 64; + +#ifdef FATTN_BANDED_MMA_AVAILABLE +static __device__ __forceinline__ void fattn_banded_mma_16816( + float (&c)[4], const uint32_t a0, const uint32_t a1, const uint32_t a2, const uint32_t a3, + const uint32_t b0, const uint32_t b1) { +#ifdef AMPERE_MMA_AVAILABLE + asm("mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, {%8, %9}, {%0, %1, %2, %3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1)); +#else + asm("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0, %1, %2, %3}, {%4, %5}, {%6}, {%0, %1, %2, %3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a0), "r"(a1), "r"(b0)); + asm("mma.sync.aligned.m16n8k8.row.col.f32.f16.f16.f32 {%0, %1, %2, %3}, {%4, %5}, {%6}, {%0, %1, %2, %3};" + : "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3]) + : "r"(a2), "r"(a3), "r"(b1)); +#endif // AMPERE_MMA_AVAILABLE +} + +static __device__ __forceinline__ void fattn_banded_ldmatrix_x4(uint32_t (&r)[4], const half * p) { + const uint32_t a = (uint32_t) __cvta_generic_to_shared(p); + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); +} + +static __device__ __forceinline__ void fattn_banded_ldmatrix_x4_trans(uint32_t (&r)[4], const half * p) { + const uint32_t a = (uint32_t) __cvta_generic_to_shared(p); + asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0, %1, %2, %3}, [%4];" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) : "r"(a)); +} + +static __device__ __forceinline__ uint32_t fattn_banded_pack_h2(const float lo, const float hi) { + const half2 h = __floats2half2_rn(lo, hi); + return *(const uint32_t *) &h; +} + +template +static __device__ __forceinline__ void fattn_banded_mma_load_tile( + half * __restrict__ tile, const char * __restrict__ src, const uint64_t nb1, const int64_t kv0, const int64_t n_kv) { + constexpr int stride = D + 8; + constexpr int chunks = D/8; + constexpr int nthreads = NW*WARP_SIZE; +#pragma unroll + for (int c0 = 0; c0 < fattn_banded_mma_bk*chunks; c0 += nthreads) { + const int c = c0 + threadIdx.x; + const int row = c / chunks; + const int col = (c % chunks)*8; + half * dst = tile + row*stride + col; + if (kv0 + row < n_kv) { + const char * s = src + uint64_t(kv0 + row)*nb1 + uint64_t(col)*sizeof(half); +#ifdef CP_ASYNC_AVAILABLE + const uint32_t d = (uint32_t) __cvta_generic_to_shared(dst); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" : : "r"(d), "l"(s)); +#else + *(int4 *) dst = *(const int4 *) s; +#endif // CP_ASYNC_AVAILABLE + } else { + *(int4 *) dst = make_int4(0, 0, 0, 0); + } + } +#ifdef CP_ASYNC_AVAILABLE + asm volatile("cp.async.commit_group;"); +#endif // CP_ASYNC_AVAILABLE +} + +template +static __device__ __forceinline__ void fattn_banded_mma_wait() { +#ifdef CP_ASYNC_AVAILABLE + asm volatile("cp.async.wait_group %0;" : : "n"(n)); +#endif // CP_ASYNC_AVAILABLE +} +#endif // FATTN_BANDED_MMA_AVAILABLE + +static __global__ void flash_attn_ext_banded_mma_tile_flags( + const char * __restrict__ mask, + uint8_t * __restrict__ flags, + int64_t n_q, + int64_t n_kv, + int bq, + int64_t mask_ne2, + uint64_t m_nb1, + uint64_t m_nb2, + uint64_t m_nb3) { + const int64_t kt = blockIdx.x; + const int64_t qt = blockIdx.y; + const int64_t z = blockIdx.z; + const int64_t z2 = z % mask_ne2; + const int64_t z3 = z / mask_ne2; + const char * mrow = mask + z2*m_nb2 + z3*m_nb3; + + bool any_visible = false; + bool any_nonzero = false; + for (int e = threadIdx.x; e < bq*fattn_banded_mma_bk; e += blockDim.x) { + const int64_t iq = qt*bq + e / fattn_banded_mma_bk; + const int64_t ik = kt*fattn_banded_mma_bk + e % fattn_banded_mma_bk; + if (iq < n_q && ik < n_kv) { + const float m = __half2float(*(const half *) (mrow + uint64_t(iq)*m_nb1 + uint64_t(ik)*sizeof(half))); + any_visible |= m != -INFINITY; + any_nonzero |= m != 0.0f; + } + } + any_visible = __syncthreads_or(any_visible); + any_nonzero = __syncthreads_or(any_nonzero); + if (threadIdx.x == 0) { + const int64_t n_kt = gridDim.x; + const int64_t n_qt = gridDim.y; + flags[(z*n_qt + qt)*n_kt + kt] = !any_visible ? 0 : (any_nonzero ? 2 : 1); + } +} + +template +__launch_bounds__(NW*WARP_SIZE, 1) +static __global__ void flash_attn_ext_banded_mma( + const char * __restrict__ q, + const char * __restrict__ k, + const char * __restrict__ v, + const char * __restrict__ mask, + const uint8_t * __restrict__ flags, + const char * __restrict__ rel, + const float * __restrict__ sinks, + float * __restrict__ dst, + float * __restrict__ part, + float scale, + int type_rel, + int64_t n_q, + int64_t n_kv, + int64_t n_head_q, + int64_t n_head_kv, + int64_t n_chunks, + int64_t tiles_per_chunk, + int64_t rel_extent, + int64_t mask_ne2, + int64_t mask_ne3, + uint64_t q_nb1, + uint64_t q_nb2, + uint64_t q_nb3, + uint64_t k_nb1, + uint64_t k_nb2, + uint64_t k_nb3, + uint64_t v_nb1, + uint64_t v_nb2, + uint64_t v_nb3, + uint64_t m_nb1, + uint64_t m_nb2, + uint64_t m_nb3, + uint64_t r_nb0, + uint64_t r_nb1, + uint64_t r_nb2, + uint64_t r_nb3, + int64_t rel_ne3, + int64_t sinks_s1, + int64_t sinks_s2) { +#ifdef FATTN_BANDED_MMA_AVAILABLE + static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); + constexpr int BK = fattn_banded_mma_bk; + constexpr int BQ = NW*16; + constexpr int stride = D + 8; // padded smem row (halfs): conflict-free ldmatrix + constexpr int ND = D/8; + constexpr int NK = D/16; + + __shared__ __align__(16) half K_s[BK*stride]; + __shared__ __align__(16) half V_s[BK*stride]; + + const int lane = threadIdx.x % WARP_SIZE; + const int warp = threadIdx.x / WARP_SIZE; + const int g = lane / 4; + const int t = lane % 4; + + const int64_t n_qt = (n_q + BQ - 1)/BQ; + const int64_t qt = int64_t(blockIdx.x) / n_chunks; + const int64_t ic = int64_t(blockIdx.x) % n_chunks; + const int64_t ih = blockIdx.y; + const int64_t ib = blockIdx.z; + const int64_t ih_kv = ih / (n_head_q / n_head_kv); + + const int64_t n_kt = (n_kv + BK - 1)/BK; + const int64_t kt_begin = ic*tiles_per_chunk; + const int64_t kt_end = kt_begin + tiles_per_chunk < n_kt ? kt_begin + tiles_per_chunk : n_kt; + + const int64_t iq_w = qt*BQ + warp*16; + const int64_t iq_r[2] = {iq_w + g, iq_w + g + 8}; + const int64_t q_offset = n_kv - n_q; + + const char * k_base = k + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; + const char * v_base = v + uint64_t(ih_kv)*v_nb2 + uint64_t(ib)*v_nb3; + const char * m_base = mask ? mask + uint64_t(ih % mask_ne2)*m_nb2 + uint64_t(ib % mask_ne3)*m_nb3 : nullptr; + const uint8_t * f_base = flags ? flags + ((ih % mask_ne2) + mask_ne2*(ib % mask_ne3))*n_qt*n_kt + qt*n_kt : nullptr; + const char * r_base = rel + uint64_t(ih)*r_nb1 + uint64_t(ib % rel_ne3)*r_nb3; + + uint32_t Q_a[NK][4]; +#pragma unroll + for (int kk = 0; kk < NK; ++kk) { +#pragma unroll + for (int r = 0; r < 2; ++r) { + float lo0 = 0.0f, hi0 = 0.0f, lo1 = 0.0f, hi1 = 0.0f; + if (iq_r[r] < n_q) { + const float * qr = (const float *) (q + uint64_t(iq_r[r])*q_nb1 + uint64_t(ih)*q_nb2 + uint64_t(ib)*q_nb3); + lo0 = qr[kk*16 + 2*t + 0]; + hi0 = qr[kk*16 + 2*t + 1]; + lo1 = qr[kk*16 + 2*t + 8]; + hi1 = qr[kk*16 + 2*t + 9]; + } + Q_a[kk][r + 0] = fattn_banded_pack_h2(lo0, hi0); + Q_a[kk][r + 2] = fattn_banded_pack_h2(lo1, hi1); + } + } + + float O[ND][4]; +#pragma unroll + for (int n = 0; n < ND; ++n) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + O[n][e] = 0.0f; + } + } + float row_max[2] = {-INFINITY, -INFINITY}; + float row_sum[2] = {0.0f, 0.0f}; + + auto next_tile = [&](int64_t kt) { + if (f_base) { + while (kt < kt_end && f_base[kt] == 0) { + ++kt; + } + } + return kt; + }; + + int64_t kt = next_tile(kt_begin); + if (kt < kt_end) { + fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt*BK, n_kv); + fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt*BK, n_kv); + } + + while (kt < kt_end) { + const int64_t kv0 = kt*BK; + const int flag = f_base ? f_base[kt] : 1; + + fattn_banded_mma_wait<1>(); // K tile landed, V may still be in flight + __syncthreads(); + + float S[BK/8][4]; +#pragma unroll + for (int j = 0; j < BK/8; ++j) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + S[j][e] = 0.0f; + } + } +#pragma unroll + for (int kk = 0; kk < NK; ++kk) { +#pragma unroll + for (int j = 0; j < BK/8; j += 2) { + const int mi = lane / 8; + uint32_t b[4]; + fattn_banded_ldmatrix_x4(b, K_s + ((j + mi/2)*8 + lane % 8)*stride + kk*16 + (mi % 2)*8); + fattn_banded_mma_16816(S[j + 0], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[0], b[1]); + fattn_banded_mma_16816(S[j + 1], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[2], b[3]); + } + } + + const int64_t dist_hi = iq_w + 15 + q_offset - kv0; + const int64_t dist_lo = iq_w + q_offset - (kv0 + BK - 1); + const bool in_band = dist_hi >= 0 && dist_lo < rel_extent; + +#pragma unroll + for (int j = 0; j < BK/8; ++j) { +#pragma unroll + for (int e = 0; e < 4; ++e) { + const int r = e / 2; + const int64_t ik = kv0 + j*8 + 2*t + (e % 2); + float s = S[j][e]*scale; + if (ik >= n_kv) { + s = -INFINITY; + } else if (iq_r[r] < n_q) { + if (in_band) { + const int64_t dist = iq_r[r] + q_offset - ik; + if (dist >= 0 && dist < rel_extent) { + s += fattn_banded_load(r_base + uint64_t(dist)*r_nb0 + uint64_t(iq_r[r])*r_nb2, type_rel); + } + } + if (flag == 2) { + s += __half2float(*(const half *) (m_base + uint64_t(iq_r[r])*m_nb1 + uint64_t(ik)*sizeof(half))); + } + } + S[j][e] = s; + } + } + + float alpha[2]; + float msub[2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + float m = row_max[r]; +#pragma unroll + for (int j = 0; j < BK/8; ++j) { + m = fmaxf(m, fmaxf(S[j][2*r + 0], S[j][2*r + 1])); + } + m = fmaxf(m, __shfl_xor_sync(GGML_CUDA_FULL_THREAD_MASK, m, 1, WARP_SIZE)); + m = fmaxf(m, __shfl_xor_sync(GGML_CUDA_FULL_THREAD_MASK, m, 2, WARP_SIZE)); + msub[r] = m == -INFINITY ? 0.0f : m; + alpha[r] = expf(row_max[r] - msub[r]); + row_max[r] = m; + } + uint32_t P_a[BK/8][2]; +#pragma unroll + for (int r = 0; r < 2; ++r) { + row_sum[r] *= alpha[r]; + } +#pragma unroll + for (int j = 0; j < BK/8; ++j) { +#pragma unroll + for (int r = 0; r < 2; ++r) { + const float p0 = expf(S[j][2*r + 0] - msub[r]); + const float p1 = expf(S[j][2*r + 1] - msub[r]); + row_sum[r] += p0 + p1; + P_a[j][r] = fattn_banded_pack_h2(p0, p1); + } + } +#pragma unroll + for (int n = 0; n < ND; ++n) { + O[n][0] *= alpha[0]; + O[n][1] *= alpha[0]; + O[n][2] *= alpha[1]; + O[n][3] *= alpha[1]; + } + + __syncthreads(); // every warp is done with K_s + const int64_t kt_next = next_tile(kt + 1); + if (kt_next < kt_end) { + fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt_next*BK, n_kv); + fattn_banded_mma_wait<1>(); // V tile of this iteration landed + } else { + fattn_banded_mma_wait<0>(); + } + __syncthreads(); + +#pragma unroll + for (int s = 0; s < BK/16; ++s) { +#pragma unroll + for (int n = 0; n < ND; n += 2) { + const int mi = lane / 8; + uint32_t b[4]; + fattn_banded_ldmatrix_x4_trans(b, V_s + (s*16 + (mi % 2)*8 + lane % 8)*stride + (n + mi/2)*8); + fattn_banded_mma_16816(O[n + 0], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[0], b[1]); + fattn_banded_mma_16816(O[n + 1], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[2], b[3]); + } + } + + __syncthreads(); // every warp is done with V_s + if (kt_next < kt_end) { + fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt_next*BK, n_kv); + } + kt = kt_next; + } + +#pragma unroll + for (int r = 0; r < 2; ++r) { + row_sum[r] += __shfl_xor_sync(GGML_CUDA_FULL_THREAD_MASK, row_sum[r], 1, WARP_SIZE); + row_sum[r] += __shfl_xor_sync(GGML_CUDA_FULL_THREAD_MASK, row_sum[r], 2, WARP_SIZE); + } + +#pragma unroll + for (int r = 0; r < 2; ++r) { + const int64_t iq = iq_r[r]; + if (iq >= n_q) { + continue; + } + const int64_t row = (ib*n_q + iq)*n_head_q + ih; + if (n_chunks == 1) { + float m = row_max[r]; + float sum = row_sum[r]; + float f = 1.0f; + if (sinks) { + const float sink = sinks[ih + iq*sinks_s1 + ib*sinks_s2]; + const float m_new = fmaxf(m, sink); + f = expf(m - m_new); + sum = sum*f + expf(sink - m_new); + } + const float inv = sum == 0.0f ? 0.0f : f/sum; + float2 * d = (float2 *) (dst + row*D); +#pragma unroll + for (int n = 0; n < ND; ++n) { + d[n*4 + t] = make_float2(O[n][2*r + 0]*inv, O[n][2*r + 1]*inv); + } + } else { + float * p = part + (row*n_chunks + ic)*(D + 2); + if (t == 0) { + p[0] = row_max[r]; + p[1] = row_sum[r]; + } +#pragma unroll + for (int n = 0; n < ND; ++n) { + p[2 + n*8 + 2*t + 0] = O[n][2*r + 0]; + p[2 + n*8 + 2*t + 1] = O[n][2*r + 1]; + } + } + } +#else + GGML_UNUSED_VARS(q, k, v, mask, flags, rel, sinks, dst, part, scale, type_rel, n_q, n_kv, n_head_q, n_head_kv, + n_chunks, tiles_per_chunk, rel_extent, mask_ne2, mask_ne3, q_nb1, q_nb2, q_nb3, k_nb1, k_nb2, k_nb3, + v_nb1, v_nb2, v_nb3, m_nb1, m_nb2, m_nb3, r_nb0, r_nb1, r_nb2, r_nb3, rel_ne3, sinks_s1, sinks_s2); + NO_DEVICE_CODE; +#endif // FATTN_BANDED_MMA_AVAILABLE +} + static bool fattn_banded_type_supported(ggml_type type) { return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; } @@ -200,11 +878,169 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d (rel->ne[3] != 1 && rel->ne[3] != q->ne[3])) { return false; } + const ggml_tensor * sinks = dst->src[4]; + if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float))) { + return false; + } return !m || (m->type == GGML_TYPE_F16 && ggml_is_contiguous(m) && q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0); #endif } +static constexpr int64_t fattn_banded_mma_min_q = 16; + +static bool fattn_banded_mma_aligned(const ggml_tensor * t) { + return (uintptr_t) t->data % 16 == 0 && t->nb[1] % 16 == 0 && t->nb[2] % 16 == 0 && t->nb[3] % 16 == 0; +} + +static bool fattn_banded_mma_usable(const int device, const ggml_tensor * dst) { + static const bool disabled = [] { + const char * env = getenv("GGML_CUDA_DISABLE_BANDED_MMA"); + return env != nullptr && atoi(env) != 0; + }(); + if (disabled) { + return false; + } + if (!turing_mma_available(ggml_cuda_info().devices[device].cc)) { + return false; + } + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + if (q->ne[1] < fattn_banded_mma_min_q) { + return false; + } + for (const ggml_tensor * t : {k, v}) { + if (t->type == GGML_TYPE_F16 ? !fattn_banded_mma_aligned(t) : t->type != GGML_TYPE_BF16) { + return false; + } + } + return true; +} + +static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const float scale, const int64_t rel_extent) { + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * m = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const ggml_tensor * rel = dst->src[6]; + cudaStream_t stream = ctx.stream(); + + const int64_t D = q->ne[0]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + + const char * k_data = (const char *) k->data; + const char * v_data = (const char *) v->data; + uint64_t k_nb[4] = {k->nb[0], k->nb[1], k->nb[2], k->nb[3]}; + uint64_t v_nb[4] = {v->nb[0], v->nb[1], v->nb[2], v->nb[3]}; + ggml_cuda_pool_alloc k_f16(ctx.pool()); + ggml_cuda_pool_alloc v_f16(ctx.pool()); + auto to_f16 = [&](const ggml_tensor * t, ggml_cuda_pool_alloc & buf, const char *& data, uint64_t (&nb)[4]) { + if (t->type == GGML_TYPE_F16) { + return; + } + const size_t ts = ggml_type_size(t->type); + buf.alloc(ggml_nelements(t)); + ggml_get_to_fp16_nc_cuda(t->type)(t->data, buf.get(), t->ne[0], t->ne[1], t->ne[2], t->ne[3], + t->nb[1]/ts, t->nb[2]/ts, t->nb[3]/ts, stream); + data = (const char *) buf.get(); + nb[0] = sizeof(half); + nb[1] = t->ne[0]*nb[0]; + nb[2] = t->ne[1]*nb[1]; + nb[3] = t->ne[2]*nb[2]; + }; + to_f16(k, k_f16, k_data, k_nb); + to_f16(v, v_f16, v_data, v_nb); + + const int nw = n_q >= 64 ? 4 : (n_q >= 32 ? 2 : 1); + const int bq = nw*16; + const int64_t n_qt = (n_q + bq - 1)/bq; + const int64_t n_kt = (n_kv + fattn_banded_mma_bk - 1)/fattn_banded_mma_bk; + + ggml_cuda_pool_alloc flags(ctx.pool()); + if (m) { + const int64_t n_z = m->ne[2]*m->ne[3]; + flags.alloc(n_z*n_qt*n_kt); + flash_attn_ext_banded_mma_tile_flags<<>>( + (const char *) m->data, flags.get(), n_q, n_kv, bq, m->ne[2], m->nb[1], m->nb[2], m->nb[3]); + } + + int occ = 0; +#define OCC_BANDED_MMA(DD, NW) CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, flash_attn_ext_banded_mma, NW*WARP_SIZE, 0)) + if (D == 64) { + if (nw == 4) { OCC_BANDED_MMA(64, 4); } else if (nw == 2) { OCC_BANDED_MMA(64, 2); } else { OCC_BANDED_MMA(64, 1); } + } else { + if (nw == 4) { OCC_BANDED_MMA(128, 4); } else if (nw == 2) { OCC_BANDED_MMA(128, 2); } else { OCC_BANDED_MMA(128, 1); } + } +#undef OCC_BANDED_MMA + const int64_t resident = int64_t(std::max(occ, 1))*ggml_cuda_info().devices[ctx.device].nsm; + const int64_t base_blocks = n_qt*q->ne[2]*q->ne[3]; + constexpr int64_t min_tiles_per_chunk = 4; + const int64_t max_chunks = std::max(1, std::min(n_kt/min_tiles_per_chunk, (4*resident + base_blocks - 1)/base_blocks)); + int64_t n_chunks = 1; + double best_eff = 0.0; + for (int64_t c = 1; c <= max_chunks; ++c) { + const int64_t blocks = base_blocks*c; + const double eff = double(blocks) / double(((blocks + resident - 1)/resident)*resident); + if (eff > best_eff + 1e-3) { + best_eff = eff; + n_chunks = c; + } + } + const int64_t tiles_per_chunk = (n_kt + n_chunks - 1)/n_chunks; + n_chunks = (n_kt + tiles_per_chunk - 1)/tiles_per_chunk; + + const int64_t n_rows = n_q*q->ne[2]*q->ne[3]; + ggml_cuda_pool_alloc part(ctx.pool()); + if (n_chunks > 1) { + part.alloc(n_rows*n_chunks*(D + 2)); + } + + const float * sinks_d = (const float *) sinks->data; + const int64_t sinks_s1 = sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0; + const int64_t sinks_s2 = sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0; + + const dim3 blocks(n_qt*n_chunks, q->ne[2], q->ne[3]); +#define LAUNCH_BANDED_MMA(DD, NW) \ + flash_attn_ext_banded_mma<<>>( \ + (const char *) q->data, k_data, v_data, m ? (const char *) m->data : nullptr, m ? flags.get() : nullptr, \ + (const char *) rel->data, n_chunks == 1 ? sinks_d : nullptr, (float *) dst->data, part.get(), \ + scale, rel->type, n_q, n_kv, q->ne[2], k->ne[2], n_chunks, tiles_per_chunk, rel_extent, \ + m ? m->ne[2] : 1, m ? m->ne[3] : 1, q->nb[1], q->nb[2], q->nb[3], \ + k_nb[1], k_nb[2], k_nb[3], v_nb[1], v_nb[2], v_nb[3], \ + m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2) +#define LAUNCH_BANDED_MMA_NW(DD) \ + switch (nw) { \ + case 4: LAUNCH_BANDED_MMA(DD, 4); break; \ + case 2: LAUNCH_BANDED_MMA(DD, 2); break; \ + default: LAUNCH_BANDED_MMA(DD, 1); break; \ + } + if (D == 64) { + LAUNCH_BANDED_MMA_NW(64); + } else { + LAUNCH_BANDED_MMA_NW(128); + } +#undef LAUNCH_BANDED_MMA_NW +#undef LAUNCH_BANDED_MMA + CUDA_CHECK(cudaGetLastError()); + + if (n_chunks > 1) { + constexpr int merge_warps = 4; + const dim3 mblocks((n_rows + merge_warps - 1)/merge_warps, 1, 1); + const dim3 mthreads(merge_warps*WARP_SIZE, 1, 1); + if (D == 64) { + flash_attn_ext_banded_f32_merge<64><<>>( + part.get(), (float *) dst->data, n_rows, q->ne[2], n_q, n_chunks, sinks_d, sinks_s1, sinks_s2); + } else { + flash_attn_ext_banded_f32_merge<128><<>>( + part.get(), (float *) dst->data, n_rows, q->ne[2], n_q, n_chunks, sinks_d, sinks_s1, sinks_s2); + } + } +} + void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { GGML_ASSERT(ggml_cuda_flash_attn_ext_banded_supported(ctx.device, dst)); @@ -213,6 +1049,7 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso const ggml_tensor * v = dst->src[2]; const ggml_tensor * m = dst->src[3]; const ggml_tensor * rel = dst->src[6]; + const ggml_tensor * sinks = dst->src[4]; // only the MMA kernel reads src[6]; delegating otherwise drops the bias if (ggml_cuda_flash_attn_ext_banded_use_mma(ctx.device, dst)) { @@ -225,6 +1062,55 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso // the tensor extent (not op_params) is authoritative after graph cloning const int64_t rel_extent = rel->ne[0]; + if (sinks && fattn_banded_mma_usable(ctx.device, dst)) { + fattn_banded_mma_launch(ctx, dst, scale, rel_extent); + return; + } + + { + constexpr int split_warps = 4; + constexpr int min_chunk = 64; + const int64_t n_rows = q->ne[1]*q->ne[2]*q->ne[3]; + const int64_t n_kv = k->ne[1]; + const int64_t target_blocks = int64_t(ggml_cuda_info().devices[ctx.device].nsm)*16; + int64_t n_chunks = n_rows < target_blocks ? (target_blocks + n_rows - 1)/n_rows : 1; + n_chunks = std::min(n_chunks, (n_kv + min_chunk - 1)/min_chunk); + if (n_chunks > 1 && q->ne[1]*q->ne[3] <= 65535) { + const int64_t chunk = (n_kv + n_chunks - 1)/n_chunks; + n_chunks = (n_kv + chunk - 1)/chunk; + const int64_t D = q->ne[0]; + ggml_cuda_pool_alloc part(ctx.pool(), n_rows*n_chunks*(D + 2)); + const dim3 sblocks(n_chunks, q->ne[2], q->ne[1]*q->ne[3]); + const dim3 sthreads(split_warps*WARP_SIZE, 1, 1); + constexpr int merge_warps = 4; + const dim3 mblocks((n_rows + merge_warps - 1)/merge_warps, 1, 1); + const dim3 mthreads(merge_warps*WARP_SIZE, 1, 1); + cudaStream_t stream = ctx.stream(); +#define LAUNCH_SPLIT(DD) \ + flash_attn_ext_banded_f32_split<<>>( \ + (const char *) q->data, (const char *) k->data, (const char *) v->data, \ + m ? (const char *) m->data : nullptr, (const char *) rel->data, part.get(), \ + scale, k->type, v->type, rel->type, q->ne[1], n_kv, q->ne[2], k->ne[2], n_chunks, chunk, \ + rel_extent, m ? m->ne[2] : 1, m ? m->ne[3] : 1, \ + q->nb[1], q->nb[2], q->nb[3], k->nb[0], k->nb[1], k->nb[2], k->nb[3], \ + v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ + m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]); \ + flash_attn_ext_banded_f32_merge
<<>>( \ + part.get(), (float *) dst->data, n_rows, q->ne[2], q->ne[1], n_chunks, \ + sinks ? (const float *) sinks->data : nullptr, \ + sinks && sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0, \ + sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0) + if (D == 64) { + LAUNCH_SPLIT(64); + } else { + LAUNCH_SPLIT(128); + } +#undef LAUNCH_SPLIT + return; + } + } + constexpr int warps_per_block = 4; const dim3 blocks((q->ne[1] + warps_per_block - 1) / warps_per_block, q->ne[2], q->ne[3]); const dim3 threads(warps_per_block * WARP_SIZE, 1, 1); @@ -239,6 +1125,9 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso q->nb[1], q->nb[2], q->nb[3], k->nb[0], k->nb[1], k->nb[2], k->nb[3], \ v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ + sinks ? (const float *) sinks->data : nullptr, \ + sinks && sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0, \ + sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0, \ rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]) if (q->ne[0] == 64) { diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 391be7083923..2ad26cbd452e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -599,6 +599,11 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + // the MMA kernel passes rel in the sinks slot + if (dst->src[4]) { + return false; + } + // the MMA ABI indexes rel linearly and by Q's batch if (rel->type != GGML_TYPE_F32 || !ggml_is_contiguous(rel) || rel->ne[3] != Q->ne[3] || rel->ne[0] > (1 << 20)) { diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index cbbd9a4b2c63..b3adbee06e61 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5564,10 +5564,12 @@ void ggml_flash_attn_ext_add_sinks( return; } - GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT || a->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_ASSERT(a->src[4] == NULL); GGML_ASSERT(a->src[0]->ne[2] == sinks->ne[0]); GGML_ASSERT(sinks->type == GGML_TYPE_F32); + GGML_ASSERT(ggml_nelements(sinks) == sinks->ne[0] || (a->op == GGML_OP_FLASH_ATTN_EXT_BANDED && + sinks->ne[1] == a->src[0]->ne[1] && (sinks->ne[2] == 1 || sinks->ne[2] == a->src[0]->ne[3]))); a->src[4] = sinks; } diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index f5a2beb88065..2b39c86406c1 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1475,6 +1475,11 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par 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; + if (banded) { + res &= attn_ctx->get_base()->get_n_kv_pos_contiguous() == n_kv_banded[0]; + res &= attn_ctx->get_swa()->get_n_kv_pos_contiguous() == n_kv_banded[1]; + } + 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; diff --git a/src/llama-graph.h b/src/llama-graph.h index e0c3881c01a9..b1cae6006025 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -812,6 +812,10 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { ggml_tensor * self_rel_pos_dev[2] = { nullptr, nullptr }; ggml_tensor * self_kq_mask_dev[2] = { nullptr, nullptr }; + // [base, swa] K/V cells of the banded attention, 0 = dense + uint32_t n_kv_banded[2] = { 0, 0 }; + bool banded = false; + const uint32_t extent; const uint32_t extent_swa; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index fbb09aa54c20..086f7847eeee 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -7,6 +7,8 @@ // max elements of the dense relative bias per attention call, and max chunks per layer static constexpr int64_t n_kq_bias_max = int64_t(1) << 29; static constexpr int64_t n_kq_chunk_max = 64; +// ubatches up to this many tokens keep the dense path +static constexpr int64_t n_tokens_banded_min = 32; void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); @@ -246,6 +248,46 @@ ggml_tensor * llama_model_inkling2::graph::convolve( llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { auto * inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); auto * attn = inp->get_attn(); + // banded FA needs a position-contiguous cache; small ubatches stay dense so the graph can be reused while decoding + inp->banded = cparams.flash_attn && n_tokens > n_tokens_banded_min; + for (int i = 0; i < 2 && inp->banded; ++i) { + inp->n_kv_banded[i] = (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); + } + std::vector, bool>> banded_dev_ok; // per (swa, device) + const auto use_banded = [&](int il, bool swa) { + const auto * cache = swa ? attn->mctx->get_swa() : attn->mctx->get_base(); + const int64_t hd = hparams.n_embd_head_k(il); + const auto type_ok = [](ggml_type t) { + return t == GGML_TYPE_F32 || t == GGML_TYPE_F16 || t == GGML_TYPE_BF16; + }; + if (!(inp->n_kv_banded[swa] > 0 && (hd == 64 || hd == 128) && hparams.n_embd_head_v(il) == hd && + type_ok(cache->type_k()) && type_ok(cache->type_v()) && !cache->get_k_scale(il) && !cache->get_v_scale(il) && + (swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3] == 1)) { + return false; + } + ggml_backend_dev_t dev = model.dev_layer(il); + if (!dev) { + return false; + } + for (const auto & [key, ok] : banded_dev_ok) { + if (key.first == swa && key.second == dev) { + return ok; + } + } + const int64_t nh = hparams.n_head(il); + const int64_t nkv = hparams.n_head_kv(il); + ggml_tensor * pq = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, hd, 1, nh, 1); + ggml_tensor * pk = ggml_new_tensor_4d(ctx0, cache->type_k(), hd, 1, nkv, 1); + ggml_tensor * pv = ggml_new_tensor_4d(ctx0, cache->type_v(), hd, 1, nkv, 1); + ggml_tensor * pm = ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, 1, 1, 1, 1); + ggml_tensor * pr = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, nh, 1, 1); + ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); + ggml_flash_attn_ext_add_sinks(op, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, nh, 1, 1)); + ggml_prec_set_acc(op, GGML_PREC_F32); + const bool ok = ggml_backend_dev_supports_op(dev, op); + banded_dev_ok.push_back({ { swa, dev }, ok }); + return ok; + }; auto * recr = inp->get_recr(); ggml_tensor * inp_pos = build_inp_pos(); @@ -329,75 +371,125 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ 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)); - - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); - - // the dense bias is n_kv x n_tokens x n_head: past the budget, attend in chunks of query rows - const int64_t n_seq_tokens = n_tokens/n_stream; - // sized for a full cache so the chunking does not change while it fills - const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); - int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), - (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); - if (n_rows_max < n_seq_tokens) { - // equal chunks of whole 64-row tiles - const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; - n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); - } - // rows [r0, r0 + nr) of every stream along dim d - auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { - int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; - ne[d] = nr; - return ggml_cont(ctx0, ggml_view_4d(ctx0, t, ne[0], ne[1], ne[2], ne[3], t->nb[1], t->nb[2], t->nb[3], r0*t->nb[d])); - }; - std::vector outs; - for (int64_t r0 = 0; r0 < n_seq_tokens; r0 += n_rows_max) { - const int64_t nr = std::min(n_rows_max, n_seq_tokens - r0); - const bool all = nr == n_seq_tokens; - ggml_tensor * q_c = Qcur; - ggml_tensor * kq_b = nullptr; - if (all) { - kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, nr, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + if (use_banded(il, is_swa)) { + const auto * cache = is_swa ? attn->mctx->get_swa() : attn->mctx->get_base(); + auto * k_rot = is_swa ? attn->self_k_rot_swa[il] : attn->self_k_rot[il]; + auto * v_rot = is_swa ? attn->self_v_rot_swa[il] : attn->self_v_rot[il]; + if (k_rot) { + Qcur = llama_mul_mat_hadamard(ctx0, Qcur, k_rot); + Kcur = llama_mul_mat_hadamard(ctx0, Kcur, k_rot); + } + if (v_rot) { + Vcur = llama_mul_mat_hadamard(ctx0, Vcur, v_rot); + } + ggml_build_forward_expand(gf, Qcur); + ggml_build_forward_expand(gf, Kcur); + ggml_build_forward_expand(gf, Vcur); + ggml_build_forward_expand(gf, cache->cpy_k(ctx0, Kcur, is_swa ? attn->get_k_idxs_swa() : attn->get_k_idxs(), il)); + ggml_build_forward_expand(gf, cache->cpy_v(ctx0, Vcur, is_swa ? attn->get_v_idxs_swa() : attn->get_v_idxs(), il)); + + const int64_t n_kv_b = inp->n_kv_banded[is_swa]; + ggml_tensor * k_all = cache->get_k(ctx0, il); + ggml_tensor * v_all = cache->get_v(ctx0, il); + GGML_ASSERT(n_kv_b <= k_all->ne[2]); + ggml_tensor * q_fa = ggml_permute(ctx0, ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_tokens, 1), 0, 2, 1, 3); + ggml_tensor * k_fa = ggml_permute(ctx0, ggml_view_4d(ctx0, k_all, k_all->ne[0], k_all->ne[1], n_kv_b, k_all->ne[3], + k_all->nb[1], k_all->nb[2], k_all->nb[3], 0), 0, 2, 1, 3); + ggml_tensor * v_fa; + if (v_all->nb[1] > v_all->nb[2]) { // transposed V + v_fa = ggml_view_4d(ctx0, v_all, n_kv_b, v_all->ne[1], v_all->ne[2], v_all->ne[3], + v_all->nb[1], v_all->nb[2], v_all->nb[3], 0); + v_fa = ggml_transpose(ctx0, ggml_permute(ctx0, v_fa, 0, 2, 1, 3)); } else { - q_c = ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_seq_tokens, n_stream), 2, r0, nr), - n_embd_head, n_head, nr*n_stream); - ggml_tensor * table_c = ggml_reshape_4d(ctx0, table, table->ne[0], table->ne[1], n_seq_tokens, n_stream); - table_c = ggml_view_4d(ctx0, table_c, table_c->ne[0], table_c->ne[1], nr, n_stream, - table_c->nb[1], table_c->nb[2], table_c->nb[3], r0*table_c->nb[2]); - ggml_tensor *& rel_pos_dev = inp->self_rel_pos_dev[is_swa]; - if (!rel_pos_dev) { - rel_pos_dev = ggml_cont(ctx0, rel_pos); - } - ggml_tensor * rel_pos_c = ggml_view_3d(ctx0, rel_pos_dev, n_kv, nr, n_stream, - rel_pos_dev->nb[1], n_seq_tokens*rel_pos_dev->nb[1], r0*rel_pos_dev->nb[1]); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, ggml_get_rows(ctx0, table_c, rel_pos_c), 2, 0, 1, 3)); + v_fa = ggml_permute(ctx0, ggml_view_4d(ctx0, v_all, v_all->ne[0], v_all->ne[1], n_kv_b, v_all->ne[3], + v_all->nb[1], v_all->nb[2], v_all->nb[3], 0), 0, 2, 1, 3); + } + ggml_tensor * mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; + ggml_tensor * m = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], + mask->nb[1], mask->nb[2], mask->nb[3], 0)); + // exp(s + b)/(exp(t) + sum(exp(s + b))): the dense mask b - t with a zero sink + ggml_tensor * rel_b = ggml_mul_mat(ctx0, layer.attn_rel_bias, Rcur); + rel_b = ggml_reshape_4d(ctx0, rel_b, rel_b->ne[0], n_head, n_tokens, 1); + cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, m, rel_b, 1.0f/sqrtf(n_embd_head), rel_b->ne[0]); + ggml_flash_attn_ext_add_sinks(cur, ggml_reshape_3d(ctx0, sinks, n_head, n_tokens, 1)); + ggml_prec_set_acc(cur, GGML_PREC_F32); + res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); + cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); + cb(cur, "kqv_out", il); + if (v_rot) { + cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); } - cb(kq_b, "kq_b", il); + } else { + // 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)); + + sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + + // the dense bias is n_kv x n_tokens x n_head: past the budget, attend in chunks of query rows + const int64_t n_seq_tokens = n_tokens/n_stream; + // sized for a full cache so the chunking does not change while it fills + const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); + int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), + (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); + if (n_rows_max < n_seq_tokens) { + // equal chunks of whole 64-row tiles + const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; + n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); + } + // rows [r0, r0 + nr) of every stream along dim d + auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { + int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; + ne[d] = nr; + return ggml_cont(ctx0, ggml_view_4d(ctx0, t, ne[0], ne[1], ne[2], ne[3], t->nb[1], t->nb[2], t->nb[3], r0*t->nb[d])); + }; + std::vector outs; + for (int64_t r0 = 0; r0 < n_seq_tokens; r0 += n_rows_max) { + const int64_t nr = std::min(n_rows_max, n_seq_tokens - r0); + const bool all = nr == n_seq_tokens; + ggml_tensor * q_c = Qcur; + ggml_tensor * kq_b = nullptr; + if (all) { + kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, nr, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + } else { + q_c = ggml_reshape_3d(ctx0, rows(ggml_reshape_4d(ctx0, Qcur, n_embd_head, n_head, n_seq_tokens, n_stream), 2, r0, nr), + n_embd_head, n_head, nr*n_stream); + ggml_tensor * table_c = ggml_reshape_4d(ctx0, table, table->ne[0], table->ne[1], n_seq_tokens, n_stream); + table_c = ggml_view_4d(ctx0, table_c, table_c->ne[0], table_c->ne[1], nr, n_stream, + table_c->nb[1], table_c->nb[2], table_c->nb[3], r0*table_c->nb[2]); + ggml_tensor *& rel_pos_dev = inp->self_rel_pos_dev[is_swa]; + if (!rel_pos_dev) { + rel_pos_dev = ggml_cont(ctx0, rel_pos); + } + ggml_tensor * rel_pos_c = ggml_view_3d(ctx0, rel_pos_dev, n_kv, nr, n_stream, + rel_pos_dev->nb[1], n_seq_tokens*rel_pos_dev->nb[1], r0*rel_pos_dev->nb[1]); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, ggml_get_rows(ctx0, table_c, rel_pos_c), 2, 0, 1, 3)); + } + cb(kq_b, "kq_b", il); - // only the first chunk stores K and V - ggml_tensor * out = build_attn(inp, - nullptr, nullptr, nullptr, - q_c, r0 == 0 ? Kcur : nullptr, r0 == 0 ? Vcur : nullptr, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il, r0); - outs.push_back(all ? out : ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream)); - } - while (outs.size() > 1) { - std::vector next; - for (size_t c = 0; c + 1 < outs.size(); c += 2) { - next.push_back(ggml_concat(ctx0, outs[c], outs[c + 1], 1)); + // only the first chunk stores K and V + ggml_tensor * out = build_attn(inp, + nullptr, nullptr, nullptr, + q_c, r0 == 0 ? Kcur : nullptr, r0 == 0 ? Vcur : nullptr, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il, r0); + outs.push_back(all ? out : ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream)); } - if (outs.size() % 2) { - next.push_back(outs.back()); + while (outs.size() > 1) { + std::vector next; + for (size_t c = 0; c + 1 < outs.size(); c += 2) { + next.push_back(ggml_concat(ctx0, outs[c], outs[c + 1], 1)); + } + if (outs.size() % 2) { + next.push_back(outs.back()); + } + outs = std::move(next); } - outs = std::move(next); + cur = n_rows_max >= n_seq_tokens ? outs[0] : ggml_reshape_2d(ctx0, outs[0], outs[0]->ne[0], n_tokens); } - cur = n_rows_max >= n_seq_tokens ? outs[0] : ggml_reshape_2d(ctx0, outs[0], outs[0]->ne[0], n_tokens); cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 0b94d717c3cf..aef6377e950e 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9257,6 +9257,31 @@ struct test_flash_attn_ext_banded : public test_case { } }; +struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { + const int sinks; + + std::string vars() override { + return test_flash_attn_ext_banded::vars() + ",sinks=" + std::to_string(sinks); + } + + test_flash_attn_ext_banded_sinks(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided), sinks(sinks) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, sinks == 2 ? n_q : 1); + ggml_set_name(s, "sinks"); + ggml_flash_attn_ext_add_sinks(out, s); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + test_flash_attn_ext_banded::initialize_tensors(ctx); + init_tensor_uniform(ggml_get_tensor(ctx, "sinks"), -4.0f, 4.0f); + } +}; + // large Q values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { static constexpr int q_range = 20; @@ -13349,6 +13374,32 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 1, 64, 64, 512, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 17, 33, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, true)); + for (int sinks : {1, 2}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 1, 64, 8, 1, GGML_TYPE_F32, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 33, 64, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 64, 256, 32, 2, GGML_TYPE_F32, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 1, 4096, 1024, 2, GGML_TYPE_F32, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 4, 2048, 1024, 2, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 1, 1000, 8, 1, GGML_TYPE_F32, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 16, 16, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 4, 1, 77, 1000, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 4, 2, 64, 300, 16, 0, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 100, 100, 64, 1, GGML_TYPE_BF16, GGML_TYPE_BF16, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 65, 333, 32, 2, GGML_TYPE_F16, GGML_TYPE_F32, sinks, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 6, 1, 17, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 512, 4096, 1024, 2, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 512, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 2048, 2048, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 511, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 512, 32768, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + // Inkling-2-Small shapes with per-query sinks + for (int64_t n_q : { 1, 3, 8, 512 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, n_q, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 2048, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 512, 3000, 1024, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From c9c6322d81ee13f39e794d8e027568cdd9cbd1ad Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 20 Nov 2026 05:13:31 -0800 Subject: [PATCH 014/115] Trim comments --- ggml/src/ggml-cuda/fattn-banded.cu | 6 +++--- src/models/inkling2.cpp | 12 +++++------- tests/test-backend-ops.cpp | 2 +- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 4995319167ca..dd655609d5e3 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -585,7 +585,7 @@ static __global__ void flash_attn_ext_banded_mma( static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); constexpr int BK = fattn_banded_mma_bk; constexpr int BQ = NW*16; - constexpr int stride = D + 8; // padded smem row (halfs): conflict-free ldmatrix + constexpr int stride = D + 8; // padding keeps ldmatrix bank-conflict free constexpr int ND = D/8; constexpr int NK = D/16; @@ -755,7 +755,7 @@ static __global__ void flash_attn_ext_banded_mma( O[n][3] *= alpha[1]; } - __syncthreads(); // every warp is done with K_s + __syncthreads(); const int64_t kt_next = next_tile(kt + 1); if (kt_next < kt_end) { fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt_next*BK, n_kv); @@ -777,7 +777,7 @@ static __global__ void flash_attn_ext_banded_mma( } } - __syncthreads(); // every warp is done with V_s + __syncthreads(); if (kt_next < kt_end) { fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt_next*BK, n_kv); } diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 086f7847eeee..1cfdaeb8e592 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -248,12 +248,12 @@ ggml_tensor * llama_model_inkling2::graph::convolve( llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { auto * inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); auto * attn = inp->get_attn(); - // banded FA needs a position-contiguous cache; small ubatches stay dense so the graph can be reused while decoding + // banded FA needs a position-contiguous cache; small ubatches stay dense for graph reuse inp->banded = cparams.flash_attn && n_tokens > n_tokens_banded_min; for (int i = 0; i < 2 && inp->banded; ++i) { inp->n_kv_banded[i] = (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); } - std::vector, bool>> banded_dev_ok; // per (swa, device) + std::vector, bool>> banded_dev_ok; const auto use_banded = [&](int il, bool swa) { const auto * cache = swa ? attn->mctx->get_swa() : attn->mctx->get_base(); const int64_t hd = hparams.n_embd_head_k(il); @@ -420,27 +420,25 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); } } else { - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + // project before gathering: 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 + // per-query sink t: 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, n_head, n_tokens)); table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); - // the dense bias is n_kv x n_tokens x n_head: past the budget, attend in chunks of query rows + // dense bias is n_kv x n_tokens x n_head: chunk query rows past the budget const int64_t n_seq_tokens = n_tokens/n_stream; // sized for a full cache so the chunking does not change while it fills const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); if (n_rows_max < n_seq_tokens) { - // equal chunks of whole 64-row tiles const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); } - // rows [r0, r0 + nr) of every stream along dim d auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; ne[d] = nr; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index aef6377e950e..9fd1ef59efcc 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13393,7 +13393,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 511, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 512, 32768, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); - // Inkling-2-Small shapes with per-query sinks + // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, n_q, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); } From 8825dc242d5fc111316fa83faf1c674aa1cc1857 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 20 Nov 2026 05:13:31 -0800 Subject: [PATCH 015/115] Trim comments --- src/llama-graph.h | 2 +- src/models/inkling2.cpp | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/llama-graph.h b/src/llama-graph.h index fcde13d3e55f..bdf109bf09fe 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -808,7 +808,7 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] - // [base, swa] device copies, made once per graph when attention is chunked over query rows + // [base, swa] device copies, made once per graph ggml_tensor * self_rel_pos_dev[2] = { nullptr, nullptr }; ggml_tensor * self_kq_mask_dev[2] = { nullptr, nullptr }; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index fbb09aa54c20..38100989c712 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -338,18 +338,16 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); - // the dense bias is n_kv x n_tokens x n_head: past the budget, attend in chunks of query rows + // dense bias is n_kv x n_tokens x n_head: chunk query rows past the budget const int64_t n_seq_tokens = n_tokens/n_stream; // sized for a full cache so the chunking does not change while it fills const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); if (n_rows_max < n_seq_tokens) { - // equal chunks of whole 64-row tiles const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); } - // rows [r0, r0 + nr) of every stream along dim d auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; ne[d] = nr; From c729a87dd9a0b02ce6facad87d3926aa8dd45608 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 07:45:43 -0800 Subject: [PATCH 016/115] inkling2 : share normalized block stacks and repeated subexpressions in the graph The attention residual mix rebuilt a concat chain of every earlier block, RMS-normalized all of them and copied the transposed states on every call. Normalize each block once per graph, keep its stacks (rows and transposed), and reuse the stacked rows of a mix over the same blocks and input (the loop messages of one pass share them across the core layers). The values and their order are unchanged. Also, without changing any arithmetic: - one-token graphs use the mix query directly instead of a repeat - the clip threshold tensor is filled once per device and shape - a SWA layer takes its single mixed input without a copy and normalizes it once for the loop controllers; the messages are normalized once per layer and read through views - the dynamic convolution taps read one channel-major copy of the inputs instead of one transposed copy per lag --- src/models/inkling2.cpp | 115 ++++++++++++++++++++++++++++++---------- src/models/models.h | 21 ++++++-- 2 files changed, 105 insertions(+), 31 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 0020bf56aa13..8a624930fb7c 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -170,7 +170,7 @@ std::unique_ptr llama_model_inkling2::build_arch_graph(const } // 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) { +ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold, int il) { if (scale) { cur = ggml_mul(ctx0, cur, scale); } @@ -178,25 +178,67 @@ ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + // the threshold tensor only depends on the shape: fill it once per graph and layer device + ggml_tensor *& limit = clip_limits[{ { model.dev_layer(il), norm->ne[1] }, threshold }]; + if (!limit) { + limit = ggml_fill(ctx0, ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, norm->ne[0], norm->ne[1], norm->ne[2], norm->ne[3]), threshold); + } + + ggml_tensor * factor = ggml_div(ctx0, limit, 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) { - 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); +// the normalized blocks, newest first, [n_embd, n, n_tokens] and transposed [n, n_embd, n_tokens] +// a block is normalized once per graph, and each block list is stacked once and shared by every mix over it +const llama_model_inkling2::graph::block_stack * llama_model_inkling2::graph::stack(const std::vector & blocks, int il) { + if (blocks.empty()) { + return nullptr; + } + // one stack per device, so that a split does not pull another device's stack + const auto key = std::make_pair(il < 0 ? nullptr : model.dev_layer(il), blocks); + auto it = block_stacks.find(key); + if (it != block_stacks.end()) { + return &it->second; + } + const std::vector prefix(blocks.begin(), blocks.end() - 1); + const block_stack * prev = stack(prefix, il); + + ggml_tensor * normed = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, blocks.back(), n_embd, 1, n_tokens), 1e-6f); + ggml_tensor * normed_t = ggml_reshape_3d(ctx0, normed, 1, n_embd, n_tokens); + + block_stack st; + st.states = prev ? ggml_concat(ctx0, normed, prev->states, 1) : normed; + st.states_t = prev ? ggml_concat(ctx0, normed_t, prev->states_t, 0) : normed_t; + return &block_stacks.emplace(key, st).first->second; +} + +ggml_tensor * llama_model_inkling2::graph::mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query, int il) { + // rows [blocks.back(), ..., blocks.front(), cur], each RMS-normalized; shared by every mix over the same blocks and cur + const ggml_backend_dev_t dev = il < 0 ? nullptr : model.dev_layer(il); + auto key = std::make_pair(dev, blocks); + key.second.push_back(cur); + block_stack & all = mix_states[key]; + if (!all.states) { + ggml_tensor * normed = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens), 1e-6f); + ggml_tensor * normed_t = ggml_reshape_3d(ctx0, normed, 1, n_embd, n_tokens); + + const block_stack * st = stack(blocks, il); + all.states = st ? ggml_concat(ctx0, st->states, normed, 1) : normed; + all.states_t = st ? ggml_concat(ctx0, st->states_t, normed_t, 0) : normed_t; } - states = ggml_rms_norm(ctx0, states, 1e-6f); + ggml_tensor * states = all.states; + ggml_tensor * states_t = all.states_t; - ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); + // one token: the query broadcasts as is + ggml_tensor * queries = n_tokens == 1 ? query : + 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); + return ggml_mul_mat(ctx0, states_t, scores); } // causal short convolution with a residual; dynamic adds input-dependent taps per head @@ -229,12 +271,14 @@ ggml_tensor * llama_model_inkling2::graph::convolve( 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]); + // the inputs channel-major once, [n_channels, n_conv - 1 + n_seq_tokens, n_seqs]: each lag is a row offset + ggml_tensor * xt = ggml_cont(ctx0, ggml_transpose(ctx0, x)); - window = ggml_cont(ctx0, ggml_transpose(ctx0, window)); - window = ggml_reshape_3d(ctx0, window, n_channels/n_heads, n_heads, n_tokens); + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_4d(ctx0, dynamic, 1, n_heads, n_seq_tokens, n_seqs, + dynamic->nb[1], dynamic->nb[2], n_seq_tokens*dynamic->nb[2], lag*dynamic->nb[0]); + ggml_tensor * window = ggml_view_4d(ctx0, xt, n_channels/n_heads, n_heads, n_seq_tokens, n_seqs, + (n_channels/n_heads)*xt->nb[0], xt->nb[1], xt->nb[2], (n_conv - 1 - lag)*xt->nb[1]); ggml_tensor * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), n_channels, n_tokens); @@ -246,8 +290,10 @@ ggml_tensor * llama_model_inkling2::graph::convolve( } // mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message -ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl) { - ggml_tensor * gate = ggml_concat(ctx0, ggml_rms_norm(ctx0, cur, 1e-6f), ggml_rms_norm(ctx0, message, 1e-6f), 0); +// cur_norm and message_norm are cur and message RMS-normalized +ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * cur_norm, ggml_tensor * message, ggml_tensor * message_norm, + const loop_layer & loop, int ctrl) { + ggml_tensor * gate = ggml_concat(ctx0, cur_norm, message_norm, 0); gate = build_lora_mm(loop.ctrl_down[ctrl], gate); ggml_tensor * gain = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_gain[ctrl], gate)); @@ -332,9 +378,10 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens 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; - // the message of controller ctrl, [n_embd, n_tokens] - auto message = [&](int ctrl) { - return ggml_cont(ctx0, ggml_view_2d(ctx0, messages, n_embd, n_tokens, messages->nb[2], ctrl*messages->nb[1])); + // the message of controller ctrl, [n_embd, n_tokens], and the messages RMS-normalized once + ggml_tensor * messages_norm = messages ? ggml_rms_norm(ctx0, messages, 1e-6f) : nullptr; + auto message = [&](ggml_tensor * t, int ctrl) { + return ggml_view_2d(ctx0, t, n_embd, n_tokens, t->nb[2], ctrl*t->nb[1]); }; ggml_tensor * state = recr->mctx->get_r_l(il); @@ -346,16 +393,27 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V ggml_tensor * inputs[3] = {cur, cur, cur}; 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], (is_swa ? 0 : j)*mixed->nb[1])); + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query, il); + if (is_swa) { + // one query, already contiguous + inputs[0] = inputs[1] = inputs[2] = ggml_reshape_2d(ctx0, mixed, n_embd, n_tokens); + } else { + for (int j = 0; j < 3; ++j) { + inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], j*mixed->nb[1])); + } } } if (messages) { // the messages make the Q, K and V inputs of a SWA layer differ + ggml_tensor * inputs_norm[3] = {}; + for (int j = 0; j < 3; ++j) { + // a SWA layer normalizes its one input once + inputs_norm[j] = j > 0 && inputs[j] == inputs[0] ? inputs_norm[0] : ggml_rms_norm(ctx0, inputs[j], 1e-6f); + } for (int j = 0; j < 3; ++j) { - inputs[j] = control(inputs[j], message(LOOP_CTRL_Q + j), *loop, LOOP_CTRL_Q + j); + inputs[j] = control(inputs[j], inputs_norm[j], message(messages, LOOP_CTRL_Q + j), message(messages_norm, LOOP_CTRL_Q + j), + *loop, LOOP_CTRL_Q + j); } } @@ -381,10 +439,10 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens 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); + Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip, il); + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip, il); 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); + Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip, il); if (!is_swa) { Qcur = ggml_mul(ctx0, Qcur, tau); @@ -537,9 +595,10 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(ffn_inp, "ffn_inp", il); // MoE - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query, il), n_embd, n_tokens); if (messages) { - cur = control(cur, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN); + cur = control(cur, ggml_rms_norm(ctx0, cur, 1e-6f), message(messages, LOOP_CTRL_FFN), message(messages_norm, LOOP_CTRL_FFN), + *loop, LOOP_CTRL_FFN); } cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); diff --git a/src/models/models.h b/src/models/models.h index ae7aec7783c4..2e49c34a4f43 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2507,8 +2507,9 @@ struct llama_model_inkling2 : public llama_model_base { 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); + // il: the layer whose device runs the mix (the shared stacks are kept per device), -1 if unknown + ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query, int il = -1); + ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold, int il); ggml_tensor * convolve( ggml_tensor * cur, ggml_tensor * weight, @@ -2517,7 +2518,8 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset); - ggml_tensor * control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl); + ggml_tensor * control(ggml_tensor * cur, ggml_tensor * cur_norm, ggml_tensor * message, ggml_tensor * message_norm, + const loop_layer & loop, int ctrl); protected: // the helpers alone, a derived graph builds its own body @@ -2540,6 +2542,19 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * inp_out_ids = nullptr; ggml_tensor * tau = nullptr; // log-scaled positions + + // the normalized block stacks of mix(), per block list + struct block_stack { + ggml_tensor * states = nullptr; + ggml_tensor * states_t = nullptr; + }; + std::map>, block_stack> block_stacks; + // the rows of each mix, the stack of its blocks and its current input last + std::map>, block_stack> mix_states; + const block_stack * stack(const std::vector & blocks, int il); + + // the clip thresholds, per layer device, row count and threshold + std::map, float>, ggml_tensor *> clip_limits; }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; From 96225013c71e33e6410532db59a330f832d5940a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 08:15:42 -0800 Subject: [PATCH 017/115] inkling2 : fill the zero sinks of the dense attention once per graph and device --- src/models/inkling2.cpp | 7 ++++++- src/models/models.h | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 8a624930fb7c..afcefe7771f6 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -517,7 +517,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens 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)); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + // zero sinks, filled once per graph and layer device + ggml_tensor *& zero = clip_limits[{ { model.dev_layer(il), -n_head }, 0.0f }]; + if (!zero) { + zero = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + } + sinks = zero; // dense bias is n_kv x n_tokens x n_head: chunk query rows past the budget const int64_t n_seq_tokens = n_tokens/n_stream; diff --git a/src/models/models.h b/src/models/models.h index 2e49c34a4f43..f35ebaa35045 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2553,7 +2553,7 @@ struct llama_model_inkling2 : public llama_model_base { std::map>, block_stack> mix_states; const block_stack * stack(const std::vector & blocks, int il); - // the clip thresholds, per layer device, row count and threshold + // the clip thresholds, per layer device, row count and threshold (and the zero sinks, keyed by -n_head) std::map, float>, ggml_tensor *> clip_limits; }; From 7db4a7064afffe7fbed81227473182559d227222 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 07:26:57 -0800 Subject: [PATCH 018/115] CUDA: quantized K/V for the banded relative-bias attention q8_0 / q4_0 K/V were not accepted by the banded kernel, so Inkling 2 fell back to the dense relative bias (n_kv x n_tokens x n_head F32) for every quantized cache and reserved far more compute memory than the cache saves. The MMA kernel now dequantizes q8_0 / q4_0 tiles into shared memory; other quantized types and the scalar kernels use an F16 copy of K/V. GGML_CUDA_BANDED_NO_QUANT_TILES=1 forces the F16 copy. The banded op no longer reserves the F16 K/V extra of the regular FA kernels unless it delegates to them, which also drops a cache-sized compute buffer for BF16 K/V. --- ggml/src/ggml-cuda/fattn-banded.cu | 189 +++++++++++++++++++++++++---- ggml/src/ggml-cuda/fattn.cu | 5 + src/models/inkling2.cpp | 3 +- tests/test-backend-ops.cpp | 9 ++ 4 files changed, 180 insertions(+), 26 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index dd655609d5e3..47e0cb6b5bf6 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -465,9 +465,63 @@ static __device__ __forceinline__ uint32_t fattn_banded_pack_h2(const float lo, return *(const uint32_t *) &h; } -template +// q8_0 / q4_0 K/V rows are dequantized to F16 per tile, so the cache is never copied to F16 as a whole +template +static __device__ __forceinline__ void fattn_banded_mma_load_tile_q( + half * __restrict__ tile, const char * __restrict__ src, const uint64_t nb1, const int64_t kv0, const int64_t n_kv) { + static_assert(type_kv == GGML_TYPE_Q8_0 || type_kv == GGML_TYPE_Q4_0, "unsupported banded K/V tile type"); + constexpr int stride = D + 8; + constexpr int chunks = D/8; + constexpr int nthreads = NW*WARP_SIZE; +#pragma unroll + for (int c0 = 0; c0 < fattn_banded_mma_bk*chunks; c0 += nthreads) { + const int c = c0 + threadIdx.x; + const int row = c / chunks; + const int col = (c % chunks)*8; + half2 h[4]; + if (kv0 + row < n_kv) { + const char * s = src + uint64_t(kv0 + row)*nb1; + if constexpr (type_kv == GGML_TYPE_Q8_0) { + const block_q8_0 * b = (const block_q8_0 *) s + col/QK8_0; + const float d = __half2float(b->d); + const int o = col % QK8_0; +#pragma unroll + for (int i = 0; i < 4; ++i) { + h[i] = __floats2half2_rn(float(b->qs[o + 2*i + 0])*d, float(b->qs[o + 2*i + 1])*d); + } + } else { + const block_q4_0 * b = (const block_q4_0 *) s + col/QK4_0; + const float d = __half2float(b->d); + const int o = col % QK4_0; + const int shift = o < QK4_0/2 ? 0 : 4; + const int j0 = o % (QK4_0/2); +#pragma unroll + for (int i = 0; i < 4; ++i) { + const int q0 = ((b->qs[j0 + 2*i + 0] >> shift) & 0x0F) - 8; + const int q1 = ((b->qs[j0 + 2*i + 1] >> shift) & 0x0F) - 8; + h[i] = __floats2half2_rn(float(q0)*d, float(q1)*d); + } + } + } else { +#pragma unroll + for (int i = 0; i < 4; ++i) { + h[i] = make_half2(0.0f, 0.0f); + } + } + *(int4 *) (tile + row*stride + col) = *(const int4 *) h; + } +#ifdef CP_ASYNC_AVAILABLE + asm volatile("cp.async.commit_group;"); // keeps the wait_group counts of the F16 pipeline +#endif // CP_ASYNC_AVAILABLE +} + +template static __device__ __forceinline__ void fattn_banded_mma_load_tile( half * __restrict__ tile, const char * __restrict__ src, const uint64_t nb1, const int64_t kv0, const int64_t n_kv) { + if constexpr (type_kv != GGML_TYPE_F16) { + fattn_banded_mma_load_tile_q(tile, src, nb1, kv0, n_kv); + return; + } constexpr int stride = D + 8; constexpr int chunks = D/8; constexpr int nthreads = NW*WARP_SIZE; @@ -539,7 +593,7 @@ static __global__ void flash_attn_ext_banded_mma_tile_flags( } } -template +template __launch_bounds__(NW*WARP_SIZE, 1) static __global__ void flash_attn_ext_banded_mma( const char * __restrict__ q, @@ -658,8 +712,8 @@ static __global__ void flash_attn_ext_banded_mma( int64_t kt = next_tile(kt_begin); if (kt < kt_end) { - fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt*BK, n_kv); - fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt*BK, n_kv); + fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt*BK, n_kv); + fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt*BK, n_kv); } while (kt < kt_end) { @@ -758,7 +812,7 @@ static __global__ void flash_attn_ext_banded_mma( __syncthreads(); const int64_t kt_next = next_tile(kt + 1); if (kt_next < kt_end) { - fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt_next*BK, n_kv); + fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt_next*BK, n_kv); fattn_banded_mma_wait<1>(); // V tile of this iteration landed } else { fattn_banded_mma_wait<0>(); @@ -779,7 +833,7 @@ static __global__ void flash_attn_ext_banded_mma( __syncthreads(); if (kt_next < kt_end) { - fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt_next*BK, n_kv); + fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt_next*BK, n_kv); } kt = kt_next; } @@ -838,6 +892,19 @@ static bool fattn_banded_type_supported(ggml_type type) { return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; } +// quantized K/V: the MMA kernel dequantizes q8_0 / q4_0 tiles itself, other types are converted to F16 first +static bool fattn_banded_kv_f16_convertible(ggml_type type) { + return ggml_is_quantized(type) && ggml_get_to_fp16_nc_cuda(type) != nullptr; +} + +static bool fattn_banded_mma_tile_type(ggml_type type) { + static const bool disabled = [] { + const char * env = getenv("GGML_CUDA_BANDED_NO_QUANT_TILES"); + return env != nullptr && atoi(env) != 0; + }(); + return !disabled && (type == GGML_TYPE_Q8_0 || type == GGML_TYPE_Q4_0); +} + bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * dst) { GGML_UNUSED(device); #if defined(GGML_USE_MUSA) @@ -848,6 +915,26 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d return false; } + // quantized K/V are read as F16: check the op with F16 K/V of the same shape + if (dst->src[1] && dst->src[2] && + (fattn_banded_kv_f16_convertible(dst->src[1]->type) || fattn_banded_kv_f16_convertible(dst->src[2]->type))) { + ggml_tensor op = *dst; + ggml_tensor k16 = *dst->src[1]; + ggml_tensor v16 = *dst->src[2]; + for (ggml_tensor * t : {&k16, &v16}) { + if (fattn_banded_kv_f16_convertible(t->type)) { + if (t->nb[0] != ggml_type_size(t->type) || t->ne[0] % ggml_blck_size(t->type) != 0) { + return false; + } + t->type = GGML_TYPE_F16; + t->nb[0] = sizeof(half); + } + } + op.src[1] = &k16; + op.src[2] = &v16; + return ggml_cuda_flash_attn_ext_banded_supported(device, &op); + } + const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; @@ -911,13 +998,43 @@ static bool fattn_banded_mma_usable(const int device, const ggml_tensor * dst) { return false; } for (const ggml_tensor * t : {k, v}) { - if (t->type == GGML_TYPE_F16 ? !fattn_banded_mma_aligned(t) : t->type != GGML_TYPE_BF16) { + if (t->type == GGML_TYPE_F16 ? !fattn_banded_mma_aligned(t) : (t->type != GGML_TYPE_BF16 && !ggml_is_quantized(t->type))) { return false; } } return true; } +// K/V the kernels cannot read directly are converted to a contiguous F16 copy in the pool +static void fattn_banded_kv_to_f16(ggml_backend_cuda_context & ctx, const ggml_tensor * t, ggml_cuda_pool_alloc & buf, + const char *& data, ggml_type & type, uint64_t (&nb)[4]) { + const size_t ts = ggml_type_size(t->type); // strides in blocks + buf.alloc(ggml_nelements(t)); + ggml_get_to_fp16_nc_cuda(t->type)(t->data, buf.get(), t->ne[0], t->ne[1], t->ne[2], t->ne[3], + t->nb[1]/ts, t->nb[2]/ts, t->nb[3]/ts, ctx.stream()); + data = (const char *) buf.get(); + type = GGML_TYPE_F16; + nb[0] = sizeof(half); + nb[1] = t->ne[0]*nb[0]; + nb[2] = t->ne[1]*nb[1]; + nb[3] = t->ne[2]*nb[2]; +} + +static const ggml_tensor * fattn_banded_kv_to_f16_tensor(ggml_backend_cuda_context & ctx, const ggml_tensor * t, + ggml_cuda_pool_alloc & buf, ggml_tensor & t_f16) { + const char * data = nullptr; + ggml_type type = t->type; + uint64_t nb[4]; + fattn_banded_kv_to_f16(ctx, t, buf, data, type, nb); + t_f16 = *t; + t_f16.data = (void *) data; + t_f16.type = type; + for (int i = 0; i < 4; ++i) { + t_f16.nb[i] = nb[i]; + } + return &t_f16; +} + static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const float scale, const int64_t rel_extent) { const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; @@ -937,22 +1054,18 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor uint64_t v_nb[4] = {v->nb[0], v->nb[1], v->nb[2], v->nb[3]}; ggml_cuda_pool_alloc k_f16(ctx.pool()); ggml_cuda_pool_alloc v_f16(ctx.pool()); - auto to_f16 = [&](const ggml_tensor * t, ggml_cuda_pool_alloc & buf, const char *& data, uint64_t (&nb)[4]) { - if (t->type == GGML_TYPE_F16) { - return; + // matching q8_0 / q4_0 K and V are dequantized per tile in the kernel + ggml_type type_kv = k->type == v->type && fattn_banded_mma_tile_type(k->type) ? k->type : GGML_TYPE_F16; + if (type_kv == GGML_TYPE_F16) { + ggml_type type_k = k->type; + ggml_type type_v = v->type; + if (type_k != GGML_TYPE_F16) { + fattn_banded_kv_to_f16(ctx, k, k_f16, k_data, type_k, k_nb); } - const size_t ts = ggml_type_size(t->type); - buf.alloc(ggml_nelements(t)); - ggml_get_to_fp16_nc_cuda(t->type)(t->data, buf.get(), t->ne[0], t->ne[1], t->ne[2], t->ne[3], - t->nb[1]/ts, t->nb[2]/ts, t->nb[3]/ts, stream); - data = (const char *) buf.get(); - nb[0] = sizeof(half); - nb[1] = t->ne[0]*nb[0]; - nb[2] = t->ne[1]*nb[1]; - nb[3] = t->ne[2]*nb[2]; - }; - to_f16(k, k_f16, k_data, k_nb); - to_f16(v, v_f16, v_data, v_nb); + if (type_v != GGML_TYPE_F16) { + fattn_banded_kv_to_f16(ctx, v, v_f16, v_data, type_v, v_nb); + } + } const int nw = n_q >= 64 ? 4 : (n_q >= 32 ? 2 : 1); const int bq = nw*16; @@ -968,13 +1081,20 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor } int occ = 0; -#define OCC_BANDED_MMA(DD, NW) CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, flash_attn_ext_banded_mma, NW*WARP_SIZE, 0)) +#define OCC_BANDED_MMA_T(DD, NW, T) CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&occ, flash_attn_ext_banded_mma, NW*WARP_SIZE, 0)) +#define OCC_BANDED_MMA(DD, NW) \ + switch (type_kv) { \ + case GGML_TYPE_Q8_0: OCC_BANDED_MMA_T(DD, NW, GGML_TYPE_Q8_0); break; \ + case GGML_TYPE_Q4_0: OCC_BANDED_MMA_T(DD, NW, GGML_TYPE_Q4_0); break; \ + default: OCC_BANDED_MMA_T(DD, NW, GGML_TYPE_F16); break; \ + } if (D == 64) { if (nw == 4) { OCC_BANDED_MMA(64, 4); } else if (nw == 2) { OCC_BANDED_MMA(64, 2); } else { OCC_BANDED_MMA(64, 1); } } else { if (nw == 4) { OCC_BANDED_MMA(128, 4); } else if (nw == 2) { OCC_BANDED_MMA(128, 2); } else { OCC_BANDED_MMA(128, 1); } } #undef OCC_BANDED_MMA +#undef OCC_BANDED_MMA_T const int64_t resident = int64_t(std::max(occ, 1))*ggml_cuda_info().devices[ctx.device].nsm; const int64_t base_blocks = n_qt*q->ne[2]*q->ne[3]; constexpr int64_t min_tiles_per_chunk = 4; @@ -1003,8 +1123,8 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor const int64_t sinks_s2 = sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0; const dim3 blocks(n_qt*n_chunks, q->ne[2], q->ne[3]); -#define LAUNCH_BANDED_MMA(DD, NW) \ - flash_attn_ext_banded_mma<<>>( \ +#define LAUNCH_BANDED_MMA_T(DD, NW, T) \ + flash_attn_ext_banded_mma<<>>( \ (const char *) q->data, k_data, v_data, m ? (const char *) m->data : nullptr, m ? flags.get() : nullptr, \ (const char *) rel->data, n_chunks == 1 ? sinks_d : nullptr, (float *) dst->data, part.get(), \ scale, rel->type, n_q, n_kv, q->ne[2], k->ne[2], n_chunks, tiles_per_chunk, rel_extent, \ @@ -1012,6 +1132,12 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor k_nb[1], k_nb[2], k_nb[3], v_nb[1], v_nb[2], v_nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2) +#define LAUNCH_BANDED_MMA(DD, NW) \ + switch (type_kv) { \ + case GGML_TYPE_Q8_0: LAUNCH_BANDED_MMA_T(DD, NW, GGML_TYPE_Q8_0); break; \ + case GGML_TYPE_Q4_0: LAUNCH_BANDED_MMA_T(DD, NW, GGML_TYPE_Q4_0); break; \ + default: LAUNCH_BANDED_MMA_T(DD, NW, GGML_TYPE_F16); break; \ + } #define LAUNCH_BANDED_MMA_NW(DD) \ switch (nw) { \ case 4: LAUNCH_BANDED_MMA(DD, 4); break; \ @@ -1025,6 +1151,7 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor } #undef LAUNCH_BANDED_MMA_NW #undef LAUNCH_BANDED_MMA +#undef LAUNCH_BANDED_MMA_T CUDA_CHECK(cudaGetLastError()); if (n_chunks > 1) { @@ -1067,6 +1194,18 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso return; } + // the scalar kernels read F32 / F16 / BF16 elements: other K/V types go through an F16 copy + ggml_cuda_pool_alloc k_f16(ctx.pool()); + ggml_cuda_pool_alloc v_f16(ctx.pool()); + ggml_tensor k_f16_t; + ggml_tensor v_f16_t; + if (!fattn_banded_type_supported(k->type)) { + k = fattn_banded_kv_to_f16_tensor(ctx, k, k_f16, k_f16_t); + } + if (!fattn_banded_type_supported(v->type)) { + v = fattn_banded_kv_to_f16_tensor(ctx, v, v_f16, v_f16_t); + } + { constexpr int split_warps = 4; constexpr int min_chunk = 64; diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index b14532b4c1d9..a328a82fe4fc 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -832,6 +832,11 @@ size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * d GGML_ASSERT(K != nullptr); GGML_ASSERT(V != nullptr); + // the banded kernels read or convert K/V themselves; only the delegated FA kernel uses the F16 extra + if (dst->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_cuda_flash_attn_ext_banded_use_mma(device, dst)) { + return ggml_nbytes(dst); + } + const best_fattn_kernel kernel = ggml_cuda_get_best_fattn_kernel(device, dst); bool need_f16_K = false; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 0020bf56aa13..b37f98021bd3 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -259,8 +259,9 @@ ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tenso bool llama_model_inkling2::graph::use_banded(int il, bool swa) { const auto * cache = swa ? attn->mctx->get_swa() : attn->mctx->get_base(); const int64_t hd = hparams.n_embd_head_k(il); + // quantized K/V too: the dense fallback materializes an n_kv x n_tokens x n_head bias, far more than the cache saves const auto type_ok = [](ggml_type t) { - return t == GGML_TYPE_F32 || t == GGML_TYPE_F16 || t == GGML_TYPE_BF16; + return t == GGML_TYPE_F32 || t == GGML_TYPE_F16 || t == GGML_TYPE_BF16 || ggml_is_quantized(t); }; if (!(inp->n_kv_banded[swa] > 0 && (hd == 64 || hd == 128) && hparams.n_embd_head_v(il) == hd && type_ok(cache->type_k()) && type_ok(cache->type_v()) && !cache->get_k_scale(il) && !cache->get_v_scale(il) && diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 44debf2f563e..1ae0741da52c 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13517,6 +13517,15 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 2048, 2048, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 511, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); } + // quantized K/V cache: q8_0 / q4_0 tiles, other types via an F16 copy, scalar kernels for small n_q + for (ggml_type kv_type : { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, GGML_TYPE_Q5_1 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 64, 300, 16, 2, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 4, 1, 77, 1000, 8, 1, kv_type, GGML_TYPE_F32, 1)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 65, 333, 32, 2, kv_type, GGML_TYPE_F32, 2, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 1, 4096, 1024, 2, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 512, 3000, 1024, 1, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, kv_type, GGML_TYPE_F32)); + } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 512, 32768, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { From 02b68e647eb538892b565c39011a350871d7f737 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 09:28:42 -0800 Subject: [PATCH 019/115] inkling : banded attention for a quantized K cache A quantized K cache (-ctk q8_0 / q4_0) never took the banded attention, so every ubatch built the dense relative bias (n_kv x n_tokens x n_head) and used far more compute memory than the smaller cache saves. The banded op now accepts quantized K/V where the layer's device supports it (probed per device, F16/BF16/F32 caches are unchanged); on CUDA the delegated FA kernel reads them. --- ggml/src/ggml-cuda/fattn-banded.cu | 7 ++++-- src/models/inkling.cpp | 36 ++++++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 99687a16d64c..f9daf6588b3e 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -178,8 +178,11 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d if (!q || !k || !v || !rel || q->type != GGML_TYPE_F32) { return false; } - if (!fattn_banded_type_supported(k->type) || - !fattn_banded_type_supported(v->type) || + // quantized K/V: only the delegated FA kernel reads them, it converts them to F16 + const bool kv_quant_ok = (ggml_is_quantized(k->type) || ggml_is_quantized(v->type)) && + ggml_cuda_flash_attn_ext_banded_use_mma(device, dst); + if (!(fattn_banded_type_supported(k->type) || (kv_quant_ok && ggml_is_quantized(k->type))) || + !(fattn_banded_type_supported(v->type) || (kv_quant_ok && ggml_is_quantized(v->type))) || !fattn_banded_type_supported(rel->type)) { return false; } diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 6ae0155982f9..80d557dbbbff 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -227,6 +227,39 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; }; + // a quantized cache takes the banded op only where the layer's device runs it, else the dense path + std::vector> banded_quant_dev_ok; + const auto banded_cache_types_ok = [&](int il, ggml_type type_k, ggml_type type_v) { + if (banded_cache_type_supported(type_k) && banded_cache_type_supported(type_v)) { + return true; + } + if (!(banded_cache_type_supported(type_k) || ggml_is_quantized(type_k)) || + !(banded_cache_type_supported(type_v) || ggml_is_quantized(type_v))) { + return false; + } + ggml_backend_dev_t dev = model.dev_layer(il); + if (!dev) { + return false; + } + for (const auto & [d, ok] : banded_quant_dev_ok) { + if (d == dev) { + return ok; + } + } + const int64_t nh = hparams.n_head(il); + const int64_t nkv = hparams.n_head_kv(il); + ggml_tensor * pq = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, head_dim, 1, nh, 1); + ggml_tensor * pk = ggml_new_tensor_4d(ctx0, type_k, head_dim, 1, nkv, 1); + ggml_tensor * pv = ggml_new_tensor_4d(ctx0, type_v, head_dim, 1, nkv, 1); + ggml_tensor * pm = ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, 1, 1, 1, 1); + ggml_tensor * pr = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, nh, 1, 1); + ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); + ggml_prec_set_acc(op, GGML_PREC_F32); + const bool ok = ggml_backend_dev_supports_op(dev, op); + banded_quant_dev_ok.push_back({ dev, ok }); + return ok; + }; + const auto use_banded_flash = [&](int il) { const auto * cache = hparams.is_swa(il) ? mctx_attn->get_swa() : mctx_attn->get_base(); const uint32_t n_kv_flash = hparams.is_swa(il) ? n_kv_flash_swa : n_kv_flash_base; @@ -237,8 +270,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par (head_dim == 64 || head_dim == 128) && hparams.n_embd_head_v(il) == head_dim && hparams.n_head(il) % hparams.n_head_kv(il) == 0 && - banded_cache_type_supported(cache->type_k()) && - banded_cache_type_supported(cache->type_v()); + banded_cache_types_ok(il, cache->type_k(), cache->type_v()); }; for (int il = 0; il < n_layer; ++il) { From 493fc82c203df099de234a3260b12c0d417df0c3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 09:32:50 -0800 Subject: [PATCH 020/115] model : share the banded attention mask of Inkling 2 across layers Each banded layer took its own view of the n_kv x n_tokens mask, and the scheduler copied every view as a separate split input, so the compute buffer held one mask copy per full-attention layer (2 GB at 256K, 8 GB at 1M with -ub 512). The contiguous banded mask is now built once per graph and cache. --- src/models/inkling2.cpp | 8 ++++++-- src/models/models.h | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index b37f98021bd3..9754252c200c 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -438,8 +438,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens v_all->nb[1], v_all->nb[2], v_all->nb[3], 0), 0, 2, 1, 3); } ggml_tensor * mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - ggml_tensor * m = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], - mask->nb[1], mask->nb[2], mask->nb[3], 0)); + // one banded mask per graph and cache: each layer's own view would be a separate scheduler input copy + ggml_tensor *& m = mask_banded[is_swa]; + if (!m) { + m = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], + mask->nb[1], mask->nb[2], mask->nb[3], 0)); + } // exp(s + b)/(exp(t) + sum(exp(s + b))): the dense mask b - t with a zero sink ggml_tensor * rel_b = ggml_mul_mat(ctx0, layer.attn_rel_bias, Rcur); rel_b = ggml_reshape_4d(ctx0, rel_b, rel_b->ne[0], n_head, n_tokens, 1); diff --git a/src/models/models.h b/src/models/models.h index ae7aec7783c4..6156e0819abb 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2533,6 +2533,8 @@ struct llama_model_inkling2 : public llama_model_base { // banded flash attention for layer il on its device and cache bool use_banded(int il, bool swa); std::vector, bool>> banded_dev_ok; + // [base, swa] contiguous mask of the banded attention, shared by the layers of a graph + ggml_tensor * mask_banded[2] = { nullptr, nullptr }; llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; llm_graph_input_attn_kv_iswa * attn = nullptr; From 1da4c937303f6916525fa3d0cea77514a04536c3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 09:33:05 -0800 Subject: [PATCH 021/115] inkling : share the banded attention mask across layers Each banded layer took its own view of the n_kv x n_tokens mask, and the scheduler copied every view as a separate split input, so the compute buffer held one mask copy per layer. The contiguous banded mask is now built once per graph and cache. --- src/models/inkling.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 80d557dbbbff..05e1e778bf50 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -273,6 +273,9 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par banded_cache_types_ok(il, cache->type_k(), cache->type_v()); }; + // [base, swa] contiguous mask of the banded attention, shared by the layers of the graph + ggml_tensor * mask_banded[2] = { nullptr, nullptr }; + for (int il = 0; il < n_layer; ++il) { if (hparams.is_swa(il)) { needs_rel_idx_local |= !use_banded_flash(il); @@ -478,10 +481,14 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * rel_fa = ggml_reshape_4d(ctx0, rel, rel_extent, n_head, n_tokens/n_stream, n_stream); - ggml_tensor * mask = is_swa ? inp_attn->self_attn_mask_swa.raw : inp_attn->self_attn_mask.raw; - mask = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, - n_kv_flash, mask->ne[1], mask->ne[2], mask->ne[3], - mask->nb[1], mask->nb[2], mask->nb[3], 0)); + // one banded mask per graph and cache: each layer's own view would be a separate scheduler input copy + ggml_tensor *& mask = mask_banded[is_swa]; + if (!mask) { + ggml_tensor * mask_raw = is_swa ? inp_attn->self_attn_mask_swa.raw : inp_attn->self_attn_mask.raw; + mask = ggml_cont(ctx0, ggml_view_4d(ctx0, mask_raw, + n_kv_flash, mask_raw->ne[1], mask_raw->ne[2], mask_raw->ne[3], + mask_raw->nb[1], mask_raw->nb[2], mask_raw->nb[3], 0)); + } cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, mask, rel_fa, 1.0f/float(head_dim), rel_extent); From 1ac4b1c915b1137de94782a35c4be79e85589299 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 09:45:53 -0800 Subject: [PATCH 022/115] kv-cache : banded attention for a sequence stored at a cell offset With several slots in a unified cache only the sequence starting at cell 0 took the banded attention; every other slot fell back to the dense relative bias. A sequence held in one run of cells c0 + pos is now banded too: the cells before c0 belong to other sequences and are masked, and the relative distances are unchanged cell differences. --- src/llama-kv-cache.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 1387d82e09e3..b852715749a1 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -1349,13 +1349,23 @@ uint32_t llama_kv_cache::get_n_kv_pos_contiguous(const slot_info & sinfo, const } } + // the sequence must be one run of cells c0 + pos, pos = 0..pos_max; the cells before c0 hold other sequences + // (several slots in a unified cache) and are masked, so the distances stay cell differences + uint32_t c0 = 0; + while (c0 < cells.size() && (cells.is_empty(c0) || !cells.seq_has(c0, seq_id))) { + ++c0; + } + if ((uint64_t) c0 + pos_max + 1 > cells.size()) { + return 0; + } for (llama_pos pos = 0; pos <= pos_max; ++pos) { - if (cells.is_empty(pos) || cells.pos_get(pos) != pos || !cells.seq_has(pos, seq_id)) { + const uint32_t i = c0 + pos; + if (cells.is_empty(i) || cells.pos_get(i) != pos || !cells.seq_has(i, seq_id)) { return 0; } } - return pos_max + 1; + return c0 + pos_max + 1; } uint32_t llama_kv_cache::get_n_kv_slices(const llama_ubatch & ubatch) { From 58d6e4c5bc337efd837664c864c061d797353c1f Mon Sep 17 00:00:00 2001 From: Tom Skeggs <271377083+skeggsguy@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:33:45 +1100 Subject: [PATCH 023/115] metal : add FLASH_ATTN_EXT_BANDED in both attention kernels Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-metal/ggml-metal-device.cpp | 33 +++- ggml/src/ggml-metal/ggml-metal-device.h | 9 +- ggml/src/ggml-metal/ggml-metal-device.m | 44 +++++ ggml/src/ggml-metal/ggml-metal-impl.h | 7 + ggml/src/ggml-metal/ggml-metal-ops.cpp | 198 ++++++++++++-------- ggml/src/ggml-metal/ggml-metal.cpp | 1 + ggml/src/ggml-metal/kernels/fa_common.metal | 39 +++- ggml/src/ggml-metal/kernels/fa_tensor.metal | 76 +++++++- tests/test-backend-ops.cpp | 48 +++++ 9 files changed, 356 insertions(+), 99 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index cd9e0785053c..82418c7d55b7 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1788,7 +1788,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_p const struct ggml_tensor * op, bool has_mask, int32_t ncpsg) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_UNUSED(op); char base[256]; @@ -1829,7 +1829,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_p ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_kv_f16( ggml_metal_library_t lib, const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); char base[256]; @@ -1848,7 +1848,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_b const struct ggml_tensor * op, int32_t nqptg, int32_t ncpsg) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_UNUSED(op); char base[256]; @@ -1892,8 +1892,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_t bool has_mask, bool has_sinks, bool has_bias, - bool has_scap) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + bool has_scap, + bool has_kvpad, + bool has_rel, + int32_t rel_type) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); char base[256]; char name[256]; @@ -1904,7 +1907,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_t const char * type = op->src[1]->type == GGML_TYPE_BF16 ? "bf16" : "f16"; snprintf(base, 256, "kernel_flash_attn_ext_tensor_%s_dk%d_dv%d", type, dk, dv); - snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d", base, has_mask, has_sinks, has_bias, has_scap); + snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_rel=%d_rt=%d", base, has_mask, has_sinks, has_bias, has_scap, has_kvpad, has_rel, rel_type); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); if (!res.pipeline) { @@ -1914,6 +1917,10 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_t ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT_TENSOR + 1); ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT_TENSOR + 2); ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_TENSOR + 3); + ggml_metal_cv_set_bool(cv, has_rel, FC_FLASH_ATTN_EXT_TENSOR + 4); + ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_TENSOR + 5); + + ggml_metal_cv_set_int32(cv, rel_type, FC_FLASH_ATTN_EXT_TENSOR + 6); res = ggml_metal_library_compile_pipeline(lib, base, name, cv); @@ -1934,8 +1941,10 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( int32_t nsg, bool use_kv_f16, int32_t ns10, - int32_t ns20) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + int32_t ns20, + bool has_rel, + int32_t rel_type) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); char base[256]; char name[256]; @@ -1954,7 +1963,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( dk, dv); - snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_ns10=%d_ns20=%d_nsg=%d", + snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d_kvpad=%d_bcm=%d_ns10=%d_ns20=%d_nsg=%d_rel=%d_rt=%d", base, has_mask, has_sinks, @@ -1964,7 +1973,9 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( bc_mask, ns10, ns20, - nsg); + nsg, + has_rel, + rel_type); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); if (!res.pipeline) { @@ -1975,12 +1986,14 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT + 2); ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT + 3); ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT + 4); + ggml_metal_cv_set_bool(cv, has_rel, FC_FLASH_ATTN_EXT + 5); ggml_metal_cv_set_bool(cv, bc_mask, FC_FLASH_ATTN_EXT + 10); ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT + 20); ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT + 21); ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT + 22); + ggml_metal_cv_set_int32(cv, rel_type, FC_FLASH_ATTN_EXT + 23); res = ggml_metal_library_compile_pipeline(lib, base, name, cv); diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h index c0466d62ff6f..4baec44610f5 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -206,7 +206,10 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att bool has_mask, bool has_sinks, bool has_bias, - bool has_scap); + bool has_scap, + bool has_kvpad, + bool has_rel, + int32_t rel_type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( ggml_metal_library_t lib, @@ -219,7 +222,9 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att int32_t nsg, bool use_kv_f16, int32_t ns10, - int32_t ns20); + int32_t ns20, + bool has_rel, + int32_t rel_type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( ggml_metal_library_t lib, diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 2e085453adb9..e12294a7efcb 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1824,6 +1824,50 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return false; } return has_simdgroup_mm; // TODO: over-restricted for vec-kernels + case GGML_OP_FLASH_ATTN_EXT_BANDED: + { + // no vec kernel: the half8x8 or tensor kernel runs for any number of queries + const struct ggml_tensor * mask = op->src[3]; + const struct ggml_tensor * sinks = op->src[4]; + const struct ggml_tensor * rel = op->src[6]; + + if (op->src[0]->ne[0] != 64 && op->src[0]->ne[0] != 128) { + return false; + } + if (op->src[2]->ne[0] != op->src[1]->ne[0]) { + return false; + } + if (op->src[1]->type != op->src[2]->type) { + return false; + } + switch (op->src[1]->type) { + case GGML_TYPE_F32: + case GGML_TYPE_F16: + break; + case GGML_TYPE_BF16: + if (!has_bfloat) { + return false; + } + break; + default: + return false; + } + if (rel->type != GGML_TYPE_F32 && rel->type != GGML_TYPE_F16) { + return false; + } + if (rel->nb[0] != ggml_type_size(rel->type)) { + return false; + } + if (mask && (mask->type != GGML_TYPE_F16 || mask->ne[1] < op->src[0]->ne[1])) { + return false; + } + if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float) || + (sinks->ne[1] != 1 && sinks->ne[1] != op->src[0]->ne[1]) || + (sinks->ne[2] != 1 && sinks->ne[2] != op->src[0]->ne[3]))) { + return false; + } + return has_simdgroup_mm; + } case GGML_OP_LIGHTNING_INDEXER: if (op->src[0]->ne[0] != OP_LIGHTNING_INDEXER_DK) { return false; diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index aad014d837e9..ac81b58a1559 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -463,6 +463,13 @@ typedef struct { float m1; int32_t n_head_log2; float logit_softcap; + int32_t ne_r0; // rel extent (banded) + int32_t q_off; // ne11 - ne01 + uint64_t nb_r1; + uint64_t nb_r2; + uint64_t nb_r3; // 0 when rel is broadcast over ne03 + uint64_t nb_s1; // 0 when sinks are per head only + uint64_t nb_s2; } ggml_metal_kargs_flash_attn_ext; typedef struct { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index a7a1ef61e9cf..e61efb13543c 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -483,6 +483,7 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) { n_fuse = ggml_metal_op_tri(ctx, idx); } break; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { n_fuse = ggml_metal_op_flash_attn_ext(ctx, idx); } break; @@ -3198,7 +3199,12 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) { } bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); + + // banded attention runs on the half8x8 or the tensor kernel + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + return false; + } const int64_t ne00 = op->src[0]->ne[0]; // head size const int64_t ne01 = op->src[0]->ne[1]; // batch size @@ -3210,7 +3216,7 @@ bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { // ref: https://github.com/ggml-org/llama.cpp/pull/27390 // dequantize the quantized KV cache to F16 before running the F16 flash attention kernels static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 @@ -3234,7 +3240,7 @@ static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { } static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool has_tensor) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); if (!has_tensor || ggml_metal_op_flash_attn_ext_use_vec(op)) { return false; @@ -3271,6 +3277,11 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool return false; } + // banded attention handles a partial last chunk with the pad buffer + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + return true; + } + // with kv_rows, the attention runs over the compacted row lists (padded to 256), not over the cache const int64_t ne11_attn = op->src[5] ? op->src[5]->ne[0] : op->src[1]->ne[1]; @@ -3281,7 +3292,7 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool // the mask (src[3]) remains the single source of truth: finite entries are the valid KV positions, // n_kv_max is only an upper bound on their number per mask row, used to size the index lists static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); // K/V row lists are handled by the dense kernels, not by the sparse path if (op->src[5] != nullptr) { @@ -3347,7 +3358,7 @@ static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) // the dequantized V is then a view of the dequantized K and does not need its own dequant or scratch // - ref: https://github.com/ggml-org/llama.cpp/pull/13435 static bool ggml_metal_op_flash_attn_ext_v_is_view_of_k(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const ggml_tensor * K = op->src[1]; const ggml_tensor * V = op->src[2]; @@ -3357,7 +3368,7 @@ static bool ggml_metal_op_flash_attn_ext_v_is_view_of_k(const ggml_tensor * op) // size of the F16 dequantized K tensor; the dequantized V tensor follows it in the same scratch buffer static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_TENSOR_LOCALS( int32_t, ne1, op->src[1], ne); @@ -3365,7 +3376,7 @@ static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) } size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); @@ -3423,7 +3434,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { } size_t ggml_metal_op_flash_attn_ext_extra_blk(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); //GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); @@ -3462,7 +3473,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_blk(const ggml_tensor * op) { } size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_TENSOR_LOCALS( int32_t, ne0, op->src[0], ne); GGML_TENSOR_LOCALS(uint64_t, nb0, op->src[0], nb); @@ -3491,7 +3502,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { } size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); // note: always reserve the temp buffer to avoid graph reallocations //if (!ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { @@ -3516,7 +3527,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { // size of the sparse index lists: one list of KV indices per mask row, // padded with -1 up to a multiple of OP_FLASH_ATTN_EXT_VEC_NCPSG size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); GGML_TENSOR_LOCALS( int32_t, ne3, op->src[3], ne); @@ -3534,7 +3545,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { // size of the contiguous F16 buffers holding the K/V rows referenced by the kv_rows lists // the attention over these buffers is a standard dense op (no per-tile gather in the main kernel) size_t ggml_metal_op_flash_attn_ext_extra_rows(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); const ggml_tensor * kv_rows = op->src[5]; @@ -3620,6 +3631,25 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const bool has_mask = op->src[3] != NULL; const bool has_sinks = op->src[4] != NULL; + // banded: add rel[dist] to the scores for 0 <= dist < ne_r0, with dist = iq1 + (ne11 - ne01) - ic + const ggml_tensor * rel = op->op == GGML_OP_FLASH_ATTN_EXT_BANDED ? op->src[6] : nullptr; + const bool has_rel = rel != nullptr; + + GGML_ASSERT(!has_rel || rel->type == GGML_TYPE_F32 || rel->type == GGML_TYPE_F16); + GGML_ASSERT(!has_rel || rel->nb[0] == ggml_type_size(rel->type)); + + // 0 - F32, 1 - F16 + const int32_t rel_type = has_rel && rel->type == GGML_TYPE_F16 ? 1 : 0; + + const int32_t ne_r0 = has_rel ? (int32_t) rel->ne[0] : 0; + const uint64_t nb_r1 = has_rel ? rel->nb[1] : 0; + const uint64_t nb_r2 = has_rel ? rel->nb[2] : 0; + const uint64_t nb_r3 = has_rel && rel->ne[3] > 1 ? rel->nb[3] : 0; + + // per-query sinks (banded); a zero stride broadcasts + const uint64_t nb_s1 = has_sinks && op->src[4]->ne[1] > 1 ? op->src[4]->nb[1] : 0; + const uint64_t nb_s2 = has_sinks && op->src[4]->ne[2] > 1 ? op->src[4]->nb[2] : 0; + GGML_ASSERT(!has_rows || has_mask); const bool has_bias = max_bias != 0.0f; const bool has_scap = logit_softcap != 0.0f; @@ -3637,6 +3667,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_buffer_id bid_src2 = ggml_metal_get_buffer_id(op->src[2]); ggml_metal_buffer_id bid_src3 = has_mask ? ggml_metal_get_buffer_id(op->src[3]) : bid_src0; ggml_metal_buffer_id bid_src4 = has_sinks ? ggml_metal_get_buffer_id(op->src[4]) : bid_src0; + ggml_metal_buffer_id bid_rel = has_rel ? ggml_metal_get_buffer_id(rel) : bid_src0; ggml_metal_buffer_id bid_dst = ggml_metal_get_buffer_id(op); @@ -3840,12 +3871,62 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { } } + // copy the last partial chunk of K, V and the mask to the pad buffer + auto encode_pad = [&](int32_t ncpsg) { + assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); + + ggml_metal_kargs_flash_attn_ext_pad args0 = { + /*.ne11 =*/ne11, + /*.ne_12_2 =*/ne12, + /*.ne_12_3 =*/ne13, + /*.nb11 =*/nb11_attn, + /*.nb12 =*/nb12_attn, + /*.nb13 =*/nb13_attn, + /*.nb21 =*/nb21_attn, + /*.nb22 =*/nb22_attn, + /*.nb23 =*/nb23_attn, + /*.ne31 =*/ne31, + /*.ne32 =*/ne32, + /*.ne33 =*/ne33, + /*.nb31 =*/nb31, + /*.nb32 =*/nb32, + /*.nb33 =*/nb33, + }; + + auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); + + ggml_metal_encoder_set_pipeline(enc, pipeline0); + ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); + ggml_metal_encoder_set_buffer (enc, bid_k, 1); + ggml_metal_encoder_set_buffer (enc, bid_v, 2); + ggml_metal_encoder_set_buffer (enc, bid_src3, 3); + ggml_metal_encoder_set_buffer (enc, bid_pad, 4); + + assert(ne12 == ne22); + assert(ne13 == ne23); + + ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1); + }; + if (!use_sparse && ggml_metal_op_flash_attn_ext_use_tensor(op, props_dev->has_tensor)) { // tensor API kernel const int nqptg = ne00 >= 512 ? OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE : OP_FLASH_ATTN_EXT_TENSOR_NQPSG; // queries per threadgroup const int ncpsg = OP_FLASH_ATTN_EXT_TENSOR_NCPSG; // cache values per threadgroup const int nsg = OP_FLASH_ATTN_EXT_TENSOR_NSG; + // the pad buffer is sized for OP_FLASH_ATTN_EXT_NCPSG items + static_assert(OP_FLASH_ATTN_EXT_TENSOR_NCPSG == OP_FLASH_ATTN_EXT_NCPSG, "pad buffer size"); + + bool need_sync = false; + + const bool has_kvpad = ne11_attn % ncpsg != 0; + + if (has_kvpad) { + encode_pad(ncpsg); + + need_sync = true; + } + if (has_mask) { assert(ggml_metal_op_flash_attn_ext_extra_blk(op) != 0); @@ -3872,6 +3953,10 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_dispatch_threadgroups(enc, nblk0, nblk1, ne32*ne33, 32, 1, 1); + need_sync = true; + } + + if (need_sync) { ggml_metal_op_concurrency_reset(ctx); } @@ -3911,12 +3996,19 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.m1 =*/ m1, /*.n_head_log2 =*/ n_head_log2, /*.logit_softcap =*/ logit_softcap, + /*.ne_r0 =*/ ne_r0, + /*.q_off =*/ ne11 - ne01, + /*.nb_r1 =*/ nb_r1, + /*.nb_r2 =*/ nb_r2, + /*.nb_r3 =*/ nb_r3, + /*.nb_s1 =*/ nb_s1, + /*.nb_s2 =*/ nb_s2, }; // shared memory layout: queries (16-bit), scores (float), probabilities (16-bit), row scale (float), rescale flag (int) const size_t smem = GGML_PAD(nqptg*ne00*sizeof(ggml_fp16_t) + nqptg*ncpsg*(sizeof(float) + sizeof(ggml_fp16_t)) + nqptg*sizeof(float) + sizeof(int32_t), 16); - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_tensor(lib, op, has_mask, has_sinks, has_bias, has_scap); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_tensor(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, has_rel, rel_type); GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size); @@ -3930,6 +4022,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, bid_src4, 5); ggml_metal_encoder_set_buffer (enc, bid_blk, 6); ggml_metal_encoder_set_buffer (enc, bid_dst, 7); + ggml_metal_encoder_set_buffer (enc, bid_pad, 8); + ggml_metal_encoder_set_buffer (enc, bid_rel, 9); ggml_metal_encoder_set_threadgroup_memory_size(enc, smem, 0); @@ -3948,39 +4042,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const bool has_kvpad = ne11_attn % ncpsg != 0; if (has_kvpad) { - assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); - - ggml_metal_kargs_flash_attn_ext_pad args0 = { - /*.ne11 =*/ne11, - /*.ne_12_2 =*/ne12, - /*.ne_12_3 =*/ne13, - /*.nb11 =*/nb11_attn, - /*.nb12 =*/nb12_attn, - /*.nb13 =*/nb13_attn, - /*.nb21 =*/nb21_attn, - /*.nb22 =*/nb22_attn, - /*.nb23 =*/nb23_attn, - /*.ne31 =*/ne31, - /*.ne32 =*/ne32, - /*.ne33 =*/ne33, - /*.nb31 =*/nb31, - /*.nb32 =*/nb32, - /*.nb33 =*/nb33, - }; - - auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); - - ggml_metal_encoder_set_pipeline(enc, pipeline0); - ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); - ggml_metal_encoder_set_buffer (enc, bid_k, 1); - ggml_metal_encoder_set_buffer (enc, bid_v, 2); - ggml_metal_encoder_set_buffer (enc, bid_src3, 3); - ggml_metal_encoder_set_buffer (enc, bid_pad, 4); - - assert(ne12 == ne22); - assert(ne13 == ne23); - - ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1); + encode_pad(ncpsg); need_sync = true; } @@ -4071,9 +4133,16 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.m1 =*/ m1, /*.n_head_log2 =*/ n_head_log2, /*.logit_softcap =*/ logit_softcap, + /*.ne_r0 =*/ ne_r0, + /*.q_off =*/ ne11 - ne01, + /*.nb_r1 =*/ nb_r1, + /*.nb_r2 =*/ nb_r2, + /*.nb_r3 =*/ nb_r3, + /*.nb_s1 =*/ nb_s1, + /*.nb_s2 =*/ nb_s2, }; - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20, has_rel, rel_type); ggml_metal_encoder_set_pipeline(enc, pipeline); ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0); @@ -4085,6 +4154,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, bid_pad, 6); ggml_metal_encoder_set_buffer (enc, bid_blk, 7); ggml_metal_encoder_set_buffer (enc, bid_dst, 8); + ggml_metal_encoder_set_buffer (enc, bid_rel, 9); GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size); @@ -4148,39 +4218,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { } if (has_kvpad) { - assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); - - ggml_metal_kargs_flash_attn_ext_pad args0 = { - /*.ne11 =*/ne11, - /*.ne_12_2 =*/ne12, - /*.ne_12_3 =*/ne13, - /*.nb11 =*/nb11_attn, - /*.nb12 =*/nb12_attn, - /*.nb13 =*/nb13_attn, - /*.nb21 =*/nb21_attn, - /*.nb22 =*/nb22_attn, - /*.nb23 =*/nb23_attn, - /*.ne31 =*/ne31, - /*.ne32 =*/ne32, - /*.ne33 =*/ne33, - /*.nb31 =*/nb31, - /*.nb32 =*/nb32, - /*.nb33 =*/nb33, - }; - - auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); - - ggml_metal_encoder_set_pipeline(enc, pipeline0); - ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); - ggml_metal_encoder_set_buffer (enc, bid_k, 1); - ggml_metal_encoder_set_buffer (enc, bid_v, 2); - ggml_metal_encoder_set_buffer (enc, bid_src3, 3); - ggml_metal_encoder_set_buffer (enc, bid_pad, 4); - - assert(ne12 == ne22); - assert(ne13 == ne23); - - ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1); + encode_pad(ncpsg); need_sync = true; } diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 9a1bd2c773a3..97a0fc0d1ea6 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -294,6 +294,7 @@ static size_t ggml_backend_metal_buffer_type_get_alloc_size(ggml_backend_buffer_ res += ggml_metal_op_mul_mat_id_extra_ids(tensor); } break; case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: { res += ggml_metal_op_flash_attn_ext_extra_pad(tensor); res += ggml_metal_op_flash_attn_ext_extra_blk(tensor); diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 5e08bf85fa89..22f31a8db24b 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -3,6 +3,7 @@ constant bool FC_flash_attn_ext_has_sinks [[function_constant(FC_FLASH_ATTN_EXT constant bool FC_flash_attn_ext_has_bias [[function_constant(FC_FLASH_ATTN_EXT + 2)]]; constant bool FC_flash_attn_ext_has_scap [[function_constant(FC_FLASH_ATTN_EXT + 3)]]; constant bool FC_flash_attn_ext_has_kvpad [[function_constant(FC_FLASH_ATTN_EXT + 4)]]; +constant bool FC_flash_attn_ext_has_rel [[function_constant(FC_FLASH_ATTN_EXT + 5)]]; constant bool FC_flash_attn_ext_bc_mask [[function_constant(FC_FLASH_ATTN_EXT + 10)]]; @@ -14,6 +15,16 @@ constant int32_t FC_flash_attn_ext_ns10 [[function_constant(FC_FLASH_ATTN_EXT + constant int32_t FC_flash_attn_ext_ns20 [[function_constant(FC_FLASH_ATTN_EXT + 21)]]; constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + 22)]]; +// rel type: 0 - F32, 1 - F16 +constant int32_t FC_flash_attn_ext_rel_type [[function_constant(FC_FLASH_ATTN_EXT + 23)]]; + +static inline float flash_attn_ext_rel_load(device const char * rel, int32_t i) { + if (FC_flash_attn_ext_rel_type == 1) { + return ((device const half *) rel)[i]; + } + return ((device const float *) rel)[i]; +} + // ref: https://arxiv.org/pdf/2307.08691.pdf template< typename q_t, // query types in shared memory @@ -54,6 +65,7 @@ void kernel_flash_attn_ext_impl( device const char * pad, device const char * blk, device char * dst, + device const char * rel, threadgroup half * shmem_f16, uint3 tgpig, ushort tiisg, @@ -421,6 +433,25 @@ void kernel_flash_attn_ext_impl( s2 = args.logit_softcap*precise::tanh(s2); } + // banded: the distance of column ic0*C + 2*tiisg is d0, of the next column d0 - 1 + // note: the blk value classifies the mask only, so this does not depend on it + if (FC_flash_attn_ext_has_rel) { + const int32_t dmax = iq1 + j + args.q_off - ic0*C; + + if (iq1 + j < args.ne01 && dmax >= 0 && dmax - (C - 1) < args.ne_r0) { + device const char * pr = rel + iq2*args.nb_r1 + (iq1 + j)*args.nb_r2 + iq3*args.nb_r3; + + const int32_t d0 = dmax - 2*tiisg; + + if (d0 >= 0 && d0 < args.ne_r0) { + s2[0] += flash_attn_ext_rel_load(pr, d0); + } + if (d0 >= 1 && d0 - 1 < args.ne_r0) { + s2[1] += flash_attn_ext_rel_load(pr, d0 - 1); + } + } + } + // mqk = mqk + slope*mask if (blk_cur != 2) { if (FC_flash_attn_ext_has_bias) { @@ -610,7 +641,10 @@ void kernel_flash_attn_ext_impl( const short j = jj*NSG + sgitg; const float m = M[jj]; - const float s = tiisg == 0 ? ((device const float *) sinks)[iq2] : -FLT_MAX/2; + + // per-query sinks use non-zero strides + const int32_t jq = min(iq1 + j, args.ne01 - 1); + const float s = tiisg == 0 ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) : -FLT_MAX/2; M[jj] = simd_max(max(M[jj], s)); @@ -692,12 +726,13 @@ kernel void kernel_flash_attn_ext( device const char * pad, device const char * blk, device char * dst, + device const char * rel, threadgroup half * shmem_f16 [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { #define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C -#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg +#define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, rel, shmem_f16, tgpig, tiisg, sgitg switch (FC_flash_attn_ext_nsg) { // note: disabled cases to reduce library load time //case 1: kernel_flash_attn_ext_impl(FWD_ARGS); break; diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 4a9ed30e3b25..2e9e6012e5db 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -6,6 +6,18 @@ constant bool FC_flash_attn_ext_tensor_has_mask [[function_constant(FC_FLASH_AT constant bool FC_flash_attn_ext_tensor_has_sinks [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 1)]]; constant bool FC_flash_attn_ext_tensor_has_bias [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 2)]]; constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 3)]]; +constant bool FC_flash_attn_ext_tensor_has_rel [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 4)]]; +constant bool FC_flash_attn_ext_tensor_has_kvpad [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 5)]]; + +// rel type: 0 - F32, 1 - F16 +constant int32_t FC_flash_attn_ext_tensor_rel_type [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 6)]]; + +static inline float flash_attn_ext_tensor_rel_load(device const char * rel, int32_t i) { + if (FC_flash_attn_ext_tensor_rel_type == 1) { + return ((device const half *) rel)[i]; + } + return ((device const float *) rel)[i]; +} // ref: https://arxiv.org/pdf/2307.08691.pdf template< @@ -25,6 +37,8 @@ kernel void kernel_flash_attn_ext_tensor( device const char * sinks, device const char * blk, device char * dst, + device const char * pad, + device const char * rel, threadgroup char * shmem [[threadgroup(0)]], uint3 tgpig [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], @@ -37,6 +51,7 @@ kernel void kernel_flash_attn_ext_tensor( static_assert(DK % 4 == 0, "DK must be divisible by 4"); static_assert(Q % NSG == 0, "Q must be divisible by NSG"); static_assert(C % NW == 0, "C must be divisible by NW"); + static_assert(C == OP_FLASH_ATTN_EXT_TENSOR_NCPSG, "the pad pass fills chunks of OP_FLASH_ATTN_EXT_TENSOR_NCPSG"); const int iq3 = tgpig[2]; const int iq2 = tgpig[1]; @@ -142,8 +157,30 @@ kernel void kernel_flash_attn_ext_tensor( threadgroup_barrier(mem_flags::mem_threadgroup); - // the host guarantees ne11 % C == 0 + // the host guarantees ne11 % C == 0, unless has_kvpad for (int ic0 = 0, ic = 0; ic < args.ne11; ++ic0, ic += C) { + // the last partial chunk uses the pad buffer as source, read from offset 0 + const bool is_pad = FC_flash_attn_ext_tensor_has_kvpad && ic + C > args.ne11; + const int icr = is_pad ? 0 : ic; + + if (is_pad) { + k = pad; + v = k + args.nb11*C*args.ne_12_2*args.ne_12_3; + mask = v + args.nb21*C*args.ne_12_2*args.ne_12_3; + + const int ikv2 = iq2/(args.ne02/args.ne_12_2); + const int ikv3 = iq3/(args.ne03/args.ne_12_3); + + k += (ikv2 + ikv3*args.ne_12_2)*args.nb11*C; + v += (ikv2 + ikv3*args.ne_12_2)*args.nb21*C; + + FOR_UNROLL (short jj = 0; jj < NQ; ++jj) { + const short j = jj*NSG + sgitg; + + pm[jj] = (device const half *) mask + (iq1 + j)*C + (iq2%args.ne32)*(C*args.ne31) + (iq3%args.ne33)*(C*args.ne31*args.ne32); + } + } + char blk_cur = 1; if (FC_flash_attn_ext_tensor_has_mask) { @@ -156,7 +193,7 @@ kernel void kernel_flash_attn_ext_tensor( // Q*K^T { - auto tk = tensor((device T *) (k + (uint64_t) ic*args.nb11), dextents(DK, C), array({1, sk})); + auto tk = tensor((device T *) (k + (uint64_t) icr*args.nb11), dextents(DK, C), array({1, sk})); mm_qk.run(tq, tk, ts); } @@ -179,9 +216,36 @@ kernel void kernel_flash_attn_ext_tensor( } } + // banded: the distance of column ic + ii*NW + tiisg is dmax - ii*NW - tiisg + // add rel before the row max, else exp(s - M) can overflow + if (FC_flash_attn_ext_tensor_has_rel) { + const int dmax = iq1 + j + args.q_off - ic; + + if (iq1 + j < args.ne01 && dmax >= 0 && dmax - (C - 1) < args.ne_r0) { + device const char * pr = rel + iq2*args.nb_r1 + (iq1 + j)*args.nb_r2 + iq3*args.nb_r3; + + FOR_UNROLL (short ii = 0; ii < NC; ++ii) { + const int d = dmax - ii*NW - tiisg; + + if (d >= 0 && d < args.ne_r0) { + s[ii] += flash_attn_ext_tensor_rel_load(pr, d); + } + } + } + } + if (FC_flash_attn_ext_tensor_has_mask && blk_cur != 2 && iq1 + j < args.ne31) { FOR_UNROLL (short ii = 0; ii < NC; ++ii) { - s[ii] += slope*(float) pm[jj][ic + ii*NW + tiisg]; + s[ii] += slope*(float) pm[jj][icr + ii*NW + tiisg]; + } + } + + // the pad rows of K are zero - mask the columns past ne11 (the blk value does not cover them) + if (is_pad) { + FOR_UNROLL (short ii = 0; ii < NC; ++ii) { + if (ic + ii*NW + tiisg >= args.ne11) { + s[ii] = -FLT_MAX/2; + } } } @@ -235,7 +299,7 @@ kernel void kernel_flash_attn_ext_tensor( } { - auto tv = tensor((device T *) (v + (uint64_t) ic*args.nb21), dextents(DV, C), array({1, sv})); + auto tv = tensor((device T *) (v + (uint64_t) icr*args.nb21), dextents(DV, C), array({1, sv})); mm_pv.run(tp, tv, co); } @@ -250,7 +314,9 @@ kernel void kernel_flash_attn_ext_tensor( float ms = 1.0f; if (FC_flash_attn_ext_tensor_has_sinks) { - const float s = ((device const float *) sinks)[iq2]; + // per-query sinks use non-zero strides + const int jq = min(iq1 + j, args.ne01 - 1); + const float s = *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)); const float m = max(M[jj], s); ms = exp(M[jj] - m); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 1ae0741da52c..3ea319a944db 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9347,6 +9347,31 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } }; +// large rel values, so the online softmax has to rescale the partial results +struct test_flash_attn_ext_banded_large_rel : public test_flash_attn_ext_banded_sinks { + static constexpr int rel_range = 20; + + using test_flash_attn_ext_banded_sinks::test_flash_attn_ext_banded_sinks; + + std::string vars() override { + return test_flash_attn_ext_banded_sinks::vars() + ",rel_range=" + std::to_string(rel_range); + } + + void initialize_tensors(ggml_context * ctx) override { + test_flash_attn_ext_banded_sinks::initialize_tensors(ctx); + init_tensor_uniform(ggml_get_tensor(ctx, "rel_logits"), -(float) rel_range, (float) rel_range); + } +}; + +// small extent and a tight tolerance, so that per-query sinks and the band edges are visible +struct test_flash_attn_ext_banded_tight : public test_flash_attn_ext_banded_sinks { + using test_flash_attn_ext_banded_sinks::test_flash_attn_ext_banded_sinks; + + double max_nmse_err() override { + return 1e-6; + } +}; + // large Q values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { static constexpr int q_range = 20; @@ -13533,6 +13558,24 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 2048, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, 512, 3000, 1024, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); + // Inkling-2-Mini shapes + for (int64_t n_q : { 33, 512 }) { + for (int64_t n_kv : { 4096, 32785 }) { + for (int mask_kind : { 1, 2 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, n_kv, 1024, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + } + } + } + test_cases.emplace_back(new test_flash_attn_ext_banded_large_rel(128, 24, 8, 512, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + for (int64_t n_q : { 33, 100 }) { + for (int64_t n_kv : { 300, 1000 }) { + for (int mask_kind : { 0, 1, 2 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_tight(128, 24, 8, n_q, n_kv, 96, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + } + } + } + test_cases.emplace_back(new test_flash_attn_ext_banded_tight(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_F16, GGML_TYPE_F16, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); @@ -14329,6 +14372,11 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_flash_attn_ext(128, 128, 2, {16, 1}, 4096, nq, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0, {0, 2, 1, 3}, false)); } + // banded attention, Inkling-2-Mini prompt processing + for (int64_t n_kv : { 4096, 32768 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, n_kv, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + } + // q8_0 KV cases with long context (decode and prompt) test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {16, 1}, 128, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0)); test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {16, 1}, 512, 1, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0)); From 982dee7a2995f26325d0d7c0a13359a06c1ec7d1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 21:22:27 -0800 Subject: [PATCH 024/115] metal : do not reserve the vec and F16 K/V scratch for FLASH_ATTN_EXT_BANDED The banded op never runs the vec kernel and supports_op refuses quantized K/V, so neither the per-workgroup reduce buffer nor the F16 copy of K and V is ever used. The F16 copy alone is 4 bytes per cell, KV head and head dim of compute buffer. --- ggml/src/ggml-metal/ggml-metal-ops.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index e61efb13543c..976c91ebef55 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3486,6 +3486,11 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { size_t res = 0; + // banded: never runs the vec kernel, so there are no per-workgroup results to reduce + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + return res; + } + // note: always reserve the temp buffer to avoid graph reallocations //if (ggml_metal_op_flash_attn_ext_use_vec(op)) { if (true) { @@ -3509,6 +3514,12 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { // return 0; //} + // banded: supports_op refuses quantized K/V, so the F16 copy of K and V is never made; reserving it + // would cost 4 bytes per cell, KV head and head dim (781 MiB at 200K cells for 8 KV heads of 128) + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { + return 0; + } + GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne); const size_t k_size = ggml_metal_op_flash_attn_ext_kv_f16_k_size(op); From 944cd7e55da728c964355ef4a2d088b5d0021f96 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 22:52:15 -0800 Subject: [PATCH 025/115] metal : bound the FA pad copy to the K/V row width kernel_flash_attn_ext_pad copied nb11/nb21 bytes per row. For an interleaved [D, Hkv, Nkv] cache view permuted to [D, Nkv, Hkv], that stride spans every KV head, so with a ragged n_kv the last head's last row was read past the end of K/V (F16 D=128, Hkv=8: 1792 bytes). The attention only reads ne10/ne20 elements per pad row, so copy ggml_row_size(type, ne10/ne20) bytes instead (F16 after a dequant or row gather). The pad layout keeps the nb11/nb21 row stride, so the attention kernels are unchanged. Add banded test cases with interleaved, exactly sized, ragged K/V. --- ggml/src/ggml-metal/ggml-metal-impl.h | 2 ++ ggml/src/ggml-metal/ggml-metal-ops.cpp | 17 ++++++++++++++ ggml/src/ggml-metal/kernels/fa_aux.metal | 10 +++++---- tests/test-backend-ops.cpp | 28 +++++++++++++++++++----- 4 files changed, 47 insertions(+), 10 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index ac81b58a1559..05d69e4f309c 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -417,6 +417,8 @@ typedef struct { uint64_t nb31; uint64_t nb32; uint64_t nb33; + uint64_t nbk_row; // bytes of one K row (ne10 elements); nb11 can be larger, e.g. for an interleaved [D, Hkv, Nkv] cache + uint64_t nbv_row; // bytes of one V row (ne20 elements) } ggml_metal_kargs_flash_attn_ext_pad; typedef struct { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 976c91ebef55..0dd2253025bc 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3730,6 +3730,10 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { uint64_t nb22_attn = nb22; uint64_t nb23_attn = nb23; + // element types of the K/V the pad and attention kernels read (F16 after a dequant or a row gather) + ggml_type type_k_attn = op->src[1]->type; + ggml_type type_v_attn = op->src[2]->type; + if (dequant_kv) { assert(ggml_metal_op_flash_attn_ext_extra_kv_f16(op) != 0); @@ -3797,6 +3801,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { bid_k = bid_kv_f16; bid_v = v_is_view_of_k ? bid_k : bid_v_f16; + type_k_attn = GGML_TYPE_F16; + type_v_attn = GGML_TYPE_F16; + // contiguous F16 layout of the dequantized K nb10_attn = sizeof(ggml_fp16_t); nb11_attn = nb10_attn*ne10; @@ -3858,6 +3865,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { // contiguous F16 layout of the gathered rows: [DK, n_rows, n_head_kv, n_streams] bid_k = bid_rows; + type_k_attn = GGML_TYPE_F16; + type_v_attn = GGML_TYPE_F16; + nb10_attn = sizeof(ggml_fp16_t); nb11_attn = nb10_attn*ne10; nb12_attn = nb11_attn*ne11_attn; @@ -3886,6 +3896,11 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { auto encode_pad = [&](int32_t ncpsg) { assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); + const uint64_t nbk_row = ggml_row_size(type_k_attn, ne10); + const uint64_t nbv_row = ggml_row_size(type_v_attn, ne20); + + GGML_ASSERT(nbk_row <= nb11_attn && nbv_row <= nb21_attn); + ggml_metal_kargs_flash_attn_ext_pad args0 = { /*.ne11 =*/ne11, /*.ne_12_2 =*/ne12, @@ -3902,6 +3917,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.nb31 =*/nb31, /*.nb32 =*/nb32, /*.nb33 =*/nb33, + /*.nbk_row =*/nbk_row, + /*.nbv_row =*/nbv_row, }; auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal index 6fe47470fb2d..0829932bf348 100644 --- a/ggml/src/ggml-metal/kernels/fa_aux.metal +++ b/ggml/src/ggml-metal/kernels/fa_aux.metal @@ -156,19 +156,21 @@ kernel void kernel_flash_attn_ext_pad( device char * k_dst = k_pad + args.nb11*i1 + args.nb11*C*i2 + args.nb11*C*args.ne_12_2*i3; device char * v_dst = v_pad + args.nb21*i1 + args.nb21*C*i2 + args.nb21*C*args.ne_12_2*i3; + // copy only the row itself: the row stride nb11/nb21 can span all the heads (interleaved cache views), + // and the last head's row would then be read past the end of K/V; the attention reads ne10/ne20 elements per row if (i1 >= icp) { // here it is not important the exact value that will be used as we rely on masking out the scores in the attention - for (uint64_t i = tiitg; i < args.nb11; i += ntg.x) { + for (uint64_t i = tiitg; i < args.nbk_row; i += ntg.x) { k_dst[i] = 0; } - for (uint64_t i = tiitg; i < args.nb21; i += ntg.x) { + for (uint64_t i = tiitg; i < args.nbv_row; i += ntg.x) { v_dst[i] = 0; } } else { - for (uint64_t i = tiitg; i < args.nb11; i += ntg.x) { + for (uint64_t i = tiitg; i < args.nbk_row; i += ntg.x) { k_dst[i] = k_src[i]; } - for (uint64_t i = tiitg; i < args.nb21; i += ntg.x) { + for (uint64_t i = tiitg; i < args.nbv_row; i += ntg.x) { v_dst[i] = v_src[i]; } } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 3ea319a944db..57f397be6119 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9243,9 +9243,11 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type kv_type; const ggml_type rel_type; const bool strided; + const bool interleaved; // K/V as a permuted [d, n_head_kv, n_kv] cache view: the row stride spans all KV heads std::string vars() override { - return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); + return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) + + (interleaved ? ",interleaved=1" : ""); } double max_nmse_err() override { @@ -9263,16 +9265,22 @@ struct test_flash_attn_ext_banded : public test_case { test_flash_attn_ext_banded( int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false) + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, bool interleaved = false) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), - rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided) {} + rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), + interleaved(interleaved) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); ggml_tensor * k; ggml_tensor * v; ggml_tensor * r; - if (strided) { + if (interleaved) { + // exactly sized, like the KV cache: the last head's last row ends at the end of the buffer + k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); + v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); + r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); + } else if (strided) { ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); ggml_tensor * vb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); @@ -9330,8 +9338,8 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } test_flash_attn_ext_banded_sinks(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false) - : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided), sinks(sinks) {} + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false, bool interleaved = false) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, interleaved), sinks(sinks) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); @@ -13575,6 +13583,14 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_flash_attn_ext_banded_tight(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_F16, GGML_TYPE_F16, 2)); + // interleaved [d, n_head_kv, n_kv] K/V views (the KV cache layout) with a ragged n_kv: the pad pass must stay inside K/V + for (int64_t n_kv : { 72, 1000 }) { + for (int mask_kind : { 0, 1 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, n_kv, 96, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); + } + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 77, 333, 16, 2, GGML_TYPE_F32, GGML_TYPE_F32, 1, false, true)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From b64ef9d63b0b1ad81b40a20e1bc3064640dc14e7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 23:34:52 -0800 Subject: [PATCH 026/115] metal : refuse FLASH_ATTN_EXT_BANDED when K and V have different head counts Both Metal kernels take the V head from the K broadcast factor (iq2/(ne02/ne12)), so a V with fewer heads than K was read past its end. The banded op allows K and V to broadcast to the Q heads separately, and the CPU reference does that, so refuse the case in supports_op; the CUDA banded op already refuses it. Inkling always has equal K/V heads. Add banded test cases with different K and V head counts. --- ggml/src/ggml-metal/ggml-metal-device.m | 4 ++++ tests/test-backend-ops.cpp | 20 ++++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index e12294a7efcb..792e11723435 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1837,6 +1837,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[2]->ne[0] != op->src[1]->ne[0]) { return false; } + // both kernels take the V head from the K broadcast factor (iq2/(ne02/ne12)) + if (op->src[2]->ne[2] != op->src[1]->ne[2]) { + return false; + } if (op->src[1]->type != op->src[2]->type) { return false; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 734691351d55..61f980e3f5e5 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9296,10 +9296,11 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type rel_type; const bool strided; const bool interleaved; // K/V as a permuted [d, n_head_kv, n_kv] cache view: the row stride spans all KV heads + const int64_t n_head_v; // V heads when they differ from the K heads (0: same as n_head_kv) std::string vars() override { return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) + - (interleaved ? ",interleaved=1" : ""); + (interleaved ? ",interleaved=1" : "") + (n_head_v ? ",n_head_v=" + std::to_string(n_head_v) : ""); } double max_nmse_err() override { @@ -9317,10 +9318,11 @@ struct test_flash_attn_ext_banded : public test_case { test_flash_attn_ext_banded( int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, bool interleaved = false) + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, bool interleaved = false, + int64_t n_head_v = 0) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), - interleaved(interleaved) {} + interleaved(interleaved), n_head_v(n_head_v) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); @@ -9341,7 +9343,7 @@ struct test_flash_attn_ext_banded : public test_case { r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); } else { k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_v ? n_head_v : n_head_kv, 1); r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); } ggml_set_name(q, "q"); @@ -9390,8 +9392,10 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } test_flash_attn_ext_banded_sinks(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false, bool interleaved = false) - : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, interleaved), sinks(sinks) {} + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false, bool interleaved = false, + int64_t n_head_v = 0) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, interleaved, + n_head_v), sinks(sinks) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); @@ -13654,6 +13658,10 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 77, 333, 16, 2, GGML_TYPE_F32, GGML_TYPE_F32, 1, false, true)); + // K and V with different head counts (each broadcast to the Q heads on its own); backends may refuse these + test_cases.emplace_back(new test_flash_attn_ext_banded ( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 1)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, false, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 33, 100, 16, 1, GGML_TYPE_F16, GGML_TYPE_F32, 1, false, false, 4)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From aa8d61c2736ff49fe6f7f8343f175ac913c4bc50 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 00:20:40 -0800 Subject: [PATCH 027/115] metal : banded FA, require mask width == n_kv and the row layouts the kernels load The mask block classification is written over the mask width (ne30) but read over the K length (ne11), so a mask wider than K shifted every tile's classification and zeroed the output of later query tiles. Refuse a mask whose ne0 differs from K's ne1, as well as Q rows that are not float4 loadable and K/V rows that are not contiguous in their elements. Add banded test cases for the shapes the op admits beyond the cache layout: several sequences, per-head and per-sequence masks, broadcast rel tables, padded mask rows, masks wider than K, a permuted Q and per-sequence sinks. --- ggml/src/ggml-metal/ggml-metal-device.m | 15 +++- tests/test-backend-ops.cpp | 98 +++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 792e11723435..21fc8698d4ab 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1862,7 +1862,20 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (rel->nb[0] != ggml_type_size(rel->type)) { return false; } - if (mask && (mask->type != GGML_TYPE_F16 || mask->ne[1] < op->src[0]->ne[1])) { + // the kernels load Q rows as float4 and K/V rows with an element stride of nb1/nb0 + if (op->src[0]->nb[0] != sizeof(float) || op->src[0]->nb[1] % 16 != 0 || + op->src[0]->nb[2] % 16 != 0 || op->src[0]->nb[3] % 16 != 0) { + return false; + } + for (int i = 1; i <= 2; ++i) { + const struct ggml_tensor * t = op->src[i]; + if (t->nb[0] != ggml_type_size(t->type) || t->nb[1] % t->nb[0] != 0) { + return false; + } + } + // the mask blocks are classified over the mask width but read over the K length + if (mask && (mask->type != GGML_TYPE_F16 || mask->ne[0] != op->src[1]->ne[1] || + mask->ne[1] < op->src[0]->ne[1])) { return false; } if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float) || diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 61f980e3f5e5..89d39ed98b84 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9436,6 +9436,93 @@ struct test_flash_attn_ext_banded_tight : public test_flash_attn_ext_banded_sink } }; +// banded attention over the shapes the op admits beyond the cache layout: several sequences (ne3), per-head and +// per-sequence masks, broadcast rel tables, padded mask rows, a mask wider than K, a permuted Q, per-sequence sinks +struct test_flash_attn_ext_banded_shapes : public test_case { + const int64_t d, n_head, n_head_kv, n_q, n_kv, rel_extent; + const int mask_kind; // 0: all visible, 1: causal, 2: causal sliding window with dist < rel_extent + const ggml_type kv_type; + const int64_t n_seq; + const bool rel_bcast; // rel_logits ne3 = 1 + const bool mask_heads; // mask ne2 = n_head (else 1) + const bool mask_seq_bcast; // mask ne3 = 1 (else n_seq) + const int64_t mask_rows; // mask ne1 (>= n_q) + const int64_t mask_cols; // mask ne0 (>= n_kv) + const bool q_perm; // Q as a permuted [d, n_head, n_q, n_seq] view + const bool sinks_seq; // sinks ne2 = n_seq (else 1) + + std::string vars() override { + return VARS_TO_STR8(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type) + "," + + VARS_TO_STR8(n_seq, rel_bcast, mask_heads, mask_seq_bcast, mask_rows, mask_cols, q_perm, sinks_seq); + } + + double max_nmse_err() override { + return kv_type == GGML_TYPE_F32 ? 2e-6 : 5e-4; + } + + test_flash_attn_ext_banded_shapes(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + int mask_kind, ggml_type kv_type, int64_t n_seq, bool rel_bcast, bool mask_heads, bool mask_seq_bcast, + int64_t mask_rows, int64_t mask_cols, bool q_perm, bool sinks_seq) + : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), mask_kind(mask_kind), + kv_type(kv_type), n_seq(n_seq), rel_bcast(rel_bcast), mask_heads(mask_heads), mask_seq_bcast(mask_seq_bcast), + mask_rows(mask_rows), mask_cols(mask_cols), q_perm(q_perm), sinks_seq(sinks_seq) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = q_perm + ? ggml_permute(ctx, ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_head, n_q, n_seq), 0, 2, 1, 3) + : ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, n_seq); + ggml_tensor * k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, n_seq); + ggml_tensor * v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, n_seq); + ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, rel_extent, n_head, n_q, rel_bcast ? 1 : n_seq); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, mask_cols, mask_rows, mask_heads ? n_head : 1, mask_seq_bcast ? 1 : n_seq); + ggml_tensor * sk = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_head, n_q, sinks_seq ? n_seq : 1); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + ggml_set_name(m, "m"); + ggml_set_name(sk, "sinks"); + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); + ggml_flash_attn_ext_add_sinks(out, sk); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + // columns past n_kv and rows past n_q are -inf: a kernel that reads them as K columns zeroes the output + std::vector data(ggml_nelements(t)); + for (int64_t i3 = 0; i3 < t->ne[3]; ++i3) { + for (int64_t i2 = 0; i2 < t->ne[2]; ++i2) { + for (int64_t iq = 0; iq < t->ne[1]; ++iq) { + for (int64_t ik = 0; ik < t->ne[0]; ++ik) { + const int64_t rel_dist = iq + (n_kv - n_q) - ik; + bool visible = iq < n_q && ik < n_kv && + (mask_kind == 0 || (rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent))); + // per head / sequence pattern, so that a wrong mask slice changes the result + if (visible && rel_dist != 0 && (ik + 3*i2 + 5*i3) % 7 == 0) { + visible = false; + } + data[((i3*t->ne[2] + i2)*t->ne[1] + iq)*t->ne[0] + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (strcmp(t->name, "rel_logits") == 0) { + init_tensor_uniform(t, -1.0f, 1.0f); + } else if (strcmp(t->name, "sinks") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + // large Q values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { static constexpr int q_range = 20; @@ -13658,6 +13745,17 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 77, 333, 16, 2, GGML_TYPE_F32, GGML_TYPE_F32, 1, false, true)); + // shapes beyond the cache layout (backends may refuse some): + // d, nh, nkv, n_q, n_kv, ext, mk, kv type, seq, rel_bc, m_heads, m_seq_bc, m_rows, m_cols, q_perm, s_seq + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 33, 300, 16, 1, GGML_TYPE_F16, 2, false, true, false, 33, 300, true, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes( 64, 4, 1, 17, 1000, 8, 2, GGML_TYPE_F32, 2, true, false, true, 17, 1000, false, false)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 33, 333, 32, 1, GGML_TYPE_F16, 1, false, false, false, 64, 333, true, false)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 7, 100, 16, 1, GGML_TYPE_F16, 1, false, true, false, 7, 100, true, false)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 1, 100, 16, 1, GGML_TYPE_F16, 2, false, false, false, 1, 100, true, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, 2, true, false, false, 512, 4161, true, true)); + // mask wider than K (the mask block classification must not use the mask width as the K length) + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes( 64, 1, 1, 16, 64, 8, 0, GGML_TYPE_F16, 1, false, false, false, 16, 128, false, false)); + test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 100, 1000, 96, 1, GGML_TYPE_F16, 1, false, false, false, 100, 1037, false, false)); // K and V with different head counts (each broadcast to the Q heads on its own); backends may refuse these test_cases.emplace_back(new test_flash_attn_ext_banded ( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 1)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, false, 2)); From 675186062a74acde56490f80950cc203356af390 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 01:42:01 -0800 Subject: [PATCH 028/115] metal : banded FA, keep each comment sentence on one line --- ggml/src/ggml-metal/ggml-metal-ops.cpp | 4 ++-- ggml/src/ggml-metal/kernels/fa_aux.metal | 4 ++-- tests/test-backend-ops.cpp | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 0dd2253025bc..23ced1a5aaf5 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3514,8 +3514,8 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { // return 0; //} - // banded: supports_op refuses quantized K/V, so the F16 copy of K and V is never made; reserving it - // would cost 4 bytes per cell, KV head and head dim (781 MiB at 200K cells for 8 KV heads of 128) + // banded: supports_op refuses quantized K/V, so the F16 copy of K and V is never made + // reserving it would cost 781 MiB at 200K cells for 8 KV heads of 128 if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { return 0; } diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal index 0829932bf348..4df668cd30ab 100644 --- a/ggml/src/ggml-metal/kernels/fa_aux.metal +++ b/ggml/src/ggml-metal/kernels/fa_aux.metal @@ -156,8 +156,8 @@ kernel void kernel_flash_attn_ext_pad( device char * k_dst = k_pad + args.nb11*i1 + args.nb11*C*i2 + args.nb11*C*args.ne_12_2*i3; device char * v_dst = v_pad + args.nb21*i1 + args.nb21*C*i2 + args.nb21*C*args.ne_12_2*i3; - // copy only the row itself: the row stride nb11/nb21 can span all the heads (interleaved cache views), - // and the last head's row would then be read past the end of K/V; the attention reads ne10/ne20 elements per row + // copy only ne10/ne20 elements: the row stride nb11/nb21 can span all KV heads (interleaved cache views) + // reading a full stride for the last head would go past the end of K/V if (i1 >= icp) { // here it is not important the exact value that will be used as we rely on masking out the scores in the attention for (uint64_t i = tiitg; i < args.nbk_row; i += ntg.x) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 89d39ed98b84..891121022a6a 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9436,8 +9436,7 @@ struct test_flash_attn_ext_banded_tight : public test_flash_attn_ext_banded_sink } }; -// banded attention over the shapes the op admits beyond the cache layout: several sequences (ne3), per-head and -// per-sequence masks, broadcast rel tables, padded mask rows, a mask wider than K, a permuted Q, per-sequence sinks +// banded attention over shapes beyond the cache layout: sequences, mask/rel broadcast, padded or wide masks, permuted Q, sinks struct test_flash_attn_ext_banded_shapes : public test_case { const int64_t d, n_head, n_head_kv, n_q, n_kv, rel_extent; const int mask_kind; // 0: all visible, 1: causal, 2: causal sliding window with dist < rel_extent From 6807804e02d9fe94f38d20a3b4b43a12c9df15ab Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 01:55:05 -0800 Subject: [PATCH 029/115] metal : banded FA, trim comments --- ggml/src/ggml-metal/ggml-metal-device.m | 2 -- ggml/src/ggml-metal/ggml-metal-impl.h | 12 +++++------ ggml/src/ggml-metal/ggml-metal-ops.cpp | 11 +---------- ggml/src/ggml-metal/kernels/fa_aux.metal | 3 +-- ggml/src/ggml-metal/kernels/fa_common.metal | 3 --- ggml/src/ggml-metal/kernels/fa_tensor.metal | 4 ---- tests/test-backend-ops.cpp | 22 +++++++++------------ 7 files changed, 17 insertions(+), 40 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 21fc8698d4ab..ab2dbc8a7e48 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1826,7 +1826,6 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return has_simdgroup_mm; // TODO: over-restricted for vec-kernels case GGML_OP_FLASH_ATTN_EXT_BANDED: { - // no vec kernel: the half8x8 or tensor kernel runs for any number of queries const struct ggml_tensor * mask = op->src[3]; const struct ggml_tensor * sinks = op->src[4]; const struct ggml_tensor * rel = op->src[6]; @@ -1837,7 +1836,6 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[2]->ne[0] != op->src[1]->ne[0]) { return false; } - // both kernels take the V head from the K broadcast factor (iq2/(ne02/ne12)) if (op->src[2]->ne[2] != op->src[1]->ne[2]) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index 05d69e4f309c..5ad0a397182a 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -417,8 +417,8 @@ typedef struct { uint64_t nb31; uint64_t nb32; uint64_t nb33; - uint64_t nbk_row; // bytes of one K row (ne10 elements); nb11 can be larger, e.g. for an interleaved [D, Hkv, Nkv] cache - uint64_t nbv_row; // bytes of one V row (ne20 elements) + uint64_t nbk_row; // bytes of one K row; nb11 can be larger for an interleaved cache + uint64_t nbv_row; } ggml_metal_kargs_flash_attn_ext_pad; typedef struct { @@ -465,12 +465,12 @@ typedef struct { float m1; int32_t n_head_log2; float logit_softcap; - int32_t ne_r0; // rel extent (banded) - int32_t q_off; // ne11 - ne01 + int32_t ne_r0; + int32_t q_off; uint64_t nb_r1; uint64_t nb_r2; - uint64_t nb_r3; // 0 when rel is broadcast over ne03 - uint64_t nb_s1; // 0 when sinks are per head only + uint64_t nb_r3; + uint64_t nb_s1; uint64_t nb_s2; } ggml_metal_kargs_flash_attn_ext; diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 23ced1a5aaf5..7eed96405f0e 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3201,7 +3201,6 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) { bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); - // banded attention runs on the half8x8 or the tensor kernel if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { return false; } @@ -3277,7 +3276,6 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool return false; } - // banded attention handles a partial last chunk with the pad buffer if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { return true; } @@ -3486,7 +3484,6 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { size_t res = 0; - // banded: never runs the vec kernel, so there are no per-workgroup results to reduce if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { return res; } @@ -3514,8 +3511,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { // return 0; //} - // banded: supports_op refuses quantized K/V, so the F16 copy of K and V is never made - // reserving it would cost 781 MiB at 200K cells for 8 KV heads of 128 + // banded: supports_op refuses quantized K/V, so no F16 copy of K/V is needed if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { return 0; } @@ -3649,7 +3645,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { GGML_ASSERT(!has_rel || rel->type == GGML_TYPE_F32 || rel->type == GGML_TYPE_F16); GGML_ASSERT(!has_rel || rel->nb[0] == ggml_type_size(rel->type)); - // 0 - F32, 1 - F16 const int32_t rel_type = has_rel && rel->type == GGML_TYPE_F16 ? 1 : 0; const int32_t ne_r0 = has_rel ? (int32_t) rel->ne[0] : 0; @@ -3657,7 +3652,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const uint64_t nb_r2 = has_rel ? rel->nb[2] : 0; const uint64_t nb_r3 = has_rel && rel->ne[3] > 1 ? rel->nb[3] : 0; - // per-query sinks (banded); a zero stride broadcasts const uint64_t nb_s1 = has_sinks && op->src[4]->ne[1] > 1 ? op->src[4]->nb[1] : 0; const uint64_t nb_s2 = has_sinks && op->src[4]->ne[2] > 1 ? op->src[4]->nb[2] : 0; @@ -3730,7 +3724,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { uint64_t nb22_attn = nb22; uint64_t nb23_attn = nb23; - // element types of the K/V the pad and attention kernels read (F16 after a dequant or a row gather) ggml_type type_k_attn = op->src[1]->type; ggml_type type_v_attn = op->src[2]->type; @@ -3892,7 +3885,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { } } - // copy the last partial chunk of K, V and the mask to the pad buffer auto encode_pad = [&](int32_t ncpsg) { assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); @@ -3942,7 +3934,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const int ncpsg = OP_FLASH_ATTN_EXT_TENSOR_NCPSG; // cache values per threadgroup const int nsg = OP_FLASH_ATTN_EXT_TENSOR_NSG; - // the pad buffer is sized for OP_FLASH_ATTN_EXT_NCPSG items static_assert(OP_FLASH_ATTN_EXT_TENSOR_NCPSG == OP_FLASH_ATTN_EXT_NCPSG, "pad buffer size"); bool need_sync = false; diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal index 4df668cd30ab..7205b1e70bcc 100644 --- a/ggml/src/ggml-metal/kernels/fa_aux.metal +++ b/ggml/src/ggml-metal/kernels/fa_aux.metal @@ -156,8 +156,7 @@ kernel void kernel_flash_attn_ext_pad( device char * k_dst = k_pad + args.nb11*i1 + args.nb11*C*i2 + args.nb11*C*args.ne_12_2*i3; device char * v_dst = v_pad + args.nb21*i1 + args.nb21*C*i2 + args.nb21*C*args.ne_12_2*i3; - // copy only ne10/ne20 elements: the row stride nb11/nb21 can span all KV heads (interleaved cache views) - // reading a full stride for the last head would go past the end of K/V + // copy only ne10/ne20 elements: nb11/nb21 can span all KV heads, so a full stride overruns K/V on the last head if (i1 >= icp) { // here it is not important the exact value that will be used as we rely on masking out the scores in the attention for (uint64_t i = tiitg; i < args.nbk_row; i += ntg.x) { diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 22f31a8db24b..e4dc888a0d87 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -15,7 +15,6 @@ constant int32_t FC_flash_attn_ext_ns10 [[function_constant(FC_FLASH_ATTN_EXT + constant int32_t FC_flash_attn_ext_ns20 [[function_constant(FC_FLASH_ATTN_EXT + 21)]]; constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + 22)]]; -// rel type: 0 - F32, 1 - F16 constant int32_t FC_flash_attn_ext_rel_type [[function_constant(FC_FLASH_ATTN_EXT + 23)]]; static inline float flash_attn_ext_rel_load(device const char * rel, int32_t i) { @@ -434,7 +433,6 @@ void kernel_flash_attn_ext_impl( } // banded: the distance of column ic0*C + 2*tiisg is d0, of the next column d0 - 1 - // note: the blk value classifies the mask only, so this does not depend on it if (FC_flash_attn_ext_has_rel) { const int32_t dmax = iq1 + j + args.q_off - ic0*C; @@ -642,7 +640,6 @@ void kernel_flash_attn_ext_impl( const float m = M[jj]; - // per-query sinks use non-zero strides const int32_t jq = min(iq1 + j, args.ne01 - 1); const float s = tiisg == 0 ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) : -FLT_MAX/2; diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 2e9e6012e5db..5655de05c3b6 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -9,7 +9,6 @@ constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_AT constant bool FC_flash_attn_ext_tensor_has_rel [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 4)]]; constant bool FC_flash_attn_ext_tensor_has_kvpad [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 5)]]; -// rel type: 0 - F32, 1 - F16 constant int32_t FC_flash_attn_ext_tensor_rel_type [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 6)]]; static inline float flash_attn_ext_tensor_rel_load(device const char * rel, int32_t i) { @@ -159,7 +158,6 @@ kernel void kernel_flash_attn_ext_tensor( // the host guarantees ne11 % C == 0, unless has_kvpad for (int ic0 = 0, ic = 0; ic < args.ne11; ++ic0, ic += C) { - // the last partial chunk uses the pad buffer as source, read from offset 0 const bool is_pad = FC_flash_attn_ext_tensor_has_kvpad && ic + C > args.ne11; const int icr = is_pad ? 0 : ic; @@ -216,7 +214,6 @@ kernel void kernel_flash_attn_ext_tensor( } } - // banded: the distance of column ic + ii*NW + tiisg is dmax - ii*NW - tiisg // add rel before the row max, else exp(s - M) can overflow if (FC_flash_attn_ext_tensor_has_rel) { const int dmax = iq1 + j + args.q_off - ic; @@ -314,7 +311,6 @@ kernel void kernel_flash_attn_ext_tensor( float ms = 1.0f; if (FC_flash_attn_ext_tensor_has_sinks) { - // per-query sinks use non-zero strides const int jq = min(iq1 + j, args.ne01 - 1); const float s = *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)); const float m = max(M[jj], s); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 891121022a6a..1c863795190c 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9296,7 +9296,7 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type rel_type; const bool strided; const bool interleaved; // K/V as a permuted [d, n_head_kv, n_kv] cache view: the row stride spans all KV heads - const int64_t n_head_v; // V heads when they differ from the K heads (0: same as n_head_kv) + const int64_t n_head_v; std::string vars() override { return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) + @@ -9411,7 +9411,6 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } }; -// large rel values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_banded_large_rel : public test_flash_attn_ext_banded_sinks { static constexpr int rel_range = 20; @@ -9427,7 +9426,6 @@ struct test_flash_attn_ext_banded_large_rel : public test_flash_attn_ext_banded_ } }; -// small extent and a tight tolerance, so that per-query sinks and the band edges are visible struct test_flash_attn_ext_banded_tight : public test_flash_attn_ext_banded_sinks { using test_flash_attn_ext_banded_sinks::test_flash_attn_ext_banded_sinks; @@ -9442,13 +9440,13 @@ struct test_flash_attn_ext_banded_shapes : public test_case { const int mask_kind; // 0: all visible, 1: causal, 2: causal sliding window with dist < rel_extent const ggml_type kv_type; const int64_t n_seq; - const bool rel_bcast; // rel_logits ne3 = 1 - const bool mask_heads; // mask ne2 = n_head (else 1) - const bool mask_seq_bcast; // mask ne3 = 1 (else n_seq) - const int64_t mask_rows; // mask ne1 (>= n_q) - const int64_t mask_cols; // mask ne0 (>= n_kv) - const bool q_perm; // Q as a permuted [d, n_head, n_q, n_seq] view - const bool sinks_seq; // sinks ne2 = n_seq (else 1) + const bool rel_bcast; + const bool mask_heads; + const bool mask_seq_bcast; + const int64_t mask_rows; + const int64_t mask_cols; + const bool q_perm; + const bool sinks_seq; std::string vars() override { return VARS_TO_STR8(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type) + "," + @@ -9501,7 +9499,6 @@ struct test_flash_attn_ext_banded_shapes : public test_case { const int64_t rel_dist = iq + (n_kv - n_q) - ik; bool visible = iq < n_q && ik < n_kv && (mask_kind == 0 || (rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent))); - // per head / sequence pattern, so that a wrong mask slice changes the result if (visible && rel_dist != 0 && (ik + 3*i2 + 5*i3) % 7 == 0) { visible = false; } @@ -13736,7 +13733,7 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_flash_attn_ext_banded_tight(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_F16, GGML_TYPE_F16, 2)); - // interleaved [d, n_head_kv, n_kv] K/V views (the KV cache layout) with a ragged n_kv: the pad pass must stay inside K/V + // interleaved K/V cache views with a ragged n_kv: the pad pass must stay inside K/V for (int64_t n_kv : { 72, 1000 }) { for (int mask_kind : { 0, 1 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, n_kv, 96, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); @@ -13755,7 +13752,6 @@ static std::vector> make_test_cases_eval() { // mask wider than K (the mask block classification must not use the mask width as the K length) test_cases.emplace_back(new test_flash_attn_ext_banded_shapes( 64, 1, 1, 16, 64, 8, 0, GGML_TYPE_F16, 1, false, false, false, 16, 128, false, false)); test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 100, 1000, 96, 1, GGML_TYPE_F16, 1, false, false, false, 100, 1037, false, false)); - // K and V with different head counts (each broadcast to the Q heads on its own); backends may refuse these test_cases.emplace_back(new test_flash_attn_ext_banded ( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 1)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, false, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 33, 100, 16, 1, GGML_TYPE_F16, GGML_TYPE_F32, 1, false, false, 4)); From ffc03a87ebd3444beb990972eac790c29462363a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 14:25:39 -0800 Subject: [PATCH 030/115] graph : build the dense relative bias in F16 for flash attention With flash attention, the per-head relative bias was made contiguous in F32, the mask cast to F32, both added in F32 and the sum cast to F16. Convert the bias to F16 in one copy instead (from the source of its contiguous copy, the same values) and add the F16 mask. The mask is 0 or -inf and adding either is exact, so the result is bit-identical, with two kernels fewer per dense attention layer (Inkling 2 decode graphs, and prefill once the SWA window wraps). --- src/llama-graph.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 365e8f84c135..9607c386aab7 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -4421,6 +4421,20 @@ ggml_tensor * llm_graph_context::build_attn( // 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 (cparams.flash_attn && kq_b->type == GGML_TYPE_F32 && kq_mask->type == GGML_TYPE_F16 && hparams.f_max_alibi_bias == 0.0f) { + // convert the bias to F16 in one copy, from the source of its contiguous copy when it is one (the same values), + // and add the mask in F16: the mask is 0 or -inf, so this rounds the same as adding in F32 and converting + ggml_tensor * src = kq_b->op == GGML_OP_CONT ? kq_b->src[0] : kq_b; + ggml_tensor * bias = ggml_cpy(ctx0, src, ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, kq_b->ne[0], kq_b->ne[1], kq_b->ne[2], kq_b->ne[3])); + if (kq_b->ne[1] != kq_mask->ne[1]) { + kq_mask = ggml_view_4d(ctx0, kq_mask, kq_mask->ne[0], kq_b->ne[1], kq_mask->ne[2], kq_mask->ne[3], + kq_mask->nb[1], kq_mask->nb[2], kq_mask->nb[3], i_row*kq_mask->nb[1]); + } + kq_mask = ggml_add(ctx0, bias, kq_mask); + 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); + } if (kq_b->ne[1] != kq_mask->ne[1]) { ggml_tensor *& dev = inp->self_kq_mask_dev[is_swa]; if (!dev) { From 4fff29ad2575bb367370fb9eb958a56030031fea Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 18:37:56 -0800 Subject: [PATCH 031/115] inkling2 : expand the short convolution inputs and outputs in order Expand cur and the dynamic taps before the conv, and the conv result right after it, so that the chain from the concat to the scale is consecutive in the graph and a backend can fuse it. Only the node order changes. --- src/models/inkling2.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index e32f5388184f..5df668a8b187 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -257,6 +257,12 @@ ggml_tensor * llama_model_inkling2::graph::convolve( const int64_t n_seq_tokens = ubatch.n_seq_tokens; const int64_t n_seqs = ubatch.n_seqs; + // the inputs first, so that the conv chain from the concat to the scale is consecutive in the graph + ggml_build_forward_expand(gf, cur); + if (dynamic) { + ggml_build_forward_expand(gf, dynamic); + } + 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)); @@ -437,8 +443,10 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens 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_build_forward_expand(gf, Kcur); 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_build_forward_expand(gf, Vcur); 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, il); @@ -592,6 +600,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens 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); + ggml_build_forward_expand(gf, cur); cb(cur, "attn_out", il); } @@ -629,6 +638,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens layer.ffn_gate_up_exps); cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); + ggml_build_forward_expand(gf, cur); cb(cur, "ffn_out", il); cur = ggml_add(ctx0, ffn_inp, cur); From 081c9bbe468dcc49d85ef574dda25cfb01b3781f Mon Sep 17 00:00:00 2001 From: Tom Skeggs <271377083+skeggsguy@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:33:51 +1100 Subject: [PATCH 032/115] metal : fix supports_op so the following don't crash for banded flash attention 65536 or more queries V with a different number of rows than K Also adds two test cases to test-backend-ops.cpp. Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-metal/ggml-metal-device.m | 4 ++++ tests/test-backend-ops.cpp | 13 +++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index ab2dbc8a7e48..9a60942b4958 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1839,6 +1839,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[2]->ne[2] != op->src[1]->ne[2]) { return false; } + // the launcher asserts ne01 < 65536 and ne11 == ne21 + if (op->src[0]->ne[1] >= 65536 || op->src[2]->ne[1] != op->src[1]->ne[1]) { + return false; + } if (op->src[1]->type != op->src[2]->type) { return false; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 1c863795190c..c8093fa91609 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9297,10 +9297,12 @@ struct test_flash_attn_ext_banded : public test_case { const bool strided; const bool interleaved; // K/V as a permuted [d, n_head_kv, n_kv] cache view: the row stride spans all KV heads const int64_t n_head_v; + const int64_t n_kv_v; std::string vars() override { return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) + - (interleaved ? ",interleaved=1" : "") + (n_head_v ? ",n_head_v=" + std::to_string(n_head_v) : ""); + (interleaved ? ",interleaved=1" : "") + (n_head_v ? ",n_head_v=" + std::to_string(n_head_v) : "") + + (n_kv_v ? ",n_kv_v=" + std::to_string(n_kv_v) : ""); } double max_nmse_err() override { @@ -9319,10 +9321,10 @@ struct test_flash_attn_ext_banded : public test_case { int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, bool interleaved = false, - int64_t n_head_v = 0) + int64_t n_head_v = 0, int64_t n_kv_v = 0) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), - interleaved(interleaved), n_head_v(n_head_v) {} + interleaved(interleaved), n_head_v(n_head_v), n_kv_v(n_kv_v) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); @@ -9343,7 +9345,7 @@ struct test_flash_attn_ext_banded : public test_case { r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); } else { k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_v ? n_head_v : n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv_v ? n_kv_v : n_kv, n_head_v ? n_head_v : n_head_kv, 1); r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); } ggml_set_name(q, "q"); @@ -13755,6 +13757,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded ( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 1)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, false, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 33, 100, 16, 1, GGML_TYPE_F16, GGML_TYPE_F32, 1, false, false, 4)); + // V with more rows than K, and 65536 queries; backends may refuse these + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 0, 100)); + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 1, 1, 65536, 64, 1, 0, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From cf37396ca7f55710c6e17dfa8fdee143d10925a3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 18:22:13 -0800 Subject: [PATCH 033/115] ggml : count GGML_OP_FLASH_ATTN_EXT_BANDED on top of GGML_OP_SIGMOID_BACK (ggml-org#32126) b12635 adds GGML_OP_SIGMOID_BACK and moves the op count asserts from 100 to 101, the same edit this branch made for GGML_OP_FLASH_ATTN_EXT_BANDED, so the merge kept 101 for 102 ops and ggml.c failed to build. --- ggml/src/ggml.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 7ad97ef694c7..cad5e0b7b5cf 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1121,7 +1121,7 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "SIGMOID_BACK", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1239,7 +1239,7 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sigmoid_back(x)", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); From 06322ffb0dfa469ed2f5ee7c646450d4c29623f3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 18:43:24 -0800 Subject: [PATCH 034/115] ggml : count GGML_OP_FLASH_ATTN_EXT_BANDED on top of GGML_OP_SIGMOID_BACK (ggml-org#32126) b12635 adds GGML_OP_SIGMOID_BACK and moves the op count asserts from 100 to 101, the same edit this branch made for GGML_OP_FLASH_ATTN_EXT_BANDED, so the merge kept 101 for 102 ops and ggml.c failed to build. --- ggml/src/ggml.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 3ac0dba792b3..bc4fca3513b4 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1121,7 +1121,7 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "SIGMOID_BACK", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1239,7 +1239,7 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sigmoid_back(x)", }; -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT != 102"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); From 34f98d2556bad673adc36a18015844f6d5748d33 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 21:16:26 -0800 Subject: [PATCH 035/115] inkling2 : keep the relative-bias chunk within the reserved graph The query-row chunk of the dense relative bias was balanced over the ubatch and then padded to whole 64-row tiles, so its height depended on n_tokens and could exceed the 2^29 element budget by half. A ubatch shorter than the one reserved at load could build a taller chunk than the reserved graph (Inkling 2 Mini at -c 131072 -ub 512: 340 rows give 192-row chunks, the reserved 512 rows 128-row ones), and the compute buffer grew at runtime. Size the chunk once per cache size: whole 64-row tiles within the budget, at least one tile, and at least n_tokens/64 rows so a layer has at most 64 chunks. The height no longer shrinks as n_tokens grows, so the graph reserved for a full cache and a full ubatch holds the largest chunk any later ubatch can build. When the budget covers a whole ubatch of whole tiles for a full cache (short contexts) the graph is unchanged. --- src/models/inkling2.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 599613130092..3b0520b14687 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -371,14 +371,13 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens // dense bias is n_kv x n_tokens x n_head: chunk query rows past the budget const int64_t n_seq_tokens = n_tokens/n_stream; - // sized for a full cache so the chunking does not change while it fills + // sized for a full cache, and the chunk never shrinks as n_tokens grows, so the graph reserved + // at load (full cache, full ubatch) has the largest chunk any later ubatch builds const int64_t n_kv_max = std::max(n_kv, (is_swa ? attn->mctx->get_swa() : attn->mctx->get_base())->get_size()); - int64_t n_rows_max = std::max({ int64_t(1), n_kq_bias_max/(n_kv_max*n_head*n_stream), - (n_seq_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max }); - if (n_rows_max < n_seq_tokens) { - const int64_t n_chunks = (n_seq_tokens + n_rows_max - 1)/n_rows_max; - n_rows_max = std::min(n_seq_tokens, GGML_PAD((n_seq_tokens + n_chunks - 1)/n_chunks, 64)); - } + // query rows per chunk over all streams: whole 64-row tiles in the budget, at most n_kq_chunk_max chunks + const int64_t n_rows_all = std::max({ int64_t(64), n_kq_bias_max/(n_kv_max*n_head)/64*64, + GGML_PAD((n_tokens + n_kq_chunk_max - 1)/n_kq_chunk_max, 64) }); + const int64_t n_rows_max = std::min(n_seq_tokens, (n_rows_all + n_stream - 1)/n_stream); auto rows = [&](ggml_tensor * t, int d, int64_t r0, int64_t nr) { int64_t ne[4] = { t->ne[0], t->ne[1], t->ne[2], t->ne[3] }; ne[d] = nr; From 7adbb5d3ffdef95c8f615a000fd35db896736162 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 21:20:04 -0800 Subject: [PATCH 036/115] inkling2 : reserve the dense relative bias when a ubatch can hold several sequences The reserve graph took the banded path whenever the cache had one stream, but at runtime a ubatch of several sequences in a unified cache (-kvu) is never banded: it falls back to the dense bias, which was not in the reserved graph, so the compute buffer grew far past the size reported at load (Inkling 2 Mini UD-IQ1_S, -c 524288 -ctk q4_0 -ctv q4_0 -kvu, 2 x 250K-token prompts: 4308.7 MiB reserved and 7380.1 MiB at runtime at -ub 2048; 269.1 MiB reserved and 9925.9 MiB at -ub 128). Take the dense path for any ubatch of more than one sequence. At runtime this is what the cache already decided; at reserve the worst case ubatch holds every sequence, so a context with several sequences now reserves the dense graph, whose chunks are the largest any runtime ubatch builds. One sequence reserves the banded path as before. --- src/models/inkling2.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index f6af4dc87094..35fe4914142d 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -353,7 +353,10 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { // banded FA needs a position-contiguous cache; small ubatches stay dense for graph reuse inp->banded = cparams.flash_attn && n_tokens > n_tokens_banded_min; for (int i = 0; i < 2 && inp->banded; ++i) { - inp->n_kv_banded[i] = (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); + // a ubatch of several sequences is dense at runtime, so the reserved worst case (a ubatch + // of every sequence) must be dense too, else the dense graph outgrows the reserved buffer + inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : + (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); } ggml_tensor * inp_pos = build_inp_pos(); From e328b4da08d5246d157ec5afac073773a5b40ef1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 21:29:26 -0800 Subject: [PATCH 037/115] graph : cast the dense relative bias to F16 instead of copying it into a leaf The F16 bias for flash attention was made with ggml_cpy into a tensor from ggml_new_tensor_4d. That destination is a graph leaf, and the graph allocator keeps leaves allocated for the whole graph, so the bias of every query-row chunk and every dense layer stayed resident at once and the chunking did not bound the compute buffer. Inkling 2 Mini at -c 131072 -ub 2048 -kvu -np 2 needed 121154 MiB for one dense ubatch, and one slot with a prompt past the SWA cache (whose 40 SWA layers then take the dense bias) 13120 MiB against 3151 MiB reserved. ggml_cast makes the same F16 copy as a graph node, which is freed after its last use, so only one chunk of one layer is live at a time. The values are the same. --- src/llama-graph.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 9607c386aab7..0b5ad710d68e 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -4425,7 +4425,9 @@ ggml_tensor * llm_graph_context::build_attn( // convert the bias to F16 in one copy, from the source of its contiguous copy when it is one (the same values), // and add the mask in F16: the mask is 0 or -inf, so this rounds the same as adding in F32 and converting ggml_tensor * src = kq_b->op == GGML_OP_CONT ? kq_b->src[0] : kq_b; - ggml_tensor * bias = ggml_cpy(ctx0, src, ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, kq_b->ne[0], kq_b->ne[1], kq_b->ne[2], kq_b->ne[3])); + // a cast, not a copy into a new tensor: that tensor would be a graph leaf, which the allocator keeps + // for the whole graph, so the bias of every chunk and layer would stay allocated at once + ggml_tensor * bias = ggml_cast(ctx0, src, GGML_TYPE_F16); if (kq_b->ne[1] != kq_mask->ne[1]) { kq_mask = ggml_view_4d(ctx0, kq_mask, kq_mask->ne[0], kq_b->ne[1], kq_mask->ne[2], kq_mask->ne[3], kq_mask->nb[1], kq_mask->nb[2], kq_mask->nb[3], i_row*kq_mask->nb[1]); From 4aae13c1358b5a9d3b1b8eb19f9cab77fd9fa960 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 21:45:35 -0800 Subject: [PATCH 038/115] inkling2 : write the relative-bias chunks into one output The chunk outputs stayed live until a tree of concatenations at the end of the layer. Each one was allocated while the previous chunk's bias had just been freed, so it split the region the next bias needed and the graph allocator extended the buffer at almost every chunk: Inkling 2 Mini at -c 524288 -ctk q4_0 -ctv q4_0 -kvu -np 2 -ub 2048 reserved 87631 MiB for the 32 chunks of each full-attention layer. Allocate the layer output before the first chunk and copy each chunk's rows into it, so the chunks only hold transient tensors and reuse one region: 26705 MiB for the same graph. The values are the same; a ubatch that is not chunked builds the same graph as before. --- src/models/inkling2.cpp | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 3b0520b14687..ba903280a82e 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -383,7 +383,13 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ne[d] = nr; return ggml_cont(ctx0, ggml_view_4d(ctx0, t, ne[0], ne[1], ne[2], ne[3], t->nb[1], t->nb[2], t->nb[3], r0*t->nb[d])); }; - std::vector outs; + // the chunks write their rows into one output made before their biases: outputs that stayed live until + // a final concatenation split the region the next chunk's bias reuses, and the buffer grew with each chunk + ggml_tensor * out_all = nullptr; + if (n_rows_max < n_seq_tokens) { + out_all = ggml_cont(ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head*n_head, n_seq_tokens, n_stream)); + ggml_build_forward_expand(gf, out_all); + } for (int64_t r0 = 0; r0 < n_seq_tokens; r0 += n_rows_max) { const int64_t nr = std::min(n_rows_max, n_seq_tokens - r0); const bool all = nr == n_seq_tokens; @@ -413,19 +419,16 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * out = build_attn(inp, nullptr, nullptr, nullptr, q_c, r0 == 0 ? Kcur : nullptr, r0 == 0 ? Vcur : nullptr, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il, r0); - outs.push_back(all ? out : ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream)); - } - while (outs.size() > 1) { - std::vector next; - for (size_t c = 0; c + 1 < outs.size(); c += 2) { - next.push_back(ggml_concat(ctx0, outs[c], outs[c + 1], 1)); - } - if (outs.size() % 2) { - next.push_back(outs.back()); + if (all) { + cur = out; + break; } - outs = std::move(next); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, ggml_reshape_3d(ctx0, out, out->ne[0], nr, n_stream), + ggml_view_3d(ctx0, out_all, out_all->ne[0], nr, n_stream, out_all->nb[1], out_all->nb[2], r0*out_all->nb[1]))); + } + if (out_all) { + cur = ggml_reshape_2d(ctx0, out_all, out_all->ne[0], n_tokens); } - cur = n_rows_max >= n_seq_tokens ? outs[0] : ggml_reshape_2d(ctx0, outs[0], outs[0]->ne[0], n_tokens); 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); From 6510f1fde1e8bad67e202bb62015352f5adde293 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 21:45:44 -0800 Subject: [PATCH 039/115] inkling2 : reserve the dense bias that one sequence still takes at runtime With one sequence the reserve graph is banded, but two dense cases stay at runtime. Ubatches of at most 32 tokens (decode steps, drafts, prompt tails) build the dense bias over the whole cache, and once the positions pass the SWA cache, which then wraps, its layers take the dense bias for every ubatch. Neither was in the reserved graph: one slot of Inkling 2 Mini UD-IQ1_S at -c 524288 -ctk q4_0 -ctv q4_0 reserved 264 MiB at -ub 128 and 1055 MiB at -ub 512, and a 32-token batch near the end of the cache grew the buffer to 4431 MiB. The reserve graph is recognised by its placeholder positions, which the cache cannot offer as banded at runtime. There the SWA layers take the dense bias when the SWA cache is smaller than the full one, and the first banded full-attention layer also builds the dense bias of the first 32 rows over the whole cache, an unused output that only sizes the buffer. Runtime graphs are unchanged. --- src/models/inkling2.cpp | 24 ++++++++++++++++++++++++ src/models/models.h | 3 +++ 2 files changed, 27 insertions(+) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 35fe4914142d..6541971ba942 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -358,6 +358,15 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); } + // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), + // while at runtime it does so only for consecutive ones + if (inp->n_kv_banded[0] > 0 && ubatch.pos[0] == ubatch.pos[n_tokens - 1]) { + // once the positions pass the SWA cache it wraps and its layers take the dense bias for every ubatch + if (attn->mctx->get_swa()->get_size() < attn->mctx->get_base()->get_size()) { + inp->n_kv_banded[1] = 0; + } + n_rows_dense_reserve = std::min(n_tokens, n_tokens_banded_min); + } ggml_tensor * inp_pos = build_inp_pos(); inp_out_ids = build_inp_out_ids(); @@ -474,6 +483,21 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + if (use_banded(il, is_swa) && !is_swa && n_rows_dense_reserve > 0) { + // reserve only, output unused: the dense bias of the first rows over the full cache, as a small ubatch + // builds it. Once, before the first banded layer: the banded mask it allocates is not in that ubatch + const int64_t nr = n_rows_dense_reserve; + n_rows_dense_reserve = 0; + ggml_tensor * r_s = ggml_view_3d(ctx0, Rcur, Rcur->ne[0], n_head, nr, Rcur->nb[1], Rcur->nb[2], 0); + ggml_tensor * t_s = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), r_s); + t_s = ggml_cont(ctx0, ggml_permute(ctx0, t_s, 1, 0, 2, 3)); + ggml_tensor * p_s = ggml_view_2d(ctx0, rel_pos, n_kv, nr, rel_pos->nb[1], 0); + ggml_tensor * b_s = ggml_get_rows(ctx0, t_s, p_s); + b_s = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_4d(ctx0, b_s, n_head, n_kv, nr, 1), 2, 0, 1, 3)); + ggml_tensor * q_s = ggml_cont(ctx0, ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, nr, Qcur->nb[1], Qcur->nb[2], 0)); + ggml_build_forward_expand(gf, build_attn(inp, nullptr, nullptr, nullptr, q_s, nullptr, nullptr, b_s, + ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f), 1.0f/sqrtf(n_embd_head), il)); + } if (use_banded(il, is_swa)) { const auto * cache = is_swa ? attn->mctx->get_swa() : attn->mctx->get_base(); auto * k_rot = is_swa ? attn->self_k_rot_swa[il] : attn->self_k_rot[il]; diff --git a/src/models/models.h b/src/models/models.h index c274c4ba1df5..6b8f40506ee0 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2549,6 +2549,9 @@ struct llama_model_inkling2 : public llama_model_base { std::vector, bool>> banded_dev_ok; // [base, swa] contiguous mask of the banded attention, shared by the layers of a graph ggml_tensor * mask_banded[2] = { nullptr, nullptr }; + // query rows of the dense bias the first banded full-attention layer also builds in the reserve graph: + // the small ubatches that stay dense take that bias at runtime, the reserve must hold it + int64_t n_rows_dense_reserve = 0; llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; llm_graph_input_attn_kv_iswa * attn = nullptr; From 37644803eadb873db87eadb5117ee09ce50af6e5 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 040/115] ggml : read the banded rel_logits split from src[6] in the meta backend ggml_flash_attn_ext_banded stores rel_logits in src[6] and leaves src[5] null, so the meta backend asserted on an unknown split state and aborted for any banded graph run with tensor split. --- ggml/src/ggml-backend-meta.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 10786170f237..03c1dc3db650 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -855,7 +855,8 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( GGML_ASSERT( src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_2); GGML_ASSERT( src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_2); GGML_ASSERT(tensor->src[3] == nullptr || src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); - GGML_ASSERT( src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_1); + // ggml_flash_attn_ext_banded stores rel_logits [E, n_head, n_q, n_seq] in src[6], split by head like q + GGML_ASSERT( src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; }; From 1c5c0b12a2ee3231868a44e1cadb32b02e969095 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 041/115] mtmd : do not require v.patch_embd.weight for the Inkling projector The Inkling vision tower is the hMLP stem (v.hmlp.*), it has no patch embedding, so loading an Inkling mmproj failed with unable to find tensor v.patch_embd.weight. --- tools/mtmd/mtmd-model.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index d9df90349c45..9cb3bb76ab22 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1634,6 +1634,7 @@ struct mtmd_model_loader { const bool has_patch_embd = ( model.modality == MTMD_MODALITY_VISION && model.proj_type != PROJECTOR_TYPE_GEMMA3NV && + model.proj_type != PROJECTOR_TYPE_INKLING && model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR && model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR2); From 7cbffd26432a15d541bd6c6627f9b36ff13208df Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 042/115] tests : fail test-flash-attn-bias on non-finite outputs std::max drops NaN, so an output full of NaN reported max_abs 0 and passed. Count a non-finite value as an infinite error. --- tests/test-flash-attn-bias.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index 3337ecac1f13..a7f93df9ace3 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -300,7 +300,9 @@ static void error_stats(const std::vector & got, const std::vector max_abs = 0.0; max_rel = 0.0; for (size_t i = 0; i < got.size(); ++i) { - const double ae = std::abs(double(got[i]) - ref[i]); + // std::max drops NaN, so count a non-finite value as an infinite error + const bool finite = std::isfinite(got[i]) && std::isfinite(ref[i]); + const double ae = finite ? std::abs(double(got[i]) - ref[i]) : INFINITY; const double re = ae/std::max(1e-5, std::abs(double(ref[i]))); max_abs = std::max(max_abs, ae); max_rel = std::max(max_rel, re); From 0526ba14d155eff14e3f95f5542175eb8bb66663 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 043/115] ggml : read the banded rel_logits split from src[6] in the meta backend ggml_flash_attn_ext_banded stores rel_logits in src[6] and leaves src[5] null, so the meta backend asserted on an unknown split state and aborted for any banded graph run with tensor split. --- ggml/src/ggml-backend-meta.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 10786170f237..03c1dc3db650 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -855,7 +855,8 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( GGML_ASSERT( src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_2); GGML_ASSERT( src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_2); GGML_ASSERT(tensor->src[3] == nullptr || src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); - GGML_ASSERT( src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_1); + // ggml_flash_attn_ext_banded stores rel_logits [E, n_head, n_q, n_seq] in src[6], split by head like q + GGML_ASSERT( src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; }; From d7bca4fad33972eb9bf7b6b00b56c84a2d1fa900 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 044/115] mtmd : do not require v.patch_embd.weight for the Inkling projector The Inkling vision tower is the hMLP stem (v.hmlp.*), it has no patch embedding, so loading an Inkling mmproj failed with unable to find tensor v.patch_embd.weight. --- tools/mtmd/mtmd-model.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index d9df90349c45..9cb3bb76ab22 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1634,6 +1634,7 @@ struct mtmd_model_loader { const bool has_patch_embd = ( model.modality == MTMD_MODALITY_VISION && model.proj_type != PROJECTOR_TYPE_GEMMA3NV && + model.proj_type != PROJECTOR_TYPE_INKLING && model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR && model.proj_type != PROJECTOR_TYPE_DEEPSEEKOCR2); From e9ecd59e3b834a5c9e826847a5bfb748178499cd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 22:44:26 -0800 Subject: [PATCH 045/115] tests : fail test-flash-attn-bias on non-finite outputs std::max drops NaN, so an output full of NaN reported max_abs 0 and passed. Count a non-finite value as an infinite error. --- tests/test-flash-attn-bias.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index 3337ecac1f13..a7f93df9ace3 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -300,7 +300,9 @@ static void error_stats(const std::vector & got, const std::vector max_abs = 0.0; max_rel = 0.0; for (size_t i = 0; i < got.size(); ++i) { - const double ae = std::abs(double(got[i]) - ref[i]); + // std::max drops NaN, so count a non-finite value as an infinite error + const bool finite = std::isfinite(got[i]) && std::isfinite(ref[i]); + const double ae = finite ? std::abs(double(got[i]) - ref[i]) : INFINITY; const double re = ae/std::max(1e-5, std::abs(double(ref[i]))); max_abs = std::max(max_abs, ae); max_rel = std::max(max_rel, re); From 68df5082797319f0ad957215668ce8ccea742c24 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 23:03:19 -0800 Subject: [PATCH 046/115] CUDA: do not delegate banded attention to MMA when flash attention is compiled out With GGML_CUDA_FA=OFF ggml_cuda_get_best_fattn_kernel() always returns BEST_FATTN_KERNEL_NONE, so delegating aborted. Return false from the MMA helper so the standalone banded kernel runs instead. --- ggml/src/ggml-cuda/fattn.cu | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 78f1fe2d479b..900e1d2108ae 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -577,6 +577,12 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { } bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor * dst) { +#ifndef FLASH_ATTN_AVAILABLE + // with GGML_CUDA_FA=OFF there is no MMA kernel to delegate to, use the standalone banded kernel + GGML_UNUSED(device); GGML_UNUSED(dst); + return false; +#endif // FLASH_ATTN_AVAILABLE + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { return false; } From 210fc2653c6a52f89c2179adf06c91b78dcd0c63 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sun, 22 Nov 2026 23:03:19 -0800 Subject: [PATCH 047/115] CUDA: do not delegate banded attention to MMA when flash attention is compiled out With GGML_CUDA_FA=OFF ggml_cuda_get_best_fattn_kernel() always returns BEST_FATTN_KERNEL_NONE, so delegating aborted. Return false from the MMA helper so the standalone banded kernel runs instead. --- ggml/src/ggml-cuda/fattn.cu | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index a328a82fe4fc..e37b930c9bb8 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -577,6 +577,12 @@ static bool ggml_cuda_fattn_kv_type_supported(const ggml_type type) { } bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor * dst) { +#ifndef FLASH_ATTN_AVAILABLE + // with GGML_CUDA_FA=OFF there is no MMA kernel to delegate to, use the standalone banded kernel + GGML_UNUSED(device); GGML_UNUSED(dst); + return false; +#endif // FLASH_ATTN_AVAILABLE + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { return false; } From 2c38e50c15cb93afa6cac6084a18edc5c8d33f53 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 04:51:33 -0800 Subject: [PATCH 048/115] rpc : count GGML_OP_FLASH_ATTN_EXT_BANDED in the RPC op count Upstream b12635 added an op and moved the RPC check to GGML_OP_COUNT == 101 with RPC_PROTO_PATCH_VERSION 2. This branch adds GGML_OP_FLASH_ATTN_EXT_BANDED on top, so the count is 102 and GGML_RPC=ON builds stop at the static_assert. Bump the check to 102 and the patch version to 3. --- ggml/include/ggml-rpc.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index 062d5004e8d4..5f1444563fc4 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 2 +#define RPC_PROTO_PATCH_VERSION 3 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 From c56bf577091e7015451f73ad889671a5b9c51fce Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 16:56:30 -0800 Subject: [PATCH 049/115] metal : banded FA in the vec kernels, quantized K/V and BF16 rel tables - vec / split-KV kernels (n_q < 20) take FLASH_ATTN_EXT_BANDED: rel[dist] is added after the scale and before the mask, per-query sinks are read through strides (0 for one sink per head) - quantized K/V (q4_0, q4_1, q5_0, q5_1, q8_0) dequantized inline by the half8x8 and vec kernels; banded never takes the F16 copy of the cache, so the compute buffer does not grow with n_kv - BF16 rel tables when the device has bfloat - the vec temp buffer is reserved for banded ops only when the vec kernel runs - tests: Inkling-2-Mini decode / small-batch shapes for F16, q8_0, q4_0, F16/BF16 rel, no mask --- ggml/src/ggml-metal/ggml-metal-device.cpp | 16 ++++--- ggml/src/ggml-metal/ggml-metal-device.h | 4 +- ggml/src/ggml-metal/ggml-metal-device.m | 9 +++- ggml/src/ggml-metal/ggml-metal-impl.h | 7 +++ ggml/src/ggml-metal/ggml-metal-ops.cpp | 27 ++++++++---- ggml/src/ggml-metal/kernels/fa_common.metal | 5 +++ ggml/src/ggml-metal/kernels/fa_tensor.metal | 5 +++ .../ggml-metal/kernels/fa_vec_common.metal | 44 ++++++++++++++++++- tests/test-backend-ops.cpp | 21 +++++++++ 9 files changed, 121 insertions(+), 17 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 82418c7d55b7..436f2c4045f4 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -2056,8 +2056,10 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v int32_t nwg, bool use_kv_f16, int32_t ns10, - int32_t ns20) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + int32_t ns20, + bool has_rel, + int32_t rel_type) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); char base[256]; char name[256]; @@ -2079,7 +2081,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v dv, qne_suffix); - snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d", + snprintf(name, 256, "%s_mask=%d_sink=%d_bias=%d_scap=%d_kvpad=%d_sparse=%d_rows=%d_ns10=%d_ns20=%d_nsg=%d_nwg=%d_rel=%d_rt=%d", base, has_mask, has_sinks, @@ -2090,7 +2092,9 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v has_rows, ns10, ns20, - nsg, nwg); + nsg, nwg, + has_rel, + rel_type); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); if (!res.pipeline) { @@ -2103,11 +2107,13 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v ggml_metal_cv_set_bool(cv, has_kvpad, FC_FLASH_ATTN_EXT_VEC + 4); ggml_metal_cv_set_bool(cv, has_sparse, FC_FLASH_ATTN_EXT_VEC + 5); ggml_metal_cv_set_bool(cv, has_rows, FC_FLASH_ATTN_EXT_VEC + 6); + ggml_metal_cv_set_bool(cv, has_rel, FC_FLASH_ATTN_EXT_VEC + 7); ggml_metal_cv_set_int32(cv, ns10, FC_FLASH_ATTN_EXT_VEC + 20); ggml_metal_cv_set_int32(cv, ns20, FC_FLASH_ATTN_EXT_VEC + 21); ggml_metal_cv_set_int32(cv, nsg, FC_FLASH_ATTN_EXT_VEC + 22); ggml_metal_cv_set_int32(cv, nwg, FC_FLASH_ATTN_EXT_VEC + 23); + ggml_metal_cv_set_int32(cv, rel_type, FC_FLASH_ATTN_EXT_VEC + 24); res = ggml_metal_library_compile_pipeline(lib, base, name, cv); @@ -2122,7 +2128,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v const ggml_tensor * op, int32_t dv, int32_t nwg) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); + assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); char base[256]; char name[256]; diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h index 4baec44610f5..21a5a83bb870 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -250,7 +250,9 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att int32_t nwg, bool use_kv_f16, int32_t ns10, - int32_t ns20); + int32_t ns20, + bool has_rel, + int32_t rel_type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_reduce( ggml_metal_library_t lib, diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 9a60942b4958..538411c537a5 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1849,6 +1849,12 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te switch (op->src[1]->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: + // quantized K/V: dequantized inline by the half8x8 and vec kernels, no F16 copy of the cache + 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: break; case GGML_TYPE_BF16: if (!has_bfloat) { @@ -1858,7 +1864,8 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te default: return false; } - if (rel->type != GGML_TYPE_F32 && rel->type != GGML_TYPE_F16) { + if (rel->type != GGML_TYPE_F32 && rel->type != GGML_TYPE_F16 && + !(rel->type == GGML_TYPE_BF16 && has_bfloat)) { return false; } if (rel->nb[0] != ggml_type_size(rel->type)) { diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index 5ad0a397182a..2e3aa536ace3 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -508,6 +508,13 @@ typedef struct { int32_t n_head_log2; float logit_softcap; int32_t n_kv_max_padded; + int32_t ne_r0; // banded: rel extent, 0 for plain attention + int32_t q_off; // banded: ne11 - ne01 + uint64_t nb_r1; + uint64_t nb_r2; + uint64_t nb_r3; + uint64_t nb_s1; // per-query sinks, 0 for one sink per head + uint64_t nb_s2; } ggml_metal_kargs_flash_attn_ext_vec; typedef struct { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 7eed96405f0e..e8e5421ffac8 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3201,10 +3201,6 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) { bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); - if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { - return false; - } - const int64_t ne00 = op->src[0]->ne[0]; // head size const int64_t ne01 = op->src[0]->ne[1]; // batch size @@ -3219,6 +3215,11 @@ static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 + // banded: the kernels dequantize the KV inline, an F16 copy of the whole cache would grow with n_kv + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + return false; + } + // TODO: tune per device // large heads need the upfront dequant to fit the non-vec threadgroup memory if (op->src[0]->ne[1] < 32 && @@ -3484,7 +3485,8 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { size_t res = 0; - if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + // banded: only the vec kernel (small batches) writes per-workgroup partials + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_metal_op_flash_attn_ext_use_vec(op)) { return res; } @@ -3642,10 +3644,11 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const ggml_tensor * rel = op->op == GGML_OP_FLASH_ATTN_EXT_BANDED ? op->src[6] : nullptr; const bool has_rel = rel != nullptr; - GGML_ASSERT(!has_rel || rel->type == GGML_TYPE_F32 || rel->type == GGML_TYPE_F16); + GGML_ASSERT(!has_rel || rel->type == GGML_TYPE_F32 || rel->type == GGML_TYPE_F16 || rel->type == GGML_TYPE_BF16); GGML_ASSERT(!has_rel || rel->nb[0] == ggml_type_size(rel->type)); - const int32_t rel_type = has_rel && rel->type == GGML_TYPE_F16 ? 1 : 0; + // 0: F32, 1: F16, 2: BF16 + const int32_t rel_type = !has_rel ? 0 : rel->type == GGML_TYPE_F16 ? 1 : rel->type == GGML_TYPE_BF16 ? 2 : 0; const int32_t ne_r0 = has_rel ? (int32_t) rel->ne[0] : 0; const uint64_t nb_r1 = has_rel ? rel->nb[1] : 0; @@ -4338,9 +4341,16 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.n_head_log2 =*/ n_head_log2, /*.logit_softcap =*/ logit_softcap, /*.n_kv_max_padded =*/ n_kv_max_padded, + /*.ne_r0 =*/ ne_r0, + /*.q_off =*/ ne11 - ne01, + /*.nb_r1 =*/ nb_r1, + /*.nb_r2 =*/ nb_r2, + /*.nb_r3 =*/ nb_r3, + /*.nb_s1 =*/ nb_s1, + /*.nb_s2 =*/ nb_s2, }; - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20, has_rel, rel_type); GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); @@ -4352,6 +4362,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, bid_src3, 4); ggml_metal_encoder_set_buffer (enc, bid_src4, 5); ggml_metal_encoder_set_buffer (enc, use_sparse ? bid_idx : (has_rows ? ggml_metal_get_buffer_id(kv_rows) : bid_src0), 8); + ggml_metal_encoder_set_buffer (enc, bid_rel, 9); const size_t smem = fa_vec_smem(nsg, nqptg); diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index e4dc888a0d87..67ca55cd4ac7 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -18,6 +18,11 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + constant int32_t FC_flash_attn_ext_rel_type [[function_constant(FC_FLASH_ATTN_EXT + 23)]]; static inline float flash_attn_ext_rel_load(device const char * rel, int32_t i) { +#if defined(GGML_METAL_HAS_BF16) + if (FC_flash_attn_ext_rel_type == 2) { + return (float) ((device const bfloat *) rel)[i]; + } +#endif if (FC_flash_attn_ext_rel_type == 1) { return ((device const half *) rel)[i]; } diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 5655de05c3b6..5569a00efb82 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -12,6 +12,11 @@ constant bool FC_flash_attn_ext_tensor_has_kvpad [[function_constant(FC_FLASH_AT constant int32_t FC_flash_attn_ext_tensor_rel_type [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 6)]]; static inline float flash_attn_ext_tensor_rel_load(device const char * rel, int32_t i) { +#if defined(GGML_METAL_HAS_BF16) + if (FC_flash_attn_ext_tensor_rel_type == 2) { + return (float) ((device const bfloat *) rel)[i]; + } +#endif if (FC_flash_attn_ext_tensor_rel_type == 1) { return ((device const half *) rel)[i]; } diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index 1a96c6f7ec8b..648e105e67cb 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -14,6 +14,26 @@ constant int32_t FC_flash_attn_ext_vec_nsg [[function_constant(FC_FLASH_ATTN_EX constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EXT_VEC + 23)]]; constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; +constant bool FC_flash_attn_ext_vec_has_rel [[function_constant(FC_FLASH_ATTN_EXT_VEC + 7)]]; +constant int32_t FC_flash_attn_ext_vec_rel_type [[function_constant(FC_FLASH_ATTN_EXT_VEC + 24)]]; + +// banded relative bias (FLASH_ATTN_EXT_BANDED): rel row of one (head, query), indexed by the distance +static inline float flash_attn_ext_vec_rel_load(device const char * rel, int32_t i) { +#if defined(GGML_METAL_HAS_BF16) + if (FC_flash_attn_ext_vec_rel_type == 2) { + return (float) ((device const bfloat *) rel)[i]; + } +#endif + if (FC_flash_attn_ext_vec_rel_type == 1) { + return ((device const half *) rel)[i]; + } + return ((device const float *) rel)[i]; +} + +// the distance of query iq to key ik: queries align to the tail of K (FA4 seqlen_k - seqlen_q convention) +static inline int32_t flash_attn_ext_vec_rel_dist(int32_t iq, int32_t ik, int32_t q_off) { + return iq + q_off - ik; +} template< typename q4_t, // query types in shared memory typename k4_t, // key types in shared memory @@ -44,6 +64,7 @@ kernel void kernel_flash_attn_ext_vec( device const char * pad, device char * dst, device const char * idx, + device const char * rel, threadgroup half * shmem_f16 [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], @@ -393,7 +414,24 @@ kernel void kernel_flash_attn_ext_vec( } FOR_UNROLL (short qq = 0; qq < Q; ++qq) { - if (FC_flash_attn_ext_vec_has_mask && + if (FC_flash_attn_ext_vec_has_rel) { + // banded: score = scale*qk + rel[dist] (0 <= dist < ne_r0) + mask, the CPU reference order + const int32_t iq = iq1*Q + qq; + + mqk[qq][tx] *= args.scale; + + if (iq < args.ne01) { + const int32_t d = flash_attn_ext_vec_rel_dist(iq, ic0*C + NE*tx + ty, args.q_off); + + if (d >= 0 && d < args.ne_r0) { + mqk[qq][tx] += flash_attn_ext_vec_rel_load(rel + iq2*args.nb_r1 + iq*args.nb_r2 + iq3*args.nb_r3, d); + } + } + + mqk[qq][tx] += (qk_t) sm[qq*C + NE*tx + ty]; + + ss[qq*C + NE*tx + ty] = mqk[qq][tx]; + } else if (FC_flash_attn_ext_vec_has_mask && !FC_flash_attn_ext_vec_has_scap && !FC_flash_attn_ext_vec_has_bias) { ss[qq*C + NE*tx + ty] = fma(mqk[qq][tx], args.scale, (qk_t) sm[qq*C + NE*tx + ty]); @@ -568,7 +606,9 @@ kernel void kernel_flash_attn_ext_vec( if (FC_flash_attn_ext_vec_has_sinks && sgitg == 0 && iwg == 0) { FOR_UNROLL (short qq = 0; qq < Q; ++qq) { const float m = M[qq]; - const float s = tiisg == 0 ? ((device const float *) sinks)[iq2] : -FLT_MAX/2; + // per-query sinks (banded): nb_s1/nb_s2 are 0 for one sink per head + const int32_t jq = min(iq1*Q + qq, args.ne01 - 1); + const float s = tiisg == 0 ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) : -FLT_MAX/2; M[qq] = simd_max(max(M[qq], s)); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5132f05adb3d..549da9951ebc 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13811,6 +13811,20 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 1, 1, 65536, 64, 1, 0, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + // Inkling-2-Mini decode and small batches (vec / split-KV kernels on Metal), F16 and quantized K/V, + // ragged and aligned n_kv, sliding-window masks that skip whole KV chunks + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }) { + for (int64_t n_q : { 1, 2, 4, 19, 20 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 1100, 1024, 1, kv_type, GGML_TYPE_F32, 2)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 4096, 1024, 2, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 3, 1000, 96, 2, kv_type, GGML_TYPE_F32, 2, false, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 333, 16, 2, kv_type, GGML_TYPE_F32, 1)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 1000, 96, 1, GGML_TYPE_F16, GGML_TYPE_F16, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 2, 1000, 96, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, 300, 16, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 4, 300, 16, 0, GGML_TYPE_F16, GGML_TYPE_F32, 1)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); @@ -14623,6 +14637,13 @@ static std::vector> make_test_cases_perf() { // banded attention, Inkling-2-Mini prompt processing for (int64_t n_kv : { 4096, 32768 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, n_kv, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, n_kv, 1024, 1, GGML_TYPE_Q8_0, GGML_TYPE_F32, 2)); + } + // banded attention, Inkling-2-Mini decode + for (int64_t n_kv : { 4096, 32768 }) { + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_Q8_0 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, n_kv, 1024, 1, kv_type, GGML_TYPE_F32, 2)); + } } // q8_0 KV cases with long context (decode and prompt) From d24b324c8e6de5629c4b0078bba6a1134511f03f Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 17:13:29 -0800 Subject: [PATCH 050/115] ggml : banded flash attention with cell and query positions ggml_flash_attn_ext_banded_set_pos() gives the banded op the position of each K/V cell (src[7], -1 = empty) and of each query (src[8]), and the distance of the relative bias becomes q_pos - k_pos instead of the cell distance. The mask still separates the sequences and drops the empty cells. This covers the caches whose cells are not the positions: several sequences in one unified cache and a wrapped SWA ring. Without the positions the op and every kernel are unchanged. CPU and the CUDA scalar, split-KV and MMA kernels read the positions; the delegated FA MMA kernel indexes the bias by cell only and is not used with them. --- ggml/include/ggml.h | 9 ++ ggml/src/ggml-backend-meta.cpp | 3 + ggml/src/ggml-cpu/ops.cpp | 15 +++- ggml/src/ggml-cuda/fattn-banded.cu | 81 ++++++++++++++--- ggml/src/ggml-cuda/fattn.cu | 4 +- ggml/src/ggml.c | 19 ++++ tests/test-backend-ops.cpp | 140 +++++++++++++++++++++++++++++ tests/test-flash-attn-bias.cpp | 112 +++++++++++++++++++++-- 8 files changed, 363 insertions(+), 20 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 9fa4c31c4c51..4286055ed69c 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2277,6 +2277,15 @@ extern "C" { float scale, int64_t rel_extent); + // banded attention over a cache whose cells are not the positions (several sequences, a wrapped ring): + // k_pos: [n_kv, 1 or ne3] I32, position of each K/V cell, negative = no bias + // q_pos: [n_batch, 1 or ne3] I32, position of each query + // rel_dist = q_pos[q_idx] - k_pos[kv_idx] replaces the cell distance; the mask still separates sequences + GGML_API void ggml_flash_attn_ext_banded_set_pos( + struct ggml_tensor * a, + struct ggml_tensor * k_pos, + struct ggml_tensor * q_pos); + // same as ggml_flash_attn_ext, but each q slice attends to its own list of K/V rows // q: [n_embd_k, n_batch, n_head, ne3] // k: [n_embd_k, n_rows, n_head_kv, 1 ] shared by all q slices diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 03c1dc3db650..29ad905683dd 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -857,6 +857,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( GGML_ASSERT(tensor->src[3] == nullptr || src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); // ggml_flash_attn_ext_banded stores rel_logits [E, n_head, n_q, n_seq] in src[6], split by head like q GGML_ASSERT( src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); + // the optional K/V cell and query positions are shared by every head + GGML_ASSERT(tensor->src[7] == nullptr || src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + GGML_ASSERT(tensor->src[8] == nullptr || src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; }; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index e59eeebeaceb..a28beeca7012 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8993,6 +8993,19 @@ static inline float ggml_flash_attn_ext_banded_load( } } +// distance of query iq1 to cell ic: q_pos - k_pos with the positions (src[7], src[8]), else the cell distance +// aligned to the tail of K (FA4 seqlen_k - seqlen_q convention); -1 for an empty cell +static inline int64_t ggml_flash_attn_ext_banded_dist(const ggml_tensor * dst, int64_t iq1, int64_t iq3, int64_t ic) { + const ggml_tensor * k_pos = dst->src[7]; + const ggml_tensor * q_pos = dst->src[8]; + if (!k_pos) { + return iq1 + (dst->src[1]->ne[1] - dst->src[0]->ne[1]) - ic; + } + const int32_t kp = *(const int32_t *) ((const char *) k_pos->data + ic*k_pos->nb[0] + (iq3 % k_pos->ne[1])*k_pos->nb[1]); + const int32_t qp = *(const int32_t *) ((const char *) q_pos->data + iq1*q_pos->nb[0] + (iq3 % q_pos->ne[1])*q_pos->nb[1]); + return kp < 0 ? -1 : int64_t(qp) - kp; +} + static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_compute_params * params, ggml_tensor * dst, @@ -9140,7 +9153,7 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( if (rel) { // the offset aligns a short decode Q block to the tail of K (FA4 seqlen_k - seqlen_q convention) - const int64_t rel_dist = iq1 + (nek1 - neq1) - ic; + const int64_t rel_dist = ggml_flash_attn_ext_banded_dist(dst, iq1, iq3, ic); if (rel_dist >= 0 && rel_dist < rel->ne[0]) { s += ggml_flash_attn_ext_banded_load(rel, iq1, iq2, iq3, rel_dist); } diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 4005e5c4670f..0302419dc22a 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -23,6 +23,17 @@ static __device__ __forceinline__ float fattn_banded_load( } } +// distance of query iq to cell ik: the cell distance, or q_pos - k_pos when the cells are not the positions +static __device__ __forceinline__ int64_t fattn_banded_dist( + const int32_t * __restrict__ k_pos, const int32_t * __restrict__ q_pos, const int64_t iq, const int64_t ik, + const int64_t q_offset) { + if (k_pos) { + const int32_t kp = k_pos[ik]; + return kp < 0 ? -1 : int64_t(q_pos[iq]) - kp; + } + return iq + q_offset - ik; +} + template static __global__ void flash_attn_ext_banded_f32( const char * __restrict__ q, @@ -64,7 +75,11 @@ static __global__ void flash_attn_ext_banded_f32( uint64_t r_nb1, uint64_t r_nb2, uint64_t r_nb3, - int64_t rel_ne3) { + int64_t rel_ne3, + const int32_t * __restrict__ k_pos, + const int32_t * __restrict__ q_pos, + int64_t kpos_s1, + int64_t qpos_s1) { constexpr int values_per_lane = D / WARP_SIZE; static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); static_assert(D % WARP_SIZE == 0, "head dimension must be divisible by warp size"); @@ -81,6 +96,8 @@ static __global__ void flash_attn_ext_banded_f32( const int64_t ih_kv = ih / (n_head_q / n_head_kv); const char * q_row = q + uint64_t(iq)*q_nb1 + uint64_t(ih)*q_nb2 + uint64_t(ib)*q_nb3; + const int32_t * kp = k_pos ? k_pos + ib*kpos_s1 : nullptr; + const int32_t * qp = q_pos ? q_pos + ib*qpos_s1 : nullptr; float q_reg[values_per_lane]; float out[values_per_lane]; @@ -113,7 +130,7 @@ static __global__ void flash_attn_ext_banded_f32( float score = dot * scale; if (lane == 0) { - const int64_t rel_dist = iq + q_offset - ik; + const int64_t rel_dist = fattn_banded_dist(kp, qp, iq, ik, q_offset); if (rel_dist >= 0 && rel_dist < rel_extent) { const char * rel_value = rel + uint64_t(rel_dist)*r_nb0 + uint64_t(ih)*r_nb1 + @@ -216,7 +233,11 @@ static __global__ void flash_attn_ext_banded_f32_split( uint64_t r_nb1, uint64_t r_nb2, uint64_t r_nb3, - int64_t rel_ne3) { + int64_t rel_ne3, + const int32_t * __restrict__ k_pos, + const int32_t * __restrict__ q_pos, + int64_t kpos_s1, + int64_t qpos_s1) { constexpr int values_per_lane = D / WARP_SIZE; static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); @@ -229,6 +250,8 @@ static __global__ void flash_attn_ext_banded_f32_split( const int64_t ih_kv = ih / (n_head_q / n_head_kv); const char * q_row = q + uint64_t(iq)*q_nb1 + uint64_t(ih)*q_nb2 + uint64_t(ib)*q_nb3; + const int32_t * kp = k_pos ? k_pos + ib*kpos_s1 : nullptr; + const int32_t * qp = q_pos ? q_pos + ib*qpos_s1 : nullptr; float q_reg[values_per_lane]; float out[values_per_lane]; @@ -263,7 +286,7 @@ static __global__ void flash_attn_ext_banded_f32_split( float score = dot * scale; if (lane == 0) { - const int64_t rel_dist = iq + q_offset - ik; + const int64_t rel_dist = fattn_banded_dist(kp, qp, iq, ik, q_offset); if (rel_dist >= 0 && rel_dist < rel_extent) { const char * rel_value = rel + uint64_t(rel_dist)*r_nb0 + uint64_t(ih)*r_nb1 + @@ -634,7 +657,11 @@ static __global__ void flash_attn_ext_banded_mma( uint64_t r_nb3, int64_t rel_ne3, int64_t sinks_s1, - int64_t sinks_s2) { + int64_t sinks_s2, + const int32_t * __restrict__ k_pos, + const int32_t * __restrict__ q_pos, + int64_t kpos_s1, + int64_t qpos_s1) { #ifdef FATTN_BANDED_MMA_AVAILABLE static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); constexpr int BK = fattn_banded_mma_bk; @@ -671,6 +698,8 @@ static __global__ void flash_attn_ext_banded_mma( const char * m_base = mask ? mask + uint64_t(ih % mask_ne2)*m_nb2 + uint64_t(ib % mask_ne3)*m_nb3 : nullptr; const uint8_t * f_base = flags ? flags + ((ih % mask_ne2) + mask_ne2*(ib % mask_ne3))*n_qt*n_kt + qt*n_kt : nullptr; const char * r_base = rel + uint64_t(ih)*r_nb1 + uint64_t(ib % rel_ne3)*r_nb3; + const int32_t * kp = k_pos ? k_pos + ib*kpos_s1 : nullptr; + const int32_t * qp = q_pos ? q_pos + ib*qpos_s1 : nullptr; uint32_t Q_a[NK][4]; #pragma unroll @@ -745,7 +774,8 @@ static __global__ void flash_attn_ext_banded_mma( const int64_t dist_hi = iq_w + 15 + q_offset - kv0; const int64_t dist_lo = iq_w + q_offset - (kv0 + BK - 1); - const bool in_band = dist_hi >= 0 && dist_lo < rel_extent; + // with positions the band is not a cell range: test every element + const bool in_band = kp || (dist_hi >= 0 && dist_lo < rel_extent); #pragma unroll for (int j = 0; j < BK/8; ++j) { @@ -758,7 +788,7 @@ static __global__ void flash_attn_ext_banded_mma( s = -INFINITY; } else if (iq_r[r] < n_q) { if (in_band) { - const int64_t dist = iq_r[r] + q_offset - ik; + const int64_t dist = fattn_banded_dist(kp, qp, iq_r[r], ik, q_offset); if (dist >= 0 && dist < rel_extent) { s += fattn_banded_load(r_base + uint64_t(dist)*r_nb0 + uint64_t(iq_r[r])*r_nb2, type_rel); } @@ -883,7 +913,8 @@ static __global__ void flash_attn_ext_banded_mma( #else GGML_UNUSED_VARS(q, k, v, mask, flags, rel, sinks, dst, part, scale, type_rel, n_q, n_kv, n_head_q, n_head_kv, n_chunks, tiles_per_chunk, rel_extent, mask_ne2, mask_ne3, q_nb1, q_nb2, q_nb3, k_nb1, k_nb2, k_nb3, - v_nb1, v_nb2, v_nb3, m_nb1, m_nb2, m_nb3, r_nb0, r_nb1, r_nb2, r_nb3, rel_ne3, sinks_s1, sinks_s2); + v_nb1, v_nb2, v_nb3, m_nb1, m_nb2, m_nb3, r_nb0, r_nb1, r_nb2, r_nb3, rel_ne3, sinks_s1, sinks_s2, + k_pos, q_pos, kpos_s1, qpos_s1); NO_DEVICE_CODE; #endif // FATTN_BANDED_MMA_AVAILABLE } @@ -972,6 +1003,17 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float))) { return false; } + const ggml_tensor * k_pos = dst->src[7]; + const ggml_tensor * q_pos = dst->src[8]; + if ((k_pos == nullptr) != (q_pos == nullptr)) { + return false; + } + if (k_pos && (k_pos->type != GGML_TYPE_I32 || q_pos->type != GGML_TYPE_I32 || + !ggml_is_contiguous(k_pos) || !ggml_is_contiguous(q_pos) || + k_pos->ne[0] != k->ne[1] || q_pos->ne[0] != q->ne[1] || + (k_pos->ne[1] != 1 && k_pos->ne[1] != q->ne[3]) || (q_pos->ne[1] != 1 && q_pos->ne[1] != q->ne[3]))) { + return false; + } return !m || (m->type == GGML_TYPE_F16 && ggml_is_contiguous(m) && q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0); #endif @@ -1125,6 +1167,13 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor const int64_t sinks_s1 = sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0; const int64_t sinks_s2 = sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0; + const ggml_tensor * k_pos = dst->src[7]; + const ggml_tensor * q_pos = dst->src[8]; + const int32_t * k_pos_d = k_pos ? (const int32_t *) k_pos->data : nullptr; + const int32_t * q_pos_d = q_pos ? (const int32_t *) q_pos->data : nullptr; + const int64_t kpos_s1 = k_pos && k_pos->ne[1] > 1 ? k_pos->ne[0] : 0; + const int64_t qpos_s1 = q_pos && q_pos->ne[1] > 1 ? q_pos->ne[0] : 0; + const dim3 blocks(n_qt*n_chunks, q->ne[2], q->ne[3]); #define LAUNCH_BANDED_MMA_T(DD, NW, T) \ flash_attn_ext_banded_mma<<>>( \ @@ -1134,7 +1183,8 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor m ? m->ne[2] : 1, m ? m->ne[3] : 1, q->nb[1], q->nb[2], q->nb[3], \ k_nb[1], k_nb[2], k_nb[3], v_nb[1], v_nb[2], v_nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2) + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2, \ + k_pos_d, q_pos_d, kpos_s1, qpos_s1) #define LAUNCH_BANDED_MMA(DD, NW) \ switch (type_kv) { \ case GGML_TYPE_Q8_0: LAUNCH_BANDED_MMA_T(DD, NW, GGML_TYPE_Q8_0); break; \ @@ -1197,6 +1247,13 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso return; } + const ggml_tensor * k_pos = dst->src[7]; + const ggml_tensor * q_pos = dst->src[8]; + const int32_t * k_pos_d = k_pos ? (const int32_t *) k_pos->data : nullptr; + const int32_t * q_pos_d = q_pos ? (const int32_t *) q_pos->data : nullptr; + const int64_t kpos_s1 = k_pos && k_pos->ne[1] > 1 ? k_pos->ne[0] : 0; + const int64_t qpos_s1 = q_pos && q_pos->ne[1] > 1 ? q_pos->ne[0] : 0; + // the scalar kernels read F32 / F16 / BF16 elements: other K/V types go through an F16 copy ggml_cuda_pool_alloc k_f16(ctx.pool()); ggml_cuda_pool_alloc v_f16(ctx.pool()); @@ -1237,7 +1294,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso q->nb[1], q->nb[2], q->nb[3], k->nb[0], k->nb[1], k->nb[2], k->nb[3], \ v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]); \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], \ + k_pos_d, q_pos_d, kpos_s1, qpos_s1); \ flash_attn_ext_banded_f32_merge
<<>>( \ part.get(), (float *) dst->data, n_rows, q->ne[2], q->ne[1], n_chunks, \ sinks ? (const float *) sinks->data : nullptr, \ @@ -1270,7 +1328,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso sinks ? (const float *) sinks->data : nullptr, \ sinks && sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0, \ sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]) + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], \ + k_pos_d, q_pos_d, kpos_s1, qpos_s1) if (q->ne[0] == 64) { LAUNCH_BANDED(64); diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index e37b930c9bb8..3078afa26c1e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -596,8 +596,8 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } - // the MMA kernel passes rel in the sinks slot - if (dst->src[4]) { + // the MMA kernel passes rel in the sinks slot, and indexes it by cell distance only + if (dst->src[4] || dst->src[7]) { return false; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index bc4fca3513b4..74805ab9cbc8 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5537,6 +5537,25 @@ struct ggml_tensor * ggml_flash_attn_ext_banded( return result; } +void ggml_flash_attn_ext_banded_set_pos( + struct ggml_tensor * a, + struct ggml_tensor * k_pos, + struct ggml_tensor * q_pos) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT_BANDED); + GGML_ASSERT((k_pos == NULL) == (q_pos == NULL)); + if (k_pos) { + const struct ggml_tensor * q = a->src[0]; + const struct ggml_tensor * k = a->src[1]; + GGML_ASSERT(k_pos->type == GGML_TYPE_I32 && ggml_is_contiguous(k_pos)); + GGML_ASSERT(q_pos->type == GGML_TYPE_I32 && ggml_is_contiguous(q_pos)); + GGML_ASSERT(k_pos->ne[0] == k->ne[1] && (k_pos->ne[1] == 1 || k_pos->ne[1] == q->ne[3])); + GGML_ASSERT(q_pos->ne[0] == q->ne[1] && (q_pos->ne[1] == 1 || q_pos->ne[1] == q->ne[3])); + GGML_ASSERT(k_pos->ne[2] == 1 && k_pos->ne[3] == 1 && q_pos->ne[2] == 1 && q_pos->ne[3] == 1); + } + a->src[7] = k_pos; + a->src[8] = q_pos; +} + struct ggml_tensor * ggml_flash_attn_ext( struct ggml_context * ctx, struct ggml_tensor * q, diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 635a9ccda334..c1fa62d6e577 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9445,6 +9445,133 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } }; +// banded attention with cell and query positions: the cells are not the positions +// layout 1: n_seq sequences interleaved in one unified cache, layout 2: one sequence in a wrapped ring cache +// some cells are empty (position -1, masked); the mask separates the sequences and, for mask_kind 2, keeps the window +struct test_flash_attn_ext_banded_pos : public test_case { + const int64_t d; + const int64_t n_head; + const int64_t n_head_kv; + const int64_t n_q; + const int64_t n_kv; + const int64_t rel_extent; + const int layout; + const int64_t n_seq; + const int mask_kind; + const ggml_type kv_type; + const ggml_type rel_type; + + std::string vars() override { + return VARS_TO_STR11(d, n_head, n_head_kv, n_q, n_kv, rel_extent, layout, n_seq, mask_kind, kv_type, rel_type); + } + + double max_nmse_err() override { + if (kv_type == GGML_TYPE_F32 && rel_type == GGML_TYPE_F32) { + return 2e-6; + } + return n_kv > 8192 ? 1e-3 : 5e-4; + } + + uint64_t op_flops(ggml_tensor * t) override { + GGML_UNUSED(t); + return 4*n_head*n_q*n_kv*d; + } + + test_flash_attn_ext_banded_pos(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + int layout, int64_t n_seq, int mask_kind, ggml_type kv_type, ggml_type rel_type) + : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), + layout(layout), n_seq(n_seq), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, n_q); + ggml_tensor * kp = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_kv); + ggml_tensor * qp = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_q); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + ggml_set_name(m, "m"); + ggml_set_name(s, "sinks"); + ggml_set_name(kp, "k_pos"); + ggml_set_name(qp, "q_pos"); + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); + ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_banded_set_pos(out, kp, qp); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + // cell -> (sequence, position), position -1 = empty; query -> (sequence, position) + void layout_cells(std::vector & k_seq, std::vector & k_pos, std::vector & q_seq, std::vector & q_pos) const { + k_seq.assign(n_kv, -1); + k_pos.assign(n_kv, -1); + q_seq.assign(n_q, 0); + q_pos.assign(n_q, 0); + if (layout == 1) { + // cell j of sequence j % n_seq at position j / n_seq, the last n_q cells are the queries, every 7th cell empty + for (int64_t j = 0; j < n_kv; ++j) { + if (j % 7 != 3 || j >= n_kv - n_q) { + k_seq[j] = int32_t(j % n_seq); + k_pos[j] = int32_t(j / n_seq); + } + } + for (int64_t i = 0; i < n_q; ++i) { + const int64_t j = n_kv - n_q + i; + q_seq[i] = int32_t(j % n_seq); + q_pos[i] = int32_t(j / n_seq); + } + } else { + // one sequence of n_total positions in a ring of n_kv cells: cell p % n_kv holds position p, the queries are the last n_q + const int64_t n_total = 3*n_kv + n_kv/3 + 1; + for (int64_t p = 0; p < n_total; ++p) { + k_seq[p % n_kv] = 0; + k_pos[p % n_kv] = int32_t(p); + } + k_seq[(n_total + 5) % n_kv] = -1; // an empty cell outside the queries + k_pos[(n_total + 5) % n_kv] = -1; + for (int64_t i = 0; i < n_q; ++i) { + q_pos[i] = int32_t(n_total - n_q + i); + } + } + } + + void initialize_tensors(ggml_context * ctx) override { + std::vector k_seq, k_pos, q_seq, q_pos; + layout_cells(k_seq, k_pos, q_seq, q_pos); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + std::vector data(n_q*n_kv); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < n_kv; ++ik) { + const int64_t dist = int64_t(q_pos[iq]) - k_pos[ik]; + const bool visible = k_pos[ik] >= 0 && k_seq[ik] == q_seq[iq] && dist >= 0 && + (mask_kind != 2 || dist < rel_extent); + data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (strcmp(t->name, "k_pos") == 0) { + ggml_backend_tensor_set(t, k_pos.data(), 0, k_pos.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "q_pos") == 0) { + ggml_backend_tensor_set(t, q_pos.data(), 0, q_pos.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "rel_logits") == 0) { + init_tensor_uniform(t, -1.0f, 1.0f); + } else if (strcmp(t->name, "sinks") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + // large Q values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { static constexpr int q_range = 20; @@ -13611,6 +13738,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 1, 64, 64, 512, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 17, 33, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, true)); + // cells that are not the positions: several sequences in a unified cache, a wrapped SWA ring + for (ggml_type kv_type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { + // decode (one token per sequence, split-KV), short and long prefill (MMA tiles) + for (int64_t nq : {4, 17, 64, 130}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, nq, 1024, 256, 1, 4, 1, kv_type, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos( 64, 8, 1, nq, 512, 64, 2, 1, 2, kv_type, GGML_TYPE_F32)); + } + } + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 1, 4096, 1024, 1, 4, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 64, 4096, 1024, 1, 3, 1, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 512, 2048, 512, 2, 1, 2, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, 33, 700, 32, 1, 2, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos( 64, 8, 2, 7, 300, 16, 2, 1, 1, GGML_TYPE_F16, GGML_TYPE_F16)); for (int sinks : {1, 2}) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 1, 64, 8, 1, GGML_TYPE_F32, GGML_TYPE_F32, sinks)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 33, 64, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, sinks)); diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index a7f93df9ace3..2d7a0e2600ee 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -29,6 +29,11 @@ struct bias_test_config { bool strided_rel = false; float v_scale = 1.0f; float v_bias = 0.0f; + // 0: the cells are the positions; 1: n_seq sequences interleaved in one cache; 2: a wrapped ring of one sequence + int layout = 0; + int64_t n_seq = 1; + // layout 1: empty cells after the last query, as the cache pads n_kv (a cell offset would shift every distance) + int64_t n_pad = 0; }; struct test_data { @@ -44,8 +49,53 @@ struct test_data { std::vector v_rounded; std::vector rel_rounded; std::vector dense_bias; + // cell and query positions of the banded op (layout != 0), -1 = empty cell + std::vector k_pos; + std::vector q_pos; }; +// cell -> (sequence, position), query -> (sequence, position) of a layout; empty cells have position -1 +static void make_layout(const bias_test_config & c, std::vector & k_seq, std::vector & k_pos, + std::vector & q_seq, std::vector & q_pos) { + k_seq.assign(c.nkv, -1); + k_pos.assign(c.nkv, -1); + q_seq.assign(c.nq, 0); + q_pos.assign(c.nq, 0); + if (c.layout == 0) { + for (int64_t j = 0; j < c.nkv; ++j) { + k_seq[j] = 0; + k_pos[j] = int32_t(j); + } + for (int64_t i = 0; i < c.nq; ++i) { + q_pos[i] = int32_t(i + c.nkv - c.nq); + } + } else if (c.layout == 1) { + const int64_t n_used = c.nkv - c.n_pad; + for (int64_t j = 0; j < n_used; ++j) { + if (j % 7 != 3 || j >= n_used - c.nq) { + k_seq[j] = int32_t(j % c.n_seq); + k_pos[j] = int32_t(j / c.n_seq); + } + } + for (int64_t i = 0; i < c.nq; ++i) { + const int64_t j = n_used - c.nq + i; + q_seq[i] = int32_t(j % c.n_seq); + q_pos[i] = int32_t(j / c.n_seq); + } + } else { + const int64_t n_total = 3*c.nkv + c.nkv/3 + 1; + for (int64_t p = 0; p < n_total; ++p) { + k_seq[p % c.nkv] = 0; + k_pos[p % c.nkv] = int32_t(p); + } + k_seq[(n_total + 5) % c.nkv] = -1; + k_pos[(n_total + 5) % c.nkv] = -1; + for (int64_t i = 0; i < c.nq; ++i) { + q_pos[i] = int32_t(n_total - c.nq + i); + } + } +} + struct run_result { std::vector output; size_t allocated_bytes; @@ -102,10 +152,16 @@ static test_data make_data(const bias_test_config & c) { } } } + std::vector k_seq, q_seq; + make_layout(c, k_seq, data.k_pos, q_seq, data.q_pos); + // the distance of a query to a cell, -1 if the cell is empty + auto distance = [&](int64_t iq, int64_t ik) -> int64_t { + return data.k_pos[ik] < 0 ? -1 : int64_t(data.q_pos[iq]) - data.k_pos[ik]; + }; for (int64_t iq = 0; iq < c.nq; ++iq) { for (int64_t ik = 0; ik < c.nkv; ++ik) { - const int64_t dist = iq + (c.nkv - c.nq) - ik; - const bool visible = !c.use_mask || (dist >= 0 && (!c.sliding || dist < c.extent)); + const int64_t dist = distance(iq, ik); + const bool visible = !c.use_mask || (dist >= 0 && k_seq[ik] == q_seq[iq] && (!c.sliding || dist < c.extent)); data.mask[iq*c.nkv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } @@ -120,7 +176,7 @@ static test_data make_data(const bias_test_config & c) { for (int64_t ih = 0; ih < c.hq; ++ih) { for (int64_t iq = 0; iq < c.nq; ++iq) { for (int64_t ik = 0; ik < c.nkv; ++ik) { - const int64_t dist = iq + (c.nkv - c.nq) - ik; + const int64_t dist = distance(iq, ik); if (dist >= 0 && dist < c.extent) { data.dense_bias[((ib*c.hq + ih)*c.nq + iq)*c.nkv + ik] = data.rel_rounded[((irb*c.nq + iq)*c.hq + ih)*c.extent + dist]; @@ -137,7 +193,8 @@ static run_result run_graph( const bias_test_config & c, const test_data & data, bool dense, - int repeats) { + int repeats, + bool with_pos = false) { ggml_init_params params = { /* .mem_size = */ ggml_tensor_overhead()*64 + ggml_graph_overhead_custom(64, false), /* .mem_base = */ nullptr, @@ -171,8 +228,15 @@ static run_result run_graph( ggml_tensor * out; ggml_tensor * bias = nullptr; + ggml_tensor * kp = nullptr; + ggml_tensor * qp = nullptr; if (!dense) { out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, m, r, 1.0f/float(c.d), c.extent); + if (with_pos || c.layout != 0) { + kp = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, c.nkv); + qp = ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, c.nq); + ggml_flash_attn_ext_banded_set_pos(out, kp, qp); + } } else { bias = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.nkv, c.nq, c.hq, c.n_batch); ggml_set_name(bias, "dense_bias"); @@ -217,6 +281,10 @@ static run_result run_graph( if (bias) { ggml_backend_tensor_set(bias, data.dense_bias.data(), 0, data.dense_bias.size()*sizeof(float)); } + if (kp) { + ggml_backend_tensor_set(kp, data.k_pos.data(), 0, data.k_pos.size()*sizeof(int32_t)); + ggml_backend_tensor_set(qp, data.q_pos.data(), 0, data.q_pos.size()*sizeof(int32_t)); + } ggml_cgraph * graph = ggml_new_graph_custom(ctx.get(), 64, false); ggml_build_forward_expand(graph, out); @@ -506,12 +574,25 @@ int main(int argc, char ** argv) { {"decode_8k_e1024", 128, 1, 8192, 8, 1, 1024, GGML_TYPE_F16, true, false}, {"large_v_16k", 128, 16, 16384, 8, 1, 1024, GGML_TYPE_F16, true, false, 1, 1, false, 512.0f, 1.0f}, }; + } else if (suite == "pos") { + // the cells are not the positions: several sequences in one unified cache, a wrapped SWA ring + configs = { + {"multiseq_decode", 128, 4, 1024, 8, 2, 256, GGML_TYPE_F16, true, false, 1, 1, false, 1.0f, 0.0f, 1, 4}, + {"multiseq_prefill", 128, 64, 1024, 8, 2, 256, GGML_TYPE_F16, true, false, 1, 1, false, 1.0f, 0.0f, 1, 4}, + {"multiseq_f32", 64, 17, 700, 8, 2, 64, GGML_TYPE_F32, true, true, 1, 1, false, 1.0f, 0.0f, 1, 3}, + {"multiseq_bf16", 128, 130, 2048, 8, 1, 512, GGML_TYPE_BF16, true, false, 1, 1, false, 1.0f, 0.0f, 1, 2}, + {"padded_decode", 128, 4, 512, 8, 2, 256, GGML_TYPE_F16, true, false, 1, 1, false, 1.0f, 0.0f, 1, 4, 255}, + {"padded_prefill", 128, 64, 1280, 8, 2, 512, GGML_TYPE_F16, true, false, 1, 1, false, 1.0f, 0.0f, 1, 2, 250}, + {"wrapped_decode", 128, 1, 768, 8, 2, 512, GGML_TYPE_F16, true, true, 1, 1, false, 1.0f, 0.0f, 2, 1}, + {"wrapped_prefill", 128, 256, 1024, 8, 2, 512, GGML_TYPE_F16, true, true, 1, 1, false, 1.0f, 0.0f, 2, 1}, + {"wrapped_f32", 64, 33, 300, 8, 2, 64, GGML_TYPE_F32, true, true, 1, 1, false, 1.0f, 0.0f, 2, 1}, + }; } else if (suite == "hard") { configs = { {"heads64_gqa", 64, 1024, 1024, 64, 8, 512, GGML_TYPE_F16, true, false}, }; } else { - fprintf(stderr, "unknown suite: %s (expected small, medium, hard, perf, memory, or overflow)\n", + fprintf(stderr, "unknown suite: %s (expected small, medium, pos, hard, perf, memory, or overflow)\n", suite.c_str()); return 2; } @@ -529,7 +610,26 @@ int main(int argc, char ** argv) { double abs_naive = 0.0, mean_abs_naive = 0.0, rel_naive = 0.0, mean_rel_naive = 0.0, rmse_naive = 0.0; error_stats(flash.output, naive, abs_naive, mean_abs_naive, rel_naive, mean_rel_naive, rmse_naive); const double tol = (c.type == GGML_TYPE_F32 ? 2e-5 : 2e-3)*std::max(1.0f, c.v_scale); - const bool pass = abs_naive <= tol; + bool pass = abs_naive <= tol; + if (c.layout != 0) { + // the outputs are small: relative to their scale, so that a bias at the wrong distances fails + double scale = 0.0; + for (float x : naive) { + scale = std::max(scale, (double) std::fabs(x)); + } + printf("%s naive_scale=%.9g naive_max_abs_rel=%.9g\n", c.name, scale, abs_naive/scale); + pass = pass && abs_naive <= 1e-4*scale; + } + if (c.layout == 0) { + // the positions of cells that are the positions: bit for bit on the CPU, where both run the same loop; + // a GPU may pick another kernel for the cell distance (the delegated FA kernel), so within tol there + const run_result with_pos = run_graph(backend.get(), c, data, false, 1, true); + double abs_pos, mean_abs_pos, rel_pos, mean_rel_pos, rmse_pos; + error_stats(with_pos.output, flash.output, abs_pos, mean_abs_pos, rel_pos, mean_rel_pos, rmse_pos); + const bool same = backend_kind == "cpu" ? abs_pos == 0.0 : abs_pos <= tol; + printf("%s identity_positions_max_abs=%.9g %s\n", c.name, abs_pos, same ? "SAME" : "DIFFER"); + pass = pass && same; + } ok = ok && pass; printf("%s type=%s D=%lld nq=%lld nkv=%lld hq=%lld hkv=%lld E=%lld mask=%d sliding=%d " "batch=%lld rel_batch=%lld strided_rel=%d " From d262c423d714dab56044da71ed7f48f0dcc2af3f Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 17:13:29 -0800 Subject: [PATCH 051/115] inkling2 : banded attention when the cells are not the positions A ubatch of several sequences in a unified cache, a sequence whose cells are not one run (a gap) and the SWA layers once their ring cache wraps took the dense relative bias, n_kv x n_tokens x n_head, and the reserve graph sized for it. They now take the banded op with the cell positions (attn_inp_k_pos, n_kv I32 per cache) and the ubatch positions, so the reserve graph is banded for several sequences and for the SWA layers. The contiguous single-sequence path is unchanged. Small ubatches stay dense as before. LLAMA_INKLING_BANDED_POS=0 restores the previous dense routing and reserve. LLAMA_INKLING_BANDED_POS=2 takes the positions for every banded ubatch, a check on the real model: where the cells are the positions it must give the result of the cell distance. --- src/llama-graph.cpp | 21 +++++++++++++++-- src/llama-graph.h | 10 ++++++++ src/llama-kv-cache.cpp | 16 +++++++++++++ src/llama-kv-cache.h | 2 ++ src/models/inkling2.cpp | 52 ++++++++++++++++++++++++++++++++++++----- src/models/models.h | 2 ++ 6 files changed, 95 insertions(+), 8 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 0b5ad710d68e..bfc3d77d4857 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1418,6 +1418,12 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); } + for (int i = 0; i < 2; ++i) { + if (self_k_pos[i] && self_k_pos[i]->buffer) { + (i ? attn_ctx->get_swa() : attn_ctx->get_base())->set_input_cell_pos(self_k_pos[i], ubatch); + } + } + // 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); @@ -1445,6 +1451,14 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) } } +uint32_t llm_graph_input_mem_hybrid_iswa_rel::get_n_kv_banded( + const llama_kv_cache_context * kv, const llama_ubatch & ubatch, int banded_pos, bool & use_pos) { + // one sequence whose cells are its positions: the cell distance is the position distance + const uint32_t n_kv_contiguous = ubatch.n_seqs_unq == 1 ? kv->get_n_kv_pos_contiguous() : 0; + use_pos = banded_pos != 0 && (n_kv_contiguous == 0 || banded_pos == 2); + return n_kv_contiguous > 0 ? n_kv_contiguous : (use_pos ? kv->get_n_kv() : 0); +} + bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { const auto * mctx = static_cast(params.mctx); @@ -1477,8 +1491,11 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; if (banded) { - res &= attn_ctx->get_base()->get_n_kv_pos_contiguous() == n_kv_banded[0]; - res &= attn_ctx->get_swa()->get_n_kv_pos_contiguous() == n_kv_banded[1]; + for (int i = 0; i < 2; ++i) { + bool use_pos = false; + res &= get_n_kv_banded(i ? attn_ctx->get_swa() : attn_ctx->get_base(), params.ubatch, banded_pos, use_pos) == n_kv_banded[i]; + res &= use_pos == (self_k_pos[i] != nullptr); + } } res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 3c0b141294e4..e782b2a93f6a 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -815,6 +815,16 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { uint32_t n_kv_banded[2] = { 0, 0 }; bool banded = false; + // [base, swa] I32 [n_kv] position of each cell (-1 if empty), when the banded attention takes the distances + // from the positions: the cells of several sequences, or a wrapped cache. Null when the cells are the positions + ggml_tensor * self_k_pos[2] = { nullptr, nullptr }; + // the banded attention may take the positions (1), else those ubatches are dense (0); 2 takes them for every + // banded ubatch, also when the cells are the positions (a check: the result must not change) + int banded_pos = 0; + + // [base, swa] cells of the banded attention for a ubatch, and whether it takes the positions + static uint32_t get_n_kv_banded(const llama_kv_cache_context * kv, const llama_ubatch & ubatch, int banded_pos, bool & use_pos); + const uint32_t extent; const uint32_t extent_swa; diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 87957aad9635..f8a1b2619f30 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2109,6 +2109,18 @@ void llama_kv_cache::set_input_relative_pos(ggml_tensor * dst, const llama_ubatc ggml_backend_tensor_set(dst, data.data(), 0, ggml_nbytes(dst)); } +void llama_kv_cache::set_input_cell_pos(ggml_tensor * dst, const llama_ubatch * ubatch) const { + GGML_ASSERT(dst->type == GGML_TYPE_I32); + const int64_t n_kv = dst->ne[0]; + const auto & cells = v_cells.at(seq_to_stream.at(ubatch->seq_id[0][0])); + GGML_ASSERT(n_kv <= (int64_t) cells.size()); + std::vector data(n_kv); + for (int64_t j = 0; j < n_kv; ++j) { + data[j] = cells.is_empty(j) ? -1 : cells.pos_get(j); + } + ggml_backend_tensor_set(dst, data.data(), 0, ggml_nbytes(dst)); +} + void llama_kv_cache::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { const uint32_t n_tokens = ubatch.n_tokens; @@ -3237,6 +3249,10 @@ void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const lla kv->set_input_relative_pos(dst, ubatch, extent); } +void llama_kv_cache_context::set_input_cell_pos(ggml_tensor * dst, const llama_ubatch * ubatch) const { + kv->set_input_cell_pos(dst, ubatch); +} + void llama_kv_cache_context::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const { kv->get_prev_tokens(ubatch, n, res); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 605b55f0a65f..3e53799d1d2e 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -253,6 +253,7 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_cell_pos (ggml_tensor * dst, const llama_ubatch * ubatch) const; // idx(i, j) = i*(extent + 1) + rel; out-of-band cells map to the zero column `extent` void set_input_pos_rel_flat(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; @@ -463,6 +464,7 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; + void set_input_cell_pos (ggml_tensor * dst, const llama_ubatch * ubatch) const; // see llama_kv_cache::get_prev_tokens() void get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector & res) const; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 34dba7423764..01a6349e7bcb 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -10,6 +10,17 @@ static constexpr int64_t n_kq_chunk_max = 64; // ubatches up to this many tokens keep the dense path static constexpr int64_t n_tokens_banded_min = 32; +// the banded attention takes the distances from the positions when the cells are not the positions +// (several sequences in a unified cache, a wrapped SWA cache); LLAMA_INKLING_BANDED_POS=0 keeps those dense, +// =2 takes the positions for every banded ubatch (a check: the cells that are the positions give the same result) +static int inkling2_banded_pos_mode() { + static const int mode = [] { + const char * env = getenv("LLAMA_INKLING_BANDED_POS"); + return env == nullptr ? 1 : std::clamp(atoi(env), 0, 2); + }(); + return mode; +} + void llama_model_inkling2::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_QK_CLIP, hparams.f_qk_clip); @@ -339,6 +350,9 @@ bool llama_model_inkling2::graph::use_banded(int il, bool swa) { ggml_tensor * pr = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, nh, 1, 1); ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); ggml_flash_attn_ext_add_sinks(op, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, nh, 1, 1)); + if (inp->self_k_pos[swa]) { + ggml_flash_attn_ext_banded_set_pos(op, ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1), ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1)); + } ggml_prec_set_acc(op, GGML_PREC_F32); const bool ok = ggml_backend_dev_supports_op(dev, op); banded_dev_ok.push_back({ { swa, dev }, ok }); @@ -352,23 +366,46 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { // banded FA needs a position-contiguous cache; small ubatches stay dense for graph reuse inp->banded = cparams.flash_attn && n_tokens > n_tokens_banded_min; + // the cells of several sequences, or of a wrapped cache, are not the positions: the banded attention then + // takes the distances from the positions of the cells and the queries; disabled, those ubatches are dense + inp->banded_pos = inp->banded ? inkling2_banded_pos_mode() : 0; + // the positions of the n_kv_banded cells of a cache, filled at set_input + auto k_pos = [&](int i) { + inp->self_k_pos[i] = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, inp->n_kv_banded[i]); + ggml_set_input(inp->self_k_pos[i]); + ggml_set_name(inp->self_k_pos[i], i ? "attn_inp_k_pos_swa" : "attn_inp_k_pos"); + }; for (int i = 0; i < 2 && inp->banded; ++i) { - // a ubatch of several sequences is dense at runtime, so the reserved worst case (a ubatch - // of every sequence) must be dense too, else the dense graph outgrows the reserved buffer - inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : - (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); + // without the positions a ubatch of several sequences is dense at runtime, so the reserved worst case + // (a ubatch of every sequence) is dense too, else the dense graph outgrows the reserved buffer + bool use_pos = false; + inp->n_kv_banded[i] = inp->get_n_kv_banded(i ? attn->mctx->get_swa() : attn->mctx->get_base(), ubatch, inp->banded_pos, use_pos); + if (use_pos) { + k_pos(i); + } } // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), // while at runtime it does so only for consecutive ones if (inp->n_kv_banded[0] > 0 && ubatch.pos[0] == ubatch.pos[n_tokens - 1]) { - // once the positions pass the SWA cache it wraps and its layers take the dense bias for every ubatch - if (attn->mctx->get_swa()->get_size() < attn->mctx->get_base()->get_size()) { + if (inp->banded_pos) { + // a gap, several sequences or a wrapped SWA cache take the positions at runtime: reserve that graph, + // it holds the contiguous one + for (int i = 0; i < 2; ++i) { + if (!inp->self_k_pos[i]) { + inp->n_kv_banded[i] = (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv(); + k_pos(i); + } + } + } else if (attn->mctx->get_swa()->get_size() < attn->mctx->get_base()->get_size()) { + // once the positions pass the SWA cache it wraps and its layers take the dense bias for every ubatch inp->n_kv_banded[1] = 0; } n_rows_dense_reserve = std::min(n_tokens, n_tokens_banded_min); } ggml_tensor * inp_pos = build_inp_pos(); + // the query positions of the banded attention + q_pos_banded = ggml_view_1d(ctx0, inp_pos, n_tokens, 0); 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 @@ -543,6 +580,9 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens rel_b = ggml_reshape_4d(ctx0, rel_b, rel_b->ne[0], n_head, n_tokens, 1); cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, m, rel_b, 1.0f/sqrtf(n_embd_head), rel_b->ne[0]); ggml_flash_attn_ext_add_sinks(cur, ggml_reshape_3d(ctx0, sinks, n_head, n_tokens, 1)); + if (inp->self_k_pos[is_swa]) { + ggml_flash_attn_ext_banded_set_pos(cur, inp->self_k_pos[is_swa], q_pos_banded); + } ggml_prec_set_acc(cur, GGML_PREC_F32); res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); diff --git a/src/models/models.h b/src/models/models.h index 6b8f40506ee0..92099736c2d3 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2552,6 +2552,8 @@ struct llama_model_inkling2 : public llama_model_base { // query rows of the dense bias the first banded full-attention layer also builds in the reserve graph: // the small ubatches that stay dense take that bias at runtime, the reserve must hold it int64_t n_rows_dense_reserve = 0; + // I32 [n_tokens] query positions of the banded attention, used when it takes the cell positions + ggml_tensor * q_pos_banded = nullptr; llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; llm_graph_input_attn_kv_iswa * attn = nullptr; From 566ef55ac44cabc7e0a16b662b2db5f5a144823e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 18:14:46 -0800 Subject: [PATCH 052/115] CUDA: banded attention decode kernel for a few queries The banded op had no kernel for short query blocks: below 16 queries it took the scalar kernel, one warp per query row that reads K and V for every Q head and converts quantized K/V to an F16 copy of the whole cache first. At 32K cells, 24 Q / 8 KV heads, one query took 442 us (F16 K/V) and 755 us (q8_0), against 41 / 87 us for flash attention. The new kernel takes up to 8 queries. A block covers one KV head, a chunk of cells and the (query, Q head) rows of that KV head, so K and V are read once per GQA group, and q8_0 / q4_0 are read in place. Groups of D/8 lanes take one cell each and reduce K.Q in the group; per tile of cells the K, V and mask loads of a group are issued first, one warp per row takes the softmax, and each group accumulates P.V of its cells. The chunk partials are merged by a kernel with a block per row. Past 8 queries the MMA kernel is faster, so it now takes every query count it supports, the scalar kernels stay for the rest. B200, op time at 32K cells, one query: 59 us (F16), 56 us (q8_0). GGML_CUDA_BANDED_NO_VEC=1 turns the decode kernel off. test-backend-ops: banded cases of 1 to 32 queries over a padded n_kv (empty cells past the sequence masked), F16 / BF16 / q8_0 / q4_0 K/V, and perf cases of the Inkling-2-Mini decode shapes (n_kv from GGML_TEST_BANDED_PERF_KV, default 32768) beside flash attention. --- ggml/src/ggml-cuda/fattn-banded.cu | 535 ++++++++++++++++++++++++++++- tests/test-backend-ops.cpp | 29 +- 2 files changed, 560 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 4005e5c4670f..5c3ce3b0efce 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -424,6 +424,528 @@ static __global__ void flash_attn_ext_banded_f32_merge( } } +// decode: few queries. A block takes one KV head, a chunk of cells and NR (query, Q head) rows of that KV head (the +// GQA groups of up to 8 / G queries), so K and V are read once per group. Groups of D/8 lanes take one cell at a +// time, every lane holding 8 dimensions of Q, K, V and the output. Per tile, each group first issues the K, V and +// mask loads of all its cells, then reduces K.Q in the group; one warp per row takes the softmax of the tile, and +// each group accumulates P.V of its cells. The groups are merged at the end. +static constexpr int fattn_banded_vec_threads = 128; +static constexpr int fattn_banded_vec_cpg = 8; // cells per group and tile + +// 8 consecutive K/V elements [d0, d0 + 8) of a row, loaded raw and converted on use +template struct fattn_banded_kv8; + +template<> struct fattn_banded_kv8 { + int4 raw; + __device__ __forceinline__ void load(const char * row, const int d0) { raw = *(const int4 *) (row + d0*2); } + __device__ __forceinline__ void get(float (&x)[8]) const { + const half2 * h = (const half2 *) &raw; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float2 f = __half22float2(h[j]); + x[2*j + 0] = f.x; + x[2*j + 1] = f.y; + } + } +}; + +template<> struct fattn_banded_kv8 { + int4 raw; + __device__ __forceinline__ void load(const char * row, const int d0) { raw = *(const int4 *) (row + d0*2); } + __device__ __forceinline__ void get(float (&x)[8]) const { + const uint32_t * w = (const uint32_t *) &raw; +#pragma unroll + for (int j = 0; j < 4; ++j) { + x[2*j + 0] = __uint_as_float(w[j] << 16); + x[2*j + 1] = __uint_as_float(w[j] & 0xFFFF0000u); + } + } +}; + +template<> struct fattn_banded_kv8 { + uint32_t q[2]; + half d; + __device__ __forceinline__ void load(const char * row, const int d0) { + const block_q8_0 * b = (const block_q8_0 *) row + d0/QK8_0; + const uint16_t * qs = (const uint16_t *) (b->qs + d0 % QK8_0); // 2-byte aligned in the 34-byte block + q[0] = uint32_t(qs[0]) | (uint32_t(qs[1]) << 16); + q[1] = uint32_t(qs[2]) | (uint32_t(qs[3]) << 16); + d = b->d; + } + __device__ __forceinline__ void get(float (&x)[8]) const { + const float scale = __half2float(d); +#pragma unroll + for (int j = 0; j < 8; ++j) { + x[j] = scale*float(int8_t((q[j/4] >> (8*(j % 4))) & 0xFF)); + } + } +}; + +template<> struct fattn_banded_kv8 { + uint32_t q[2]; + half d; + __device__ __forceinline__ void load(const char * row, const int d0) { + // elements 0..15 are the low nibbles of qs[0..15], 16..31 the high ones + const block_q4_0 * b = (const block_q4_0 *) row + d0/QK4_0; + const uint16_t * qs = (const uint16_t *) (b->qs + d0 % (QK4_0/2)); + const int shift = d0 % QK4_0 >= QK4_0/2 ? 4 : 0; + q[0] = ((uint32_t(qs[0]) | (uint32_t(qs[1]) << 16)) >> shift) & 0x0F0F0F0Fu; + q[1] = ((uint32_t(qs[2]) | (uint32_t(qs[3]) << 16)) >> shift) & 0x0F0F0F0Fu; + d = b->d; + } + __device__ __forceinline__ void get(float (&x)[8]) const { + const float scale = __half2float(d); +#pragma unroll + for (int j = 0; j < 8; ++j) { + x[j] = scale*float(int((q[j/4] >> (8*(j % 4))) & 0xFF) - 8); + } + } +}; + +template +__launch_bounds__(fattn_banded_vec_threads) +static __global__ void flash_attn_ext_banded_vec( + const char * __restrict__ q, + const char * __restrict__ k, + const char * __restrict__ v, + const char * __restrict__ mask, + const char * __restrict__ rel, + const float * __restrict__ sinks, + float * __restrict__ dst, + float * __restrict__ part, + const float scale, + const int type_rel, + const int n_q, + const int64_t n_kv, + const int n_head_q, + const int n_head_kv, + const int64_t n_chunks, + const int64_t chunk, + const int64_t rel_extent, + const int64_t mask_ne2, + const int64_t mask_ne3, + const uint64_t q_nb1, const uint64_t q_nb2, const uint64_t q_nb3, + const uint64_t k_nb1, const uint64_t k_nb2, const uint64_t k_nb3, + const uint64_t v_nb1, const uint64_t v_nb2, const uint64_t v_nb3, + const uint64_t m_nb1, const uint64_t m_nb2, const uint64_t m_nb3, + const uint64_t r_nb0, const uint64_t r_nb1, const uint64_t r_nb2, const uint64_t r_nb3, + const int64_t rel_ne3, + const int64_t sinks_s1, + const int64_t sinks_s2) { + constexpr int NT = fattn_banded_vec_threads; + constexpr int E = 8; // dimensions per lane + constexpr int T = D / E; // lanes per cell + constexpr int NG = NT / T; // cell groups + constexpr int CPG = fattn_banded_vec_cpg; + constexpr int TC = NG*CPG; // cells per tile + static_assert(WARP_SIZE % T == 0 && T >= NR, "banded vec tiling"); + + __shared__ float S[TC][NR + 1]; // scores, then probabilities + __shared__ float alpha_s[NR]; + __shared__ float max_s[NR]; + __shared__ float sum_s[NR]; + __shared__ float o_s[NG][NR][D + 1]; + + const int tid = threadIdx.x; + const int t = tid % T; + const int grp = tid / T; + + // the KV heads of a chunk are neighbours in the launch order: they share the DRAM pages of the cells + const int ih_kv = blockIdx.x; + const int64_t ic = blockIdx.y; + const int G = n_head_q / n_head_kv; + const int n_rb = (n_q*G + NR - 1)/NR; + const int rb = blockIdx.z % n_rb; + const int ib = blockIdx.z / n_rb; + const int n_rows = min(NR, n_q*G - rb*NR); + + // row r: (query, Q head) number rb*NR + r of this KV head; rows past n_rows repeat the last one + int iq_r[NR]; + int ih_r[NR]; +#pragma unroll + for (int r = 0; r < NR; ++r) { + const int f = rb*NR + min(r, n_rows - 1); + iq_r[r] = f / G; + ih_r[r] = ih_kv*G + f % G; + } + + float qv[NR][E]; +#pragma unroll + for (int r = 0; r < NR; ++r) { + const float * qr = (const float *) (q + uint64_t(iq_r[r])*q_nb1 + uint64_t(ih_r[r])*q_nb2 + uint64_t(ib)*q_nb3) + t*E; + const float4 x0 = *(const float4 *) (qr + 0); + const float4 x1 = *(const float4 *) (qr + 4); + qv[r][0] = x0.x*scale; qv[r][1] = x0.y*scale; qv[r][2] = x0.z*scale; qv[r][3] = x0.w*scale; + qv[r][4] = x1.x*scale; qv[r][5] = x1.y*scale; qv[r][6] = x1.z*scale; qv[r][7] = x1.w*scale; + } + // lane t < NR of a group reads the mask and the bias of row t + const int rt = min(t, NR - 1); + const char * m_row = mask ? mask + uint64_t(iq_r[rt])*m_nb1 + uint64_t(ih_r[rt] % mask_ne2)*m_nb2 + uint64_t(ib % mask_ne3)*m_nb3 : nullptr; + const char * r_row = rel + uint64_t(ih_r[rt])*r_nb1 + uint64_t(iq_r[rt])*r_nb2 + uint64_t(ib % rel_ne3)*r_nb3; + const int64_t q_pos = iq_r[rt] + (n_kv - n_q); // the cell the row's query is aligned to + + if (tid < NR) { + max_s[tid] = -INFINITY; + sum_s[tid] = 0.0f; + } + float o[NR][E]; +#pragma unroll + for (int r = 0; r < NR; ++r) { +#pragma unroll + for (int e = 0; e < E; ++e) { + o[r][e] = 0.0f; + } + } + __syncthreads(); + + const int64_t c_begin = ic*chunk; + const int64_t c_end = min(c_begin + chunk, n_kv); + const char * k_base = k + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; + const char * v_base = v + uint64_t(ih_kv)*v_nb2 + uint64_t(ib)*v_nb3; + + for (int64_t c0 = c_begin; c0 < c_end; c0 += TC) { + // every load of the tile first: group grp takes cells grp, grp + NG, ... + fattn_banded_kv8 kr[CPG]; + fattn_banded_kv8 vr[CPG]; + float bm[CPG]; // lane t < NR: mask + bias of row t, -inf when masked +#pragma unroll + for (int j = 0; j < CPG; ++j) { + const int64_t c = c0 + grp + j*NG; + const int64_t cc = c < c_end ? c : c_end - 1; + kr[j].load(k_base + uint64_t(cc)*k_nb1, t*E); + vr[j].load(v_base + uint64_t(cc)*v_nb1, t*E); + bm[j] = -INFINITY; + if (t < NR && c < c_end) { + bm[j] = m_row ? __half2float(*(const half *) (m_row + uint64_t(c)*sizeof(half))) : 0.0f; + const int64_t dist = q_pos - c; + if (bm[j] != -INFINITY && dist >= 0 && dist < rel_extent) { + bm[j] += fattn_banded_load(r_row + uint64_t(dist)*r_nb0, type_rel); + } + } + } + // K.Q +#pragma unroll + for (int j = 0; j < CPG; ++j) { + float kx[E]; + kr[j].get(kx); + float sr[NR]; +#pragma unroll + for (int r = 0; r < NR; ++r) { + float s = 0.0f; +#pragma unroll + for (int e = 0; e < E; ++e) { + s += qv[r][e]*kx[e]; + } + sr[r] = warp_reduce_sum(s); + } + // lane t writes row t + float s_t = sr[0]; +#pragma unroll + for (int r = 1; r < NR; ++r) { + s_t = t == r ? sr[r] : s_t; + } + if (t < NR) { + S[grp + j*NG][t] = bm[j] == -INFINITY ? -INFINITY : s_t + bm[j]; + } + } + __syncthreads(); + + // online softmax: warp w takes rows w, w + 4, ... + { + const int lane = tid % WARP_SIZE; + const int warp = tid / WARP_SIZE; + for (int r = warp; r < n_rows; r += NT/WARP_SIZE) { + float m = -INFINITY; +#pragma unroll + for (int j = lane; j < TC; j += WARP_SIZE) { + m = fmaxf(m, S[j][r]); + } + m = warp_reduce_max(m); + const float m_old = max_s[r]; + const float m_new = fmaxf(m_old, m); + const float m_sub = m_new == -INFINITY ? 0.0f : m_new; + float sum = 0.0f; +#pragma unroll + for (int j = lane; j < TC; j += WARP_SIZE) { + const float p = expf(S[j][r] - m_sub); + S[j][r] = p; + sum += p; + } + sum = warp_reduce_sum(sum); + if (lane == 0) { + const float a = expf(m_old - m_sub); + alpha_s[r] = a; + sum_s[r] = sum_s[r]*a + sum; + max_s[r] = m_new; + } + } + } + __syncthreads(); + + // P.V of the group's cells +#pragma unroll + for (int r = 0; r < NR; ++r) { + const float a = alpha_s[r]; +#pragma unroll + for (int e = 0; e < E; ++e) { + o[r][e] *= a; + } + } +#pragma unroll + for (int j = 0; j < CPG; ++j) { + float vx[E]; + vr[j].get(vx); +#pragma unroll + for (int r = 0; r < NR; ++r) { + const float p = S[grp + j*NG][r]; +#pragma unroll + for (int e = 0; e < E; ++e) { + o[r][e] += p*vx[e]; + } + } + } + __syncthreads(); + } + + // merge the groups +#pragma unroll + for (int r = 0; r < NR; ++r) { +#pragma unroll + for (int e = 0; e < E; ++e) { + o_s[grp][r][t*E + e] = o[r][e]; + } + } + __syncthreads(); + + for (int idx = tid; idx < n_rows*D; idx += NT) { + const int r = idx / D; + const int d = idx % D; + float acc = 0.0f; +#pragma unroll + for (int g = 0; g < NG; ++g) { + acc += o_s[g][r][d]; + } + const float m = max_s[r]; + float l = sum_s[r]; + const int f = rb*NR + r; + const int iqr = f / G; + const int ihr = ih_kv*G + f % G; + const int64_t row = (int64_t(ib)*n_q + iqr)*n_head_q + ihr; + if (n_chunks == 1) { + float fs = 1.0f; + if (sinks) { + const float sink = sinks[ihr + iqr*sinks_s1 + ib*sinks_s2]; + const float m_new = fmaxf(m, sink); + fs = expf(m - m_new); + l = l*fs + expf(sink - m_new); + } + dst[row*D + d] = l == 0.0f ? 0.0f : acc*fs/l; + } else { + float * p = part + (row*n_chunks + ic)*(D + 2); + if (d == 0) { + p[0] = m; + p[1] = l; + } + p[2 + d] = acc; + } + } +} + +// merge of the chunk partials: a block per row, the chunk weights in parallel, then the dimensions +template +static __global__ void flash_attn_ext_banded_vec_merge( + const float * __restrict__ part, + float * __restrict__ dst, + const int64_t n_head_q, + const int64_t n_q, + const int n_chunks, + const float * __restrict__ sinks, + const int64_t sinks_s1, + const int64_t sinks_s2) { + constexpr int NT = 128; + extern __shared__ float w_s[]; // [n_chunks] + __shared__ float red[NT/WARP_SIZE]; + __shared__ float m_all; + __shared__ float l_all; + const int64_t row = blockIdx.x; + const int tid = threadIdx.x; + const float * p = part + row*n_chunks*(D + 2); + + float m = -INFINITY; + for (int c = tid; c < n_chunks; c += NT) { + m = fmaxf(m, p[c*(D + 2)]); + } + m = warp_reduce_max(m); + if (tid % WARP_SIZE == 0) { + red[tid / WARP_SIZE] = m; + } + __syncthreads(); + if (tid == 0) { + float mm = red[0]; + for (int w = 1; w < NT/WARP_SIZE; ++w) { + mm = fmaxf(mm, red[w]); + } + m_all = mm; + } + __syncthreads(); + m = m_all; + float l = 0.0f; + for (int c = tid; c < n_chunks; c += NT) { + const float mc = p[c*(D + 2)]; + const float f = mc == -INFINITY || m == -INFINITY ? 0.0f : expf(mc - m); + w_s[c] = f; + l += f*p[c*(D + 2) + 1]; + } + l = warp_reduce_sum(l); + __syncthreads(); + if (tid % WARP_SIZE == 0) { + red[tid / WARP_SIZE] = l; + } + __syncthreads(); + if (tid == 0) { + float ll = 0.0f; + for (int w = 0; w < NT/WARP_SIZE; ++w) { + ll += red[w]; + } + l_all = ll; + } + __syncthreads(); + l = l_all; + + const int64_t ih = row % n_head_q; + const int64_t iq = (row / n_head_q) % n_q; + const int64_t ib = row / (n_head_q*n_q); + float f = 1.0f; + if (sinks) { + const float sink = sinks[ih + iq*sinks_s1 + ib*sinks_s2]; + const float m_new = fmaxf(m, sink); + f = m == -INFINITY ? 0.0f : expf(m - m_new); + l = l*f + expf(sink - m_new); + } + const float inv = l == 0.0f ? 0.0f : f/l; + for (int d = tid; d < D; d += NT) { + float acc = 0.0f; +#pragma unroll 8 + for (int c = 0; c < n_chunks; ++c) { + acc += w_s[c]*p[c*(D + 2) + 2 + d]; + } + dst[row*D + d] = acc*inv; + } +} + +// the decode kernel reads K and V once per block of rows: past 8 queries the MMA kernel is faster +static constexpr int64_t fattn_banded_vec_max_q = 8; + +static bool fattn_banded_vec_usable(const ggml_tensor * dst) { + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + if (q->ne[1] > fattn_banded_vec_max_q || k->type != v->type) { + return false; + } + switch (k->type) { + case GGML_TYPE_F16: case GGML_TYPE_BF16: case GGML_TYPE_Q8_0: case GGML_TYPE_Q4_0: + break; + default: + return false; + } + // 16-byte F16 / BF16 and 2-byte quantized loads, 16-byte Q loads + const size_t align = k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16 ? 16 : 2; + for (const ggml_tensor * t : {k, v}) { + if (t->nb[1] % align != 0 || t->nb[2] % align != 0 || t->nb[3] % align != 0 || (uintptr_t) t->data % align != 0) { + return false; + } + } + return q->nb[1] % 16 == 0 && q->nb[2] % 16 == 0 && q->nb[3] % 16 == 0 && (uintptr_t) q->data % 16 == 0; +} + +static void fattn_banded_vec_launch(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const float scale, const int64_t rel_extent) { + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * m = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const ggml_tensor * rel = dst->src[6]; + cudaStream_t stream = ctx.stream(); + + const int64_t D = q->ne[0]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t G = q->ne[2]/k->ne[2]; + // rows per block: the GQA groups of as many queries as fit 8 rows (one query: its group alone), else 8 + // (Q heads of a KV head in steps of 8) + const int NR = G > 8 ? 8 : int(G*std::min(n_q, 8/G)); + const int64_t n_rb = (n_q*G + NR - 1)/NR; + + // split the cells so that the grid fills the GPU + constexpr int64_t tile = fattn_banded_vec_threads/16*fattn_banded_vec_cpg; // D = 128 + constexpr int64_t min_chunk = 4*tile; + const int64_t base_blocks = k->ne[2]*n_rb*q->ne[3]; + // one wave of resident blocks, 3 per SM + const int64_t target = int64_t(ggml_cuda_info().devices[ctx.device].nsm)*3; + int64_t n_chunks = std::max(1, std::min(target/base_blocks, (n_kv + min_chunk - 1)/min_chunk)); + n_chunks = std::min(n_chunks, 4096); // merge weights in shared memory + const int64_t chunk = GGML_PAD((n_kv + n_chunks - 1)/n_chunks, tile); + n_chunks = (n_kv + chunk - 1)/chunk; + + const int64_t n_rows = n_q*q->ne[2]*q->ne[3]; + ggml_cuda_pool_alloc part(ctx.pool()); + if (n_chunks > 1) { + part.alloc(n_rows*n_chunks*(D + 2)); + } + const float * sinks_d = sinks ? (const float *) sinks->data : nullptr; + const int64_t sinks_s1 = sinks && sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0; + const int64_t sinks_s2 = sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0; + + const dim3 blocks(k->ne[2], n_chunks, n_rb*q->ne[3]); +#define LAUNCH_BANDED_VEC_T(DD, NRR, T) \ + flash_attn_ext_banded_vec<<>>( \ + (const char *) q->data, (const char *) k->data, (const char *) v->data, m ? (const char *) m->data : nullptr, \ + (const char *) rel->data, n_chunks == 1 ? sinks_d : nullptr, (float *) dst->data, part.get(), \ + scale, rel->type, int(n_q), n_kv, int(q->ne[2]), int(k->ne[2]), n_chunks, chunk, rel_extent, \ + m ? m->ne[2] : 1, m ? m->ne[3] : 1, q->nb[1], q->nb[2], q->nb[3], k->nb[1], k->nb[2], k->nb[3], \ + v->nb[1], v->nb[2], v->nb[3], m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2) +#define LAUNCH_BANDED_VEC_NR(DD, T) \ + switch (NR) { \ + case 1: LAUNCH_BANDED_VEC_T(DD, 1, T); break; \ + case 2: LAUNCH_BANDED_VEC_T(DD, 2, T); break; \ + case 3: LAUNCH_BANDED_VEC_T(DD, 3, T); break; \ + case 4: LAUNCH_BANDED_VEC_T(DD, 4, T); break; \ + case 5: LAUNCH_BANDED_VEC_T(DD, 5, T); break; \ + case 6: LAUNCH_BANDED_VEC_T(DD, 6, T); break; \ + case 7: LAUNCH_BANDED_VEC_T(DD, 7, T); break; \ + default: LAUNCH_BANDED_VEC_T(DD, 8, T); break; \ + } +#define LAUNCH_BANDED_VEC(DD) \ + switch (k->type) { \ + case GGML_TYPE_F16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_F16); break; \ + case GGML_TYPE_BF16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_BF16); break; \ + case GGML_TYPE_Q8_0: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q8_0); break; \ + default: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q4_0); break; \ + } + if (D == 64) { + LAUNCH_BANDED_VEC(64); + } else { + LAUNCH_BANDED_VEC(128); + } +#undef LAUNCH_BANDED_VEC_NR +#undef LAUNCH_BANDED_VEC +#undef LAUNCH_BANDED_VEC_T + CUDA_CHECK(cudaGetLastError()); + + if (n_chunks > 1) { + const size_t smem = n_chunks*sizeof(float); + if (D == 64) { + flash_attn_ext_banded_vec_merge<64><<>>( + part.get(), (float *) dst->data, q->ne[2], n_q, int(n_chunks), sinks_d, sinks_s1, sinks_s2); + } else { + flash_attn_ext_banded_vec_merge<128><<>>( + part.get(), (float *) dst->data, q->ne[2], n_q, int(n_chunks), sinks_d, sinks_s1, sinks_s2); + } + } +} + #if defined(TURING_MMA_AVAILABLE) #define FATTN_BANDED_MMA_AVAILABLE #endif @@ -977,7 +1499,8 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d #endif } -static constexpr int64_t fattn_banded_mma_min_q = 16; +// below this the decode kernel or, without it, the MMA kernel beats the scalar kernels +static constexpr int64_t fattn_banded_mma_min_q = 1; static bool fattn_banded_mma_aligned(const ggml_tensor * t) { return (uintptr_t) t->data % 16 == 0 && t->nb[1] % 16 == 0 && t->nb[2] % 16 == 0 && t->nb[3] % 16 == 0; @@ -1192,6 +1715,16 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso // the tensor extent (not op_params) is authoritative after graph cloning const int64_t rel_extent = rel->ne[0]; + // decode: K and V read once per GQA group, quantized K/V read in place + static const bool no_vec = [] { + const char * env = getenv("GGML_CUDA_BANDED_NO_VEC"); + return env != nullptr && atoi(env) != 0; + }(); + if (!no_vec && fattn_banded_vec_usable(dst)) { + fattn_banded_vec_launch(ctx, dst, scale, rel_extent); + return; + } + if (sinks && fattn_banded_mma_usable(ctx.device, dst)) { fattn_banded_mma_launch(ctx, dst, scale, rel_extent); return; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 635a9ccda334..9a3a4dfc8468 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9337,7 +9337,7 @@ struct test_flash_attn_ext_banded : public test_case { const int64_t n_q; const int64_t n_kv; const int64_t rel_extent; - const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent + const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent, 3: causal over a padded n_kv const ggml_type kv_type; const ggml_type rel_type; const bool strided; @@ -9403,10 +9403,12 @@ struct test_flash_attn_ext_banded : public test_case { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { if (strcmp(t->name, "m") == 0) { std::vector data(n_q*n_kv); + // padded n_kv: the last cells are empty, the queries are the tail of the cells before them + const int64_t n_empty = mask_kind == 3 ? std::min(n_kv - n_q, n_kv/8 + 37) : 0; for (int64_t iq = 0; iq < n_q; ++iq) { for (int64_t ik = 0; ik < n_kv; ++ik) { - const int64_t rel_dist = iq + (n_kv - n_q) - ik; - const bool visible = rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent); + const int64_t rel_dist = iq + (n_kv - n_empty - n_q) - ik; + const bool visible = rel_dist >= 0 && ik < n_kv - n_empty && (mask_kind != 2 || rel_dist < rel_extent); data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } @@ -13639,6 +13641,13 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, kv_type, GGML_TYPE_F32)); } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 512, 32768, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); + // small ubatches over a padded n_kv (Inkling-2-Mini decode): empty cells past the sequence are masked + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }) { + for (int64_t n_q : { 1, 2, 3, 4, 8, 16, 32 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 4096, 1280, 3, kv_type, GGML_TYPE_F32, 2)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 256, 1280, 3, kv_type, GGML_TYPE_F32, 2)); + } // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, n_q, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); @@ -14059,6 +14068,20 @@ static std::vector> make_test_cases_eval() { static std::vector> make_test_cases_perf() { std::vector> test_cases; + // Inkling-2-Mini decode: banded over a padded n_kv vs flash attention with a dense bias mask + { + const char * env = std::getenv("GGML_TEST_BANDED_PERF_KV"); + const std::vector kvs = env ? std::vector{ atoll(env) } : std::vector{ 32768 }; + for (int64_t kv : kvs) { + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_Q8_0 }) { + for (int64_t n_q : { 1, 2, 3, 4, 8, 16, 32 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, kv, 1280, 3, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext(128, 128, 8, {3, 1}, kv, n_q, true, true, 0, 0, GGML_PREC_F32, kv_type, kv_type)); + } + } + } + } + test_cases.emplace_back(new test_timestep_embedding()); test_cases.emplace_back(new test_timestep_embedding(GGML_TYPE_F32, {32769, 1, 1, 1}, 4096, 10000)); test_cases.emplace_back(new test_timestep_embedding(GGML_TYPE_F32, {65, 1, 1, 1}, 1, 10000)); From 0c76ff63e35b57c71d617afe2f1e4a9fce3b4f7f Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 18:25:15 -0800 Subject: [PATCH 053/115] tests : banded positions with every quantized K/V type and mixed K/V types --- tests/test-backend-ops.cpp | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index c1fa62d6e577..837d7e509861 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9460,9 +9460,11 @@ struct test_flash_attn_ext_banded_pos : public test_case { const int mask_kind; const ggml_type kv_type; const ggml_type rel_type; + const ggml_type v_type; // V type when it differs from K, else kv_type std::string vars() override { - return VARS_TO_STR11(d, n_head, n_head_kv, n_q, n_kv, rel_extent, layout, n_seq, mask_kind, kv_type, rel_type); + return VARS_TO_STR11(d, n_head, n_head_kv, n_q, n_kv, rel_extent, layout, n_seq, mask_kind, kv_type, rel_type) + + (v_type != kv_type ? ",v_type=" + std::string(ggml_type_name(v_type)) : ""); } double max_nmse_err() override { @@ -9478,14 +9480,15 @@ struct test_flash_attn_ext_banded_pos : public test_case { } test_flash_attn_ext_banded_pos(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int layout, int64_t n_seq, int mask_kind, ggml_type kv_type, ggml_type rel_type) + int layout, int64_t n_seq, int mask_kind, ggml_type kv_type, ggml_type rel_type, ggml_type v_type = GGML_TYPE_COUNT) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), - layout(layout), n_seq(n_seq), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type) {} + layout(layout), n_seq(n_seq), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), + v_type(v_type == GGML_TYPE_COUNT ? kv_type : v_type) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); ggml_tensor * k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - ggml_tensor * v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, v_type, d, n_kv, n_head_kv, 1); ggml_tensor * r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, n_q); @@ -13746,6 +13749,20 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_pos( 64, 8, 1, nq, 512, 64, 2, 1, 2, kv_type, GGML_TYPE_F32)); } } + // every quantized K/V type of the cache, and mixed K/V types: decode (split-KV) and prefill (MMA) + for (ggml_type kv_type : {GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1}) { + for (int64_t nq : {4, 64}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, nq, 1024, 256, 1, 4, 1, kv_type, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, nq, 512, 64, 2, 1, 2, kv_type, GGML_TYPE_F32)); + } + } + for (auto kv : std::vector>{ {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}, {GGML_TYPE_Q8_0, GGML_TYPE_F16}, + {GGML_TYPE_F16, GGML_TYPE_Q8_0}, {GGML_TYPE_Q4_0, GGML_TYPE_Q8_0} }) { + for (int64_t nq : {4, 17, 64, 130}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, nq, 1024, 256, 1, 4, 1, kv.first, GGML_TYPE_F32, kv.second)); + test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 8, 2, nq, 512, 64, 2, 1, 2, kv.first, GGML_TYPE_F32, kv.second)); + } + } test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 1, 4096, 1024, 1, 4, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 64, 4096, 1024, 1, 3, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded_pos(128, 48, 8, 512, 2048, 512, 2, 1, 2, GGML_TYPE_F16, GGML_TYPE_F32)); From 235fc5071cd0f43ddf223364ad7f84cca93141d7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 18:35:31 -0800 Subject: [PATCH 054/115] metal : mixed K/V cache types in the FA and banded FA kernels - q8_0, q4_0 and f16 K/V in any K != V pair at head sizes 64 and 128, dequantized inline by the half8x8 and vec kernels (baseline vec configuration); previously refused, so the attention of -ctk q8_0 -ctv q4_0 ran on the CPU - mixed pairs never take the F16 copy of the cache, the tensor kernel or the sparse path, and do not reserve the F16 scratch - tests: mixed K/V pairs for FLASH_ATTN_EXT_BANDED (new test_flash_attn_ext_banded_kv2) and FLASH_ATTN_EXT, decode / small batches / prefill --- ggml/src/ggml-metal/ggml-metal-device.cpp | 20 ++++- ggml/src/ggml-metal/ggml-metal-device.m | 17 ++++- ggml/src/ggml-metal/ggml-metal-ops.cpp | 20 +++-- ggml/src/ggml-metal/kernels/fa_f16.metal | 6 ++ ggml/src/ggml-metal/kernels/fa_q4_0.metal | 6 ++ ggml/src/ggml-metal/kernels/fa_q8_0.metal | 6 ++ ggml/src/ggml-metal/kernels/fa_vec_f16.metal | 6 ++ ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal | 6 ++ ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal | 6 ++ tests/test-backend-ops.cpp | 76 +++++++++++++++++++ 10 files changed, 157 insertions(+), 12 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 436f2c4045f4..6988815f1b1a 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1952,7 +1952,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( const int32_t dk = (int32_t) op->src[1]->ne[0]; const int32_t dv = (int32_t) op->src[2]->ne[0]; - const char * type = use_kv_f16 ? "f16" : ggml_type_name(op->src[1]->type); + // mixed K/V cache types: kernel_...___dk*_dv* + char type[32]; + if (use_kv_f16) { + snprintf(type, sizeof(type), "f16"); + } else if (op->src[1]->type != op->src[2]->type) { + snprintf(type, sizeof(type), "%s_%s", ggml_type_name(op->src[1]->type), ggml_type_name(op->src[2]->type)); + } else { + snprintf(type, sizeof(type), "%s", ggml_type_name(op->src[1]->type)); + } // do bounds checks for the mask? const bool bc_mask = op->src[3] && (op->src[3]->ne[1] % 8 != 0); @@ -2067,7 +2075,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v const int32_t dk = (int32_t) op->src[1]->ne[0]; const int32_t dv = (int32_t) op->src[2]->ne[0]; - const char * type = use_kv_f16 ? "f16" : ggml_type_name(op->src[1]->type); + // mixed K/V cache types: kernel_...___dk*_dv* + char type[32]; + if (use_kv_f16) { + snprintf(type, sizeof(type), "f16"); + } else if (op->src[1]->type != op->src[2]->type) { + snprintf(type, sizeof(type), "%s_%s", ggml_type_name(op->src[1]->type), ggml_type_name(op->src[2]->type)); + } else { + snprintf(type, sizeof(type), "%s", ggml_type_name(op->src[1]->type)); + } char qne_suffix[16] = {0}; if (!(nqpsg == 1 && ne == ggml_metal_tuning::fa_vec_baseline_ne(dk, dv))) { diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 538411c537a5..6c4356b01d26 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1549,6 +1549,19 @@ static bool ggml_metal_supports_mul_mat_op( return mm_path; } +// mixed K/V cache types (e.g. -ctk q8_0 -ctv q4_0): the half8x8 and vec kernels are instantiated for +// these pairs at head sizes 64 and 128 and dequantize K and V inline, without an F16 copy of the cache +static bool ggml_metal_fa_kv_mixed_ok(const struct ggml_tensor * op) { + const enum ggml_type tk = op->src[1]->type; + const enum ggml_type tv = op->src[2]->type; + + const bool tk_ok = tk == GGML_TYPE_F16 || tk == GGML_TYPE_Q8_0 || tk == GGML_TYPE_Q4_0; + const bool tv_ok = tv == GGML_TYPE_F16 || tv == GGML_TYPE_Q8_0 || tv == GGML_TYPE_Q4_0; + + return tk != tv && tk_ok && tv_ok && op->src[5] == NULL && + op->src[1]->ne[0] == op->src[2]->ne[0] && (op->src[1]->ne[0] == 64 || op->src[1]->ne[0] == 128); +} + bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_tensor * op) { const bool has_simdgroup_mm = dev->props.has_simdgroup_mm; const bool has_simdgroup_reduction = dev->props.has_simdgroup_reduction; @@ -1804,7 +1817,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return false; } if (op->src[1]->type != op->src[2]->type) { - return false; + return ggml_metal_fa_kv_mixed_ok(op) && has_simdgroup_mm; } switch (op->src[1]->type) { case GGML_TYPE_F32: @@ -1843,7 +1856,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[0]->ne[1] >= 65536 || op->src[2]->ne[1] != op->src[1]->ne[1]) { return false; } - if (op->src[1]->type != op->src[2]->type) { + if (op->src[1]->type != op->src[2]->type && !ggml_metal_fa_kv_mixed_ok(op)) { return false; } switch (op->src[1]->type) { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index e8e5421ffac8..20b417a5a5d2 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3216,7 +3216,8 @@ static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 // banded: the kernels dequantize the KV inline, an F16 copy of the whole cache would grow with n_kv - if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + // mixed K/V types: dequantized inline too (the F16 pass converts K and V with one kernel type) + if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED || op->src[1]->type != op->src[2]->type) { return false; } @@ -3242,7 +3243,7 @@ static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool has_tensor) { assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); - if (!has_tensor || ggml_metal_op_flash_attn_ext_use_vec(op)) { + if (!has_tensor || ggml_metal_op_flash_attn_ext_use_vec(op) || op->src[1]->type != op->src[2]->type) { return false; } @@ -3294,7 +3295,7 @@ static int ggml_metal_op_flash_attn_ext_n_kv_max_sparse(const ggml_tensor * op) assert(op->op == GGML_OP_FLASH_ATTN_EXT || op->op == GGML_OP_FLASH_ATTN_EXT_BANDED); // K/V row lists are handled by the dense kernels, not by the sparse path - if (op->src[5] != nullptr) { + if (op->src[5] != nullptr || op->src[1]->type != op->src[2]->type) { return 0; } @@ -3513,8 +3514,9 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { // return 0; //} - // banded: supports_op refuses quantized K/V, so no F16 copy of K/V is needed - if (op->op == GGML_OP_FLASH_ATTN_EXT_BANDED && !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { + // banded and mixed K/V types: the kernels dequantize inline, no F16 copy of K/V is made + if ((op->op == GGML_OP_FLASH_ATTN_EXT_BANDED || op->src[1]->type != op->src[2]->type) && + !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { return 0; } @@ -3599,7 +3601,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { GGML_ASSERT(ne00 % 4 == 0); GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT(op->src[1]->type == op->src[2]->type); + // mixed K/V types are dequantized inline only (no F16 pass) + GGML_ASSERT(op->src[1]->type == op->src[2]->type || !ggml_metal_op_flash_attn_ext_use_kv_f16(op)); //GGML_ASSERT(ggml_are_same_shape (src1, src2)); GGML_ASSERT(ne11 == ne21); @@ -4102,7 +4105,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_op_concurrency_reset(ctx); } - const int is_q = !use_kv_f16 && ggml_is_quantized(op->src[1]->type) ? 1 : 0; + const int is_q = !use_kv_f16 && (ggml_is_quantized(op->src[1]->type) || ggml_is_quantized(op->src[2]->type)) ? 1 : 0; // shared memory layout (halfs unless noted): // queries/attn/result: Q*(DK + 2*PAD2(DV,64) + 4*C) @@ -4186,7 +4189,8 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { } else { // half4x4 kernel // sparse: the index lists are per query row, so a threadgroup can share KV with Q == 1 only - auto cfg = use_sparse + // mixed K/V types: only the baseline vec configuration is instantiated + auto cfg = use_sparse || op->src[1]->type != op->src[2]->type ? ggml_metal_tuning::fa_vec_baseline_cfg((int) ne00, (int) ne20) : ggml_metal_tuning::fa_vec_pick( props_dev->gpu_family, diff --git a/ggml/src/ggml-metal/kernels/fa_f16.metal b/ggml/src/ggml-metal/kernels/fa_f16.metal index 6e30b09e3a5a..3b772182735b 100644 --- a/ggml/src/ggml-metal/kernels/fa_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_f16.metal @@ -72,6 +72,12 @@ template [[host_name("kernel_flash_attn_ext_bf16_dk512_dv512")]] kernel flash_at template [[host_name("kernel_flash_attn_ext_bf16_dk576_dv512")]] kernel flash_attn_ext_t kernel_flash_attn_ext; #endif +// mixed K/V cache types (K = f16): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_f16_q8_0_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_f16_q8_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_f16_q4_0_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_f16_q4_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; + #undef FA_TYPES #undef FA_TYPES_BF #undef FA_TYPES_F32 diff --git a/ggml/src/ggml-metal/kernels/fa_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_q4_0.metal index 6b05b5df6bdf..709b7eb52775 100644 --- a/ggml/src/ggml-metal/kernels/fa_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q4_0.metal @@ -49,6 +49,12 @@ template [[host_name("kernel_flash_attn_ext_q4_0_dk320_dv256")]] kernel flash_at template [[host_name("kernel_flash_attn_ext_q4_0_dk512_dv512")]] kernel flash_attn_ext_t kernel_flash_attn_ext; template [[host_name("kernel_flash_attn_ext_q4_0_dk576_dv512")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +// mixed K/V cache types (K = q4_0): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_q4_0_f16_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q4_0_f16_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q4_0_q8_0_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q4_0_q8_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; + #undef FA_TYPES #undef FA_TYPES_BF #undef FA_TYPES_F32 diff --git a/ggml/src/ggml-metal/kernels/fa_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_q8_0.metal index bb29a262c1ea..0d730a3a3286 100644 --- a/ggml/src/ggml-metal/kernels/fa_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q8_0.metal @@ -49,6 +49,12 @@ template [[host_name("kernel_flash_attn_ext_q8_0_dk320_dv256")]] kernel flash_at template [[host_name("kernel_flash_attn_ext_q8_0_dk512_dv512")]] kernel flash_attn_ext_t kernel_flash_attn_ext; template [[host_name("kernel_flash_attn_ext_q8_0_dk576_dv512")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +// mixed K/V cache types (K = q8_0): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_q8_0_f16_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q8_0_f16_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q8_0_q4_0_dk64_dv64")]] kernel flash_attn_ext_t kernel_flash_attn_ext; +template [[host_name("kernel_flash_attn_ext_q8_0_q4_0_dk128_dv128")]] kernel flash_attn_ext_t kernel_flash_attn_ext; + #undef FA_TYPES #undef FA_TYPES_BF #undef FA_TYPES_F32 diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal index bea54f9f73fd..8cbd472161d2 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal @@ -124,6 +124,12 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512_q4_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif +// mixed K/V cache types (K = f16): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_vec_f16_q8_0_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_f16_q8_0_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_f16_q4_0_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_f16_q4_0_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; + #undef FA_TYPES #undef FA_TYPES_F32 diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal index 6bf5fad75cf1..98e2ed62aee5 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal @@ -90,6 +90,12 @@ template [[host_name("kernel_flash_attn_ext_vec_q4_0_dk576_dv512_q2_ne4")]] kern template [[host_name("kernel_flash_attn_ext_vec_q4_0_dk576_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_q4_0_dk576_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +// mixed K/V cache types (K = q4_0): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_vec_q4_0_f16_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q4_0_f16_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q4_0_q8_0_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q4_0_q8_0_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; + #undef FA_TYPES #undef FA_TYPES_F32 diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal index 7686ccc00126..678dc1393493 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal @@ -90,6 +90,12 @@ template [[host_name("kernel_flash_attn_ext_vec_q8_0_dk576_dv512_q2_ne4")]] kern template [[host_name("kernel_flash_attn_ext_vec_q8_0_dk576_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_q8_0_dk576_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +// mixed K/V cache types (K = q8_0): baseline configuration, head sizes 64 and 128 +template [[host_name("kernel_flash_attn_ext_vec_q8_0_f16_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q8_0_f16_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q8_0_q4_0_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_q8_0_q4_0_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; + #undef FA_TYPES #undef FA_TYPES_F32 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 549da9951ebc..f6cfa2894b00 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9567,6 +9567,69 @@ struct test_flash_attn_ext_banded_shapes : public test_case { } }; +// banded attention with different K and V cache types (e.g. -ctk q8_0 -ctv q4_0), causal mask, per-query sinks +struct test_flash_attn_ext_banded_kv2 : public test_case { + const int64_t d; + const int64_t n_head; + const int64_t n_head_kv; + const int64_t n_q; + const int64_t n_kv; + const int64_t rel_extent; + const ggml_type type_k; + const ggml_type type_v; + + std::string vars() override { + return VARS_TO_STR8(d, n_head, n_head_kv, n_q, n_kv, rel_extent, type_k, type_v); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_banded_kv2(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + ggml_type type_k, ggml_type type_v) + : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), rel_extent(rel_extent), type_k(type_k), type_v(type_v) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, type_k, d, n_kv, n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type_v, d, n_kv, n_head_kv, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, rel_extent, n_head, n_q, 1); + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, n_q); + ggml_set_name(r, "rel_logits"); + ggml_set_name(m, "m"); + ggml_set_name(s, "sinks"); + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); + ggml_flash_attn_ext_add_sinks(out, s); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + std::vector data(n_q*n_kv); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < n_kv; ++ik) { + const bool visible = iq + (n_kv - n_q) - ik >= 0; + data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (strcmp(t->name, "rel_logits") == 0) { + init_tensor_uniform(t, -1.0f, 1.0f); + } else if (strcmp(t->name, "sinks") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + // large Q values, so the online softmax has to rescale the partial results struct test_flash_attn_ext_large_logits : public test_flash_attn_ext { static constexpr int q_range = 20; @@ -13825,6 +13888,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 2, 1000, 96, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, 300, 16, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 4, 300, 16, 0, GGML_TYPE_F16, GGML_TYPE_F32, 1)); + // mixed K/V cache types (-ctk != -ctv), banded and dense, decode / small batches / prefill + for (auto [type_k, type_v] : std::initializer_list>{ + { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }, { GGML_TYPE_Q8_0, GGML_TYPE_F16 }, + { GGML_TYPE_F16, GGML_TYPE_Q8_0 }, { GGML_TYPE_Q4_0, GGML_TYPE_F16 } }) { + for (int64_t n_q : { 1, 4, 33, 512 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(128, 24, 8, n_q, 1100, 1024, type_k, type_v)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(64, 8, 2, 3, 333, 16, type_k, type_v)); + for (int64_t nb : { 1, 4, 33 }) { + test_cases.emplace_back(new test_flash_attn_ext(128, 128, 8, {3, 1}, 1100, nb, true, true, 0, 0, GGML_PREC_F32, type_k, type_v)); + } + test_cases.emplace_back(new test_flash_attn_ext(64, 64, 8, {1, 1}, 333, 3, true, false, 0, 0, GGML_PREC_F32, type_k, type_v)); + } test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16403, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From 5270100b3eb960f916429d7ead72272e1d38b761 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 18:14:46 -0800 Subject: [PATCH 055/115] inkling2 : take the banded path for ubatches of 2 to 32 tokens over the padded cache Ubatches of at most 32 tokens of one sequence (drafts, prompt tails) built the dense relative bias over the whole cache, n_kv x n_tokens x n_head F32 plus its F16 copies, to keep the graph reusable while decoding: the banded span, the populated cells, changes every token. 6510f1f then reserved the dense bias of 32 such rows over the full cache at load, so every load paid for it: one slot at -c 1048576 -ub 512 reserved 5866 MiB (F16 K/V) / 9962 MiB (q8_0). These ubatches now take the banded path over the padded n_kv, which changes only every 256 cells, so the graph is still reused. The empty cells past the sequence are masked, and the band is shifted by the padding: band column j holds distance j - (n_kv - n_used), through an I32 input per cache (extent + 256 rows of the zero-padded relative bias, gathered before the projection), filled by set_input. The graph is reused while the cache gives the same padded span. A decode step (one token) stays dense: the flash attention vec kernel is faster there, and the reserved tg graph, one token over the whole cache, already holds its bias. So the reserve-only dense rows of 6510f1f go. Several sequences, the wrapped SWA cache, a cache whose positions are not its cells, and FA off stay dense as before; the reserve keeps the dense SWA layers. --- src/llama-graph.cpp | 34 +++++++++++++++++++++++++-- src/llama-graph.h | 11 +++++++++ src/models/inkling2.cpp | 52 ++++++++++++++++++++--------------------- src/models/models.h | 3 --- 4 files changed, 68 insertions(+), 32 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 0b5ad710d68e..bf28a31641b4 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1401,6 +1401,16 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) return res; } +uint32_t llm_graph_input_mem_hybrid_iswa_rel::get_n_kv_banded(const llama_kv_cache_context * kv_ctx) const { + const uint32_t n_used = kv_ctx->get_n_kv_pos_contiguous(); + if (!banded_pad || n_used == 0) { + return n_used; + } + // the shift table covers a padding of less than n_rel_pad cells, one sequence alone in the cache always fits + const uint32_t n_kv = kv_ctx->get_n_kv(); + return n_used <= n_kv && n_kv - n_used < n_rel_pad ? n_kv : 0; +} + void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) { const auto * attn_ctx = mctx->get_attn(); @@ -1432,6 +1442,26 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); } + // padded banded: query i is at cell n_kv_used - n_tokens + i, the op aligns it to n_kv - n_tokens + i, + // so band column j holds distance j - (n_kv - n_kv_used) + for (int i = 0; i < 2; ++i) { + ggml_tensor * shift = self_rel_shift[i]; + if (!shift || !shift->buffer) { + continue; + } + const auto * kv_ctx = i ? attn_ctx->get_swa() : attn_ctx->get_base(); + const uint32_t n_used = kv_ctx->get_n_kv_pos_contiguous(); + const int32_t ext = i ? extent_swa : extent; + GGML_ASSERT(n_used > 0 && n_used <= n_kv_banded[i] && n_kv_banded[i] - n_used < n_rel_pad); + GGML_ASSERT(shift->ne[0] == ext + (int64_t) n_rel_pad); + const int32_t delta = n_kv_banded[i] - n_used; + std::vector data(shift->ne[0]); + for (int32_t j = 0; j < (int32_t) data.size(); ++j) { + data[j] = j >= delta && j - delta < ext ? j - delta : ext; + } + ggml_backend_tensor_set(shift, data.data(), 0, ggml_nbytes(shift)); + } + const int64_t n_rs = mctx->get_recr()->get_n_rs(); if (inp_rs->s_copy) { @@ -1477,8 +1507,8 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; if (banded) { - res &= attn_ctx->get_base()->get_n_kv_pos_contiguous() == n_kv_banded[0]; - res &= attn_ctx->get_swa()->get_n_kv_pos_contiguous() == n_kv_banded[1]; + res &= get_n_kv_banded(attn_ctx->get_base()) == n_kv_banded[0]; + res &= get_n_kv_banded(attn_ctx->get_swa()) == n_kv_banded[1]; } res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 3c0b141294e4..9fcf11719888 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -815,6 +815,17 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { uint32_t n_kv_banded[2] = { 0, 0 }; bool banded = false; + // padded: the banded attention spans the padded n_kv, which changes only every 256 cells, so that the graph of + // a small ubatch is reused. The empty cells past the sequence are masked, and the band is shifted by the padding + // through self_rel_shift, the row of the relative bias for each band column, extent past the band (a zero row) + bool banded_pad = false; + ggml_tensor * self_rel_shift[2] = { nullptr, nullptr }; // I32 [extent + n_rel_pad], [extent_swa + n_rel_pad] + + static constexpr uint32_t n_rel_pad = 256; + + // the n_kv_banded a graph built for this memory context takes + uint32_t get_n_kv_banded(const llama_kv_cache_context * kv_ctx) const; + const uint32_t extent; const uint32_t extent_swa; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 34dba7423764..3684b260658d 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -7,7 +7,7 @@ // max elements of the dense relative bias per attention call, and max chunks per layer static constexpr int64_t n_kq_bias_max = int64_t(1) << 29; static constexpr int64_t n_kq_chunk_max = 64; -// ubatches up to this many tokens keep the dense path +// ubatches up to this many tokens take the banded path over the padded n_kv static constexpr int64_t n_tokens_banded_min = 32; void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { @@ -350,22 +350,30 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { attn = inp->get_attn(); recr = inp->get_recr(); - // banded FA needs a position-contiguous cache; small ubatches stay dense for graph reuse - inp->banded = cparams.flash_attn && n_tokens > n_tokens_banded_min; + // banded FA needs a position-contiguous cache. Ubatches of 2 to n_tokens_banded_min tokens (drafts, prompt tails) + // span the padded n_kv, which changes only every 256 cells, so that their graph is reused. A decode step stays + // dense: the FA vec kernel is faster there, and the reserved tg graph (one token over the whole cache) holds its bias + inp->banded = cparams.flash_attn && n_tokens > 1; + inp->banded_pad = n_tokens <= n_tokens_banded_min; for (int i = 0; i < 2 && inp->banded; ++i) { // a ubatch of several sequences is dense at runtime, so the reserved worst case (a ubatch // of every sequence) must be dense too, else the dense graph outgrows the reserved buffer - inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : - (i ? attn->mctx->get_swa() : attn->mctx->get_base())->get_n_kv_pos_contiguous(); + inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : inp->get_n_kv_banded(i ? attn->mctx->get_swa() : attn->mctx->get_base()); } // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), - // while at runtime it does so only for consecutive ones - if (inp->n_kv_banded[0] > 0 && ubatch.pos[0] == ubatch.pos[n_tokens - 1]) { - // once the positions pass the SWA cache it wraps and its layers take the dense bias for every ubatch - if (attn->mctx->get_swa()->get_size() < attn->mctx->get_base()->get_size()) { - inp->n_kv_banded[1] = 0; + // while at runtime it does so only for consecutive ones. Once the positions pass the SWA cache it wraps + // and its layers take the dense bias for every ubatch + if (inp->n_kv_banded[1] > 0 && n_tokens > 1 && ubatch.pos[0] == ubatch.pos[n_tokens - 1] && + attn->mctx->get_swa()->get_size() < attn->mctx->get_base()->get_size()) { + inp->n_kv_banded[1] = 0; + } + for (int i = 0; i < 2 && inp->banded_pad; ++i) { + if (inp->n_kv_banded[i] > 0) { + ggml_tensor *& shift = inp->self_rel_shift[i]; + shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, (i ? hparams.n_swa : hparams.n_relative_extent) + inp->n_rel_pad); + ggml_set_input(shift); + ggml_set_name(shift, i ? "attn_inp_rel_shift_swa" : "attn_inp_rel_shift"); } - n_rows_dense_reserve = std::min(n_tokens, n_tokens_banded_min); } ggml_tensor * inp_pos = build_inp_pos(); @@ -483,21 +491,6 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - if (use_banded(il, is_swa) && !is_swa && n_rows_dense_reserve > 0) { - // reserve only, output unused: the dense bias of the first rows over the full cache, as a small ubatch - // builds it. Once, before the first banded layer: the banded mask it allocates is not in that ubatch - const int64_t nr = n_rows_dense_reserve; - n_rows_dense_reserve = 0; - ggml_tensor * r_s = ggml_view_3d(ctx0, Rcur, Rcur->ne[0], n_head, nr, Rcur->nb[1], Rcur->nb[2], 0); - ggml_tensor * t_s = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), r_s); - t_s = ggml_cont(ctx0, ggml_permute(ctx0, t_s, 1, 0, 2, 3)); - ggml_tensor * p_s = ggml_view_2d(ctx0, rel_pos, n_kv, nr, rel_pos->nb[1], 0); - ggml_tensor * b_s = ggml_get_rows(ctx0, t_s, p_s); - b_s = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_4d(ctx0, b_s, n_head, n_kv, nr, 1), 2, 0, 1, 3)); - ggml_tensor * q_s = ggml_cont(ctx0, ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, nr, Qcur->nb[1], Qcur->nb[2], 0)); - ggml_build_forward_expand(gf, build_attn(inp, nullptr, nullptr, nullptr, q_s, nullptr, nullptr, b_s, - ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f), 1.0f/sqrtf(n_embd_head), il)); - } if (use_banded(il, is_swa)) { const auto * cache = is_swa ? attn->mctx->get_swa() : attn->mctx->get_base(); auto * k_rot = is_swa ? attn->self_k_rot_swa[il] : attn->self_k_rot[il]; @@ -539,7 +532,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens mask->nb[1], mask->nb[2], mask->nb[3], 0)); } // exp(s + b)/(exp(t) + sum(exp(s + b))): the dense mask b - t with a zero sink - ggml_tensor * rel_b = ggml_mul_mat(ctx0, layer.attn_rel_bias, Rcur); + ggml_tensor * rel_bias = layer.attn_rel_bias; + if (ggml_tensor * shift = inp->self_rel_shift[is_swa]) { + // padded span: the band shifted by the padding, zero (the padded row) past the extent + rel_bias = ggml_get_rows(ctx0, ggml_pad(ctx0, rel_bias, 0, 1, 0, 0), shift); + } + ggml_tensor * rel_b = ggml_mul_mat(ctx0, rel_bias, Rcur); rel_b = ggml_reshape_4d(ctx0, rel_b, rel_b->ne[0], n_head, n_tokens, 1); cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, m, rel_b, 1.0f/sqrtf(n_embd_head), rel_b->ne[0]); ggml_flash_attn_ext_add_sinks(cur, ggml_reshape_3d(ctx0, sinks, n_head, n_tokens, 1)); diff --git a/src/models/models.h b/src/models/models.h index 6b8f40506ee0..c274c4ba1df5 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2549,9 +2549,6 @@ struct llama_model_inkling2 : public llama_model_base { std::vector, bool>> banded_dev_ok; // [base, swa] contiguous mask of the banded attention, shared by the layers of a graph ggml_tensor * mask_banded[2] = { nullptr, nullptr }; - // query rows of the dense bias the first banded full-attention layer also builds in the reserve graph: - // the small ubatches that stay dense take that bias at runtime, the reserve must hold it - int64_t n_rows_dense_reserve = 0; llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; llm_graph_input_attn_kv_iswa * attn = nullptr; From 56df0d22602698ea88e2222cda6902176a6bd3ff Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 19:51:53 -0800 Subject: [PATCH 056/115] ggml : read the banded attention mask in place when it is a view The banded op required a contiguous mask, so inkling2 copied the first n_kv_b cells of every row of the KQ mask into a new tensor, once per graph and cache. In the reserve graph that copy is the size of the mask: n_ctx x n_ubatch F16, 4 GiB at -c 1048576 -ub 2048, held beside the mask itself. The banded kernels (CPU, CUDA scalar, MMA and decode) index the mask by its row stride already, so the op now only requires contiguous rows, and inkling2 passes the view. Delegating to the flash attention MMA kernel still requires a contiguous mask. test-backend-ops: the strided banded cases also take the mask as a view of a wider one. --- ggml/src/ggml-cuda/fattn-banded.cu | 2 +- ggml/src/ggml-cuda/fattn.cu | 5 +++++ ggml/src/ggml.c | 3 ++- src/models/inkling2.cpp | 6 +++--- tests/test-backend-ops.cpp | 23 ++++++++++++++++++++++- 5 files changed, 33 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 5c3ce3b0efce..c6dd845aea9c 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1494,7 +1494,7 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float))) { return false; } - return !m || (m->type == GGML_TYPE_F16 && ggml_is_contiguous(m) && + return !m || (m->type == GGML_TYPE_F16 && m->nb[0] == sizeof(half) && q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0); #endif } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index e37b930c9bb8..6c6dfd092825 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -601,6 +601,11 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + // flash attention reads a contiguous mask + if (dst->src[3] && !ggml_is_contiguous(dst->src[3])) { + return false; + } + // the MMA ABI indexes rel linearly and by Q's batch if (rel->type != GGML_TYPE_F32 || !ggml_is_contiguous(rel) || rel->ne[3] != Q->ne[3] || rel->ne[0] > (1 << 20)) { diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index bc4fca3513b4..2ad730249686 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5516,7 +5516,8 @@ struct ggml_tensor * ggml_flash_attn_ext_banded( if (mask) { GGML_ASSERT(mask->type == GGML_TYPE_F16); - GGML_ASSERT(ggml_is_contiguous(mask)); + // contiguous rows: a view of the first cells of a wider mask is read in place + GGML_ASSERT(mask->nb[0] == ggml_type_size(mask->type)); GGML_ASSERT(q->ne[2] % mask->ne[2] == 0); GGML_ASSERT(q->ne[3] % mask->ne[3] == 0); } diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 3684b260658d..5ca348122edb 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -525,11 +525,11 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens v_all->nb[1], v_all->nb[2], v_all->nb[3], 0), 0, 2, 1, 3); } ggml_tensor * mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - // one banded mask per graph and cache: each layer's own view would be a separate scheduler input copy + // one banded mask per graph and cache, the first n_kv_b cells of each row read in place ggml_tensor *& m = mask_banded[is_swa]; if (!m) { - m = ggml_cont(ctx0, ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], - mask->nb[1], mask->nb[2], mask->nb[3], 0)); + m = ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], + mask->nb[1], mask->nb[2], mask->nb[3], 0); } // exp(s + b)/(exp(t) + sum(exp(s + b))): the dense mask b - t with a zero sink ggml_tensor * rel_bias = layer.attn_rel_bias; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 9a3a4dfc8468..bb5a6a4414dd 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9391,6 +9391,12 @@ struct test_flash_attn_ext_banded : public test_case { if (mask_kind != 0) { m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); ggml_set_name(m, "m"); + if (strided) { + // the first n_kv cells of a wider mask, as the model views it + ggml_tensor * mb = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv + 64, n_q, 1, 1); + ggml_set_name(mb, "m_wide"); + m = ggml_view_4d(ctx, mb, n_kv, n_q, 1, 1, mb->nb[1], mb->nb[2], mb->nb[3], 0); + } } ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); @@ -9401,7 +9407,19 @@ struct test_flash_attn_ext_banded : public test_case { void initialize_tensors(ggml_context * ctx) override { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { - if (strcmp(t->name, "m") == 0) { + if (strcmp(t->name, "m_wide") == 0) { + const int64_t nw = t->ne[0]; + const int64_t n_empty = mask_kind == 3 ? std::min(n_kv - n_q, n_kv/8 + 37) : 0; + std::vector data(n_q*nw); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < nw; ++ik) { + const int64_t rel_dist = iq + (n_kv - n_empty - n_q) - ik; + const bool visible = ik < n_kv - n_empty && rel_dist >= 0 && (mask_kind != 2 || rel_dist < rel_extent); + data[iq*nw + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (strcmp(t->name, "m") == 0) { std::vector data(n_q*n_kv); // padded n_kv: the last cells are empty, the queries are the tail of the cells before them const int64_t n_empty = mask_kind == 3 ? std::min(n_kv - n_q, n_kv/8 + 37) : 0; @@ -13647,6 +13665,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 4096, 1280, 3, kv_type, GGML_TYPE_F32, 2)); } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 256, 1280, 3, kv_type, GGML_TYPE_F32, 2)); + for (int64_t n_q : { 3, 8, 48 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 4096, 1280, 3, kv_type, GGML_TYPE_F32, 2, true)); + } } // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { From bebd19fd59d06c65a5d202e0298e636b01b2b924 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 22:11:43 -0800 Subject: [PATCH 057/115] kv-cache : check the position contiguity once per applied ubatch get_n_kv_pos_contiguous() walks every cell of the sequence, and a banded ubatch asks for it in the graph build or the reuse check and again in set_input, per cache. With drafts and prompt tails now banded, that is two walks of the whole cache per step: at 1M cells the walk reads the 4 MiB position array and 32 MiB of sequence sets. The result only changes when a ubatch is applied, so keep it until then. --- src/llama-kv-cache.cpp | 10 ++++++++-- src/llama-kv-cache.h | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 87957aad9635..b9823847dec6 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -3123,6 +3123,8 @@ bool llama_kv_cache_context::apply() { n_kv = kv->get_n_kv(sinfos[i_cur]); n_kv_rows = kv->get_n_kv_rows(ubatches[i_cur]); + i_pos_contiguous = SIZE_MAX; + return true; } @@ -3153,8 +3155,12 @@ uint32_t llama_kv_cache_context::get_n_kv_pos_contiguous() const { return 0; } - const uint32_t result = kv->get_n_kv_pos_contiguous(sinfos[i_cur], ubatches[i_cur]); - return result <= (uint32_t) n_kv ? result : 0; + if (i_pos_contiguous != i_cur) { + const uint32_t result = kv->get_n_kv_pos_contiguous(sinfos[i_cur], ubatches[i_cur]); + n_pos_contiguous = result <= (uint32_t) n_kv ? result : 0; + i_pos_contiguous = i_cur; + } + return n_pos_contiguous; } uint32_t llama_kv_cache_context::get_n_kv_rows() const { diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 605b55f0a65f..6c2704829c5a 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -5,6 +5,7 @@ #include "llama-kv-cells.h" #include "llama-memory.h" +#include #include #include @@ -490,6 +491,11 @@ class llama_kv_cache_context : public llama_memory_context_i { // the index of the cur ubatch to process size_t i_cur = 0; + // get_n_kv_pos_contiguous() of ubatch i_cur once applied: the check scans the cells of the sequence, and the + // graph build or reuse check and set_input each ask for it + mutable size_t i_pos_contiguous = SIZE_MAX; + mutable uint32_t n_pos_contiguous = 0; + slot_info_vec_t sinfos; std::vector ubatches; From 5b2da9594e0398d2d4c8816bd469f5979cd2569c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 23:45:32 -0800 Subject: [PATCH 058/115] CUDA: banded decode kernel reads q4_1 / q5_0 / q5_1 and mixed q8_0 K caches in place Dense CUDA flash attention converts K/V types other than F16 / BF16 / q8_0 / q4_0 to an F16 copy of the whole view, and so did the banded kernels below the q8_0 / q4_0 MMA tiles. The decode kernel now reads q4_1, q5_0, q5_1, q8_0-K/q4_0-V and q8_0-K/f16-V directly, up to 32 queries for these types. A single-token Inkling-2 ubatch over such a cache takes it in the full-attention layers of a single-sequence context, so neither decode, drafts nor prompt tails copy the cache, and the reserve no longer holds that copy. --- ggml/src/ggml-cuda/fattn-banded.cu | 165 +++++++++++++++++++++++------ src/llama-graph.cpp | 2 +- src/llama-graph.h | 1 + src/models/inkling2.cpp | 21 +++- src/models/models.h | 2 + tests/test-backend-ops.cpp | 28 +++-- 6 files changed, 178 insertions(+), 41 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index c6dd845aea9c..c3d059989832 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -502,7 +502,82 @@ template<> struct fattn_banded_kv8 { } }; -template +// 8 nibbles of a q4_x / q5_x block (elements e0..e0+7 of 32, e0 % 8 == 0) as bytes, 2-byte loads +static __device__ __forceinline__ void fattn_banded_nib8(const uint8_t * qs, const int e0, uint32_t (&q)[2]) { + const uint16_t * p = (const uint16_t *) (qs + e0 % 16); + const int shift = e0 >= 16 ? 4 : 0; + q[0] = ((uint32_t(p[0]) | (uint32_t(p[1]) << 16)) >> shift) & 0x0F0F0F0Fu; + q[1] = ((uint32_t(p[2]) | (uint32_t(p[3]) << 16)) >> shift) & 0x0F0F0F0Fu; +} + +// bits e0..e0+7 of the 32 high bits as bit 4 of each byte +static __device__ __forceinline__ void fattn_banded_qh8(const uint8_t * qh, const int e0, uint32_t (&q)[2]) { + const uint32_t h = qh[e0/8]; + // bit i of a nibble to bit 0 of byte i: the shifted copies do not overlap, so no carries + q[0] |= (((h & 0xF) * 0x00204081u) & 0x01010101u) << 4; + q[1] |= (((h >> 4) * 0x00204081u) & 0x01010101u) << 4; +} + +template<> struct fattn_banded_kv8 { + uint32_t q[2]; + half d, m; + __device__ __forceinline__ void load(const char * row, const int d0) { + const block_q4_1 * b = (const block_q4_1 *) row + d0/QK4_1; + fattn_banded_nib8(b->qs, d0 % QK4_1, q); + const half * dm = (const half *) &b->dm; // 2-byte loads: rows are only 2-byte aligned + d = dm[0]; + m = dm[1]; + } + __device__ __forceinline__ void get(float (&x)[8]) const { + const float fd = __half2float(d); + const float fm = __half2float(m); +#pragma unroll + for (int j = 0; j < 8; ++j) { + x[j] = fd*float((q[j/4] >> (8*(j % 4))) & 0xFF) + fm; + } + } +}; + +template<> struct fattn_banded_kv8 { + uint32_t q[2]; + half d; + __device__ __forceinline__ void load(const char * row, const int d0) { + const block_q5_0 * b = (const block_q5_0 *) row + d0/QK5_0; + fattn_banded_nib8(b->qs, d0 % QK5_0, q); + fattn_banded_qh8(b->qh, d0 % QK5_0, q); + d = b->d; + } + __device__ __forceinline__ void get(float (&x)[8]) const { + const float scale = __half2float(d); +#pragma unroll + for (int j = 0; j < 8; ++j) { + x[j] = scale*float(int((q[j/4] >> (8*(j % 4))) & 0xFF) - 16); + } + } +}; + +template<> struct fattn_banded_kv8 { + uint32_t q[2]; + half d, m; + __device__ __forceinline__ void load(const char * row, const int d0) { + const block_q5_1 * b = (const block_q5_1 *) row + d0/QK5_1; + fattn_banded_nib8(b->qs, d0 % QK5_1, q); + fattn_banded_qh8(b->qh, d0 % QK5_1, q); + const half * dm = (const half *) &b->dm; + d = dm[0]; + m = dm[1]; + } + __device__ __forceinline__ void get(float (&x)[8]) const { + const float fd = __half2float(d); + const float fm = __half2float(m); +#pragma unroll + for (int j = 0; j < 8; ++j) { + x[j] = fd*float((q[j/4] >> (8*(j % 4))) & 0xFF) + fm; + } + } +}; + +template __launch_bounds__(fattn_banded_vec_threads) static __global__ void flash_attn_ext_banded_vec( const char * __restrict__ q, @@ -605,8 +680,8 @@ static __global__ void flash_attn_ext_banded_vec( for (int64_t c0 = c_begin; c0 < c_end; c0 += TC) { // every load of the tile first: group grp takes cells grp, grp + NG, ... - fattn_banded_kv8 kr[CPG]; - fattn_banded_kv8 vr[CPG]; + fattn_banded_kv8 kr[CPG]; + fattn_banded_kv8 vr[CPG]; float bm[CPG]; // lane t < NR: mask + bias of row t, -inf when masked #pragma unroll for (int j = 0; j < CPG; ++j) { @@ -834,24 +909,42 @@ static __global__ void flash_attn_ext_banded_vec_merge( } // the decode kernel reads K and V once per block of rows: past 8 queries the MMA kernel is faster -static constexpr int64_t fattn_banded_vec_max_q = 8; +// K/V the MMA kernel reads directly (F16 / BF16, matching q8_0 / q4_0 tiles) take it from 9 queries on, +// the others stay here up to 32 queries instead of an F16 copy of the whole cache +static constexpr int64_t fattn_banded_vec_max_q = 8; +static constexpr int64_t fattn_banded_vec_max_q_conv = 32; + +static bool fattn_banded_vec_mma_direct(const ggml_type tk, const ggml_type tv) { + return tk == tv && (tk == GGML_TYPE_F16 || tk == GGML_TYPE_BF16 || tk == GGML_TYPE_Q8_0 || tk == GGML_TYPE_Q4_0); +} + +// K/V type pairs with a decode kernel instance: q4_1 / q5_x and the mixed pairs only for D = 128 +static bool fattn_banded_vec_pair(const ggml_type tk, const ggml_type tv, const int64_t D) { + if (fattn_banded_vec_mma_direct(tk, tv)) { + return true; + } + if (D != 128) { + return false; + } + if (tk == tv) { + return tk == GGML_TYPE_Q4_1 || tk == GGML_TYPE_Q5_0 || tk == GGML_TYPE_Q5_1; + } + return tk == GGML_TYPE_Q8_0 && (tv == GGML_TYPE_Q4_0 || tv == GGML_TYPE_F16); +} static bool fattn_banded_vec_usable(const ggml_tensor * dst) { const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; - if (q->ne[1] > fattn_banded_vec_max_q || k->type != v->type) { + if (!fattn_banded_vec_pair(k->type, v->type, q->ne[0])) { return false; } - switch (k->type) { - case GGML_TYPE_F16: case GGML_TYPE_BF16: case GGML_TYPE_Q8_0: case GGML_TYPE_Q4_0: - break; - default: - return false; + if (q->ne[1] > (fattn_banded_vec_mma_direct(k->type, v->type) ? fattn_banded_vec_max_q : fattn_banded_vec_max_q_conv)) { + return false; } // 16-byte F16 / BF16 and 2-byte quantized loads, 16-byte Q loads - const size_t align = k->type == GGML_TYPE_F16 || k->type == GGML_TYPE_BF16 ? 16 : 2; for (const ggml_tensor * t : {k, v}) { + const size_t align = t->type == GGML_TYPE_F16 || t->type == GGML_TYPE_BF16 ? 16 : 2; if (t->nb[1] % align != 0 || t->nb[2] % align != 0 || t->nb[3] % align != 0 || (uintptr_t) t->data % align != 0) { return false; } @@ -898,39 +991,49 @@ static void fattn_banded_vec_launch(ggml_backend_cuda_context & ctx, ggml_tensor const int64_t sinks_s2 = sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0; const dim3 blocks(k->ne[2], n_chunks, n_rb*q->ne[3]); -#define LAUNCH_BANDED_VEC_T(DD, NRR, T) \ - flash_attn_ext_banded_vec<<>>( \ +#define LAUNCH_BANDED_VEC_T(DD, NRR, TK, TV) \ + flash_attn_ext_banded_vec<<>>( \ (const char *) q->data, (const char *) k->data, (const char *) v->data, m ? (const char *) m->data : nullptr, \ (const char *) rel->data, n_chunks == 1 ? sinks_d : nullptr, (float *) dst->data, part.get(), \ scale, rel->type, int(n_q), n_kv, int(q->ne[2]), int(k->ne[2]), n_chunks, chunk, rel_extent, \ m ? m->ne[2] : 1, m ? m->ne[3] : 1, q->nb[1], q->nb[2], q->nb[3], k->nb[1], k->nb[2], k->nb[3], \ v->nb[1], v->nb[2], v->nb[3], m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2) -#define LAUNCH_BANDED_VEC_NR(DD, T) \ +#define LAUNCH_BANDED_VEC_NR(DD, TK, TV) \ switch (NR) { \ - case 1: LAUNCH_BANDED_VEC_T(DD, 1, T); break; \ - case 2: LAUNCH_BANDED_VEC_T(DD, 2, T); break; \ - case 3: LAUNCH_BANDED_VEC_T(DD, 3, T); break; \ - case 4: LAUNCH_BANDED_VEC_T(DD, 4, T); break; \ - case 5: LAUNCH_BANDED_VEC_T(DD, 5, T); break; \ - case 6: LAUNCH_BANDED_VEC_T(DD, 6, T); break; \ - case 7: LAUNCH_BANDED_VEC_T(DD, 7, T); break; \ - default: LAUNCH_BANDED_VEC_T(DD, 8, T); break; \ - } -#define LAUNCH_BANDED_VEC(DD) \ + case 1: LAUNCH_BANDED_VEC_T(DD, 1, TK, TV); break; \ + case 2: LAUNCH_BANDED_VEC_T(DD, 2, TK, TV); break; \ + case 3: LAUNCH_BANDED_VEC_T(DD, 3, TK, TV); break; \ + case 4: LAUNCH_BANDED_VEC_T(DD, 4, TK, TV); break; \ + case 5: LAUNCH_BANDED_VEC_T(DD, 5, TK, TV); break; \ + case 6: LAUNCH_BANDED_VEC_T(DD, 6, TK, TV); break; \ + case 7: LAUNCH_BANDED_VEC_T(DD, 7, TK, TV); break; \ + default: LAUNCH_BANDED_VEC_T(DD, 8, TK, TV); break; \ + } +#define LAUNCH_BANDED_VEC_SAME(DD) \ switch (k->type) { \ - case GGML_TYPE_F16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_F16); break; \ - case GGML_TYPE_BF16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_BF16); break; \ - case GGML_TYPE_Q8_0: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q8_0); break; \ - default: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q4_0); break; \ + case GGML_TYPE_F16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_F16, GGML_TYPE_F16); break; \ + case GGML_TYPE_BF16: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_BF16, GGML_TYPE_BF16); break; \ + case GGML_TYPE_Q8_0: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q8_0, GGML_TYPE_Q8_0); break; \ + default: LAUNCH_BANDED_VEC_NR(DD, GGML_TYPE_Q4_0, GGML_TYPE_Q4_0); break; \ } if (D == 64) { - LAUNCH_BANDED_VEC(64); + LAUNCH_BANDED_VEC_SAME(64); + } else if (fattn_banded_vec_mma_direct(k->type, v->type)) { + LAUNCH_BANDED_VEC_SAME(128); + } else if (k->type == v->type) { + switch (k->type) { + case GGML_TYPE_Q4_1: LAUNCH_BANDED_VEC_NR(128, GGML_TYPE_Q4_1, GGML_TYPE_Q4_1); break; + case GGML_TYPE_Q5_0: LAUNCH_BANDED_VEC_NR(128, GGML_TYPE_Q5_0, GGML_TYPE_Q5_0); break; + default: LAUNCH_BANDED_VEC_NR(128, GGML_TYPE_Q5_1, GGML_TYPE_Q5_1); break; + } + } else if (v->type == GGML_TYPE_Q4_0) { + LAUNCH_BANDED_VEC_NR(128, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0); } else { - LAUNCH_BANDED_VEC(128); + LAUNCH_BANDED_VEC_NR(128, GGML_TYPE_Q8_0, GGML_TYPE_F16); } #undef LAUNCH_BANDED_VEC_NR -#undef LAUNCH_BANDED_VEC +#undef LAUNCH_BANDED_VEC_SAME #undef LAUNCH_BANDED_VEC_T CUDA_CHECK(cudaGetLastError()); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index bf28a31641b4..036d84d1528f 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1508,7 +1508,7 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par if (banded) { res &= get_n_kv_banded(attn_ctx->get_base()) == n_kv_banded[0]; - res &= get_n_kv_banded(attn_ctx->get_swa()) == n_kv_banded[1]; + res &= (banded_swa_dense ? 0 : get_n_kv_banded(attn_ctx->get_swa())) == n_kv_banded[1]; } res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 9fcf11719888..2232d3d47cd5 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -819,6 +819,7 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { // a small ubatch is reused. The empty cells past the sequence are masked, and the band is shifted by the padding // through self_rel_shift, the row of the relative bias for each band column, extent past the band (a zero row) bool banded_pad = false; + bool banded_swa_dense = false; // the graph keeps the SWA layers dense ggml_tensor * self_rel_shift[2] = { nullptr, nullptr }; // I32 [extent + n_rel_pad], [extent_swa + n_rel_pad] static constexpr uint32_t n_rel_pad = 256; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 5ca348122edb..b17c2c0b347a 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -2,6 +2,7 @@ #include "../llama-memory-hybrid-iswa.h" #include +#include #include // max elements of the dense relative bias per attention call, and max chunks per layer @@ -325,6 +326,9 @@ bool llama_model_inkling2::graph::use_banded(int il, bool swa) { if (!dev) { return false; } + if (decode_banded && strcmp(ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)), "CUDA") != 0) { + return false; + } for (const auto & [key, ok] : banded_dev_ok) { if (key.first == swa && key.second == dev) { return ok; @@ -353,12 +357,25 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { // banded FA needs a position-contiguous cache. Ubatches of 2 to n_tokens_banded_min tokens (drafts, prompt tails) // span the padded n_kv, which changes only every 256 cells, so that their graph is reused. A decode step stays // dense: the FA vec kernel is faster there, and the reserved tg graph (one token over the whole cache) holds its bias - inp->banded = cparams.flash_attn && n_tokens > 1; + // except with a cache type that dense CUDA FA converts to F16 whole every step (it reads F16 / BF16 / q8_0 / q4_0 + // in place): then the full-attention layers of a single-sequence context take the banded kernel + const auto * base = attn->mctx->get_base(); + const ggml_type tk = base->type_k(); + const ggml_type tv = base->type_v(); + decode_banded = n_tokens == 1 && cparams.n_seq_max == 1 && (tk == tv ? + tk == GGML_TYPE_Q4_1 || tk == GGML_TYPE_Q5_0 || tk == GGML_TYPE_Q5_1 : + tk == GGML_TYPE_Q8_0 && (tv == GGML_TYPE_Q4_0 || tv == GGML_TYPE_F16)); + inp->banded = cparams.flash_attn && (n_tokens > 1 || decode_banded); inp->banded_pad = n_tokens <= n_tokens_banded_min; for (int i = 0; i < 2 && inp->banded; ++i) { // a ubatch of several sequences is dense at runtime, so the reserved worst case (a ubatch // of every sequence) must be dense too, else the dense graph outgrows the reserved buffer - inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : inp->get_n_kv_banded(i ? attn->mctx->get_swa() : attn->mctx->get_base()); + inp->n_kv_banded[i] = ubatch.n_seqs_unq != 1 ? 0 : inp->get_n_kv_banded(i ? attn->mctx->get_swa() : base); + } + // the SWA view is small, and once it wraps a decode step is dense anyway: keep it dense in the reserve too + if (decode_banded) { + inp->banded_swa_dense = true; + inp->n_kv_banded[1] = 0; } // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), // while at runtime it does so only for consecutive ones. Once the positions pass the SWA cache it wraps diff --git a/src/models/models.h b/src/models/models.h index c274c4ba1df5..ea6c763f4333 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2547,6 +2547,8 @@ struct llama_model_inkling2 : public llama_model_base { // banded flash attention for layer il on its device and cache bool use_banded(int il, bool swa); std::vector, bool>> banded_dev_ok; + // single-token ubatch over a cache type that the dense path converts to F16 whole + bool decode_banded = false; // [base, swa] contiguous mask of the banded attention, shared by the layers of a graph ggml_tensor * mask_banded[2] = { nullptr, nullptr }; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index bb5a6a4414dd..cd1ca9bbf16d 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9341,9 +9341,11 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type kv_type; const ggml_type rel_type; const bool strided; + const ggml_type v_type; // GGML_TYPE_COUNT: kv_type std::string vars() override { - return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); + std::string s = VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); + return v_type == GGML_TYPE_COUNT ? s : s + ",v_type=" + ggml_type_name(v_type); } double max_nmse_err() override { @@ -9361,25 +9363,26 @@ struct test_flash_attn_ext_banded : public test_case { test_flash_attn_ext_banded( int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false) + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, ggml_type v_type = GGML_TYPE_COUNT) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), - rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided) {} + rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), v_type(v_type) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); ggml_tensor * k; ggml_tensor * v; ggml_tensor * r; + const ggml_type vt = v_type == GGML_TYPE_COUNT ? kv_type : v_type; if (strided) { ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); - ggml_tensor * vb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, vt, 2*d, n_kv, n_head_kv, 1); ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); k = ggml_view_4d(ctx, kb, d, n_kv, n_head_kv, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0); v = ggml_view_4d(ctx, vb, d, n_kv, n_head_kv, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0); r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); } else { k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, vt, d, n_kv, n_head_kv, 1); r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); } ggml_set_name(q, "q"); @@ -9448,8 +9451,8 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } test_flash_attn_ext_banded_sinks(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false) - : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided), sinks(sinks) {} + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false, ggml_type v_type = GGML_TYPE_COUNT) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, v_type), sinks(sinks) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); @@ -13669,6 +13672,17 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 4096, 1280, 3, kv_type, GGML_TYPE_F32, 2, true)); } } + // the other cache types and mixed K/V, read in place by the decode kernel up to 32 queries + for (auto [kt, vt] : std::vector>{ + { GGML_TYPE_Q4_1, GGML_TYPE_Q4_1 }, { GGML_TYPE_Q5_0, GGML_TYPE_Q5_0 }, { GGML_TYPE_Q5_1, GGML_TYPE_Q5_1 }, + { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }, { GGML_TYPE_Q8_0, GGML_TYPE_F16 }, { GGML_TYPE_F16, GGML_TYPE_Q8_0 } }) { + for (int64_t n_q : { 1, 2, 3, 8, 9, 16, 32, 33 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 4096, 1280, 3, kt, GGML_TYPE_F32, 2, false, vt)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 256, 1280, 3, kt, GGML_TYPE_F32, 2, false, vt)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 3, 4096, 1280, 3, kt, GGML_TYPE_F32, 2, true, vt)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 1000, 8, 1, kt, GGML_TYPE_F32, 2, false, vt)); + } // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, n_q, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); From 540ca0a7eaa8f37290527fa197485df242f48e72 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 03:49:28 -0800 Subject: [PATCH 059/115] tests : keep the banded test constructors as #378 has them, layout cases in a derived struct The interleaved K/V view and the V head count / length cases move to test_flash_attn_ext_banded_layout. Case names are unchanged. --- tests/test-backend-ops.cpp | 106 +++++++++++++++++++++++++++---------- 1 file changed, 77 insertions(+), 29 deletions(-) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index f6cfa2894b00..2e705f2ef154 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9341,14 +9341,9 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type kv_type; const ggml_type rel_type; const bool strided; - const bool interleaved; // K/V as a permuted [d, n_head_kv, n_kv] cache view: the row stride spans all KV heads - const int64_t n_head_v; - const int64_t n_kv_v; std::string vars() override { - return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) + - (interleaved ? ",interleaved=1" : "") + (n_head_v ? ",n_head_v=" + std::to_string(n_head_v) : "") + - (n_kv_v ? ",n_kv_v=" + std::to_string(n_kv_v) : ""); + return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); } double max_nmse_err() override { @@ -9366,23 +9361,16 @@ struct test_flash_attn_ext_banded : public test_case { test_flash_attn_ext_banded( int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, bool interleaved = false, - int64_t n_head_v = 0, int64_t n_kv_v = 0) + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), - rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), - interleaved(interleaved), n_head_v(n_head_v), n_kv_v(n_kv_v) {} + rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); ggml_tensor * k; ggml_tensor * v; ggml_tensor * r; - if (interleaved) { - // exactly sized, like the KV cache: the last head's last row ends at the end of the buffer - k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); - v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); - r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); - } else if (strided) { + if (strided) { ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); ggml_tensor * vb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); @@ -9391,7 +9379,7 @@ struct test_flash_attn_ext_banded : public test_case { r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); } else { k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv_v ? n_kv_v : n_kv, n_head_v ? n_head_v : n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); } ggml_set_name(q, "q"); @@ -9440,10 +9428,8 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } test_flash_attn_ext_banded_sinks(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false, bool interleaved = false, - int64_t n_head_v = 0) - : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, interleaved, - n_head_v), sinks(sinks) {} + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool strided = false) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided), sinks(sinks) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); @@ -9459,6 +9445,68 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } }; +// banded attention over K/V layouts the cache builds or the backends must refuse: a permuted [d, n_head_kv, n_kv] +// cache view (the row stride spans all KV heads), or a V with its own head count or length +struct test_flash_attn_ext_banded_layout : public test_flash_attn_ext_banded { + const int sinks; // 0: none, 1: per head, 2: per head and query + const bool interleaved; + const int64_t n_head_v; + const int64_t n_kv_v; + + std::string vars() override { + return test_flash_attn_ext_banded::vars() + + (interleaved ? ",interleaved=1" : "") + (n_head_v ? ",n_head_v=" + std::to_string(n_head_v) : "") + + (n_kv_v ? ",n_kv_v=" + std::to_string(n_kv_v) : "") + (sinks ? ",sinks=" + std::to_string(sinks) : ""); + } + + test_flash_attn_ext_banded_layout(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + int mask_kind, ggml_type kv_type, ggml_type rel_type, int sinks, bool interleaved, int64_t n_head_v = 0, int64_t n_kv_v = 0) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type), + sinks(sinks), interleaved(interleaved), n_head_v(n_head_v), n_kv_v(n_kv_v) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + ggml_tensor * k; + ggml_tensor * v; + if (interleaved) { + // exactly sized, like the KV cache: the last head's last row ends at the end of the buffer + k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); + v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, kv_type, d, n_head_kv, n_kv, 1), 0, 2, 1, 3); + } else { + k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv_v ? n_kv_v : n_kv, n_head_v ? n_head_v : n_head_kv, 1); + } + ggml_tensor * r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + + ggml_tensor * m = nullptr; + if (mask_kind != 0) { + m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, n_kv, n_q, 1, 1); + ggml_set_name(m, "m"); + } + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); + if (sinks) { + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, sinks == 2 ? n_q : 1); + ggml_set_name(s, "sinks"); + ggml_flash_attn_ext_add_sinks(out, s); + } + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + test_flash_attn_ext_banded::initialize_tensors(ctx); + if (sinks) { + init_tensor_uniform(ggml_get_tensor(ctx, "sinks"), -4.0f, 4.0f); + } + } +}; + struct test_flash_attn_ext_banded_large_rel : public test_flash_attn_ext_banded_sinks { static constexpr int rel_range = 20; @@ -13850,11 +13898,11 @@ static std::vector> make_test_cases_eval() { // interleaved K/V cache views with a ragged n_kv: the pad pass must stay inside K/V for (int64_t n_kv : { 72, 1000 }) { for (int mask_kind : { 0, 1 }) { - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, n_kv, 96, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout(128, 24, 8, 33, n_kv, 96, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 2, true)); } } - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, true)); - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 77, 333, 16, 2, GGML_TYPE_F32, GGML_TYPE_F32, 1, false, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout(128, 24, 8, 512, 4161, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout( 64, 8, 2, 77, 333, 16, 2, GGML_TYPE_F32, GGML_TYPE_F32, 1, true)); // shapes beyond the cache layout (backends may refuse some): // d, nh, nkv, n_q, n_kv, ext, mk, kv type, seq, rel_bc, m_heads, m_seq_bc, m_rows, m_cols, q_perm, s_seq test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 33, 300, 16, 1, GGML_TYPE_F16, 2, false, true, false, 33, 300, true, true)); @@ -13866,11 +13914,11 @@ static std::vector> make_test_cases_eval() { // mask wider than K (the mask block classification must not use the mask width as the K length) test_cases.emplace_back(new test_flash_attn_ext_banded_shapes( 64, 1, 1, 16, 64, 8, 0, GGML_TYPE_F16, 1, false, false, false, 16, 128, false, false)); test_cases.emplace_back(new test_flash_attn_ext_banded_shapes(128, 8, 2, 100, 1000, 96, 1, GGML_TYPE_F16, 1, false, false, false, 100, 1037, false, false)); - test_cases.emplace_back(new test_flash_attn_ext_banded ( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 1)); - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, false, 2)); - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 1, 33, 100, 16, 1, GGML_TYPE_F16, GGML_TYPE_F32, 1, false, false, 4)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, 0, false, 1)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout(128, 8, 4, 33, 100, 16, 2, GGML_TYPE_F16, GGML_TYPE_F32, 2, false, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout(128, 8, 1, 33, 100, 16, 1, GGML_TYPE_F16, GGML_TYPE_F32, 1, false, 4)); // V with more rows than K, and 65536 queries; backends may refuse these - test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, false, false, 0, 100)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout( 64, 8, 2, 8, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F32, 0, false, 0, 100)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 1, 1, 65536, 64, 1, 0, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 100, 1000, 96, 2, GGML_TYPE_BF16, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 1, 4096, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); @@ -13881,7 +13929,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, 1100, 1024, 1, kv_type, GGML_TYPE_F32, 2)); } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 4096, 1024, 2, kv_type, GGML_TYPE_F32, 2)); - test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 3, 1000, 96, 2, kv_type, GGML_TYPE_F32, 2, false, true)); + test_cases.emplace_back(new test_flash_attn_ext_banded_layout(128, 24, 8, 3, 1000, 96, 2, kv_type, GGML_TYPE_F32, 2, true)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 333, 16, 2, kv_type, GGML_TYPE_F32, 1)); } test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 1000, 96, 1, GGML_TYPE_F16, GGML_TYPE_F16, 2)); From f90e56765dffe006135d1831d0c67063db82a8be Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 03:49:28 -0800 Subject: [PATCH 060/115] metal : refuse banded attention with K/V cell and query positions The kernels take the distance from the cell index. A cache whose cells are not the positions (several sequences, a wrapped SWA cache) sets src[7] / src[8]; refusing it lets the model fall back to dense attention. --- ggml/src/ggml-metal/ggml-metal-device.m | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 6c4356b01d26..eeefd3970684 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1846,6 +1846,10 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[0]->ne[0] != 64 && op->src[0]->ne[0] != 128) { return false; } + // K/V cell and query positions (src[7], src[8]): the kernels take the distance from the cell index + if (op->src[7] || op->src[8]) { + return false; + } if (op->src[2]->ne[0] != op->src[1]->ne[0]) { return false; } From c4e3077a6d5b3662ec7d685cc3fb95321034d0f7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 04:17:07 -0800 Subject: [PATCH 061/115] ggml : keep the banded split handler of the meta backend as #378 has it #378 adds the same FLASH_ATTN_EXT_BANDED split handler at the same place; the two position asserts added here made the two additions differ, so the pin set refused to merge them. The handler does not depend on src[7] / src[8], which hold the cell and query positions. --- ggml/src/ggml-backend-meta.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 6674a9000bd8..c3e4de1d2a7f 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -861,9 +861,6 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( GGML_ASSERT(tensor->src[3] == nullptr || src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); // ggml_flash_attn_ext_banded stores rel_logits [E, n_head, n_q, n_seq] in src[6], split by head like q GGML_ASSERT( src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); - // the optional K/V cell and query positions are shared by every head - GGML_ASSERT(tensor->src[7] == nullptr || src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); - GGML_ASSERT(tensor->src[8] == nullptr || src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); return {GGML_BACKEND_SPLIT_AXIS_1, {0}, {1}, 1}; }; From 8ee792043e6b15ca5ccdf66ff4e480ff86411a44 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 04:25:35 -0800 Subject: [PATCH 062/115] inkling : extend the banded code #378 carries instead of rewriting its lines The banded kernels, the CPU distance, the contiguous-position memo and the banded tests keep the lines #378 adds and grow around them: the position arguments of the scalar kernels come before the rel strides, the cell distance is the old expression in the no-position branch, a mixed K/V test uses its own constructor, and the position checks of test-flash-attn-bias report their own verdict. No change in behaviour. --- ggml/src/ggml-cpu/ops.cpp | 5 ++- ggml/src/ggml-cuda/fattn-banded.cu | 37 ++++++++++++---------- src/llama-kv-cache.cpp | 7 ++-- tests/test-backend-ops.cpp | 51 +++++++++++++++++++++--------- tests/test-flash-attn-bias.cpp | 33 +++++++++++++------ 5 files changed, 89 insertions(+), 44 deletions(-) diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 7c0bad6c44ae..6cc8b0eb0496 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8999,7 +8999,10 @@ static inline int64_t ggml_flash_attn_ext_banded_dist(const ggml_tensor * dst, i const ggml_tensor * k_pos = dst->src[7]; const ggml_tensor * q_pos = dst->src[8]; if (!k_pos) { - return iq1 + (dst->src[1]->ne[1] - dst->src[0]->ne[1]) - ic; + const int64_t nek1 = dst->src[1]->ne[1]; + const int64_t neq1 = dst->src[0]->ne[1]; + const int64_t rel_dist = iq1 + (nek1 - neq1) - ic; + return rel_dist; } const int32_t kp = *(const int32_t *) ((const char *) k_pos->data + ic*k_pos->nb[0] + (iq3 % k_pos->ne[1])*k_pos->nb[1]); const int32_t qp = *(const int32_t *) ((const char *) q_pos->data + iq1*q_pos->nb[0] + (iq3 % q_pos->ne[1])*q_pos->nb[1]); diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 60a7b31d123c..52c2f1b7924a 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -31,7 +31,8 @@ static __device__ __forceinline__ int64_t fattn_banded_dist( const int32_t kp = k_pos[ik]; return kp < 0 ? -1 : int64_t(q_pos[iq]) - kp; } - return iq + q_offset - ik; + const int64_t rel_dist = iq + q_offset - ik; + return rel_dist; } template @@ -71,15 +72,15 @@ static __global__ void flash_attn_ext_banded_f32( const float * __restrict__ sinks, int64_t sinks_s1, int64_t sinks_s2, + const int32_t * __restrict__ k_pos, + const int32_t * __restrict__ q_pos, + int64_t kpos_s1, + int64_t qpos_s1, uint64_t r_nb0, uint64_t r_nb1, uint64_t r_nb2, uint64_t r_nb3, - int64_t rel_ne3, - const int32_t * __restrict__ k_pos, - const int32_t * __restrict__ q_pos, - int64_t kpos_s1, - int64_t qpos_s1) { + int64_t rel_ne3) { constexpr int values_per_lane = D / WARP_SIZE; static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); static_assert(D % WARP_SIZE == 0, "head dimension must be divisible by warp size"); @@ -229,15 +230,15 @@ static __global__ void flash_attn_ext_banded_f32_split( uint64_t m_nb1, uint64_t m_nb2, uint64_t m_nb3, + const int32_t * __restrict__ k_pos, + const int32_t * __restrict__ q_pos, + int64_t kpos_s1, + int64_t qpos_s1, uint64_t r_nb0, uint64_t r_nb1, uint64_t r_nb2, uint64_t r_nb3, - int64_t rel_ne3, - const int32_t * __restrict__ k_pos, - const int32_t * __restrict__ q_pos, - int64_t kpos_s1, - int64_t qpos_s1) { + int64_t rel_ne3) { constexpr int values_per_lane = D / WARP_SIZE; static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); @@ -1653,7 +1654,11 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d (k_pos->ne[1] != 1 && k_pos->ne[1] != q->ne[3]) || (q_pos->ne[1] != 1 && q_pos->ne[1] != q->ne[3]))) { return false; } - return !m || (m->type == GGML_TYPE_F16 && m->nb[0] == sizeof(half) && + if (m && m->type == GGML_TYPE_F16 && m->nb[0] == sizeof(half) && !ggml_is_contiguous(m)) { + // the first n_kv cells of a wider mask, as the model views it: the rows are read with their stride + return q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0; + } + return !m || (m->type == GGML_TYPE_F16 && ggml_is_contiguous(m) && q->ne[2] % m->ne[2] == 0 && q->ne[3] % m->ne[3] == 0); #endif } @@ -1944,8 +1949,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso q->nb[1], q->nb[2], q->nb[3], k->nb[0], k->nb[1], k->nb[2], k->nb[3], \ v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], \ - k_pos_d, q_pos_d, kpos_s1, qpos_s1); \ + k_pos_d, q_pos_d, kpos_s1, qpos_s1, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]); \ flash_attn_ext_banded_f32_merge
<<>>( \ part.get(), (float *) dst->data, n_rows, q->ne[2], q->ne[1], n_chunks, \ sinks ? (const float *) sinks->data : nullptr, \ @@ -1978,8 +1983,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso sinks ? (const float *) sinks->data : nullptr, \ sinks && sinks->ne[1] > 1 ? int64_t(sinks->nb[1] / sizeof(float)) : 0, \ sinks && sinks->ne[2] > 1 ? int64_t(sinks->nb[2] / sizeof(float)) : 0, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], \ - k_pos_d, q_pos_d, kpos_s1, qpos_s1) + k_pos_d, q_pos_d, kpos_s1, qpos_s1, \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]) if (q->ne[0] == 64) { LAUNCH_BANDED(64); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 04cab8982db0..506a2a450648 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -3167,9 +3167,12 @@ uint32_t llama_kv_cache_context::get_n_kv_pos_contiguous() const { return 0; } + // memoized per ubatch: every layer of the graph asks if (i_pos_contiguous != i_cur) { - const uint32_t result = kv->get_n_kv_pos_contiguous(sinfos[i_cur], ubatches[i_cur]); - n_pos_contiguous = result <= (uint32_t) n_kv ? result : 0; + n_pos_contiguous = [&]() -> uint32_t { + const uint32_t result = kv->get_n_kv_pos_contiguous(sinfos[i_cur], ubatches[i_cur]); + return result <= (uint32_t) n_kv ? result : 0; + }(); i_pos_contiguous = i_cur; } return n_pos_contiguous; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 0e5b9acb863e..b97f5a530c2b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9427,11 +9427,13 @@ struct test_flash_attn_ext_banded : public test_case { const ggml_type kv_type; const ggml_type rel_type; const bool strided; - const ggml_type v_type; // GGML_TYPE_COUNT: kv_type + ggml_type v_type = GGML_TYPE_COUNT; // the V type when it differs from K, set by the mixed constructor std::string vars() override { - std::string s = VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); - return v_type == GGML_TYPE_COUNT ? s : s + ",v_type=" + ggml_type_name(v_type); + if (v_type != GGML_TYPE_COUNT) { + return VARS_TO_STR11(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided, v_type); + } + return VARS_TO_STR10(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided); } double max_nmse_err() override { @@ -9449,26 +9451,46 @@ struct test_flash_attn_ext_banded : public test_case { test_flash_attn_ext_banded( int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, - int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false, ggml_type v_type = GGML_TYPE_COUNT) + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided = false) : d(d), n_head(n_head), n_head_kv(n_head_kv), n_q(n_q), n_kv(n_kv), - rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided), v_type(v_type) {} + rel_extent(rel_extent), mask_kind(mask_kind), kv_type(kv_type), rel_type(rel_type), strided(strided) {} + + // K of kv_type, V of v_type (GGML_TYPE_COUNT: kv_type) + test_flash_attn_ext_banded( + int64_t d, int64_t n_head, int64_t n_head_kv, + int64_t n_q, int64_t n_kv, int64_t rel_extent, + int mask_kind, ggml_type kv_type, ggml_type rel_type, bool strided, ggml_type v_type) + : test_flash_attn_ext_banded(d, n_head, n_head_kv, n_q, n_kv, rel_extent, mask_kind, kv_type, rel_type, strided) { + this->v_type = v_type; + } ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); ggml_tensor * k; ggml_tensor * v; ggml_tensor * r; - const ggml_type vt = v_type == GGML_TYPE_COUNT ? kv_type : v_type; - if (strided) { + if (strided && v_type != GGML_TYPE_COUNT) { + // a V cache type that differs from K ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); - ggml_tensor * vb = ggml_new_tensor_4d(ctx, vt, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, v_type, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); + k = ggml_view_4d(ctx, kb, d, n_kv, n_head_kv, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0); + v = ggml_view_4d(ctx, vb, d, n_kv, n_head_kv, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0); + r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); + } else if (strided) { + ggml_tensor * kb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, kv_type, 2*d, n_kv, n_head_kv, 1); ggml_tensor * rb = ggml_new_tensor_4d(ctx, rel_type, 2*rel_extent, n_head, n_q, 1); k = ggml_view_4d(ctx, kb, d, n_kv, n_head_kv, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0); v = ggml_view_4d(ctx, vb, d, n_kv, n_head_kv, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0); r = ggml_view_4d(ctx, rb, rel_extent, n_head, n_q, 1, rb->nb[1], rb->nb[2], rb->nb[3], 0); } else { k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); - v = ggml_new_tensor_4d(ctx, vt, d, n_kv, n_head_kv, 1); + if (v_type == GGML_TYPE_COUNT) { + v = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + } else { + v = ggml_new_tensor_4d(ctx, v_type, d, n_kv, n_head_kv, 1); + } r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); } ggml_set_name(q, "q"); @@ -9496,7 +9518,8 @@ struct test_flash_attn_ext_banded : public test_case { void initialize_tensors(ggml_context * ctx) override { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { - if (strcmp(t->name, "m_wide") == 0) { + if (strcmp(t->name, "m_wide") == 0 || (strcmp(t->name, "m") == 0 && mask_kind == 3)) { + // padded n_kv (mask_kind 3): the last cells are empty, the queries are the tail of the cells before them const int64_t nw = t->ne[0]; const int64_t n_empty = mask_kind == 3 ? std::min(n_kv - n_q, n_kv/8 + 37) : 0; std::vector data(n_q*nw); @@ -9508,14 +9531,12 @@ struct test_flash_attn_ext_banded : public test_case { } } ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); - } else if (strcmp(t->name, "m") == 0) { + } else if (strcmp(t->name, "m") == 0 && mask_kind != 3) { std::vector data(n_q*n_kv); - // padded n_kv: the last cells are empty, the queries are the tail of the cells before them - const int64_t n_empty = mask_kind == 3 ? std::min(n_kv - n_q, n_kv/8 + 37) : 0; for (int64_t iq = 0; iq < n_q; ++iq) { for (int64_t ik = 0; ik < n_kv; ++ik) { - const int64_t rel_dist = iq + (n_kv - n_empty - n_q) - ik; - const bool visible = rel_dist >= 0 && ik < n_kv - n_empty && (mask_kind != 2 || rel_dist < rel_extent); + const int64_t rel_dist = iq + (n_kv - n_q) - ik; + const bool visible = rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent); data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index 2d7a0e2600ee..d4292f5386d5 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -156,12 +156,17 @@ static test_data make_data(const bias_test_config & c) { make_layout(c, k_seq, data.k_pos, q_seq, data.q_pos); // the distance of a query to a cell, -1 if the cell is empty auto distance = [&](int64_t iq, int64_t ik) -> int64_t { + if (c.layout == 0) { + const int64_t dist = iq + (c.nkv - c.nq) - ik; + return dist; + } return data.k_pos[ik] < 0 ? -1 : int64_t(data.q_pos[iq]) - data.k_pos[ik]; }; for (int64_t iq = 0; iq < c.nq; ++iq) { for (int64_t ik = 0; ik < c.nkv; ++ik) { - const int64_t dist = distance(iq, ik); - const bool visible = !c.use_mask || (dist >= 0 && k_seq[ik] == q_seq[iq] && (!c.sliding || dist < c.extent)); + // a cell of another sequence is as invisible as an empty one + const int64_t dist = k_seq[ik] == q_seq[iq] ? distance(iq, ik) : -1; + const bool visible = !c.use_mask || (dist >= 0 && (!c.sliding || dist < c.extent)); data.mask[iq*c.nkv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } @@ -193,8 +198,8 @@ static run_result run_graph( const bias_test_config & c, const test_data & data, bool dense, - int repeats, - bool with_pos = false) { + bool with_pos, + int repeats) { ggml_init_params params = { /* .mem_size = */ ggml_tensor_overhead()*64 + ggml_graph_overhead_custom(64, false), /* .mem_base = */ nullptr, @@ -306,6 +311,10 @@ static run_result run_graph( return result; } +static run_result run_graph(ggml_backend_t backend, const bias_test_config & c, const test_data & data, bool dense, int repeats) { + return run_graph(backend, c, data, dense, false, repeats); +} + static std::vector naive_materialized(const bias_test_config & c, const test_data & data) { const int64_t nrows = c.n_batch*c.hq*c.nq; std::vector scores(nrows*c.nkv); @@ -592,8 +601,9 @@ int main(int argc, char ** argv) { {"heads64_gqa", 64, 1024, 1024, 64, 8, 512, GGML_TYPE_F16, true, false}, }; } else { - fprintf(stderr, "unknown suite: %s (expected small, medium, pos, hard, perf, memory, or overflow)\n", + fprintf(stderr, "unknown suite: %s (expected small, medium, hard, perf, memory, or overflow)\n", suite.c_str()); + fprintf(stderr, "or pos: the cells are not the positions\n"); return 2; } @@ -610,26 +620,29 @@ int main(int argc, char ** argv) { double abs_naive = 0.0, mean_abs_naive = 0.0, rel_naive = 0.0, mean_rel_naive = 0.0, rmse_naive = 0.0; error_stats(flash.output, naive, abs_naive, mean_abs_naive, rel_naive, mean_rel_naive, rmse_naive); const double tol = (c.type == GGML_TYPE_F32 ? 2e-5 : 2e-3)*std::max(1.0f, c.v_scale); - bool pass = abs_naive <= tol; + const bool pass = abs_naive <= tol; + // the position checks print their own verdict and fail the run like the naive check + bool pass_pos = true; if (c.layout != 0) { // the outputs are small: relative to their scale, so that a bias at the wrong distances fails double scale = 0.0; for (float x : naive) { scale = std::max(scale, (double) std::fabs(x)); } - printf("%s naive_scale=%.9g naive_max_abs_rel=%.9g\n", c.name, scale, abs_naive/scale); - pass = pass && abs_naive <= 1e-4*scale; + pass_pos = abs_naive <= 1e-4*scale; + printf("%s naive_scale=%.9g naive_max_abs_rel=%.9g %s\n", c.name, scale, abs_naive/scale, pass_pos ? "PASS" : "FAIL"); } if (c.layout == 0) { // the positions of cells that are the positions: bit for bit on the CPU, where both run the same loop; // a GPU may pick another kernel for the cell distance (the delegated FA kernel), so within tol there - const run_result with_pos = run_graph(backend.get(), c, data, false, 1, true); + const run_result with_pos = run_graph(backend.get(), c, data, false, true, 1); double abs_pos, mean_abs_pos, rel_pos, mean_rel_pos, rmse_pos; error_stats(with_pos.output, flash.output, abs_pos, mean_abs_pos, rel_pos, mean_rel_pos, rmse_pos); const bool same = backend_kind == "cpu" ? abs_pos == 0.0 : abs_pos <= tol; printf("%s identity_positions_max_abs=%.9g %s\n", c.name, abs_pos, same ? "SAME" : "DIFFER"); - pass = pass && same; + pass_pos = same; } + ok = ok && pass_pos; ok = ok && pass; printf("%s type=%s D=%lld nq=%lld nkv=%lld hq=%lld hkv=%lld E=%lld mask=%d sliding=%d " "batch=%lld rel_batch=%lld strided_rel=%d " From 01f79590f72bd6a7ab77af8ecf6a27e9d7ae16fc Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 05:05:13 -0800 Subject: [PATCH 063/115] ggml : check the banded positions are mirrored outside the split handler #378 shares The banded split handler stays byte-identical to the one #378 carries; the cell and query positions of the banded op (src[7], src[8]) are checked before the op switch instead. --- ggml/src/ggml-backend-meta.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index c3e4de1d2a7f..27de1a22efba 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -936,6 +936,12 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( GGML_ASSERT(src_ss[i].axis != GGML_BACKEND_SPLIT_AXIS_UNKNOWN); } + if (tensor->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + // the optional K/V cell and query positions (src[7], src[8]) are shared by every head + GGML_ASSERT(tensor->src[7] == nullptr || src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + GGML_ASSERT(tensor->src[8] == nullptr || src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + } + ggml_backend_meta_split_state split_state; switch (tensor->op) { case GGML_OP_NONE: { From c1b514da9a057e9b93f050b8af532c09a12d0eb0 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 05:05:37 -0800 Subject: [PATCH 064/115] metal : banded FA, read BF16 rel tables by bit shift supports_op admits a BF16 rel table on has_bfloat, but the loaders only decoded it under GGML_METAL_HAS_BF16, which a precompiled default.metallib or Metal < 3.1 does not define: there the table was read as F32 (wrong bias, reads past the end of rel). The shift is exact and needs no bfloat type. --- ggml/src/ggml-metal/kernels/fa_common.metal | 5 ++--- ggml/src/ggml-metal/kernels/fa_tensor.metal | 5 ++--- ggml/src/ggml-metal/kernels/fa_vec_common.metal | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 8b6b53a22209..7fa646e919e3 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -18,11 +18,10 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + constant int32_t FC_flash_attn_ext_rel_type [[function_constant(FC_FLASH_ATTN_EXT + 23)]]; static inline float flash_attn_ext_rel_load(device const char * rel, int32_t i) { -#if defined(GGML_METAL_HAS_BF16) if (FC_flash_attn_ext_rel_type == 2) { - return (float) ((device const bfloat *) rel)[i]; + // BF16 by bit shift: exact, and independent of GGML_METAL_HAS_BF16, which a precompiled library or Metal < 3.1 lacks + return as_type(((uint) ((device const ushort *) rel)[i]) << 16); } -#endif if (FC_flash_attn_ext_rel_type == 1) { return ((device const half *) rel)[i]; } diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 62ea77f03525..9f6b78fc8c23 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -12,11 +12,10 @@ constant bool FC_flash_attn_ext_tensor_has_kvpad [[function_constant(FC_FLASH_AT constant int32_t FC_flash_attn_ext_tensor_rel_type [[function_constant(FC_FLASH_ATTN_EXT_TENSOR + 6)]]; static inline float flash_attn_ext_tensor_rel_load(device const char * rel, int32_t i) { -#if defined(GGML_METAL_HAS_BF16) if (FC_flash_attn_ext_tensor_rel_type == 2) { - return (float) ((device const bfloat *) rel)[i]; + // BF16 by bit shift: exact, and independent of GGML_METAL_HAS_BF16, which a precompiled library or Metal < 3.1 lacks + return as_type(((uint) ((device const ushort *) rel)[i]) << 16); } -#endif if (FC_flash_attn_ext_tensor_rel_type == 1) { return ((device const half *) rel)[i]; } diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index 9177da5fdb6b..8c98753535a2 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -19,11 +19,10 @@ constant int32_t FC_flash_attn_ext_vec_rel_type [[function_constant(FC_FLASH_A // banded relative bias (FLASH_ATTN_EXT_BANDED): rel row of one (head, query), indexed by the distance static inline float flash_attn_ext_vec_rel_load(device const char * rel, int32_t i) { -#if defined(GGML_METAL_HAS_BF16) if (FC_flash_attn_ext_vec_rel_type == 2) { - return (float) ((device const bfloat *) rel)[i]; + // BF16 by bit shift: exact, and independent of GGML_METAL_HAS_BF16, which a precompiled library or Metal < 3.1 lacks + return as_type(((uint) ((device const ushort *) rel)[i]) << 16); } -#endif if (FC_flash_attn_ext_vec_rel_type == 1) { return ((device const half *) rel)[i]; } From 1fc707a63a138138c9f73bb2583757025eb2627f Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 05:16:16 -0800 Subject: [PATCH 065/115] tests : banded FA, every Metal mixed K/V pair, head size 64 prefill, unpadded n_kv, q4_1 and q5_0 Covers the f16/q4_0 and q4_0/q8_0 kernels, the head size 64 half8x8 mixed kernels and the no-pad path, which no case ran before. --- tests/test-backend-ops.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index dce5acf2928d..b05c218197a2 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14177,18 +14177,28 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 2, 1000, 96, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 33, 300, 16, 1, GGML_TYPE_F16, GGML_TYPE_BF16, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 8, 2, 4, 300, 16, 0, GGML_TYPE_F16, GGML_TYPE_F32, 1)); + // the other inline-dequant cache types (q4_1, q5_0): prefill, decode and a ragged small batch + for (ggml_type kv_type : { GGML_TYPE_Q4_1, GGML_TYPE_Q5_0 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 512, 1100, 1024, 1, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 4096, 1024, 2, kv_type, GGML_TYPE_F32, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 333, 16, 2, kv_type, GGML_TYPE_F32, 1)); + } // mixed K/V cache types (-ctk != -ctv), banded and dense, decode / small batches / prefill for (auto [type_k, type_v] : std::initializer_list>{ { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }, { GGML_TYPE_Q8_0, GGML_TYPE_F16 }, - { GGML_TYPE_F16, GGML_TYPE_Q8_0 }, { GGML_TYPE_Q4_0, GGML_TYPE_F16 } }) { + { GGML_TYPE_F16, GGML_TYPE_Q8_0 }, { GGML_TYPE_Q4_0, GGML_TYPE_F16 }, + { GGML_TYPE_F16, GGML_TYPE_Q4_0 }, { GGML_TYPE_Q4_0, GGML_TYPE_Q8_0 } }) { for (int64_t n_q : { 1, 4, 33, 512 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(128, 24, 8, n_q, 1100, 1024, type_k, type_v)); } + test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(128, 24, 8, 33, 1024, 1024, type_k, type_v)); // n_kv % 64 == 0: no pad test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(64, 8, 2, 3, 333, 16, type_k, type_v)); + test_cases.emplace_back(new test_flash_attn_ext_banded_kv2(64, 8, 2, 33, 333, 16, type_k, type_v)); // head size 64, half8x8 for (int64_t nb : { 1, 4, 33 }) { test_cases.emplace_back(new test_flash_attn_ext(128, 128, 8, {3, 1}, 1100, nb, true, true, 0, 0, GGML_PREC_F32, type_k, type_v)); } test_cases.emplace_back(new test_flash_attn_ext(64, 64, 8, {1, 1}, 333, 3, true, false, 0, 0, GGML_PREC_F32, type_k, type_v)); + test_cases.emplace_back(new test_flash_attn_ext(64, 64, 8, {1, 1}, 333, 33, true, false, 0, 0, GGML_PREC_F32, type_k, type_v)); } test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 8192, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 1, 512, 16384, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32)); From 2422de38e1b7d3f0735ff99b5aefd9badd0f9346 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 23 Nov 2026 04:51:33 -0800 Subject: [PATCH 066/115] rpc : count GGML_OP_FLASH_ATTN_EXT_BANDED in the RPC op count Upstream b12635 added an op and moved the RPC check to GGML_OP_COUNT == 101 with RPC_PROTO_PATCH_VERSION 2. This branch adds GGML_OP_FLASH_ATTN_EXT_BANDED on top, so the count is 102 and GGML_RPC=ON builds stop at the static_assert. Bump the check to 102 and the patch version to 3. --- ggml/include/ggml-rpc.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index 062d5004e8d4..5f1444563fc4 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 2 +#define RPC_PROTO_PATCH_VERSION 3 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 102, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 From 1f4e6d793b70cabf97eda0888f8b50c2baf855e2 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:50:09 -0800 Subject: [PATCH 067/115] metal : banded and mixed K/V FA, admit only the layouts the launch can address Mixed K/V plain FA skipped the shape checks the banded op had: K and V with other head counts hit the launcher's ne12 == ne22 assert, and a mask wider than K misplaced the mask blocks. One predicate now gates both: shared K/V rows and heads, fewer than 65536 queries, float4 Q rows, F32/F16/BF16 K/V rows on 4-element boundaries (the vec kernels divide the row stride by 4), a mask exactly n_kv wide. Banded BF16 K/V needs the embedded library: a precompiled default.metallib has no BF16 K/V kernels. --- ggml/src/ggml-metal/ggml-metal-device.m | 48 +++++++++++++++++++------ 1 file changed, 38 insertions(+), 10 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index b794c8f78807..a111dae514d9 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1565,6 +1565,37 @@ static bool ggml_metal_fa_kv_mixed_ok(const struct ggml_tensor * op) { op->src[1]->ne[0] == op->src[2]->ne[0] && (op->src[1]->ne[0] == 64 || op->src[1]->ne[0] == 128); } +// the layouts the banded and mixed K/V FA launches can address (the plain same-type path keeps upstream's rules): +// K/V share rows and heads (the launcher asserts ne11 == ne21, ne12 == ne22), fewer than 65536 queries, Q rows +// loaded as float4, F32/F16/BF16 K/V rows on 4-element boundaries (the vec kernels address them as 4-vectors and +// divide the row stride by 4), and a mask exactly n_kv wide (the mask blocks are classified over its width but read +// over the K length) +static bool ggml_metal_fa_layout_ok(const struct ggml_tensor * op) { + const struct ggml_tensor * q = op->src[0]; + const struct ggml_tensor * k = op->src[1]; + const struct ggml_tensor * v = op->src[2]; + const struct ggml_tensor * mask = op->src[3]; + + if (q->type != GGML_TYPE_F32 || q->ne[1] >= 65536 || k->ne[1] != v->ne[1] || k->ne[2] != v->ne[2]) { + return false; + } + if (q->nb[0] != sizeof(float) || q->nb[1] % 16 != 0 || q->nb[2] % 16 != 0 || q->nb[3] % 16 != 0) { + return false; + } + for (int i = 1; i <= 2; ++i) { + const struct ggml_tensor * t = op->src[i]; + const size_t ts = ggml_type_size(t->type); + if (t->nb[0] != ts || t->nb[1] % ts != 0 || t->nb[1] < ggml_row_size(t->type, t->ne[0])) { + return false; + } + if (!ggml_is_quantized(t->type) && + ((t->view_offs | t->nb[1] | t->nb[2] | t->nb[3]) % (4*ts) != 0)) { + return false; + } + } + return !mask || (mask->type == GGML_TYPE_F16 && mask->ne[0] == k->ne[1] && mask->ne[1] >= q->ne[1]); +} + bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_tensor * op) { const bool has_simdgroup_mm = dev->props.has_simdgroup_mm; const bool has_simdgroup_reduction = dev->props.has_simdgroup_reduction; @@ -1823,7 +1854,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return false; } if (op->src[1]->type != op->src[2]->type) { - return ggml_metal_fa_kv_mixed_ok(op) && has_simdgroup_mm; + return ggml_metal_fa_kv_mixed_ok(op) && ggml_metal_fa_layout_ok(op) && has_simdgroup_mm; } switch (op->src[1]->type) { case GGML_TYPE_F32: @@ -1880,10 +1911,15 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_TYPE_Q8_0: break; case GGML_TYPE_BF16: +#if GGML_METAL_EMBED_LIBRARY if (!has_bfloat) { return false; } break; +#else + // a precompiled default.metallib is built without GGML_METAL_HAS_BF16: no BF16 K/V kernels + return false; +#endif default: return false; } @@ -1899,15 +1935,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te op->src[0]->nb[2] % 16 != 0 || op->src[0]->nb[3] % 16 != 0) { return false; } - for (int i = 1; i <= 2; ++i) { - const struct ggml_tensor * t = op->src[i]; - if (t->nb[0] != ggml_type_size(t->type) || t->nb[1] % t->nb[0] != 0) { - return false; - } - } - // the mask blocks are classified over the mask width but read over the K length - if (mask && (mask->type != GGML_TYPE_F16 || mask->ne[0] != op->src[1]->ne[1] || - mask->ne[1] < op->src[0]->ne[1])) { + if (!ggml_metal_fa_layout_ok(op)) { return false; } if (sinks && (sinks->type != GGML_TYPE_F32 || sinks->nb[0] != sizeof(float) || From 577327cff443a7d171e15121a355e6eac9c95d53 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:50:10 -0800 Subject: [PATCH 068/115] metal : banded FA, keep padded keys out of the softmax The pad mask of a ragged n_kv is finite (-MAXHALF): with a band that pushes the real scores to the bottom of the F16 range the padded keys tied them. The half8x8 and vec banded branches now drop columns past ne11 like the tensor kernel does. --- ggml/src/ggml-metal/kernels/fa_common.metal | 11 +++++++++++ ggml/src/ggml-metal/kernels/fa_vec_common.metal | 3 ++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 7fa646e919e3..cab80cc4e427 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -464,6 +464,17 @@ void kernel_flash_attn_ext_impl( } } + // banded: the padded keys past ne11 are out of the softmax whatever the band adds (the pad mask is finite) + if (FC_flash_attn_ext_has_rel && FC_flash_attn_ext_has_kvpad) { + const int32_t ik = ic0*C + 2*tiisg; + if (ik >= args.ne11) { + s2[0] = -FLT_MAX/2; + } + if (ik + 1 >= args.ne11) { + s2[1] = -FLT_MAX/2; + } + } + M[jj] = simd_max(max(M[jj], max(s2[0], s2[1]))); const float ms = exp(m - M[jj]); diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index 8c98753535a2..ac5c6da3e36e 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -434,7 +434,8 @@ kernel void kernel_flash_attn_ext_vec( mqk[qq][tx] += (qk_t) sm[qq*C + NE*tx + ty]; - ss[qq*C + NE*tx + ty] = mqk[qq][tx]; + // the padded keys past ne11 are out of the softmax whatever the band adds (the pad mask is finite) + ss[qq*C + NE*tx + ty] = ic0*C + NE*tx + ty < args.ne11 ? mqk[qq][tx] : -FLT_MAX/2; } else if (FC_flash_attn_ext_vec_has_mask && !FC_flash_attn_ext_vec_has_scap && !FC_flash_attn_ext_vec_has_bias) { From 0ba299ebb332d33b4b4e2176a0b5e144b0063bac Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:48 -0800 Subject: [PATCH 069/115] ggml : return the banded attention precision from ggml_prec_get_acc ggml_prec_set_acc() stores the accumulator precision of GGML_OP_FLASH_ATTN_EXT_BANDED in op param 3 and ggml_flash_attn_ext_get_prec() reads it, but the generic getter returned GGML_PREC_UNDEFINED for the banded op. test-flash-attn-bias checks the round trip. --- ggml/src/ggml.c | 1 + tests/test-flash-attn-bias.cpp | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 2a9edfd84ede..d1116b6bd17a 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -3352,6 +3352,7 @@ enum ggml_prec ggml_prec_get_acc( case GGML_OP_MUL_MAT_ID: return (enum ggml_prec) ggml_get_op_params_i32(a, 0); case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: return (enum ggml_prec) ggml_get_op_params_i32(a, 3); default: return GGML_PREC_UNDEFINED; diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index d4292f5386d5..0f3dd5f004d7 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -436,6 +436,25 @@ static void overflow_arithmetic_self_test() { (unsigned long long) offset, (long long) nq, (long long) rel_dist); } +static void prec_round_trip_test() { + ggml_init_params params = { + /* .mem_size = */ ggml_tensor_overhead()*8, + /* .mem_base = */ nullptr, + /* .no_alloc = */ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + GGML_ASSERT(ctx); + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, 64, 2, 2, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, 64, 2, 1, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, 64, 2, 1, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, 8, 2, 2, 1); + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, nullptr, r, 0.125f, 8); + GGML_ASSERT(ggml_prec_set_acc(out, GGML_PREC_F32)); + const bool pass = ggml_prec_get_acc(out) == GGML_PREC_F32 && ggml_flash_attn_ext_get_prec(out) == GGML_PREC_F32; + printf("prec_round_trip acc=%d %s\n", (int) ggml_prec_get_acc(out), pass ? "PASS" : "FAIL"); + GGML_ASSERT(pass); +} + static bool overflow_kernel_test(ggml_backend_t backend, const char * backend_kind) { // rel-logits row for query 1 sits beyond INT32_MAX; only two small logical rows are touched const bias_test_config c = { @@ -496,6 +515,7 @@ int main(int argc, char ** argv) { int repeats = argc > 3 ? std::max(1, atoi(argv[3])) : 1; overflow_arithmetic_self_test(); + prec_round_trip_test(); ggml_backend_load_all(); ggml_backend_dev_t chosen = nullptr; const enum ggml_backend_dev_type wanted = backend_kind == "cuda" ? From d16c34d0028058f0b91e0e8adf646473e417b17c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:48 -0800 Subject: [PATCH 070/115] tests : register test-flash-attn-bias and test-flash-attn-generic-hash with the main label Both were plain add_test() entries without a label, so ctest -L main skipped them. --- tests/CMakeLists.txt | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9100adb21e2e..4e307e5646b3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -371,13 +371,8 @@ 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) -add_executable(test-flash-attn-bias test-flash-attn-bias.cpp) -target_link_libraries(test-flash-attn-bias PRIVATE ggml) -add_test(NAME test-flash-attn-bias COMMAND test-flash-attn-bias) - -add_executable(test-flash-attn-generic-hash test-flash-attn-generic-hash.cpp) -target_link_libraries(test-flash-attn-generic-hash PRIVATE ggml) -add_test(NAME test-flash-attn-generic-hash COMMAND test-flash-attn-generic-hash) +llama_build_and_test(test-flash-attn-bias.cpp LINK ggml) +llama_build_and_test(test-flash-attn-generic-hash.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) From a75cc44247d4a47e09684ea4e438ed971b33dce2 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:49 -0800 Subject: [PATCH 071/115] ggml-cuda : tag the banded MMA call with a negative m0 instead of max_bias The banded op reuses the FA MMA kernel and tagged it with max_bias < 0, but ggml_flash_attn_ext() accepts a negative max_bias (no ALiBi), so an ordinary call with max_bias < 0 read the sinks as a relative-bias table. m0 of an ordinary call is a power of 2 and never negative. Add FLASH_ATTN_EXT cases with max_bias = -2. --- ggml/src/ggml-cuda/fattn-common.cuh | 7 +++---- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 ++-- tests/test-backend-ops.cpp | 5 +++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index ed065b4d0345..23d37e02e40c 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -1295,11 +1295,9 @@ void launch_fattn( memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float)); - // banded op reuses the MMA ABI: negative max_bias tags the branch, sinks_ptr carries rel_logits, -max_bias is E if (rel) { GGML_ASSERT(rel->type == GGML_TYPE_F32 && ggml_is_contiguous(rel)); GGML_ASSERT(rel->ne[0] <= (1 << 20)); // exactly representable in float - max_bias = -float(rel->ne[0]); } if (logit_softcap != 0.0f) { @@ -1309,8 +1307,9 @@ void launch_fattn( const uint32_t n_head = Q->ne[2]; const uint32_t n_head_log2 = 1u << uint32_t(floorf(log2f(float(n_head)))); - // m0/m1 are unused for banded bias; the negative tag would otherwise blow up the exponent - const float m0 = rel ? 1.0f : powf(2.0f, -(max_bias ) / n_head_log2); + // banded op reuses the MMA ABI: negative m0 tags the branch, sinks_ptr carries rel_logits, -m0 is E + // an ordinary m0 is a power of 2 and never negative, whatever max_bias is + const float m0 = rel ? -float(rel->ne[0]) : powf(2.0f, -(max_bias ) / n_head_log2); const float m1 = rel ? 1.0f : powf(2.0f, -(max_bias / 2.0f) / n_head_log2); // TODO other tensor dimensions after removal of WMMA kernel: diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index e09bc5153024..53c8cd878c5c 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -2027,8 +2027,8 @@ static __global__ void flash_attn_ext_f16( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; - const bool banded_bias = max_bias < 0.0f; - const int rel_extent = banded_bias ? int(-max_bias) : 0; + const bool banded_bias = m0 < 0.0f; + const int rel_extent = banded_bias ? int(-m0) : 0; // Skip unused kernel variants for faster compilation: if (use_logit_softcap && !(DKQ == 128 || DKQ == 256 || DKQ == 512)) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index b97f5a530c2b..424f014a5c3b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13877,6 +13877,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 17, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + // a negative max_bias disables ALiBi, it must not select the banded MMA branch + for (bool sinks : {true, false}) { + test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 512, 32, true, sinks, -2.0f, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + } + // mixed quant and Q1_0 test cases test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0)); test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_F16)); From c43530b96011a4a7ddcab8e23e1cd7dfb2aa1198 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:49 -0800 Subject: [PATCH 072/115] ggml-cuda : honor GGML_CUDA_DISABLE_BANDED_MMA on the delegated FA MMA path The switch only gated the standalone banded MMA kernel; a no-sink op still delegated to the FA MMA kernel. --- ggml/src/ggml-cuda/fattn-banded.cu | 6 +----- ggml/src/ggml-cuda/fattn.cu | 2 +- ggml/src/ggml-cuda/fattn.cuh | 8 ++++++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 52c2f1b7924a..f2acfdcca5de 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1671,11 +1671,7 @@ static bool fattn_banded_mma_aligned(const ggml_tensor * t) { } static bool fattn_banded_mma_usable(const int device, const ggml_tensor * dst) { - static const bool disabled = [] { - const char * env = getenv("GGML_CUDA_DISABLE_BANDED_MMA"); - return env != nullptr && atoi(env) != 0; - }(); - if (disabled) { + if (ggml_cuda_banded_mma_disabled()) { return false; } if (!turing_mma_available(ggml_cuda_info().devices[device].cc)) { diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 0fe1704e90fd..25db0d23013e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -583,7 +583,7 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; #endif // FLASH_ATTN_AVAILABLE - if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED || ggml_cuda_banded_mma_disabled()) { return false; } diff --git a/ggml/src/ggml-cuda/fattn.cuh b/ggml/src/ggml-cuda/fattn.cuh index b26f2f03bebc..cb1e6d4311e5 100644 --- a/ggml/src/ggml-cuda/fattn.cuh +++ b/ggml/src/ggml-cuda/fattn.cuh @@ -6,4 +6,12 @@ bool ggml_cuda_flash_attn_ext_supported(int device, const ggml_tensor * dst); bool ggml_cuda_flash_attn_ext_banded_use_mma(int device, const ggml_tensor * dst); +inline bool ggml_cuda_banded_mma_disabled() { + static const bool disabled = [] { + const char * env = getenv("GGML_CUDA_DISABLE_BANDED_MMA"); + return env != nullptr && atoi(env) != 0; + }(); + return disabled; +} + size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst); From 9ce2297fb6d405a5e642fae1f1e8f8cf502ab8a4 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:49 -0800 Subject: [PATCH 073/115] ggml-cuda : write 0 for a fully masked row in the FA MMA kernel A row without a visible cell has a zero rowsum, the MMA kernel and the stream-k fixups divided 0 by 0. The CPU and the other banded CUDA kernels return 0. Add banded cases with a fully masked query (mask_kind 4), which the op delegates to the FA MMA kernel without sinks. --- ggml/src/ggml-cuda/fattn-common.cuh | 4 ++-- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 5 +++-- tests/test-backend-ops.cpp | 10 ++++++++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 23d37e02e40c..89bf832ffc56 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -856,7 +856,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform( } // Write back final result: - *dst = dst_val / rowsum; + *dst = rowsum == 0.0f ? 0.0f : dst_val / rowsum; } // General fixup kernel for the case where the number of blocks per tile is not uniform across tiles @@ -967,7 +967,7 @@ static __global__ void flash_attn_stream_k_fixup_general( } // Write back final result: - *dst = dst_val / rowsum; + *dst = rowsum == 0.0f ? 0.0f : dst_val / rowsum; } template // D == head size diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 53c8cd878c5c..5f8a65fab1d2 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -1955,9 +1955,10 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( } if (!needs_fixup && !is_fixup) { + // a fully masked row has a zero rowsum, it is 0 like on the CPU const float KQ_rowsum_j = meta_j[1]; - dstk_val.x /= KQ_rowsum_j; - dstk_val.y /= KQ_rowsum_j; + dstk_val.x = KQ_rowsum_j == 0.0f ? 0.0f : dstk_val.x / KQ_rowsum_j; + dstk_val.y = KQ_rowsum_j == 0.0f ? 0.0f : dstk_val.y / KQ_rowsum_j; } if (is_fixup) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 424f014a5c3b..46662a10f1a6 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9423,7 +9423,8 @@ struct test_flash_attn_ext_banded : public test_case { const int64_t n_q; const int64_t n_kv; const int64_t rel_extent; - const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent, 3: causal over a padded n_kv + const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent, 3: causal over a padded n_kv, + // 4: causal with the first query fully masked const ggml_type kv_type; const ggml_type rel_type; const bool strided; @@ -9536,7 +9537,7 @@ struct test_flash_attn_ext_banded : public test_case { for (int64_t iq = 0; iq < n_q; ++iq) { for (int64_t ik = 0; ik < n_kv; ++ik) { const int64_t rel_dist = iq + (n_kv - n_q) - ik; - const bool visible = rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent); + const bool visible = rel_dist >= 0 && (mask_kind != 2 || rel_dist < rel_extent) && (mask_kind != 4 || iq != 0); data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } @@ -14031,6 +14032,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 1, 64, 64, 512, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 17, 33, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, true)); + // a fully masked query is 0, also on the FA kernel the op delegates to without sinks + for (int64_t n_kv : {64, 4096}) { + test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 1, n_kv, 32, 4, GGML_TYPE_F16, GGML_TYPE_F32)); + test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 33, n_kv, 32, 4, GGML_TYPE_Q8_0, GGML_TYPE_F32)); + } // cells that are not the positions: several sequences in a unified cache, a wrapped SWA ring for (ggml_type kv_type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { // decode (one token per sequence: the decode kernel up to 8 or 32 queries), short and long prefill (MMA tiles) From 3b5023b3d46435f134d8208c93419683612dabe1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 074/115] convert : check the remote shards and tensor names like the local ones The local index rejects a tensor in a shard the index does not assign it to and a name that two tensors map to after filtering. --remote overwrote both silently: check the shard in SafetensorRemote and the filtered name in index_tensors(). --- conversion/base.py | 4 ++ gguf-py/gguf/utility.py | 5 ++ tests/test_conversion_remote.py | 81 +++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+) create mode 100644 tests/test_conversion_remote.py diff --git a/conversion/base.py b/conversion/base.py index 894db138a44c..4d960c6d7017 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -243,6 +243,10 @@ def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Call self._source_tensor_names[name] = titem[0] if titem else None if titem: tname, tgen = titem + if tname in tensors: + raise ValueError( + f"duplicate tensor '{tname}' found in the remote model; " + f"refusing to silently overwrite") tensors[tname] = tgen return tensors diff --git a/gguf-py/gguf/utility.py b/gguf-py/gguf/utility.py index 154351d8ed63..7903207a691a 100644 --- a/gguf-py/gguf/utility.py +++ b/gguf-py/gguf/utility.py @@ -143,6 +143,11 @@ def get_list_tensors_hf_model(cls, model_id: str) -> dict[str, RemoteTensor]: for file in all_files: url = f"{cls.BASE_DOMAIN}/{model_id}/resolve/main/{file}" for key, val in cls.get_list_tensors(url).items(): + # the index maps each tensor to one shard; a duplicate would silently overwrite it + if weight_map.get(key) != file: + raise ValueError( + f"tensor '{key}' found in '{file}' but the index assigns " + f"it to '{weight_map.get(key)}'; refusing to load a wrong-shard copy") tensors[key] = val return tensors diff --git a/tests/test_conversion_remote.py b/tests/test_conversion_remote.py new file mode 100644 index 000000000000..0989ff62c559 --- /dev/null +++ b/tests/test_conversion_remote.py @@ -0,0 +1,81 @@ +"""Test the remote (--remote) tensor index with mocked Hugging Face transport; no downloads required. + +Run from the repository root: + python -m unittest discover -s tests -p 'test_conversion_remote.py' -v +""" + +from __future__ import annotations + +import json +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +import torch +from safetensors.torch import save_file + +from conversion.base import gguf +from conversion.llama import LlamaModel + +SafetensorRemote = gguf.utility.SafetensorRemote + + +def remote_tensor(url: str) -> gguf.utility.RemoteTensor: + return gguf.utility.RemoteTensor(dtype="F32", shape=(2,), offset_start=0, size=8, url=url) + + +class TestRemoteIndex(unittest.TestCase): + def list_hf_model(self, weight_map, shards): + index = json.dumps({"weight_map": weight_map}).encode() + + def list_tensors(url): + return {name: remote_tensor(url) for name in shards[url.rsplit("/", 1)[1]]} + + with mock.patch.object(SafetensorRemote, "check_file_exist", side_effect=lambda url: url.endswith(".index.json")), \ + mock.patch.object(SafetensorRemote, "get_data_by_range", return_value=index), \ + mock.patch.object(SafetensorRemote, "get_list_tensors", side_effect=list_tensors): + return SafetensorRemote.get_list_tensors_hf_model("org/model") + + def test_sharded(self): + weight_map = {"a.weight": "model-00001.safetensors", "b.weight": "model-00002.safetensors"} + shards = {"model-00001.safetensors": ["a.weight"], "model-00002.safetensors": ["b.weight"]} + tensors = self.list_hf_model(weight_map, shards) + self.assertEqual(tensors["a.weight"].url.rsplit("/", 1)[1], "model-00001.safetensors") + self.assertEqual(tensors["b.weight"].url.rsplit("/", 1)[1], "model-00002.safetensors") + + def test_wrong_shard_copy(self): + weight_map = {"a.weight": "model-00001.safetensors", "b.weight": "model-00002.safetensors"} + # the later shard holds a stale copy of a.weight + shards = {"model-00001.safetensors": ["a.weight"], "model-00002.safetensors": ["a.weight", "b.weight"]} + with self.assertRaisesRegex(ValueError, "wrong-shard"): + self.list_hf_model(weight_map, shards) + + def test_duplicate_after_filtering(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) + hparams = { + "model_type": "llama", + "architectures": ["LlamaForCausalLM"], + "num_hidden_layers": 1, + "hidden_size": 4, + "num_attention_heads": 1, + } + (path / "config.json").write_text(json.dumps(hparams)) + save_file({"model.norm.weight": torch.ones(2)}, str(path / "model.safetensors")) + model = LlamaModel(path, gguf.LlamaFileType.ALL_F32, path / "out.gguf", hparams=hparams) + + url = "https://huggingface.co/org/model/resolve/main/model.safetensors" + # both names filter to model.norm.weight + remote = {"model.norm.weight": remote_tensor(url), "model.language_model.norm.weight": remote_tensor(url)} + with mock.patch.object(SafetensorRemote, "get_list_tensors_hf_model", return_value=remote): + with self.assertRaisesRegex(ValueError, "duplicate tensor 'model.norm.weight'"): + model.index_tensors(remote_hf_model_id="org/model") + + del remote["model.language_model.norm.weight"] + with mock.patch.object(SafetensorRemote, "get_list_tensors_hf_model", return_value=remote): + self.assertEqual(list(model.index_tensors(remote_hf_model_id="org/model")), ["model.norm.weight"]) + + +if __name__ == "__main__": + unittest.main() From aa3af570d2179f403eecbed9adf258754333e43a Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 075/115] convert : reject stacked ModelOpt NVFP4 experts before the pure NVFP4 early return A pure NVFP4 checkpoint returned from dequant_model() before the check, keeping the packed experts. --- conversion/base.py | 25 ++++++++++++++----------- tests/test_conversion_fp8.py | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/conversion/base.py b/conversion/base.py index 4d960c6d7017..156030e88e8f 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -388,6 +388,20 @@ def _prepare_kv_cache_scales(self): self.gguf_writer.add_tensor(new_name, scale.flatten().numpy()) def dequant_model(self): + # stacked-expert NVFP4 (w13_weight/w2_weight) is silently skipped by the NVFP4 repack and the dequant below + quant_config = self.hparams.get("quantization_config") + if isinstance(quant_config, dict) and quant_config.get("quant_method") in ("modelopt", "modelopt_mixed"): + stacked_expert_aux = [ + n for n in self.model_tensors + if n.endswith((".scale2", ".input_amax", ".original_shape")) + ] + if stacked_expert_aux: + raise NotImplementedError( + "This checkpoint stores quantized experts in the stacked ModelOpt NVFP4 layout " + f"({len(stacked_expert_aux)} auxiliary tensors like {stacked_expert_aux[0]!r}), " + "which is not supported yet. Convert from the unquantized (BF16) checkpoint instead." + ) + # If all quantized tensors were already handled (e.g. pure NVFP4), skip if self._is_nvfp4 and not any(k.endswith((".weight_scale", ".weight_scale_inv", ".input_scale", ".activation_scale", "_activation_scale", ".k_scale", ".v_scale")) for k in self.model_tensors): return @@ -666,17 +680,6 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: raise NotImplementedError(f"Quant format {quant_format!r} for method {quant_method!r} is not yet supported") elif quant_method in ("modelopt", "modelopt_mixed"): dequant_fp8() - # stacked-expert NVFP4 (w13_weight/w2_weight) is silently skipped by the path above - stacked_expert_aux = [ - n for n in self.model_tensors - if n.endswith((".scale2", ".input_amax", ".original_shape")) - ] - if stacked_expert_aux: - raise NotImplementedError( - "This checkpoint stores quantized experts in the stacked ModelOpt NVFP4 layout " - f"({len(stacked_expert_aux)} auxiliary tensors like {stacked_expert_aux[0]!r}), " - "which is not supported yet. Convert from the unquantized (BF16) checkpoint instead." - ) # FP8_PB_WO: one scale per block, the block size follows from the two shapes for name in self.model_tensors.keys(): if not name.endswith(".weight_scale_inv"): diff --git a/tests/test_conversion_fp8.py b/tests/test_conversion_fp8.py index e191c8a55bae..a5171e83b232 100644 --- a/tests/test_conversion_fp8.py +++ b/tests/test_conversion_fp8.py @@ -123,6 +123,21 @@ def test_lazy_fp8_export(self): np.testing.assert_array_equal(gguf.dequantize(data, dtype), weight.float().numpy()) np.testing.assert_array_equal(result["blk.0.attn_q.scale"][1], [0.25]) + def test_stacked_nvfp4_experts_rejected(self): + experts = "model.layers.0.mlp.experts.w13_weight" + stacked = { + experts: torch.zeros((2, 4, 2), dtype=torch.uint8), + experts + ".scale2": torch.ones(2), + experts + ".original_shape": torch.tensor([2, 4, 4]), + } + fp8 = "model.layers.0.self_attn.q_proj.weight" + # pure NVFP4 returns early from dequant_model, mixed with FP8 does not + for name, extra in (("pure", {}), ("mixed", {fp8: torch.ones((2, 2)).to(torch.float8_e4m3fn), fp8 + "_scale": torch.ones(1)})): + with self.subTest(name): + with self.assertRaisesRegex(NotImplementedError, "stacked ModelOpt NVFP4"): + self.convert(Qwen2MoeModel, {**stacked, **extra}, ftype=gguf.LlamaFileType.MOSTLY_F16, + hparams_override={"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4"}}) + def test_mixed_compressed_fp8_block_scale(self): name = "model.layers.0.self_attn.q_proj.weight" scale = torch.tensor([[0.25, 0.5], [1.0, 2.0]]) From c7668259964a7d7b70a4c2b56e705fe9c6d78892 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 076/115] inkling : reserve the dense attention of multi-sequence ubatches and probe every cache type The reserve context reports the full span as contiguous, so the reserved graph of a unified multi-sequence context was banded while such ubatches run dense. Take the banded op for one-sequence ubatches only, as inkling2 does, and ask the layer's device for F32 / F16 / BF16 caches too, not only for quantized ones. --- src/models/inkling.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 05e1e778bf50..09bd4a74ead9 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -216,8 +216,10 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par GGML_ASSERT(ubatch.equal_seqs()); GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs); - const uint32_t n_kv_flash_base = cparams.flash_attn ? mctx_attn->get_base()->get_n_kv_pos_contiguous() : 0; - const uint32_t n_kv_flash_swa = cparams.flash_attn ? mctx_attn->get_swa ()->get_n_kv_pos_contiguous() : 0; + // one sequence: a ubatch of several is dense at runtime, so is the reserved one + const bool use_flash_banded = cparams.flash_attn && ubatch.n_seqs_unq == 1; + const uint32_t n_kv_flash_base = use_flash_banded ? mctx_attn->get_base()->get_n_kv_pos_contiguous() : 0; + const uint32_t n_kv_flash_swa = use_flash_banded ? mctx_attn->get_swa ()->get_n_kv_pos_contiguous() : 0; bool has_global = false; bool needs_rel_idx_local = false; @@ -227,12 +229,9 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; }; - // a quantized cache takes the banded op only where the layer's device runs it, else the dense path - std::vector> banded_quant_dev_ok; + // the banded op only where the layer's device runs it, else the dense path + std::vector> banded_dev_ok; const auto banded_cache_types_ok = [&](int il, ggml_type type_k, ggml_type type_v) { - if (banded_cache_type_supported(type_k) && banded_cache_type_supported(type_v)) { - return true; - } if (!(banded_cache_type_supported(type_k) || ggml_is_quantized(type_k)) || !(banded_cache_type_supported(type_v) || ggml_is_quantized(type_v))) { return false; @@ -241,7 +240,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par if (!dev) { return false; } - for (const auto & [d, ok] : banded_quant_dev_ok) { + for (const auto & [d, ok] : banded_dev_ok) { if (d == dev) { return ok; } @@ -256,7 +255,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); ggml_prec_set_acc(op, GGML_PREC_F32); const bool ok = ggml_backend_dev_supports_op(dev, op); - banded_quant_dev_ok.push_back({ dev, ok }); + banded_dev_ok.push_back({ dev, ok }); return ok; }; From 7a6f4de9eb8c43aa9c428380fb19f676d22ea563 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 077/115] inkling2 : reserve the dense graphs that run outside the banded reserve With LLAMA_INKLING_BANDED_POS=0 a cache whose cells are not the positions is dense, so reserve the full-attention layers dense too, not only a wrapping SWA cache. A unified multi-sequence context decodes one token dense, while its tg reserve of n_seq_max tokens is banded: reserve that graph as well. --- src/llama-context.cpp | 12 ++++++++++++ src/models/inkling2.cpp | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7b9510ce8b18..ff22678884a2 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -891,6 +891,18 @@ void llama_context::sched_reserve() { n_nodes_tg = ggml_graph_n_nodes(gf); n_inputs_tg = get_gf_res_reserve()->inputs.size(); n_input_tensors_tg = this->n_input_tensors; + + // Inkling 2 decodes one token of a unified multi-sequence cache dense, the tg graph above is banded + if (n_seqs > 1 && cparams.flash_attn && cparams.kv_unified && + (model.arch == LLM_ARCH_INKLING2 || model.arch == LLM_ARCH_INKLING2_LOOP)) { + std::vector sizes(backend_buf_exp_size.size(), 0); + if (!graph_reserve(1, 1, 1, mctx.get(), model.no_alloc(), model.no_alloc() ? sizes.data() : nullptr)) { + throw std::runtime_error("failed to allocate compute tg buffers"); + } + for (size_t i = 0; i < sizes.size(); ++i) { + backend_buf_exp_size[i] = std::max(backend_buf_exp_size[i], sizes[i]); + } + } } // reserve again with pp graph to avoid ggml-alloc reallocations during inference diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index ce4669706b32..9b7340bfbcec 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -413,8 +413,10 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { k_pos(i); } } - } else if (attn->mctx->get_swa()->get_size() < base->get_size()) { - // once the positions pass the SWA cache it wraps and its layers take the dense bias for every ubatch + } else { + // without the positions a cache whose cells are not the positions is dense: a wrapped SWA cache, + // a sequence that does not start at cell 0 + inp->n_kv_banded[0] = 0; inp->n_kv_banded[1] = 0; } } From 073ad783c3240db145468f07498be45187df923b Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 09:05:12 -0800 Subject: [PATCH 078/115] tests : banded FA at the F16 floor over a ragged n_kv, K/V layouts and masks the Metal launch must refuse rel_floor: every band score near -65504, so padded keys left in the softmax tie the real ones. kv_layout: K rows padded off a 4-element boundary, a mask wider than K and (banded) K/V head counts that differ, for plain mixed K/V FA and the banded op. --- tests/test-backend-ops.cpp | 101 +++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index bc95a7a97c81..7382ba44b272 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9746,6 +9746,90 @@ struct test_flash_attn_ext_banded_shapes : public test_case { }; // banded attention with different K and V cache types (e.g. -ctk q8_0 -ctv q4_0), causal mask, per-query sinks +// banded attention with every relative bias at the bottom of the F16 range: the padded keys of a ragged n_kv +// must stay out of the softmax, they would otherwise tie the real keys +struct test_flash_attn_ext_banded_rel_floor : public test_flash_attn_ext_banded { + using test_flash_attn_ext_banded::test_flash_attn_ext_banded; + + std::string vars() override { + return test_flash_attn_ext_banded::vars() + ",rel_floor=1"; + } + + void initialize_tensors(ggml_context * ctx) override { + test_flash_attn_ext_banded::initialize_tensors(ctx); + init_tensor_uniform(ggml_get_tensor(ctx, "rel_logits"), -65504.0f, -65500.0f); + } +}; + +// K/V layouts and masks the Metal banded / mixed K/V kernels cannot address (backends may refuse them): +// K and V with their own types and head counts, K/V rows padded to a stride the 4-vector loads would round down, +// a mask wider than K +struct test_flash_attn_ext_kv_layout : public test_case { + const bool banded; + const int64_t d, n_head, n_q, n_kv; + const ggml_type type_k, type_v; + const int64_t n_head_k, n_head_v, row_pad, mask_cols; + + std::string vars() override { + return VARS_TO_STR10(banded, d, n_head, n_q, n_kv, type_k, type_v, n_head_k, n_head_v, row_pad) + + ",mask_cols=" + std::to_string(mask_cols); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_kv_layout(bool banded, int64_t d, int64_t n_head, int64_t n_q, int64_t n_kv, ggml_type type_k, ggml_type type_v, + int64_t n_head_k, int64_t n_head_v, int64_t row_pad, int64_t mask_cols) + : banded(banded), d(d), n_head(n_head), n_q(n_q), n_kv(n_kv), type_k(type_k), type_v(type_v), + n_head_k(n_head_k), n_head_v(n_head_v), row_pad(row_pad), mask_cols(mask_cols) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + // the row padding applies to the non-quantized side(s) only (a quantized row is whole blocks) + const int64_t pad_k = ggml_is_quantized(type_k) ? 0 : row_pad; + const int64_t pad_v = ggml_is_quantized(type_v) ? 0 : row_pad; + ggml_tensor * kb = ggml_new_tensor_4d(ctx, type_k, d + pad_k, n_kv, n_head_k, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, type_v, d + pad_v, n_kv, n_head_v, 1); + ggml_tensor * k = pad_k ? ggml_view_4d(ctx, kb, d, n_kv, n_head_k, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0) : kb; + ggml_tensor * v = pad_v ? ggml_view_4d(ctx, vb, d, n_kv, n_head_v, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0) : vb; + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, mask_cols, n_q, 1, 1); + ggml_set_name(q, "q"); + ggml_set_name(kb, "kb"); + ggml_set_name(vb, "vb"); + ggml_set_name(m, "m"); + ggml_tensor * out; + if (banded) { + ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 16, n_head, n_q, 1); + ggml_set_name(r, "rel_logits"); + out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), 16); + } else { + out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/float(d), 0.0f, 0.0f); + } + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + // causal over the first n_kv columns, the rest masked + std::vector data(n_q*mask_cols); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < mask_cols; ++ik) { + const bool visible = ik < n_kv && iq + (n_kv - n_q) - ik >= 0; + data[iq*mask_cols + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (t->view_src == nullptr) { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + struct test_flash_attn_ext_banded_kv2 : public test_case { const int64_t d; const int64_t n_head; @@ -14405,6 +14489,23 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 1, 4096, 1024, 2, kv_type, GGML_TYPE_F32, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 333, 16, 2, kv_type, GGML_TYPE_F32, 1)); } + // padded keys of a ragged n_kv out of the softmax when the band pushes every score to the F16 floor + for (int64_t n_q : { 1, 4, 33 }) { + for (int mask_kind : { 0, 1 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_rel_floor(128, 8, 2, n_q, 333, 512, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32)); + } + } + // layouts and masks backends may refuse: K rows padded off a 4-element boundary, a mask wider than K, and (banded) + // K/V head counts that differ. Left out: plain mixed FA with K/V head counts that differ and banded F16/F16 with + // padded rows, which CUDA accepts and gets wrong today (Metal refuses both) + // banded, d, nh, n_q, n_kv, type_k, type_v, hk, hv, pad, mask_cols + for (bool banded : { false, true }) { + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 1, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 33, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 128)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 64)); + } + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(true, 128, 4, 1, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 1, 0, 64)); // mixed K/V cache types (-ctk != -ctv), banded and dense, decode / small batches / prefill for (auto [type_k, type_v] : std::initializer_list>{ { GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }, { GGML_TYPE_Q8_0, GGML_TYPE_F16 }, From 4d7a835eb6dfde736ad4bfd6f535856489d5b7b6 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 10:03:30 -0800 Subject: [PATCH 079/115] ggml-cuda : do not delegate banded attention over unaligned F16 K/V rows The FA kernels read F16 K/V in place with 16-byte loads, so a K/V view whose rows are padded off that boundary (a 129-wide backing tensor) was mis-addressed. Keep such ops on the banded kernels, which read any row stride. Add the kv_layout cases: padded K/V rows, a mask wider than K and K/V head counts that differ. --- ggml/src/ggml-cuda/fattn.cu | 8 ++++ tests/test-backend-ops.cpp | 82 +++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 25db0d23013e..37e56d67e746 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -616,6 +616,14 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + // F16 K/V are read in place with 16-byte loads, the banded kernels read other rows + for (const ggml_tensor * t : {K, V}) { + if (t->type == GGML_TYPE_F16 && + ((uintptr_t) t->data % 16 != 0 || t->nb[1] % 16 != 0 || t->nb[2] % 16 != 0 || t->nb[3] % 16 != 0)) { + return false; + } + } + if ((Q->ne[0] != 64 && Q->ne[0] != 128) || V->ne[0] != Q->ne[0]) { return false; } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 46662a10f1a6..58b427a9feac 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9576,6 +9576,75 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { } }; +// K/V layouts and masks the Metal banded / mixed K/V kernels cannot address (backends may refuse them): +// K and V with their own types and head counts, K/V rows padded to a stride the 4-vector loads would round down, +// a mask wider than K +struct test_flash_attn_ext_kv_layout : public test_case { + const bool banded; + const int64_t d, n_head, n_q, n_kv; + const ggml_type type_k, type_v; + const int64_t n_head_k, n_head_v, row_pad, mask_cols; + + std::string vars() override { + return VARS_TO_STR10(banded, d, n_head, n_q, n_kv, type_k, type_v, n_head_k, n_head_v, row_pad) + + ",mask_cols=" + std::to_string(mask_cols); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_kv_layout(bool banded, int64_t d, int64_t n_head, int64_t n_q, int64_t n_kv, ggml_type type_k, ggml_type type_v, + int64_t n_head_k, int64_t n_head_v, int64_t row_pad, int64_t mask_cols) + : banded(banded), d(d), n_head(n_head), n_q(n_q), n_kv(n_kv), type_k(type_k), type_v(type_v), + n_head_k(n_head_k), n_head_v(n_head_v), row_pad(row_pad), mask_cols(mask_cols) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + // the row padding applies to the non-quantized side(s) only (a quantized row is whole blocks) + const int64_t pad_k = ggml_is_quantized(type_k) ? 0 : row_pad; + const int64_t pad_v = ggml_is_quantized(type_v) ? 0 : row_pad; + ggml_tensor * kb = ggml_new_tensor_4d(ctx, type_k, d + pad_k, n_kv, n_head_k, 1); + ggml_tensor * vb = ggml_new_tensor_4d(ctx, type_v, d + pad_v, n_kv, n_head_v, 1); + ggml_tensor * k = pad_k ? ggml_view_4d(ctx, kb, d, n_kv, n_head_k, 1, kb->nb[1], kb->nb[2], kb->nb[3], 0) : kb; + ggml_tensor * v = pad_v ? ggml_view_4d(ctx, vb, d, n_kv, n_head_v, 1, vb->nb[1], vb->nb[2], vb->nb[3], 0) : vb; + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, mask_cols, n_q, 1, 1); + ggml_set_name(q, "q"); + ggml_set_name(kb, "kb"); + ggml_set_name(vb, "vb"); + ggml_set_name(m, "m"); + ggml_tensor * out; + if (banded) { + ggml_tensor * r = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 16, n_head, n_q, 1); + ggml_set_name(r, "rel_logits"); + out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), 16); + } else { + out = ggml_flash_attn_ext(ctx, q, k, v, m, 1.0f/float(d), 0.0f, 0.0f); + } + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "m") == 0) { + // causal over the first n_kv columns, the rest masked + std::vector data(n_q*mask_cols); + for (int64_t iq = 0; iq < n_q; ++iq) { + for (int64_t ik = 0; ik < mask_cols; ++ik) { + const bool visible = ik < n_kv && iq + (n_kv - n_q) - ik >= 0; + data[iq*mask_cols + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(data[0])); + } else if (t->view_src == nullptr) { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + // banded attention with cell and query positions: the cells are not the positions // layout 1: n_seq sequences interleaved in one unified cache, layout 2: one sequence in a wrapped ring cache // some cells are empty (position -1, masked); the mask separates the sequences and, for mask_kind 2, keeps the window @@ -14037,6 +14106,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 1, n_kv, 32, 4, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 33, n_kv, 32, 4, GGML_TYPE_Q8_0, GGML_TYPE_F32)); } + // layouts and masks backends may refuse: K/V rows padded off a 4-element boundary, a mask wider than K, and (banded) + // K/V head counts that differ. Left out: plain FA with padded F16/F16 rows, which CUDA FA reads in place and gets wrong + // banded, d, nh, n_q, n_kv, type_k, type_v, hk, hv, pad, mask_cols + for (int64_t n_q : { 1, 33 }) { + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(true, 128, 4, n_q, 64, GGML_TYPE_F16, GGML_TYPE_F16, 2, 2, 1, 64)); + } + for (bool banded : { false, true }) { + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 1, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 33, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 128)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 64)); + } + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(true, 128, 4, 1, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 1, 0, 64)); // cells that are not the positions: several sequences in a unified cache, a wrapped SWA ring for (ggml_type kv_type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { // decode (one token per sequence: the decode kernel up to 8 or 32 queries), short and long prefill (MMA tiles) From 6249123b1f1984a3313e8fd9d34cd6a09a606667 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 09:47:56 -0800 Subject: [PATCH 080/115] ggml-cuda : compile banded rel_logits paths out of non-banded FA head sizes --- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 5f8a65fab1d2..580bd5943d45 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -778,19 +778,21 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } float KQ_max_new[cols_per_thread]; + // the banded op only delegates DKQ == DV in {64, 128}: keep rel_f out of the other head sizes + constexpr bool banded_ok = (DKQ == 64 || DKQ == 128) && DV == DKQ; #pragma unroll for (int col = 0; col < cols_per_thread; ++col) { KQ_max_new[col] = KQ_max[col]; // banded only: large V overflows the fp16 VKQ accumulator, so bump the running max to rescale // by 2^-8 (cancelled by the final normalization); bumps are logarithmic in n_kv - if (rel_f && KQ_rowsum[col] > 4.0f) { + if (banded_ok && rel_f && KQ_rowsum[col] > 4.0f) { KQ_max_new[col] += 8.0f*0.6931f; } } float KQ_rowsum_add[cols_per_thread] = {0.0f}; if constexpr (cols_per_warp == 8) { - if (rel_f) { + if (banded_ok && rel_f) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::I) { const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::I; @@ -873,7 +875,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } } } else { // not Turing mma or T_B_KQ::I > 8 - if (rel_f) { + if (banded_ok && rel_f) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::J) { const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::J; From 12db614a9c34dc77869b72bc475cbaa69228166e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 10:39:51 -0800 Subject: [PATCH 081/115] metal : FA, per-query sink loads for the banded op only Plain FA (one sink per head) reads the sink exactly as upstream again in the vec, half8x8 and tensor kernels; the strided per-query load is behind the rel function constant. --- ggml/src/ggml-metal/kernels/fa_common.metal | 5 ++++- ggml/src/ggml-metal/kernels/fa_tensor.metal | 5 ++++- ggml/src/ggml-metal/kernels/fa_vec_common.metal | 6 ++++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index cab80cc4e427..cf3fdc4d205c 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -656,8 +656,11 @@ void kernel_flash_attn_ext_impl( const float m = M[jj]; + // per-query sinks (banded only); plain FA keeps the per-head load const int32_t jq = min(iq1 + j, args.ne01 - 1); - const float s = tiisg == 0 ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) : -FLT_MAX/2; + const float s = tiisg != 0 ? -FLT_MAX/2 : FC_flash_attn_ext_has_rel + ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) + : ((device const float *) sinks)[iq2]; M[jj] = simd_max(max(M[jj], s)); diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 9f6b78fc8c23..f2c80fe6419d 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -316,8 +316,11 @@ kernel void kernel_flash_attn_ext_tensor( float ms = 1.0f; if (FC_flash_attn_ext_tensor_has_sinks) { + // per-query sinks (banded only); plain FA keeps the per-head load const int jq = min(iq1 + j, args.ne01 - 1); - const float s = *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)); + const float s = FC_flash_attn_ext_tensor_has_rel + ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) + : ((device const float *) sinks)[iq2]; const float m = max(M[jj], s); ms = exp(M[jj] - m); diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index ac5c6da3e36e..147548d0114c 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -611,9 +611,11 @@ kernel void kernel_flash_attn_ext_vec( if (FC_flash_attn_ext_vec_has_sinks && sgitg == 0 && iwg == 0) { FOR_UNROLL (short qq = 0; qq < Q; ++qq) { const float m = M[qq]; - // per-query sinks (banded): nb_s1/nb_s2 are 0 for one sink per head + // per-query sinks (banded only): nb_s1/nb_s2 are 0 for one sink per head; plain FA keeps the per-head load const int32_t jq = min(iq1*Q + qq, args.ne01 - 1); - const float s = tiisg == 0 ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) : -FLT_MAX/2; + const float s = tiisg != 0 ? -FLT_MAX/2 : FC_flash_attn_ext_vec_has_rel + ? *((device const float *) (sinks + iq2*sizeof(float) + jq*args.nb_s1 + iq3*args.nb_s2)) + : ((device const float *) sinks)[iq2]; M[qq] = simd_max(max(M[qq], s)); From 5b3e29e29d6c07a79452c83dd86f3e0bcf58b946 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 10:47:05 -0800 Subject: [PATCH 082/115] ggml-cuda : check GGML_CUDA_DISABLE_BANDED_MMA in its own statement, leaving the banded op check as it was --- ggml/src/ggml-cuda/fattn.cu | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 37e56d67e746..682c04655c9d 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -583,7 +583,11 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; #endif // FLASH_ATTN_AVAILABLE - if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED || ggml_cuda_banded_mma_disabled()) { + if (ggml_cuda_banded_mma_disabled()) { + return false; + } + + if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { return false; } From a8ca6dab00107ff51f02c38124c3d978e3f0261e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 10:50:14 -0800 Subject: [PATCH 083/115] ggml-cuda : check GGML_CUDA_DISABLE_BANDED_MMA beside the other banded-only MMA checks --- ggml/src/ggml-cuda/fattn.cu | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 682c04655c9d..7d7838b3732e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -583,10 +583,6 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; #endif // FLASH_ATTN_AVAILABLE - if (ggml_cuda_banded_mma_disabled()) { - return false; - } - if (dst->op != GGML_OP_FLASH_ATTN_EXT_BANDED) { return false; } @@ -600,6 +596,10 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + if (ggml_cuda_banded_mma_disabled()) { + return false; + } + // the MMA kernel passes rel in the sinks slot, and indexes it by cell distance only if (dst->src[4] || dst->src[7]) { return false; From 05caeeb62378b0caeceb0ec002eae9818c2e7cf9 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:48 -0800 Subject: [PATCH 084/115] ggml : return the banded attention precision from ggml_prec_get_acc ggml_prec_set_acc() stores the accumulator precision of GGML_OP_FLASH_ATTN_EXT_BANDED in op param 3 and ggml_flash_attn_ext_get_prec() reads it, but the generic getter returned GGML_PREC_UNDEFINED for the banded op. test-flash-attn-bias checks the round trip. --- ggml/src/ggml.c | 1 + tests/test-flash-attn-bias.cpp | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index d2e1859bb41d..3fdb2fea73de 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -3352,6 +3352,7 @@ enum ggml_prec ggml_prec_get_acc( case GGML_OP_MUL_MAT_ID: return (enum ggml_prec) ggml_get_op_params_i32(a, 0); case GGML_OP_FLASH_ATTN_EXT: + case GGML_OP_FLASH_ATTN_EXT_BANDED: return (enum ggml_prec) ggml_get_op_params_i32(a, 3); default: return GGML_PREC_UNDEFINED; diff --git a/tests/test-flash-attn-bias.cpp b/tests/test-flash-attn-bias.cpp index a7f93df9ace3..3f96a8c76e57 100644 --- a/tests/test-flash-attn-bias.cpp +++ b/tests/test-flash-attn-bias.cpp @@ -359,6 +359,25 @@ static void overflow_arithmetic_self_test() { (unsigned long long) offset, (long long) nq, (long long) rel_dist); } +static void prec_round_trip_test() { + ggml_init_params params = { + /* .mem_size = */ ggml_tensor_overhead()*8, + /* .mem_base = */ nullptr, + /* .no_alloc = */ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + GGML_ASSERT(ctx); + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, 64, 2, 2, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, 64, 2, 1, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, 64, 2, 1, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, 8, 2, 2, 1); + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, nullptr, r, 0.125f, 8); + GGML_ASSERT(ggml_prec_set_acc(out, GGML_PREC_F32)); + const bool pass = ggml_prec_get_acc(out) == GGML_PREC_F32 && ggml_flash_attn_ext_get_prec(out) == GGML_PREC_F32; + printf("prec_round_trip acc=%d %s\n", (int) ggml_prec_get_acc(out), pass ? "PASS" : "FAIL"); + GGML_ASSERT(pass); +} + static bool overflow_kernel_test(ggml_backend_t backend, const char * backend_kind) { // rel-logits row for query 1 sits beyond INT32_MAX; only two small logical rows are touched const bias_test_config c = { @@ -419,6 +438,7 @@ int main(int argc, char ** argv) { int repeats = argc > 3 ? std::max(1, atoi(argv[3])) : 1; overflow_arithmetic_self_test(); + prec_round_trip_test(); ggml_backend_load_all(); ggml_backend_dev_t chosen = nullptr; const enum ggml_backend_dev_type wanted = backend_kind == "cuda" ? From 82e03c68c54bb05ba6545f9f94a7da9ba23446b1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:48 -0800 Subject: [PATCH 085/115] tests : register test-flash-attn-bias and test-flash-attn-generic-hash with the main label Both were plain add_test() entries without a label, so ctest -L main skipped them. --- tests/CMakeLists.txt | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9100adb21e2e..4e307e5646b3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -371,13 +371,8 @@ 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) -add_executable(test-flash-attn-bias test-flash-attn-bias.cpp) -target_link_libraries(test-flash-attn-bias PRIVATE ggml) -add_test(NAME test-flash-attn-bias COMMAND test-flash-attn-bias) - -add_executable(test-flash-attn-generic-hash test-flash-attn-generic-hash.cpp) -target_link_libraries(test-flash-attn-generic-hash PRIVATE ggml) -add_test(NAME test-flash-attn-generic-hash COMMAND test-flash-attn-generic-hash) +llama_build_and_test(test-flash-attn-bias.cpp LINK ggml) +llama_build_and_test(test-flash-attn-generic-hash.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) From d8e01c2187c0e6ec45a799b8e68d9e5a805270c3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:49 -0800 Subject: [PATCH 086/115] ggml-cuda : tag the banded MMA call with a negative m0 instead of max_bias The banded op reuses the FA MMA kernel and tagged it with max_bias < 0, but ggml_flash_attn_ext() accepts a negative max_bias (no ALiBi), so an ordinary call with max_bias < 0 read the sinks as a relative-bias table. m0 of an ordinary call is a power of 2 and never negative. Add FLASH_ATTN_EXT cases with max_bias = -2. --- ggml/src/ggml-cuda/fattn-common.cuh | 7 +++---- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 ++-- tests/test-backend-ops.cpp | 5 +++++ 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index ed065b4d0345..23d37e02e40c 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -1295,11 +1295,9 @@ void launch_fattn( memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float)); - // banded op reuses the MMA ABI: negative max_bias tags the branch, sinks_ptr carries rel_logits, -max_bias is E if (rel) { GGML_ASSERT(rel->type == GGML_TYPE_F32 && ggml_is_contiguous(rel)); GGML_ASSERT(rel->ne[0] <= (1 << 20)); // exactly representable in float - max_bias = -float(rel->ne[0]); } if (logit_softcap != 0.0f) { @@ -1309,8 +1307,9 @@ void launch_fattn( const uint32_t n_head = Q->ne[2]; const uint32_t n_head_log2 = 1u << uint32_t(floorf(log2f(float(n_head)))); - // m0/m1 are unused for banded bias; the negative tag would otherwise blow up the exponent - const float m0 = rel ? 1.0f : powf(2.0f, -(max_bias ) / n_head_log2); + // banded op reuses the MMA ABI: negative m0 tags the branch, sinks_ptr carries rel_logits, -m0 is E + // an ordinary m0 is a power of 2 and never negative, whatever max_bias is + const float m0 = rel ? -float(rel->ne[0]) : powf(2.0f, -(max_bias ) / n_head_log2); const float m1 = rel ? 1.0f : powf(2.0f, -(max_bias / 2.0f) / n_head_log2); // TODO other tensor dimensions after removal of WMMA kernel: diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index e09bc5153024..53c8cd878c5c 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -2027,8 +2027,8 @@ static __global__ void flash_attn_ext_f16( const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; - const bool banded_bias = max_bias < 0.0f; - const int rel_extent = banded_bias ? int(-max_bias) : 0; + const bool banded_bias = m0 < 0.0f; + const int rel_extent = banded_bias ? int(-m0) : 0; // Skip unused kernel variants for faster compilation: if (use_logit_softcap && !(DKQ == 128 || DKQ == 256 || DKQ == 512)) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a881c85a6170..bd352ee076ad 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13678,6 +13678,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 17, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); test_cases.emplace_back(new test_flash_attn_ext(65, 67, 4, {1, 1}, 113, 75, false, false, 0, 1.0f, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + // a negative max_bias disables ALiBi, it must not select the banded MMA branch + for (bool sinks : {true, false}) { + test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 512, 32, true, sinks, -2.0f, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + } + // mixed quant and Q1_0 test cases test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0)); test_cases.emplace_back(new test_flash_attn_ext(64, 64, 4, {1, 1}, 128, 2, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_Q4_0, GGML_TYPE_F16)); From b8d2bf7e76927a06713f939acd926a6ce11edbfe Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 11:01:53 -0800 Subject: [PATCH 087/115] ggml-cuda : write 0 for a fully masked row in the FA MMA kernel A row without a visible cell has a zero rowsum, the MMA kernel and the stream-k fixups divided 0 by 0. The CPU and the other banded CUDA kernels return 0. Let the banded test mask a whole query (mask_kind 4). --- ggml/src/ggml-cuda/fattn-common.cuh | 4 ++-- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 5 +++-- tests/test-backend-ops.cpp | 5 +++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index 23d37e02e40c..89bf832ffc56 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -856,7 +856,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform( } // Write back final result: - *dst = dst_val / rowsum; + *dst = rowsum == 0.0f ? 0.0f : dst_val / rowsum; } // General fixup kernel for the case where the number of blocks per tile is not uniform across tiles @@ -967,7 +967,7 @@ static __global__ void flash_attn_stream_k_fixup_general( } // Write back final result: - *dst = dst_val / rowsum; + *dst = rowsum == 0.0f ? 0.0f : dst_val / rowsum; } template // D == head size diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 53c8cd878c5c..5f8a65fab1d2 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -1955,9 +1955,10 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( } if (!needs_fixup && !is_fixup) { + // a fully masked row has a zero rowsum, it is 0 like on the CPU const float KQ_rowsum_j = meta_j[1]; - dstk_val.x /= KQ_rowsum_j; - dstk_val.y /= KQ_rowsum_j; + dstk_val.x = KQ_rowsum_j == 0.0f ? 0.0f : dstk_val.x / KQ_rowsum_j; + dstk_val.y = KQ_rowsum_j == 0.0f ? 0.0f : dstk_val.y / KQ_rowsum_j; } if (is_fixup) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index bd352ee076ad..575e0312abf2 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9423,7 +9423,8 @@ struct test_flash_attn_ext_banded : public test_case { const int64_t n_q; const int64_t n_kv; const int64_t rel_extent; - const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent + const int mask_kind; // 0: none, 1: causal, 2: causal sliding window with dist < rel_extent, 3: causal over a padded n_kv, + // 4: causal with the first query fully masked const ggml_type kv_type; const ggml_type rel_type; const bool strided; @@ -9492,7 +9493,7 @@ struct test_flash_attn_ext_banded : public test_case { for (int64_t iq = 0; iq < n_q; ++iq) { for (int64_t ik = 0; ik < n_kv; ++ik) { const int64_t rel_dist = iq + (n_kv - n_q) - ik; - const bool visible = rel_dist >= 0 && (mask_kind == 1 || rel_dist < rel_extent); + const bool visible = rel_dist >= 0 && (mask_kind != 2 || rel_dist < rel_extent) && (mask_kind != 4 || iq != 0); data[iq*n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); } } From 734e78664b930293695a29359e9f635dee3426d1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 088/115] convert : reject stacked ModelOpt NVFP4 experts before the pure NVFP4 early return A pure NVFP4 checkpoint returned from dequant_model() before the check, keeping the packed experts. --- conversion/base.py | 25 ++++++++++++++----------- tests/test_conversion_fp8.py | 15 +++++++++++++++ 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/conversion/base.py b/conversion/base.py index 894db138a44c..ec58755701bc 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -384,6 +384,20 @@ def _prepare_kv_cache_scales(self): self.gguf_writer.add_tensor(new_name, scale.flatten().numpy()) def dequant_model(self): + # stacked-expert NVFP4 (w13_weight/w2_weight) is silently skipped by the NVFP4 repack and the dequant below + quant_config = self.hparams.get("quantization_config") + if isinstance(quant_config, dict) and quant_config.get("quant_method") in ("modelopt", "modelopt_mixed"): + stacked_expert_aux = [ + n for n in self.model_tensors + if n.endswith((".scale2", ".input_amax", ".original_shape")) + ] + if stacked_expert_aux: + raise NotImplementedError( + "This checkpoint stores quantized experts in the stacked ModelOpt NVFP4 layout " + f"({len(stacked_expert_aux)} auxiliary tensors like {stacked_expert_aux[0]!r}), " + "which is not supported yet. Convert from the unquantized (BF16) checkpoint instead." + ) + # If all quantized tensors were already handled (e.g. pure NVFP4), skip if self._is_nvfp4 and not any(k.endswith((".weight_scale", ".weight_scale_inv", ".input_scale", ".activation_scale", "_activation_scale", ".k_scale", ".v_scale")) for k in self.model_tensors): return @@ -662,17 +676,6 @@ def dequant_fp8(fp8_configs: list[dict[str, Any]] | None = None) -> None: raise NotImplementedError(f"Quant format {quant_format!r} for method {quant_method!r} is not yet supported") elif quant_method in ("modelopt", "modelopt_mixed"): dequant_fp8() - # stacked-expert NVFP4 (w13_weight/w2_weight) is silently skipped by the path above - stacked_expert_aux = [ - n for n in self.model_tensors - if n.endswith((".scale2", ".input_amax", ".original_shape")) - ] - if stacked_expert_aux: - raise NotImplementedError( - "This checkpoint stores quantized experts in the stacked ModelOpt NVFP4 layout " - f"({len(stacked_expert_aux)} auxiliary tensors like {stacked_expert_aux[0]!r}), " - "which is not supported yet. Convert from the unquantized (BF16) checkpoint instead." - ) # FP8_PB_WO: one scale per block, the block size follows from the two shapes for name in self.model_tensors.keys(): if not name.endswith(".weight_scale_inv"): diff --git a/tests/test_conversion_fp8.py b/tests/test_conversion_fp8.py index e191c8a55bae..a5171e83b232 100644 --- a/tests/test_conversion_fp8.py +++ b/tests/test_conversion_fp8.py @@ -123,6 +123,21 @@ def test_lazy_fp8_export(self): np.testing.assert_array_equal(gguf.dequantize(data, dtype), weight.float().numpy()) np.testing.assert_array_equal(result["blk.0.attn_q.scale"][1], [0.25]) + def test_stacked_nvfp4_experts_rejected(self): + experts = "model.layers.0.mlp.experts.w13_weight" + stacked = { + experts: torch.zeros((2, 4, 2), dtype=torch.uint8), + experts + ".scale2": torch.ones(2), + experts + ".original_shape": torch.tensor([2, 4, 4]), + } + fp8 = "model.layers.0.self_attn.q_proj.weight" + # pure NVFP4 returns early from dequant_model, mixed with FP8 does not + for name, extra in (("pure", {}), ("mixed", {fp8: torch.ones((2, 2)).to(torch.float8_e4m3fn), fp8 + "_scale": torch.ones(1)})): + with self.subTest(name): + with self.assertRaisesRegex(NotImplementedError, "stacked ModelOpt NVFP4"): + self.convert(Qwen2MoeModel, {**stacked, **extra}, ftype=gguf.LlamaFileType.MOSTLY_F16, + hparams_override={"quantization_config": {"quant_method": "modelopt", "quant_algo": "NVFP4"}}) + def test_mixed_compressed_fp8_block_scale(self): name = "model.layers.0.self_attn.q_proj.weight" scale = torch.tensor([[0.25, 0.5], [1.0, 2.0]]) From 429cfdc75554e68dd7a97047d1fe94eeb4798f1c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 08:54:59 -0800 Subject: [PATCH 089/115] inkling : reserve the dense attention of multi-sequence ubatches and probe every cache type The reserve context reports the full span as contiguous, so the reserved graph of a unified multi-sequence context was banded while such ubatches run dense. Take the banded op for one-sequence ubatches only, as inkling2 does, and ask the layer's device for F32 / F16 / BF16 caches too, not only for quantized ones. --- src/models/inkling.cpp | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 05e1e778bf50..09bd4a74ead9 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -216,8 +216,10 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par GGML_ASSERT(ubatch.equal_seqs()); GGML_ASSERT(ubatch.n_tokens == n_seq_tokens * n_seqs); - const uint32_t n_kv_flash_base = cparams.flash_attn ? mctx_attn->get_base()->get_n_kv_pos_contiguous() : 0; - const uint32_t n_kv_flash_swa = cparams.flash_attn ? mctx_attn->get_swa ()->get_n_kv_pos_contiguous() : 0; + // one sequence: a ubatch of several is dense at runtime, so is the reserved one + const bool use_flash_banded = cparams.flash_attn && ubatch.n_seqs_unq == 1; + const uint32_t n_kv_flash_base = use_flash_banded ? mctx_attn->get_base()->get_n_kv_pos_contiguous() : 0; + const uint32_t n_kv_flash_swa = use_flash_banded ? mctx_attn->get_swa ()->get_n_kv_pos_contiguous() : 0; bool has_global = false; bool needs_rel_idx_local = false; @@ -227,12 +229,9 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par return type == GGML_TYPE_F32 || type == GGML_TYPE_F16 || type == GGML_TYPE_BF16; }; - // a quantized cache takes the banded op only where the layer's device runs it, else the dense path - std::vector> banded_quant_dev_ok; + // the banded op only where the layer's device runs it, else the dense path + std::vector> banded_dev_ok; const auto banded_cache_types_ok = [&](int il, ggml_type type_k, ggml_type type_v) { - if (banded_cache_type_supported(type_k) && banded_cache_type_supported(type_v)) { - return true; - } if (!(banded_cache_type_supported(type_k) || ggml_is_quantized(type_k)) || !(banded_cache_type_supported(type_v) || ggml_is_quantized(type_v))) { return false; @@ -241,7 +240,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par if (!dev) { return false; } - for (const auto & [d, ok] : banded_quant_dev_ok) { + for (const auto & [d, ok] : banded_dev_ok) { if (d == dev) { return ok; } @@ -256,7 +255,7 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); ggml_prec_set_acc(op, GGML_PREC_F32); const bool ok = ggml_backend_dev_supports_op(dev, op); - banded_quant_dev_ok.push_back({ dev, ok }); + banded_dev_ok.push_back({ dev, ok }); return ok; }; From 18f8fe100613f7aa90cbf0f1cf109f2f7b4f450d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 10:58:11 -0800 Subject: [PATCH 090/115] ggml-cuda : do not delegate banded attention over unaligned F16 K/V rows The FA kernels read F16 K/V in place with 16-byte loads, so a K/V view whose rows are padded off that boundary (a 129-wide backing tensor) was mis-addressed. Keep such ops on the banded kernels, which read any row stride. --- ggml/src/ggml-cuda/fattn.cu | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index ef8f30ace00e..63b6ee4aa332 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -606,6 +606,14 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + // F16 K/V are read in place with 16-byte loads, the banded kernels read other rows + for (const ggml_tensor * t : {K, V}) { + if (t->type == GGML_TYPE_F16 && + ((uintptr_t) t->data % 16 != 0 || t->nb[1] % 16 != 0 || t->nb[2] % 16 != 0 || t->nb[3] % 16 != 0)) { + return false; + } + } + if ((Q->ne[0] != 64 && Q->ne[0] != 128) || V->ne[0] != Q->ne[0]) { return false; } From e1b2a332f45697af03ce2b77759cfdcbd1a5db49 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 09:47:56 -0800 Subject: [PATCH 091/115] ggml-cuda : compile banded rel_logits paths out of non-banded FA head sizes --- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 5f8a65fab1d2..580bd5943d45 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -778,19 +778,21 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } float KQ_max_new[cols_per_thread]; + // the banded op only delegates DKQ == DV in {64, 128}: keep rel_f out of the other head sizes + constexpr bool banded_ok = (DKQ == 64 || DKQ == 128) && DV == DKQ; #pragma unroll for (int col = 0; col < cols_per_thread; ++col) { KQ_max_new[col] = KQ_max[col]; // banded only: large V overflows the fp16 VKQ accumulator, so bump the running max to rescale // by 2^-8 (cancelled by the final normalization); bumps are logarithmic in n_kv - if (rel_f && KQ_rowsum[col] > 4.0f) { + if (banded_ok && rel_f && KQ_rowsum[col] > 4.0f) { KQ_max_new[col] += 8.0f*0.6931f; } } float KQ_rowsum_add[cols_per_thread] = {0.0f}; if constexpr (cols_per_warp == 8) { - if (rel_f) { + if (banded_ok && rel_f) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::I) { const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::I; @@ -873,7 +875,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( } } } else { // not Turing mma or T_B_KQ::I > 8 - if (rel_f) { + if (banded_ok && rel_f) { #pragma unroll for (int i00 = 0; i00 < nbatch_fa; i00 += np*T_C_KQ::J) { const int i0 = i00 + (threadIdx.y % np)*T_C_KQ::J; From f44881ab6c3c0bb47f26f46e2fef3f38c4716d2e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 12:07:52 -0800 Subject: [PATCH 092/115] ggml-metal : treat max_bias <= 0 as no ALiBi in flash attention Metal enabled the ALiBi slope path for any non-zero max_bias, so a negative max_bias produced slopes above 1 while the CPU reference uses a slope of 1 for max_bias <= 0. soft_max on Metal already checks max_bias > 0. Fixes the FLASH_ATTN_EXT max_bias=-2 cases in test-backend-ops. --- ggml/src/ggml-metal/ggml-metal-ops.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 20b417a5a5d2..d9771eb65fe6 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3662,7 +3662,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const uint64_t nb_s2 = has_sinks && op->src[4]->ne[2] > 1 ? op->src[4]->nb[2] : 0; GGML_ASSERT(!has_rows || has_mask); - const bool has_bias = max_bias != 0.0f; + const bool has_bias = max_bias > 0.0f; // max_bias <= 0 disables ALiBi (matches CPU and soft_max) const bool has_scap = logit_softcap != 0.0f; const uint32_t n_head = op->src[0]->ne[2]; From abcfe87aad1b0047c625065f959f88b4b84d45cd Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 13:55:15 -0800 Subject: [PATCH 093/115] ggml-cuda : const_cast the banded F16 K/V view data instead of a C cast (-Werror=cast-qual) --- ggml/src/ggml-cuda/fattn-banded.cu | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index f2acfdcca5de..48c3ea2f0f7a 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1713,7 +1713,7 @@ static const ggml_tensor * fattn_banded_kv_to_f16_tensor(ggml_backend_cuda_conte uint64_t nb[4]; fattn_banded_kv_to_f16(ctx, t, buf, data, type, nb); t_f16 = *t; - t_f16.data = (void *) data; + t_f16.data = const_cast(data); t_f16.type = type; for (int i = 0; i < 4; ++i) { t_f16.nb[i] = nb[i]; From 87d71c1993136f79e119170967ce0e5627397b64 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 17:20:57 -0800 Subject: [PATCH 094/115] inkling2 : causal banded attention without a mask for a cache of one sequence With one sequence in the cache a cell is visible to a query iff its distance to the query (the cell distance, or the position distance with empty cells at -1) is not negative. Add ggml_flash_attn_ext_banded_set_causal, which drops the mask and lets the CPU and CUDA banded kernels mask by the sign of the distance, and use it for the full-attention layers of Inkling 2 when the context has one sequence. Those layers no longer read the n_kv x n_tokens F16 mask input, so it is neither reserved on the device nor staged in pinned host memory (1 GiB each at 1M cells and 512 tokens, 4 GiB at 2048). Sliding-window layers, padded spans without positions, several sequences and other backends keep the mask. LLAMA_INKLING_BANDED_CAUSAL=0 keeps it everywhere. --- ggml/include/ggml.h | 7 ++++++ ggml/src/ggml-cpu/ops.cpp | 5 ++++ ggml/src/ggml-cuda/fattn-banded.cu | 40 +++++++++++++++++++++++------- ggml/src/ggml-cuda/fattn.cu | 5 ++++ ggml/src/ggml-impl.h | 7 ++++++ ggml/src/ggml.c | 8 ++++++ src/models/inkling2.cpp | 39 ++++++++++++++++++++++++----- src/models/models.h | 2 ++ tests/test-backend-ops.cpp | 27 ++++++++++++++++++++ 9 files changed, 125 insertions(+), 15 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 305ba3560174..ac40a1ade908 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2286,6 +2286,13 @@ extern "C" { struct ggml_tensor * k_pos, struct ggml_tensor * q_pos); + // causal banded attention without a mask: a cell is visible to a query iff its distance (the cell distance, or + // q_pos - k_pos with the positions, -1 for an empty cell) is >= 0; the op must have no mask. This is the causal + // mask of one sequence whose cells are its positions, or, with the positions, of a cache that holds one sequence + GGML_API void ggml_flash_attn_ext_banded_set_causal( + struct ggml_tensor * a, + bool causal); + // same as ggml_flash_attn_ext, but each q slice attends to its own list of K/V rows // q: [n_embd_k, n_batch, n_head, ne3] // k: [n_embd_k, n_rows, n_head_kv, 1 ] shared by all q slices diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 5ebdd4f2e9dd..d0e84b3486ab 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -9141,7 +9141,12 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( // loop over n_kv and n_head_kv // ref: https://arxiv.org/pdf/2112.05682.pdf + const bool causal = ggml_flash_attn_ext_banded_is_causal(dst); for (int64_t ic = ic_start; ic < ic_end; ++ic) { + // causal without a mask: the cells after the query (and the empty ones, with positions) are masked + if (causal && ggml_flash_attn_ext_banded_dist(dst, iq1, iq3, ic) < 0) { + continue; + } float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; if (bias) { GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins); diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 48c3ea2f0f7a..608a15abf25d 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -238,7 +238,8 @@ static __global__ void flash_attn_ext_banded_f32_split( uint64_t r_nb1, uint64_t r_nb2, uint64_t r_nb3, - int64_t rel_ne3) { + int64_t rel_ne3, + const int causal) { constexpr int values_per_lane = D / WARP_SIZE; static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); @@ -270,6 +271,10 @@ static __global__ void flash_attn_ext_banded_f32_split( const int64_t ik1 = ik0 + chunk < n_kv ? ik0 + chunk : n_kv; for (int64_t ik = ik0 + warp; ik < ik1; ik += NW) { + // causal without a mask: the cells after the query (and the empty ones, with positions) are masked + if (causal && fattn_banded_dist(kp, qp, iq, ik, q_offset) < 0) { + continue; + } if (mask && __half2float(*(const half *) (mask + uint64_t(ik)*sizeof(half) + uint64_t(iq)*m_nb1 + uint64_t(ih % mask_ne2)*m_nb2 + uint64_t(ib % mask_ne3)*m_nb3)) == -INFINITY) { @@ -634,7 +639,8 @@ static __global__ void flash_attn_ext_banded_vec( const int32_t * __restrict__ k_pos, const int32_t * __restrict__ q_pos_d, const int64_t kpos_s1, - const int64_t qpos_s1) { + const int64_t qpos_s1, + const int causal) { constexpr int NT = fattn_banded_vec_threads; constexpr int E = 8; // dimensions per lane constexpr int T = D / E; // lanes per cell @@ -723,6 +729,9 @@ static __global__ void flash_attn_ext_banded_vec( if (t < NR && c < c_end) { bm[j] = m_row ? __half2float(*(const half *) (m_row + uint64_t(c)*sizeof(half))) : 0.0f; const int64_t dist = kp ? (kp[c] < 0 ? -1 : q_pos - kp[c]) : q_pos - c; + if (causal && dist < 0) { + bm[j] = -INFINITY; + } if (bm[j] != -INFINITY && dist >= 0 && dist < rel_extent) { bm[j] += fattn_banded_load(r_row + uint64_t(dist)*r_nb0, type_rel); } @@ -983,6 +992,8 @@ static bool fattn_banded_vec_usable(const ggml_tensor * dst) { } static void fattn_banded_vec_launch(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const float scale, const int64_t rel_extent) { + // ggml_flash_attn_ext_banded_set_causal: no mask, the kernels mask the cells after each query + const int causal = ggml_flash_attn_ext_banded_is_causal(dst); const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; @@ -1036,7 +1047,7 @@ static void fattn_banded_vec_launch(ggml_backend_cuda_context & ctx, ggml_tensor m ? m->ne[2] : 1, m ? m->ne[3] : 1, q->nb[1], q->nb[2], q->nb[3], k->nb[1], k->nb[2], k->nb[3], \ v->nb[1], v->nb[2], v->nb[3], m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2, \ - k_pos_d, q_pos_d, kpos_s1, qpos_s1) + k_pos_d, q_pos_d, kpos_s1, qpos_s1, causal) #define LAUNCH_BANDED_VEC_NR(DD, TK, TV) \ switch (NR) { \ case 1: LAUNCH_BANDED_VEC_T(DD, 1, TK, TV); break; \ @@ -1301,7 +1312,8 @@ static __global__ void flash_attn_ext_banded_mma( const int32_t * __restrict__ k_pos, const int32_t * __restrict__ q_pos, int64_t kpos_s1, - int64_t qpos_s1) { + int64_t qpos_s1, + const int causal) { #ifdef FATTN_BANDED_MMA_AVAILABLE static_assert(D == 64 || D == 128, "banded FA supports head dimensions 64 and 128"); constexpr int BK = fattn_banded_mma_bk; @@ -1427,11 +1439,15 @@ static __global__ void flash_attn_ext_banded_mma( if (ik >= n_kv) { s = -INFINITY; } else if (iq_r[r] < n_q) { - if (in_band) { + if (in_band || causal) { const int64_t dist = fattn_banded_dist(kp, qp, iq_r[r], ik, q_offset); - if (dist >= 0 && dist < rel_extent) { + if (in_band && dist >= 0 && dist < rel_extent) { s += fattn_banded_load(r_base + uint64_t(dist)*r_nb0 + uint64_t(iq_r[r])*r_nb2, type_rel); } + // causal without a mask: the cells after the query (and the empty ones, with positions) + if (causal && dist < 0) { + s = -INFINITY; + } } if (flag == 2) { s += __half2float(*(const half *) (m_base + uint64_t(iq_r[r])*m_nb1 + uint64_t(ik)*sizeof(half))); @@ -1722,6 +1738,8 @@ static const ggml_tensor * fattn_banded_kv_to_f16_tensor(ggml_backend_cuda_conte } static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor * dst, const float scale, const int64_t rel_extent) { + // ggml_flash_attn_ext_banded_set_causal: no mask, the kernels mask the cells after each query + const int causal = ggml_flash_attn_ext_banded_is_causal(dst); const ggml_tensor * q = dst->src[0]; const ggml_tensor * k = dst->src[1]; const ggml_tensor * v = dst->src[2]; @@ -1825,7 +1843,7 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor k_nb[1], k_nb[2], k_nb[3], v_nb[1], v_nb[2], v_nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], sinks_s1, sinks_s2, \ - k_pos_d, q_pos_d, kpos_s1, qpos_s1) + k_pos_d, q_pos_d, kpos_s1, qpos_s1, causal) #define LAUNCH_BANDED_MMA(DD, NW) \ switch (type_kv) { \ case GGML_TYPE_Q8_0: LAUNCH_BANDED_MMA_T(DD, NW, GGML_TYPE_Q8_0); break; \ @@ -1863,6 +1881,8 @@ static void fattn_banded_mma_launch(ggml_backend_cuda_context & ctx, ggml_tensor } void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + // ggml_flash_attn_ext_banded_set_causal: no mask, the kernels mask the cells after each query + const int causal = ggml_flash_attn_ext_banded_is_causal(dst); GGML_ASSERT(ggml_cuda_flash_attn_ext_banded_supported(ctx.device, dst)); const ggml_tensor * q = dst->src[0]; @@ -1925,7 +1945,8 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso const int64_t target_blocks = int64_t(ggml_cuda_info().devices[ctx.device].nsm)*16; int64_t n_chunks = n_rows < target_blocks ? (target_blocks + n_rows - 1)/n_rows : 1; n_chunks = std::min(n_chunks, (n_kv + min_chunk - 1)/min_chunk); - if (n_chunks > 1 && q->ne[1]*q->ne[3] <= 65535) { + // the causal attention without a mask is masked in the split kernel, even in one chunk + if ((n_chunks > 1 || causal) && q->ne[1]*q->ne[3] <= 65535) { const int64_t chunk = (n_kv + n_chunks - 1)/n_chunks; n_chunks = (n_kv + chunk - 1)/chunk; const int64_t D = q->ne[0]; @@ -1946,7 +1967,7 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso v->nb[0], v->nb[1], v->nb[2], v->nb[3], \ m ? m->nb[1] : 0, m ? m->nb[2] : 0, m ? m->nb[3] : 0, \ k_pos_d, q_pos_d, kpos_s1, qpos_s1, \ - rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3]); \ + rel->nb[0], rel->nb[1], rel->nb[2], rel->nb[3], rel->ne[3], causal); \ flash_attn_ext_banded_f32_merge
<<>>( \ part.get(), (float *) dst->data, n_rows, q->ne[2], q->ne[1], n_chunks, \ sinks ? (const float *) sinks->data : nullptr, \ @@ -1962,6 +1983,7 @@ void ggml_cuda_flash_attn_ext_banded(ggml_backend_cuda_context & ctx, ggml_tenso } } + GGML_ASSERT(!causal && "the causal banded attention without a mask needs the split kernel"); constexpr int warps_per_block = 4; const dim3 blocks((q->ne[1] + warps_per_block - 1) / warps_per_block, q->ne[2], q->ne[3]); const dim3 threads(warps_per_block * WARP_SIZE, 1, 1); diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 7d7838b3732e..ee205b728d06 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -605,6 +605,11 @@ bool ggml_cuda_flash_attn_ext_banded_use_mma(const int device, const ggml_tensor return false; } + // flash attention masks with the mask tensor only + if (ggml_flash_attn_ext_banded_is_causal(dst)) { + return false; + } + // flash attention reads a contiguous mask if (dst->src[3] && !ggml_is_contiguous(dst->src[3])) { return false; diff --git a/ggml/src/ggml-impl.h b/ggml/src/ggml-impl.h index b1b5c2fcf352..1c67d57c5bc8 100644 --- a/ggml/src/ggml-impl.h +++ b/ggml/src/ggml-impl.h @@ -194,6 +194,13 @@ static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, floa ((float *)(tensor->op_params))[i] = value; } +// GGML_OP_FLASH_ATTN_EXT_BANDED: op param 6 is 1 when the op is causal without a mask (ggml_flash_attn_ext_banded_set_causal) +#define GGML_FLASH_ATTN_EXT_BANDED_CAUSAL_PARAM 6 + +static inline bool ggml_flash_attn_ext_banded_is_causal(const struct ggml_tensor * tensor) { + return tensor->op == GGML_OP_FLASH_ATTN_EXT_BANDED && ggml_get_op_params_i32(tensor, GGML_FLASH_ATTN_EXT_BANDED_CAUSAL_PARAM) != 0; +} + struct ggml_map_custom1_op_params { ggml_custom1_op_t fun; int n_tasks; diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index cc997a7b0b36..c844b287ed33 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5558,6 +5558,14 @@ void ggml_flash_attn_ext_banded_set_pos( a->src[8] = q_pos; } +void ggml_flash_attn_ext_banded_set_causal( + struct ggml_tensor * a, + bool causal) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT_BANDED); + GGML_ASSERT(!causal || a->src[3] == NULL); + ggml_set_op_params_i32(a, GGML_FLASH_ATTN_EXT_BANDED_CAUSAL_PARAM, causal ? 1 : 0); +} + struct ggml_tensor * ggml_flash_attn_ext( struct ggml_context * ctx, struct ggml_tensor * q, diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 350f2109ae60..e4b20baaf185 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -14,6 +14,15 @@ static constexpr int64_t n_tokens_banded_min = 32; // the banded attention takes the distances from the positions when the cells are not the positions // (several sequences in a unified cache, a wrapped SWA cache); LLAMA_INKLING_BANDED_POS=0 keeps those dense, // =2 takes the positions for every banded ubatch (a check: the cells that are the positions give the same result) +// LLAMA_INKLING_BANDED_CAUSAL=0 keeps the mask input of the full-attention layers when the cache holds one sequence +static bool inkling2_banded_causal_enabled() { + static const bool enabled = [] { + const char * env = getenv("LLAMA_INKLING_BANDED_CAUSAL"); + return env == nullptr || atoi(env) != 0; + }(); + return enabled; +} + static int inkling2_banded_pos_mode() { static const int mode = [] { const char * env = getenv("LLAMA_INKLING_BANDED_POS"); @@ -420,6 +429,13 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { } } + // a cache of one sequence: a cell is visible iff its distance to the query is not negative (empty cells have no + // position), so the full-attention layers need no mask, an n_kv x n_tokens F16 input (1 GiB at 1M cells and 512 + // tokens, on the host and on the device); padded spans without the positions measure the distance from the padded + // tail, they keep it + banded_causal = inp->banded && cparams.n_seq_max == 1 && cparams.causal_attn && inp->n_kv_banded[0] > 0 && n_tokens <= 65535 && + (inp->self_k_pos[0] || !inp->banded_pad) && inkling2_banded_causal_enabled(); + ggml_tensor * inp_pos = build_inp_pos(); // the query positions of the banded attention q_pos_banded = ggml_view_1d(ctx0, inp_pos, n_tokens, 0); @@ -572,12 +588,20 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens v_fa = ggml_permute(ctx0, ggml_view_4d(ctx0, v_all, v_all->ne[0], v_all->ne[1], n_kv_b, v_all->ne[3], v_all->nb[1], v_all->nb[2], v_all->nb[3], 0), 0, 2, 1, 3); } - ggml_tensor * mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - // one banded mask per graph and cache, the first n_kv_b cells of each row read in place - ggml_tensor *& m = mask_banded[is_swa]; - if (!m) { - m = ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], - mask->nb[1], mask->nb[2], mask->nb[3], 0); + // the causal attention without a mask runs on the CUDA and CPU kernels only + ggml_backend_dev_t dev = model.dev_layer(il); + const char * reg = dev ? ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)) : ""; + const bool causal = !is_swa && banded_causal && (strcmp(reg, "CUDA") == 0 || strcmp(reg, "CPU") == 0); + ggml_tensor * m = nullptr; + if (!causal) { + ggml_tensor * mask = is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; + // one banded mask per graph and cache, the first n_kv_b cells of each row read in place + ggml_tensor *& mb = mask_banded[is_swa]; + if (!mb) { + mb = ggml_view_4d(ctx0, mask, n_kv_b, mask->ne[1], mask->ne[2], mask->ne[3], + mask->nb[1], mask->nb[2], mask->nb[3], 0); + } + m = mb; } // exp(s + b)/(exp(t) + sum(exp(s + b))): the dense mask b - t with a zero sink ggml_tensor * rel_bias = layer.attn_rel_bias; @@ -592,6 +616,9 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens if (inp->self_k_pos[is_swa]) { ggml_flash_attn_ext_banded_set_pos(cur, inp->self_k_pos[is_swa], q_pos_banded); } + if (causal) { + ggml_flash_attn_ext_banded_set_causal(cur, true); + } ggml_prec_set_acc(cur, GGML_PREC_F32); res->add_fused_node({LLM_FUSED_OP_FLASH_ATTN, cur, il}); cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); diff --git a/src/models/models.h b/src/models/models.h index 5c4ac9227610..f24e00632a84 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2583,6 +2583,8 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * mask_banded[2] = { nullptr, nullptr }; // I32 [n_tokens] query positions of the banded attention, used when it takes the cell positions ggml_tensor * q_pos_banded = nullptr; + // one sequence in the cache: the full-attention layers take the causal mask from the distances, no mask input + bool banded_causal = false; llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; llm_graph_input_attn_kv_iswa * attn = nullptr; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 38ec0f519a8d..a1672163b3a2 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -11515,6 +11515,23 @@ static const ggml_type other_types[] = { #endif // Test cases for evaluation: should try to cover edge cases while using small input sizes to keep the runtime low +// banded attention without a mask, causal by the sign of the distance (ggml_flash_attn_ext_banded_set_causal) +struct test_flash_attn_ext_banded_causal : public test_flash_attn_ext_banded_sinks { + test_flash_attn_ext_banded_causal(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + ggml_type kv_type, int sinks, bool strided = false) + : test_flash_attn_ext_banded_sinks(d, n_head, n_head_kv, n_q, n_kv, rel_extent, 0, kv_type, GGML_TYPE_F32, sinks, strided) {} + + std::string vars() override { + return test_flash_attn_ext_banded_sinks::vars() + ",causal=1"; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_flash_attn_ext_banded_sinks::build_graph(ctx); + ggml_flash_attn_ext_banded_set_causal(out, true); + return out; + } +}; + static std::vector> make_test_cases_eval() { std::vector> test_cases; std::default_random_engine rng(0); @@ -14364,6 +14381,16 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, 3, 4096, 1280, 3, kt, GGML_TYPE_F32, 2, true, vt)); test_cases.emplace_back(new test_flash_attn_ext_banded_sinks( 64, 8, 2, 3, 1000, 8, 1, kt, GGML_TYPE_F32, 2, false, vt)); } + // causal without a mask (a cache of one sequence): decode, small, scalar, split and tensor-core shapes, every cache type + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_F32, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, GGML_TYPE_Q5_1 }) { + for (int64_t n_q : { 1, 3, 17, 64, 512 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_causal(128, 24, 8, n_q, 4096, 1280, kv_type, 2)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_causal( 64, 8, 2, 77, 1000, 8, kv_type, 1)); + test_cases.emplace_back(new test_flash_attn_ext_banded_causal(128, 8, 1, 511, 16403, 1024, kv_type, 2)); + test_cases.emplace_back(new test_flash_attn_ext_banded_causal(128, 8, 2, 65, 333, 32, kv_type, 2, true)); + } + // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 48, 8, n_q, 9000, 1024, 1, GGML_TYPE_F16, GGML_TYPE_F32, 2)); From 079491319ba41cc3600a66e52028673401abb87e Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 19:04:43 -0800 Subject: [PATCH 095/115] metal : do not report the causal banded attention without a mask as supported The Metal banded attention kernels do not read the causal flag set by ggml_flash_attn_ext_banded_set_causal, so with several queries they would attend to the cells after each query. supports_op now returns false for it and the scheduler runs the op on the CPU until the kernels implement it. --- ggml/src/ggml-metal/ggml-metal-device.m | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index b07425d7d7fe..df0b35eb5a32 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1882,6 +1882,11 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te if (op->src[0]->ne[0] != 64 && op->src[0]->ne[0] != 128) { return false; } + // causal without a mask (ggml_flash_attn_ext_banded_set_causal): the kernels do not mask the cells + // after each query, so this falls back to the CPU until they do + if (ggml_flash_attn_ext_banded_is_causal(op)) { + return false; + } // K/V cell and query positions (src[7], src[8]): the kernels take the distance from the cell index if (op->src[7] || op->src[8]) { return false; From bb942f19f57fdb6b3c90e4637c5e7c116aa072b1 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 19:27:23 -0800 Subject: [PATCH 096/115] CUDA: banded MMA attention: load the quantized K/V tiles one step ahead With q8_0 or q4_0 K/V the MMA kernel dequantized each tile with plain loads right where the F16 path issues its cp.async copies, so the loads of the next K tile stalled before the PV products and the next V tile before the QK products. The main loop now loads the quants and scales of the next tile into registers at that point and writes the F16 tile after the products that do not read it (K after PV, V after QK and the softmax), so the loads overlap the MMAs. The quants are read with 16-bit loads and dequantized with half arithmetic that gives the same values bit for bit (the int8 or nibble as an exact half, one half multiply of an exact product). The first tile keeps the one-step load. --- ggml/src/ggml-cuda/fattn-banded.cu | 109 ++++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 608a15abf25d..1c585eba6cf7 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1189,6 +1189,83 @@ static __device__ __forceinline__ void fattn_banded_mma_load_tile_q( #endif // CP_ASYNC_AVAILABLE } +// The quantized tiles of the main loop in two steps, so that the global loads overlap the MMAs as cp.async does for F16: +// fattn_banded_mma_issue_tile_q only loads the quants and scales of this thread's chunks into registers, fattn_banded_mma_store_tile_q later +// dequantizes them into the F16 tile with the values fattn_banded_mma_load_tile_q gives, bit for bit. +// Rows past n_kv get zero quants and a zero scale, which store as +0 like the zero fill of the one-step load. +template +struct fattn_banded_mma_qregs { + static constexpr int n = fattn_banded_mma_bk*(D/8)/(NW*WARP_SIZE); + static_assert(n*NW*WARP_SIZE == fattn_banded_mma_bk*(D/8), "the tile chunks must split evenly over the threads"); + uint2 q[n]; + half d[n]; +}; + +template +static __device__ __forceinline__ void fattn_banded_mma_issue_tile_q( + fattn_banded_mma_qregs & r, const char * __restrict__ src, const uint64_t nb1, const int64_t kv0, const int64_t n_kv) { + static_assert(type_kv == GGML_TYPE_Q8_0 || type_kv == GGML_TYPE_Q4_0, "unsupported banded K/V tile type"); + constexpr int chunks = D/8; + constexpr int nthreads = NW*WARP_SIZE; +#pragma unroll + for (int i = 0; i < fattn_banded_mma_qregs::n; ++i) { + const int c = i*nthreads + threadIdx.x; + const int row = c / chunks; + const int col = (c % chunks)*8; + r.q[i] = make_uint2(0, 0); + r.d[i] = __float2half(0.0f); + if (kv0 + row < n_kv) { + const char * s = src + uint64_t(kv0 + row)*nb1; + // the quants of a block start 2 bytes in: 16-bit loads + const uint16_t * q16; + if constexpr (type_kv == GGML_TYPE_Q8_0) { + const block_q8_0 * b = (const block_q8_0 *) s + col/QK8_0; + r.d[i] = b->d; + q16 = (const uint16_t *) (b->qs + col % QK8_0); + } else { + const block_q4_0 * b = (const block_q4_0 *) s + col/QK4_0; + r.d[i] = b->d; + q16 = (const uint16_t *) (b->qs + (col % QK4_0) % (QK4_0/2)); + } + r.q[i].x = q16[0] | ((uint32_t) q16[1] << 16); + r.q[i].y = q16[2] | ((uint32_t) q16[3] << 16); + } + } +} + +template +static __device__ __forceinline__ void fattn_banded_mma_store_tile_q(half * __restrict__ tile, const fattn_banded_mma_qregs & r) { + constexpr int stride = D + 8; + constexpr int chunks = D/8; + constexpr int nthreads = NW*WARP_SIZE; + // a quant u in [0, 255] as the half 1024 + u (exponent byte 0x64), minus 1152 (q8_0, u = q + 128) or 1032 (q4_0, u = q + 8), is exact. + // q*d is exact in F32, so one half multiply rounds it as the F32 product rounded to half does. + const half2 off = __float2half2_rn(type_kv == GGML_TYPE_Q8_0 ? 1152.0f : 1032.0f); +#pragma unroll + for (int i = 0; i < fattn_banded_mma_qregs::n; ++i) { + const int c = i*nthreads + threadIdx.x; + const int row = c / chunks; + const int col = (c % chunks)*8; + const half2 d2 = __half2half2(r.d[i]); + const uint32_t w[2] = { r.q[i].x, r.q[i].y }; + half2 h[4]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + uint32_t u; + if constexpr (type_kv == GGML_TYPE_Q8_0) { + u = w[k] ^ 0x80808080u; + } else { + u = (w[k] >> (col % QK4_0 < QK4_0/2 ? 0 : 4)) & 0x0F0F0F0Fu; + } + const uint32_t lo = __byte_perm(u, 0x64646464u, 0x4140); + const uint32_t hi = __byte_perm(u, 0x64646464u, 0x4342); + h[2*k + 0] = __hmul2(__hsub2(*(const half2 *) &lo, off), d2); + h[2*k + 1] = __hmul2(__hsub2(*(const half2 *) &hi, off), d2); + } + *(int4 *) (tile + row*stride + col) = *(const int4 *) h; + } +} + template static __device__ __forceinline__ void fattn_banded_mma_load_tile( half * __restrict__ tile, const char * __restrict__ src, const uint64_t nb1, const int64_t kv0, const int64_t n_kv) { @@ -1396,6 +1473,13 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt*BK, n_kv); fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt*BK, n_kv); } + // quantized K/V: the tiles after the first are loaded into registers one step ahead (see fattn_banded_mma_issue_tile_q) + fattn_banded_mma_qregs kq; + fattn_banded_mma_qregs vq; + bool v_pending = false; + GGML_UNUSED(kq); + GGML_UNUSED(vq); + GGML_UNUSED(v_pending); while (kt < kt_end) { const int64_t kv0 = kt*BK; @@ -1495,9 +1579,19 @@ static __global__ void flash_attn_ext_banded_mma( O[n][3] *= alpha[1]; } + if constexpr (type_kv != GGML_TYPE_F16) { + // the V tile of this iteration, loaded during the QK MMAs; the PV MMAs of the previous one are done (barrier after them) + if (v_pending) { + fattn_banded_mma_store_tile_q(V_s, vq); + } + } __syncthreads(); const int64_t kt_next = next_tile(kt + 1); - if (kt_next < kt_end) { + if constexpr (type_kv != GGML_TYPE_F16) { + if (kt_next < kt_end) { + fattn_banded_mma_issue_tile_q(kq, k_base, k_nb1, kt_next*BK, n_kv); + } + } else if (kt_next < kt_end) { fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt_next*BK, n_kv); fattn_banded_mma_wait<1>(); // V tile of this iteration landed } else { @@ -1517,8 +1611,19 @@ static __global__ void flash_attn_ext_banded_mma( } } + if constexpr (type_kv != GGML_TYPE_F16) { + // the next K tile, loaded during the PV MMAs (which read only V_s; every warp left the QK MMAs before the barrier above) + if (kt_next < kt_end) { + fattn_banded_mma_store_tile_q(K_s, kq); + } + } __syncthreads(); - if (kt_next < kt_end) { + if constexpr (type_kv != GGML_TYPE_F16) { + v_pending = kt_next < kt_end; + if (v_pending) { + fattn_banded_mma_issue_tile_q(vq, v_base, v_nb1, kt_next*BK, n_kv); + } + } else if (kt_next < kt_end) { fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt_next*BK, n_kv); } kt = kt_next; From 4c4e10487b64065ccf1e4d65c028d8ed6484ab3c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 20:47:47 -0800 Subject: [PATCH 097/115] CUDA: banded MMA attention: dequantize the next K/V tile between the MMAs The quantized K and V tiles loaded one step ahead were dequantized into shared memory in one block right before a barrier (V after the QK products and the softmax, K after the PV products). The chunks are now written over the second half of the QK loop (V) and of the PV loop (K), so the dequantization issues between the MMAs. Same values bit for bit. --- ggml/src/ggml-cuda/fattn-banded.cu | 80 +++++++++++++++++------------- 1 file changed, 46 insertions(+), 34 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 1c585eba6cf7..88ea7a8fd2e8 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1190,7 +1190,7 @@ static __device__ __forceinline__ void fattn_banded_mma_load_tile_q( } // The quantized tiles of the main loop in two steps, so that the global loads overlap the MMAs as cp.async does for F16: -// fattn_banded_mma_issue_tile_q only loads the quants and scales of this thread's chunks into registers, fattn_banded_mma_store_tile_q later +// fattn_banded_mma_issue_tile_q only loads the quants and scales of this thread's chunks into registers, fattn_banded_mma_store_chunk_q later // dequantizes them into the F16 tile with the values fattn_banded_mma_load_tile_q gives, bit for bit. // Rows past n_kv get zero quants and a zero scale, which store as +0 like the zero fill of the one-step load. template @@ -1233,36 +1233,47 @@ static __device__ __forceinline__ void fattn_banded_mma_issue_tile_q( } } +// chunk i of this thread's part of the tile template -static __device__ __forceinline__ void fattn_banded_mma_store_tile_q(half * __restrict__ tile, const fattn_banded_mma_qregs & r) { +static __device__ __forceinline__ void fattn_banded_mma_store_chunk_q(half * __restrict__ tile, const fattn_banded_mma_qregs & r, const int i) { constexpr int stride = D + 8; constexpr int chunks = D/8; constexpr int nthreads = NW*WARP_SIZE; // a quant u in [0, 255] as the half 1024 + u (exponent byte 0x64), minus 1152 (q8_0, u = q + 128) or 1032 (q4_0, u = q + 8), is exact. // q*d is exact in F32, so one half multiply rounds it as the F32 product rounded to half does. const half2 off = __float2half2_rn(type_kv == GGML_TYPE_Q8_0 ? 1152.0f : 1032.0f); + const int c = i*nthreads + threadIdx.x; + const int row = c / chunks; + const int col = (c % chunks)*8; + const half2 d2 = __half2half2(r.d[i]); + const uint32_t w[2] = { r.q[i].x, r.q[i].y }; + half2 h[4]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + uint32_t u; + if constexpr (type_kv == GGML_TYPE_Q8_0) { + u = w[k] ^ 0x80808080u; + } else { + u = (w[k] >> (col % QK4_0 < QK4_0/2 ? 0 : 4)) & 0x0F0F0F0Fu; + } + const uint32_t lo = __byte_perm(u, 0x64646464u, 0x4140); + const uint32_t hi = __byte_perm(u, 0x64646464u, 0x4342); + h[2*k + 0] = __hmul2(__hsub2(*(const half2 *) &lo, off), d2); + h[2*k + 1] = __hmul2(__hsub2(*(const half2 *) &hi, off), d2); + } + *(int4 *) (tile + row*stride + col) = *(const int4 *) h; +} + +// the chunks of step `step` of n_steps (step is a constant once the calling loop is unrolled): spreading the dequantization over the +// iterations of an MMA loop lets it issue between the MMAs instead of in front of the next barrier +template +static __device__ __forceinline__ void fattn_banded_mma_store_tile_q_step(half * __restrict__ tile, const fattn_banded_mma_qregs & r, const int step) { + constexpr int n = fattn_banded_mma_qregs::n; #pragma unroll - for (int i = 0; i < fattn_banded_mma_qregs::n; ++i) { - const int c = i*nthreads + threadIdx.x; - const int row = c / chunks; - const int col = (c % chunks)*8; - const half2 d2 = __half2half2(r.d[i]); - const uint32_t w[2] = { r.q[i].x, r.q[i].y }; - half2 h[4]; -#pragma unroll - for (int k = 0; k < 2; ++k) { - uint32_t u; - if constexpr (type_kv == GGML_TYPE_Q8_0) { - u = w[k] ^ 0x80808080u; - } else { - u = (w[k] >> (col % QK4_0 < QK4_0/2 ? 0 : 4)) & 0x0F0F0F0Fu; - } - const uint32_t lo = __byte_perm(u, 0x64646464u, 0x4140); - const uint32_t hi = __byte_perm(u, 0x64646464u, 0x4342); - h[2*k + 0] = __hmul2(__hsub2(*(const half2 *) &lo, off), d2); - h[2*k + 1] = __hmul2(__hsub2(*(const half2 *) &hi, off), d2); + for (int i = 0; i < n; ++i) { + if (i*n_steps/n == step) { + fattn_banded_mma_store_chunk_q(tile, r, i); } - *(int4 *) (tile + row*stride + col) = *(const int4 *) h; } } @@ -1506,6 +1517,13 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_16816(S[j + 0], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[0], b[1]); fattn_banded_mma_16816(S[j + 1], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[2], b[3]); } + if constexpr (type_kv != GGML_TYPE_F16) { + // the V tile of this iteration (V_s is free: the PV MMAs of the previous one ended before the barrier above), over + // the second half of the QK MMAs so that its loads, issued after the previous PV MMAs, have landed + if (v_pending && kk >= NK/2) { + fattn_banded_mma_store_tile_q_step(V_s, vq, kk - NK/2); + } + } } const int64_t dist_hi = iq_w + 15 + q_offset - kv0; @@ -1579,12 +1597,6 @@ static __global__ void flash_attn_ext_banded_mma( O[n][3] *= alpha[1]; } - if constexpr (type_kv != GGML_TYPE_F16) { - // the V tile of this iteration, loaded during the QK MMAs; the PV MMAs of the previous one are done (barrier after them) - if (v_pending) { - fattn_banded_mma_store_tile_q(V_s, vq); - } - } __syncthreads(); const int64_t kt_next = next_tile(kt + 1); if constexpr (type_kv != GGML_TYPE_F16) { @@ -1609,12 +1621,12 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_16816(O[n + 0], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[0], b[1]); fattn_banded_mma_16816(O[n + 1], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[2], b[3]); } - } - - if constexpr (type_kv != GGML_TYPE_F16) { - // the next K tile, loaded during the PV MMAs (which read only V_s; every warp left the QK MMAs before the barrier above) - if (kt_next < kt_end) { - fattn_banded_mma_store_tile_q(K_s, kq); + if constexpr (type_kv != GGML_TYPE_F16) { + // the next K tile (K_s is free: every warp left the QK MMAs before the barrier above), over the second half of the PV + // MMAs so that its loads, issued before them, have landed + if (kt_next < kt_end && s >= (BK/16)/2) { + fattn_banded_mma_store_tile_q_step(K_s, kq, s - (BK/16)/2); + } } } __syncthreads(); From 8686ca7e287cd4cc4a1ba622c46eb4016ab5df48 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 21:50:06 -0800 Subject: [PATCH 098/115] CUDA: banded MMA attention: load quantized K/V tiles ahead only at head size 128 At head size 64 the registers for the tile loaded one step ahead cost more than the overlap gains: on B200 at a batch of 512 queries with sinks, q8_0 K/V took 16% longer with the tiles loaded ahead and 11% longer with the interleaved dequantization than with the one-step load, from 166 to about 200 registers per thread for four warps. Head size 64 keeps the one-step load; head size 128 is unchanged. --- ggml/src/ggml-cuda/fattn-banded.cu | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 88ea7a8fd2e8..e82a006db960 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1484,7 +1484,9 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_load_tile(K_s, k_base, k_nb1, kt*BK, n_kv); fattn_banded_mma_load_tile(V_s, v_base, v_nb1, kt*BK, n_kv); } - // quantized K/V: the tiles after the first are loaded into registers one step ahead (see fattn_banded_mma_issue_tile_q) + // quantized K/V: the tiles after the first are loaded into registers one step ahead (see fattn_banded_mma_issue_tile_q). + // Head size 128 only: at 64 the extra registers cost more than the overlap gains (B200, prefill batch), so it keeps the one-step load. + constexpr bool q_ahead = type_kv != GGML_TYPE_F16 && D >= 128; fattn_banded_mma_qregs kq; fattn_banded_mma_qregs vq; bool v_pending = false; @@ -1517,7 +1519,7 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_16816(S[j + 0], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[0], b[1]); fattn_banded_mma_16816(S[j + 1], Q_a[kk][0], Q_a[kk][1], Q_a[kk][2], Q_a[kk][3], b[2], b[3]); } - if constexpr (type_kv != GGML_TYPE_F16) { + if constexpr (q_ahead) { // the V tile of this iteration (V_s is free: the PV MMAs of the previous one ended before the barrier above), over // the second half of the QK MMAs so that its loads, issued after the previous PV MMAs, have landed if (v_pending && kk >= NK/2) { @@ -1599,7 +1601,7 @@ static __global__ void flash_attn_ext_banded_mma( __syncthreads(); const int64_t kt_next = next_tile(kt + 1); - if constexpr (type_kv != GGML_TYPE_F16) { + if constexpr (q_ahead) { if (kt_next < kt_end) { fattn_banded_mma_issue_tile_q(kq, k_base, k_nb1, kt_next*BK, n_kv); } @@ -1621,7 +1623,7 @@ static __global__ void flash_attn_ext_banded_mma( fattn_banded_mma_16816(O[n + 0], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[0], b[1]); fattn_banded_mma_16816(O[n + 1], P_a[2*s][0], P_a[2*s][1], P_a[2*s + 1][0], P_a[2*s + 1][1], b[2], b[3]); } - if constexpr (type_kv != GGML_TYPE_F16) { + if constexpr (q_ahead) { // the next K tile (K_s is free: every warp left the QK MMAs before the barrier above), over the second half of the PV // MMAs so that its loads, issued before them, have landed if (kt_next < kt_end && s >= (BK/16)/2) { @@ -1630,7 +1632,7 @@ static __global__ void flash_attn_ext_banded_mma( } } __syncthreads(); - if constexpr (type_kv != GGML_TYPE_F16) { + if constexpr (q_ahead) { v_pending = kt_next < kt_end; if (v_pending) { fattn_banded_mma_issue_tile_q(vq, v_base, v_nb1, kt_next*BK, n_kv); From 11830fe1b24a913212d5ac91529d6198a6feef77 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 22:45:17 -0800 Subject: [PATCH 099/115] CUDA: banded attention: refuse causal ops the kernels cannot run, skip future tiles The causal attention without a mask runs in the decode, MMA or split kernel, and the split kernel puts the queries of all streams on grid z: supports_op now refuses a causal op with more than 65535 of them instead of aborting in the launch. With cell distances the MMA kernel stops at the last tile the last query of a block can see, since every later tile is masked whole. The tail rows of a q4_0 tile loaded ahead store +0 like the one-step load (zero nibbles are 8). --- ggml/src/ggml-cuda/fattn-banded.cu | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index e82a006db960..9901ab7a3c27 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1212,7 +1212,8 @@ static __device__ __forceinline__ void fattn_banded_mma_issue_tile_q( const int c = i*nthreads + threadIdx.x; const int row = c / chunks; const int col = (c % chunks)*8; - r.q[i] = make_uint2(0, 0); + // zero quants (byte 0 for q8_0, nibble 8 for q4_0) and a zero scale store +0, as the one-step load does + r.q[i] = type_kv == GGML_TYPE_Q8_0 ? make_uint2(0u, 0u) : make_uint2(0x88888888u, 0x88888888u); r.d[i] = __float2half(0.0f); if (kv0 + row < n_kv) { const char * s = src + uint64_t(kv0 + row)*nb1; @@ -1427,12 +1428,19 @@ static __global__ void flash_attn_ext_banded_mma( const int64_t n_kt = (n_kv + BK - 1)/BK; const int64_t kt_begin = ic*tiles_per_chunk; - const int64_t kt_end = kt_begin + tiles_per_chunk < n_kt ? kt_begin + tiles_per_chunk : n_kt; + int64_t kt_end = kt_begin + tiles_per_chunk < n_kt ? kt_begin + tiles_per_chunk : n_kt; const int64_t iq_w = qt*BQ + warp*16; const int64_t iq_r[2] = {iq_w + g, iq_w + g + 8}; const int64_t q_offset = n_kv - n_q; + // causal without a mask and with cell distances: the tiles after the last cell the last query of this block sees + // are masked whole, skip them (with positions the cells are not in order) + if (causal && !k_pos) { + const int64_t last = ((qt + 1)*BQ < n_q ? (qt + 1)*BQ : n_q) - 1 + q_offset; + kt_end = last < 0 ? kt_begin : (last/BK + 1 < kt_end ? last/BK + 1 : kt_end); + } + const char * k_base = k + uint64_t(ih_kv)*k_nb2 + uint64_t(ib)*k_nb3; const char * v_base = v + uint64_t(ih_kv)*v_nb2 + uint64_t(ib)*v_nb3; const char * m_base = mask ? mask + uint64_t(ih % mask_ne2)*m_nb2 + uint64_t(ib % mask_ne3)*m_nb3 : nullptr; @@ -1721,6 +1729,12 @@ bool ggml_cuda_flash_attn_ext_banded_supported(int device, const ggml_tensor * d return false; } + // the causal attention without a mask runs in the decode, MMA or split kernel; the split kernel puts the queries of + // all streams on grid z (at most 65535), so larger ubatches are left to another backend rather than abort + if (ggml_flash_attn_ext_banded_is_causal(dst) && dst->src[0] && dst->src[0]->ne[1]*dst->src[0]->ne[3] > 65535) { + return false; + } + // quantized K/V are read as F16: check the op with F16 K/V of the same shape if (dst->src[1] && dst->src[2] && (fattn_banded_kv_f16_convertible(dst->src[1]->type) || fattn_banded_kv_f16_convertible(dst->src[2]->type))) { From 7fd34f558b0d647b527fa5bf3f9e88a641581a24 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 22:45:28 -0800 Subject: [PATCH 100/115] inkling2 : causal banded attention: positions for padded spans, cell 0 start without them A padded span of 2 to 32 tokens (drafts, prompt tails) of the full-attention cache measured its distances from the padded tail and needed the n_kv x n_tokens mask, which the causal reserve graph does not hold, so such a span over a long cache grew the compute buffers at run time (pinned host compute 11.5 to 13.5 MiB with a 30-token prompt tail over 256K cells; the mask grows with the cache). When the causal attention applies (one sequence, CUDA or CPU layers) such spans now take the cell positions and need no mask. Without the positions the causal path takes cell distances, which hide nothing before the sequence: it is now used only when the sequence starts at cell 0, otherwise the mask hides the cells before it. --- src/models/inkling2.cpp | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index e4b20baaf185..8fe17a5d6a24 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -419,6 +419,25 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { inp->n_kv_banded[1] = 0; } } + // the causal attention without a mask (below) runs on the CUDA and CPU kernels only + bool causal_devs = true; + for (uint32_t il = 0; il < hparams.n_layer() && causal_devs; ++il) { + if (hparams.is_swa(il)) { + continue; + } + ggml_backend_dev_t dev = model.dev_layer(il); + const char * reg = dev ? ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)) : ""; + causal_devs = strcmp(reg, "CUDA") == 0 || strcmp(reg, "CPU") == 0; + } + const bool causal_ok = inp->banded && cparams.n_seq_max == 1 && cparams.causal_attn && n_tokens <= 65535 && + causal_devs && inkling2_banded_causal_enabled(); + // a padded span of 2 or more tokens (drafts, prompt tails) of the full-attention cache takes the positions when the + // causal attention applies: it then needs neither the shift table nor the n_kv x n_tokens mask, which the reserve graph + // (a full ubatch, causal) does not hold, so the first such span would grow the compute buffers + if (causal_ok && inp->banded_pad && n_tokens > 1 && inp->banded_pos != 0 && inp->n_kv_banded[0] > 0 && !inp->self_k_pos[0]) { + inp->n_kv_banded[0] = base->get_n_kv(); + k_pos(0); + } // the band of a padded span is shifted by the padding; with the positions the distances need no shift for (int i = 0; i < 2 && inp->banded_pad; ++i) { if (inp->n_kv_banded[i] > 0 && !inp->self_k_pos[i]) { @@ -431,10 +450,13 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { // a cache of one sequence: a cell is visible iff its distance to the query is not negative (empty cells have no // position), so the full-attention layers need no mask, an n_kv x n_tokens F16 input (1 GiB at 1M cells and 512 - // tokens, on the host and on the device); padded spans without the positions measure the distance from the padded - // tail, they keep it - banded_causal = inp->banded && cparams.n_seq_max == 1 && cparams.causal_attn && inp->n_kv_banded[0] > 0 && n_tokens <= 65535 && - (inp->self_k_pos[0] || !inp->banded_pad) && inkling2_banded_causal_enabled(); + // tokens, on the host and on the device). Without the positions the distance is a cell difference, which hides + // nothing before the sequence: it must start at cell 0 (n_kv_banded is then pos_max + 1, the cells before a later + // start are masked by the mask path); padded spans without the positions measure the distance from the padded tail + // and keep the mask + banded_causal = causal_ok && inp->n_kv_banded[0] > 0 && + (inp->self_k_pos[0] || (!inp->banded_pad && ubatch.pos != nullptr && + inp->n_kv_banded[0] == (uint32_t) ubatch.pos[n_tokens - 1] + 1)); ggml_tensor * inp_pos = build_inp_pos(); // the query positions of the banded attention From 7280c5e26b9c37acda40b73a323df5940db7bc2c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 24 Nov 2026 22:45:18 -0800 Subject: [PATCH 101/115] tests : causal banded attention over cell positions, and against an explicit mask New FLASH_ATTN_EXT_BANDED cases run the causal attention without a mask over cell positions (one sequence with empty cells, a gap of positions and cells of later positions) in the decode, MMA and split kernels. test-flash-attn-banded-causal builds the same op with an explicit causal mask and with set_causal and checks they agree on every backend, with cell distances and with positions, and that a backend refuses a causal op it cannot run. --- tests/CMakeLists.txt | 1 + tests/test-backend-ops.cpp | 82 ++++++++ tests/test-flash-attn-banded-causal.cpp | 255 ++++++++++++++++++++++++ 3 files changed, 338 insertions(+) create mode 100644 tests/test-flash-attn-banded-causal.cpp diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4e307e5646b3..28f56b9f4cfb 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -385,6 +385,7 @@ llama_build_and_test(test-tiled-mulmat.cpp LABEL "main behavior backend" LINK llama_build_and_test(test-model-load-cancel.cpp LABEL "model behavior") llama_build_and_test(test-autorelease.cpp LABEL "model behavior") llama_build_and_test(test-backend-sampler.cpp LABEL "model behavior backend") +llama_build_and_test(test-flash-attn-banded-causal.cpp LINK ggml) if (APPLE) llama_build(test-rset-release.cpp) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a1672163b3a2..49aeaf82eac8 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -11532,6 +11532,76 @@ struct test_flash_attn_ext_banded_causal : public test_flash_attn_ext_banded_sin } }; +// the causal attention without a mask over cell positions (a cache of one sequence: padded spans, decode-banded steps, +// the reserve graph): a cell is visible iff its position is not -1 and not after the query's. One sequence with a few +// empty cells, a gap of positions, empty cells after the queries and two cells of later positions +struct test_flash_attn_ext_banded_causal_pos : public test_flash_attn_ext_banded_pos { + test_flash_attn_ext_banded_causal_pos(int64_t d, int64_t n_head, int64_t n_head_kv, int64_t n_q, int64_t n_kv, int64_t rel_extent, + ggml_type kv_type) + : test_flash_attn_ext_banded_pos(d, n_head, n_head_kv, n_q, n_kv, rel_extent, 3, 1, 0, kv_type, GGML_TYPE_F32) {} + + std::string vars() override { + return test_flash_attn_ext_banded_pos::vars() + ",causal=1"; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, d, n_q, n_head, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx, kv_type, d, n_kv, n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx, v_type, d, n_kv, n_head_kv, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx, rel_type, rel_extent, n_head, n_q, 1); + ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, n_q); + ggml_tensor * kp = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_kv); + ggml_tensor * qp = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_q); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + ggml_set_name(r, "rel_logits"); + ggml_set_name(s, "sinks"); + ggml_set_name(kp, "k_pos"); + ggml_set_name(qp, "q_pos"); + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, nullptr, r, 1.0f/float(d), rel_extent); + ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_banded_set_pos(out, kp, qp); + ggml_flash_attn_ext_banded_set_causal(out, true); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + // the queries are cells [q0, q0 + n_q); cell j < q0 + n_q holds position j, plus 9 from n_kv/2 on (a gap), every + // 13th cell before the queries is empty; after the queries two cells of later positions, then empty cells + const int64_t q0 = n_kv - n_q - 4; + std::vector k_pos(n_kv, -1); + std::vector q_pos(n_q); + auto pos_of = [&](int64_t j) { return int32_t(j + (j >= n_kv/2 ? 9 : 0)); }; + for (int64_t j = 0; j < q0 + n_q; ++j) { + if (j % 13 != 7 || j >= q0) { + k_pos[j] = pos_of(j); + } + } + k_pos[q0 + n_q + 0] = pos_of(q0 + n_q) + 3; + k_pos[q0 + n_q + 1] = pos_of(q0 + n_q) + 4; + for (int64_t i = 0; i < n_q; ++i) { + q_pos[i] = pos_of(q0 + i); + } + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "k_pos") == 0) { + ggml_backend_tensor_set(t, k_pos.data(), 0, k_pos.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "q_pos") == 0) { + ggml_backend_tensor_set(t, q_pos.data(), 0, q_pos.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "rel_logits") == 0) { + init_tensor_uniform(t, -1.0f, 1.0f); + } else if (strcmp(t->name, "sinks") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else { + init_tensor_uniform(t, -0.25f, 0.25f); + } + } + } +}; + static std::vector> make_test_cases_eval() { std::vector> test_cases; std::default_random_engine rng(0); @@ -14390,6 +14460,18 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded_causal(128, 8, 1, 511, 16403, 1024, kv_type, 2)); test_cases.emplace_back(new test_flash_attn_ext_banded_causal(128, 8, 2, 65, 333, 32, kv_type, 2, true)); } + // causal without a mask over cell positions: decode (vec), MMA and split shapes + for (ggml_type kv_type : { GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0 }) { + for (int64_t n_q : { 1, 17, 512 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_causal_pos(128, 24, 8, n_q, n_q == 512 ? 2048 : 1000, 1280, kv_type)); + } + test_cases.emplace_back(new test_flash_attn_ext_banded_causal_pos(64, 8, 2, 17, 700, 64, kv_type)); + } + // K/V the MMA kernel does not read take the split kernel + for (ggml_type kv_type : { GGML_TYPE_F32, GGML_TYPE_Q5_1 }) { + test_cases.emplace_back(new test_flash_attn_ext_banded_causal_pos(128, 24, 8, 17, 1000, 1280, kv_type)); + test_cases.emplace_back(new test_flash_attn_ext_banded_causal_pos(128, 24, 8, 300, 1000, 1280, kv_type)); + } // Inkling-2-Small shapes for (int64_t n_q : { 1, 3, 8, 512 }) { diff --git a/tests/test-flash-attn-banded-causal.cpp b/tests/test-flash-attn-banded-causal.cpp new file mode 100644 index 000000000000..ede964635f5c --- /dev/null +++ b/tests/test-flash-attn-banded-causal.cpp @@ -0,0 +1,255 @@ +// ggml_flash_attn_ext_banded_set_causal against an explicit causal mask: the same op, inputs and backend, once with an +// F16 mask that hides the cells after each query (and the empty cells) and once with no mask and the causal flag. +// The two must agree on every backend that runs the causal op, with cell distances and with cell positions. +// Also checks that a backend refuses a causal op it cannot run instead of aborting. + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include +#include +#include + +struct causal_config { + int64_t d; + int64_t n_head; + int64_t n_head_kv; + int64_t n_q; + int64_t n_kv; + int64_t extent; + ggml_type kv_type; + bool sinks; + bool positions; // cell positions with empty cells and a gap; else the cells are the positions, queries at the tail +}; + +struct causal_data { + std::vector q, k, v, rel, sinks; + std::vector k_pos, q_pos; +}; + +static causal_data make_data(const causal_config & c, uint32_t seed) { + std::mt19937 rng(seed); + std::uniform_real_distribution u(-0.25f, 0.25f); + std::uniform_real_distribution ur(-1.0f, 1.0f); + std::uniform_real_distribution us(-4.0f, 4.0f); + causal_data data; + data.q.resize(c.d*c.n_q*c.n_head); + data.k.resize(c.d*c.n_kv*c.n_head_kv); + data.v.resize(c.d*c.n_kv*c.n_head_kv); + data.rel.resize(c.extent*c.n_head*c.n_q); + data.sinks.resize(c.n_head*c.n_q); + for (auto & x : data.q) { x = u(rng); } + for (auto & x : data.k) { x = u(rng); } + for (auto & x : data.v) { x = u(rng); } + for (auto & x : data.rel) { x = ur(rng); } + for (auto & x : data.sinks) { x = us(rng); } + + data.k_pos.assign(c.n_kv, -1); + data.q_pos.resize(c.n_q); + if (c.positions) { + // as the causal test-backend-ops case: queries at cells [q0, q0 + n_q), a gap of 9 positions from n_kv/2 on, + // every 13th cell before the queries empty, two cells of later positions after them, then empty cells + const int64_t q0 = c.n_kv - c.n_q - 4; + auto pos_of = [&](int64_t j) { return int32_t(j + (j >= c.n_kv/2 ? 9 : 0)); }; + for (int64_t j = 0; j < q0 + c.n_q; ++j) { + if (j % 13 != 7 || j >= q0) { + data.k_pos[j] = pos_of(j); + } + } + data.k_pos[q0 + c.n_q + 0] = pos_of(q0 + c.n_q) + 3; + data.k_pos[q0 + c.n_q + 1] = pos_of(q0 + c.n_q) + 4; + for (int64_t i = 0; i < c.n_q; ++i) { + data.q_pos[i] = pos_of(q0 + i); + } + } else { + // the cells are the positions, the queries the last n_q + for (int64_t j = 0; j < c.n_kv; ++j) { + data.k_pos[j] = int32_t(j); + } + for (int64_t i = 0; i < c.n_q; ++i) { + data.q_pos[i] = int32_t(c.n_kv - c.n_q + i); + } + } + return data; +} + +static void set_typed(ggml_tensor * t, const std::vector & src) { + if (t->type == GGML_TYPE_F32) { + ggml_backend_tensor_set(t, src.data(), 0, src.size()*sizeof(float)); + return; + } + const int64_t n_per_row = t->ne[0]; + const int64_t nrows = (int64_t) src.size()/n_per_row; + std::vector buf(ggml_row_size(t->type, n_per_row)*nrows); + if (t->type == GGML_TYPE_F16) { + ggml_fp32_to_fp16_row(src.data(), (ggml_fp16_t *) buf.data(), (int64_t) src.size()); + } else { + ggml_quantize_chunk(t->type, src.data(), buf.data(), 0, nrows, n_per_row, nullptr); + } + ggml_backend_tensor_set(t, buf.data(), 0, buf.size()); +} + +// runs the op with the explicit mask (causal = false) or with the causal flag; returns false if the backend refuses it +static bool run(ggml_backend_t backend, const causal_config & c, const causal_data & data, bool causal, std::vector & out_data) { + ggml_init_params params = { 64*ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true }; + ggml_context_ptr ctx(ggml_init(params)); + + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.d, c.n_q, c.n_head, 1); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), c.kv_type, c.d, c.n_kv, c.n_head_kv, 1); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), c.kv_type, c.d, c.n_kv, c.n_head_kv, 1); + ggml_tensor * r = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, c.extent, c.n_head, c.n_q, 1); + ggml_tensor * m = causal ? nullptr : ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, c.n_kv, c.n_q, 1, 1); + ggml_tensor * s = c.sinks ? ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, c.n_head, c.n_q) : nullptr; + ggml_tensor * kp = c.positions ? ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, c.n_kv) : nullptr; + ggml_tensor * qp = c.positions ? ggml_new_tensor_1d(ctx.get(), GGML_TYPE_I32, c.n_q) : nullptr; + + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, m, r, 1.0f/float(c.d), c.extent); + if (s) { + ggml_flash_attn_ext_add_sinks(out, s); + } + if (kp) { + ggml_flash_attn_ext_banded_set_pos(out, kp, qp); + } + if (causal) { + ggml_flash_attn_ext_banded_set_causal(out, true); + } + ggml_prec_set_acc(out, GGML_PREC_F32); + + if (!ggml_backend_supports_op(backend, out)) { + return false; + } + + ggml_backend_buffer_ptr buf(ggml_backend_alloc_ctx_tensors(ctx.get(), backend)); + GGML_ASSERT(buf); + + ggml_backend_tensor_set(q, data.q.data(), 0, data.q.size()*sizeof(float)); + set_typed(k, data.k); + set_typed(v, data.v); + ggml_backend_tensor_set(r, data.rel.data(), 0, data.rel.size()*sizeof(float)); + if (s) { + ggml_backend_tensor_set(s, data.sinks.data(), 0, data.sinks.size()*sizeof(float)); + } + if (kp) { + ggml_backend_tensor_set(kp, data.k_pos.data(), 0, data.k_pos.size()*sizeof(int32_t)); + ggml_backend_tensor_set(qp, data.q_pos.data(), 0, data.q_pos.size()*sizeof(int32_t)); + } + if (m) { + // visible iff the cell has a position and it is not after the query's + std::vector mask(c.n_kv*c.n_q); + for (int64_t iq = 0; iq < c.n_q; ++iq) { + for (int64_t ik = 0; ik < c.n_kv; ++ik) { + const bool visible = data.k_pos[ik] >= 0 && data.k_pos[ik] <= data.q_pos[iq]; + mask[iq*c.n_kv + ik] = ggml_fp32_to_fp16(visible ? 0.0f : -INFINITY); + } + } + ggml_backend_tensor_set(m, mask.data(), 0, mask.size()*sizeof(ggml_fp16_t)); + } + + ggml_cgraph * graph = ggml_new_graph(ctx.get()); + ggml_build_forward_expand(graph, out); + GGML_ASSERT(ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS); + + out_data.resize(ggml_nelements(out)); + ggml_backend_tensor_get(out, out_data.data(), 0, out_data.size()*sizeof(float)); + return true; +} + +static double nmse(const std::vector & a, const std::vector & b) { + double num = 0.0, den = 0.0; + for (size_t i = 0; i < a.size(); ++i) { + if (!std::isfinite(a[i]) || !std::isfinite(b[i])) { + return INFINITY; + } + num += double(a[i] - b[i])*double(a[i] - b[i]); + den += double(b[i])*double(b[i]); + } + return den > 0.0 ? num/den : num; +} + +// a causal op whose queries exceed what the backend can run must be refused by supports_op, not abort in compute +static bool check_large_refused(ggml_backend_t backend, const char * name) { + ggml_init_params params = { 16*ggml_tensor_overhead(), nullptr, true }; + ggml_context_ptr ctx(ggml_init(params)); + const int64_t d = 128, n_head = 8, n_q = 300, n_seq = 219; // n_q*n_seq = 65700 > 65535 + ggml_tensor * q = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, d, n_q, n_head, n_seq); + ggml_tensor * k = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, d, 512, 2, n_seq); + ggml_tensor * v = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F16, d, 512, 2, n_seq); + ggml_tensor * r = ggml_new_tensor_4d(ctx.get(), GGML_TYPE_F32, 64, n_head, n_q, 1); + ggml_tensor * out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, nullptr, r, 0.125f, 64); + ggml_flash_attn_ext_banded_set_causal(out, true); + ggml_prec_set_acc(out, GGML_PREC_F32); + const bool supported = ggml_backend_supports_op(backend, out); + // the CPU kernel has no such limit; a GPU backend that cannot run it must say so + const bool ok = strcmp(name, "CPU") == 0 || !supported; + printf(" %-6s causal n_q %lld x %lld streams: supported %d -> %s\n", name, (long long) n_q, (long long) n_seq, supported, ok ? "ok" : "FAIL"); + return ok; +} + +int main() { + ggml_backend_load_all(); + + const std::vector configs = { + // d, heads, kv heads, n_q, n_kv, extent, K/V, sinks, positions + { 128, 24, 8, 1, 1000, 1280, GGML_TYPE_F16, true, false }, + { 128, 24, 8, 17, 1000, 1280, GGML_TYPE_F16, true, false }, + { 128, 24, 8, 512, 2048, 1280, GGML_TYPE_F16, true, false }, + { 128, 24, 8, 512, 2048, 1280, GGML_TYPE_Q8_0, true, false }, + { 128, 24, 8, 17, 1000, 1280, GGML_TYPE_Q4_0, true, false }, + { 64, 8, 2, 77, 1000, 8, GGML_TYPE_F16, false, false }, + { 128, 8, 2, 65, 333, 32, GGML_TYPE_F32, false, false }, + { 128, 24, 8, 1, 1000, 1280, GGML_TYPE_Q8_0, true, true }, + { 128, 24, 8, 17, 1000, 1280, GGML_TYPE_F16, true, true }, + { 128, 24, 8, 512, 2048, 1280, GGML_TYPE_Q8_0, true, true }, + { 128, 24, 8, 17, 1000, 1280, GGML_TYPE_Q4_0, true, true }, + { 128, 24, 8, 17, 1000, 1280, GGML_TYPE_F32, true, true }, + { 64, 8, 2, 17, 700, 64, GGML_TYPE_F16, false, true }, + }; + const double max_nmse = 1e-5; + + bool all_ok = true; + int n_run = 0; + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) { + continue; + } + ggml_backend_ptr backend(ggml_backend_dev_init(dev, nullptr)); + const char * name = ggml_backend_dev_name(dev); + printf("%s (%s)\n", name, ggml_backend_dev_description(dev)); + for (const auto & c : configs) { + const causal_data data = make_data(c, 1234); + std::vector masked, causal; + const bool ok_m = run(backend.get(), c, data, false, masked); + const bool ok_c = run(backend.get(), c, data, true, causal); + char desc[160]; + snprintf(desc, sizeof(desc), "d %lld n_q %lld n_kv %lld %s sinks %d pos %d", (long long) c.d, (long long) c.n_q, + (long long) c.n_kv, ggml_type_name(c.kv_type), c.sinks, c.positions); + if (!ok_c) { + printf(" %-60s causal not supported, skipped\n", desc); + continue; + } + if (!ok_m) { + printf(" %-60s masked not supported, skipped\n", desc); + continue; + } + const double err = nmse(causal, masked); + const bool ok = err <= max_nmse; + all_ok &= ok; + ++n_run; + printf(" %-60s nmse %.3e %s\n", desc, err, ok ? "ok" : "FAIL"); + } + all_ok &= check_large_refused(backend.get(), name); + } + if (n_run == 0) { + printf("no backend ran the causal op\n"); + return 1; + } + printf("%s\n", all_ok ? "OK" : "FAILED"); + return all_ok ? 0 : 1; +} From 97f7c624573ccd41bdff075dbe5d7ffe1e39145b Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 25 Nov 2026 16:09:03 -0800 Subject: [PATCH 102/115] metal : drop the unused mask local in the banded attention supports_op The mask layout check moved into a helper, which left this local unused. The macOS prebuilt builds with -Werror and stopped on -Wunused-variable. --- ggml/src/ggml-metal/ggml-metal-device.m | 1 - 1 file changed, 1 deletion(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index df0b35eb5a32..19556cce1532 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1875,7 +1875,6 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return has_simdgroup_mm; // TODO: over-restricted for vec-kernels case GGML_OP_FLASH_ATTN_EXT_BANDED: { - const struct ggml_tensor * mask = op->src[3]; const struct ggml_tensor * sinks = op->src[4]; const struct ggml_tensor * rel = op->src[6]; From 762ef4dc98a6a7a2b7abdba04f85a79c3f1200d7 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 26 Nov 2026 01:23:22 -0800 Subject: [PATCH 103/115] inkling2 : reuse the graph of a causal padded span A padded span of 2 to 32 tokens (drafts, prompt tails) takes the cell positions of the full-attention cache when the causal attention applies, but can_reuse() recomputed only the per-cache rule, which leaves those cells without the positions, so it saw a different graph every time: a DSpark verify step rebuilt the target graph every step (0 of 190 reused, about 8 ms of host time per step on B200). The graph build and can_reuse() now take the cells and the positions from one helper, so a graph is reused by the next span of the same shape and a different decision still rebuilds it. --- src/llama-graph.cpp | 53 +++++++++++++++++++++++++++++++++++++---- src/llama-graph.h | 10 ++++++-- src/models/inkling2.cpp | 42 +++++++------------------------- 3 files changed, 64 insertions(+), 41 deletions(-) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index d3954146b91f..43b10058c7e3 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1526,6 +1526,49 @@ uint32_t llm_graph_input_mem_hybrid_iswa_rel::get_n_kv_banded( return use_pos ? n_kv : 0; } +void llm_graph_input_mem_hybrid_iswa_rel::get_n_kv_banded(const llama_kv_cache_iswa_context * kv, + const llama_ubatch & ubatch, uint32_t (&n)[2], bool (&use_pos)[2]) const { + for (int i = 0; i < 2; ++i) { + n[i] = 0; + use_pos[i] = false; + } + if (!banded) { + return; + } + for (int i = 0; i < (banded_swa_dense ? 1 : 2); ++i) { + // without the positions a ubatch of several sequences is dense at runtime, so the reserved worst case + // (a ubatch of every sequence) is dense too, else the dense graph outgrows the reserved buffer + n[i] = get_n_kv_banded(i ? kv->get_swa() : kv->get_base(), ubatch, use_pos[i]); + } + const uint32_t n_tokens = ubatch.n_tokens; + // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), + // while at runtime it does so only for consecutive ones + if (n[0] > 0 && n_tokens > 1 && ubatch.pos[0] == ubatch.pos[n_tokens - 1]) { + if (banded_pos) { + // a gap, several sequences or a wrapped SWA cache take the positions at runtime: reserve that graph, + // it holds the contiguous one + for (int i = 0; i < 2; ++i) { + if (!use_pos[i]) { + n[i] = (i ? kv->get_swa() : kv->get_base())->get_n_kv(); + use_pos[i] = true; + } + } + } else { + // without the positions a cache whose cells are not the positions is dense: a wrapped SWA cache, + // a sequence that does not start at cell 0 + n[0] = 0; + n[1] = 0; + } + } + // a padded span of 2 or more tokens (drafts, prompt tails) of the full-attention cache takes the positions when the + // causal attention applies: it then needs neither the shift table nor the n_kv x n_tokens mask, which the reserve graph + // (a full ubatch, causal) does not hold, so the first such span would grow the compute buffers + if (banded_causal_ok && banded_pad && n_tokens > 1 && banded_pos != 0 && n[0] > 0 && !use_pos[0]) { + n[0] = kv->get_base()->get_n_kv(); + use_pos[0] = true; + } +} + bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { const auto * mctx = static_cast(params.mctx); @@ -1558,12 +1601,12 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; if (banded) { + uint32_t n[2]; + bool use_pos[2]; + get_n_kv_banded(attn_ctx, params.ubatch, n, use_pos); for (int i = 0; i < 2; ++i) { - bool use_pos = false; - const uint32_t n = i == 1 && banded_swa_dense ? 0 : - get_n_kv_banded(i ? attn_ctx->get_swa() : attn_ctx->get_base(), params.ubatch, use_pos); - res &= n == n_kv_banded[i]; - res &= use_pos == (self_k_pos[i] != nullptr); + res &= n[i] == n_kv_banded[i]; + res &= use_pos[i] == (self_k_pos[i] != nullptr); } } diff --git a/src/llama-graph.h b/src/llama-graph.h index e456ca1b18b6..a24d2538ea84 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -843,11 +843,17 @@ class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { // the banded attention may take the positions (1), else those ubatches are dense (0); 2 takes them for every // banded ubatch, also when the cells are the positions (a check: the result must not change) int banded_pos = 0; + // the graph may take the causal attention without a mask (one sequence, causal, CUDA or CPU layers) + bool banded_causal_ok = false; - // [base, swa] cells of the banded attention a graph built for this memory context and ubatch takes, - // and whether it takes the positions + // cells of the banded attention of one cache for this memory context and ubatch, and whether it takes the positions uint32_t get_n_kv_banded(const llama_kv_cache_context * kv, const llama_ubatch & ubatch, bool & use_pos) const; + // [base, swa] cells of the banded attention a graph built for this memory context and ubatch takes, and whether it + // takes the positions: the graph build and can_reuse() take the same decision + void get_n_kv_banded(const llama_kv_cache_iswa_context * kv, const llama_ubatch & ubatch, + uint32_t (&n)[2], bool (&use_pos)[2]) const; + const uint32_t extent; const uint32_t extent_swa; diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 8fe17a5d6a24..eafd833ae23c 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -391,34 +391,6 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { }; // that decode step keeps the small SWA view dense, in the reserve too inp->banded_swa_dense = decode_banded; - for (int i = 0; i < (decode_banded ? 1 : 2) && inp->banded; ++i) { - // without the positions a ubatch of several sequences is dense at runtime, so the reserved worst case - // (a ubatch of every sequence) is dense too, else the dense graph outgrows the reserved buffer - bool use_pos = false; - inp->n_kv_banded[i] = inp->get_n_kv_banded(i ? attn->mctx->get_swa() : base, ubatch, use_pos); - if (use_pos) { - k_pos(i); - } - } - // the reserve graph: the cache offers the banded path for a ubatch of placeholder positions (all 0), - // while at runtime it does so only for consecutive ones - if (inp->n_kv_banded[0] > 0 && n_tokens > 1 && ubatch.pos[0] == ubatch.pos[n_tokens - 1]) { - if (inp->banded_pos) { - // a gap, several sequences or a wrapped SWA cache take the positions at runtime: reserve that graph, - // it holds the contiguous one - for (int i = 0; i < 2; ++i) { - if (!inp->self_k_pos[i]) { - inp->n_kv_banded[i] = (i ? attn->mctx->get_swa() : base)->get_n_kv(); - k_pos(i); - } - } - } else { - // without the positions a cache whose cells are not the positions is dense: a wrapped SWA cache, - // a sequence that does not start at cell 0 - inp->n_kv_banded[0] = 0; - inp->n_kv_banded[1] = 0; - } - } // the causal attention without a mask (below) runs on the CUDA and CPU kernels only bool causal_devs = true; for (uint32_t il = 0; il < hparams.n_layer() && causal_devs; ++il) { @@ -431,12 +403,14 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { } const bool causal_ok = inp->banded && cparams.n_seq_max == 1 && cparams.causal_attn && n_tokens <= 65535 && causal_devs && inkling2_banded_causal_enabled(); - // a padded span of 2 or more tokens (drafts, prompt tails) of the full-attention cache takes the positions when the - // causal attention applies: it then needs neither the shift table nor the n_kv x n_tokens mask, which the reserve graph - // (a full ubatch, causal) does not hold, so the first such span would grow the compute buffers - if (causal_ok && inp->banded_pad && n_tokens > 1 && inp->banded_pos != 0 && inp->n_kv_banded[0] > 0 && !inp->self_k_pos[0]) { - inp->n_kv_banded[0] = base->get_n_kv(); - k_pos(0); + inp->banded_causal_ok = causal_ok; + // the cells of each cache and whether they take the positions, the decision can_reuse() repeats + bool use_pos[2]; + inp->get_n_kv_banded(attn->mctx, ubatch, inp->n_kv_banded, use_pos); + for (int i = 0; i < 2; ++i) { + if (use_pos[i]) { + k_pos(i); + } } // the band of a padded span is shifted by the padding; with the positions the distances need no shift for (int i = 0; i < 2 && inp->banded_pad; ++i) { From 710aed3cd2f372974eb75f8692bd3dd90ef7bef0 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 26 Nov 2026 06:16:45 -0800 Subject: [PATCH 104/115] CUDA: split the banded vec cells finer at a few queries A few queries give the banded vec kernel few blocks per KV head (Inkling 2: 8 KV heads x 2 row blocks at 3 queries), and chunks of at least 4 tiles kept the cells serial: a 3-token speculative verify spent 32 us per layer in it against 13 us for decode. Chunks now go down to one tile with a target of 2 blocks per SM. B200, 24 Q / 8 KV heads, F16 K/V: 2-2.6x at 256-1024 cells, 1.3x at 4096, prefill (512 queries) unchanged. --- ggml/src/ggml-cuda/fattn-banded.cu | 8 +++++--- tests/test-backend-ops.cpp | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-banded.cu b/ggml/src/ggml-cuda/fattn-banded.cu index 9901ab7a3c27..f03e36c091ba 100644 --- a/ggml/src/ggml-cuda/fattn-banded.cu +++ b/ggml/src/ggml-cuda/fattn-banded.cu @@ -1012,11 +1012,13 @@ static void fattn_banded_vec_launch(ggml_backend_cuda_context & ctx, ggml_tensor const int64_t n_rb = (n_q*G + NR - 1)/NR; // split the cells so that the grid fills the GPU + // chunks down to one tile: a few queries give few blocks per KV head, so the cells are what fills the GPU constexpr int64_t tile = fattn_banded_vec_threads/16*fattn_banded_vec_cpg; // D = 128 - constexpr int64_t min_chunk = 4*tile; + constexpr int64_t min_chunk = tile; const int64_t base_blocks = k->ne[2]*n_rb*q->ne[3]; - // one wave of resident blocks, 3 per SM - const int64_t target = int64_t(ggml_cuda_info().devices[ctx.device].nsm)*3; + // two blocks per SM: at 1-8 queries and 256-4096 cells this beats one wave of 3 per SM with 4-tile chunks + // (B200: 2-2.6x at 256-1024 cells, 1.3x at 4096) + const int64_t target = int64_t(ggml_cuda_info().devices[ctx.device].nsm)*2; int64_t n_chunks = std::max(1, std::min(target/base_blocks, (n_kv + min_chunk - 1)/min_chunk)); n_chunks = std::min(n_chunks, 4096); // merge weights in shared memory const int64_t chunk = GGML_PAD((n_kv + n_chunks - 1)/n_chunks, tile); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 99b1534326e8..bd79fdf37316 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14982,6 +14982,14 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 64, 64, 8, 2, GGML_TYPE_BF16, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 1, 64, 64, 512, 1, GGML_TYPE_F16, GGML_TYPE_F32)); test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 17, 33, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16, true)); + // Inkling 2 at a few tokens (a speculative verify batch): 24 Q heads on 8 KV heads, cells split one tile per block + for (int64_t n_q : {2, 3, 4, 8}) { + for (int64_t n_kv : {64, 256, 1088}) { + for (int mask_kind : {1, 3}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, n_kv, 1024, mask_kind, GGML_TYPE_F16, GGML_TYPE_F32, 1)); + } + } + } // a fully masked query is 0, also on the FA kernel the op delegates to without sinks for (int64_t n_kv : {64, 4096}) { test_cases.emplace_back(new test_flash_attn_ext_banded(128, 8, 2, 1, n_kv, 32, 4, GGML_TYPE_F16, GGML_TYPE_F32)); @@ -15530,6 +15538,13 @@ static std::vector> make_test_cases_eval() { static std::vector> make_test_cases_perf() { std::vector> test_cases; + // Inkling-2-Mini speculative verify (a few tokens): banded attention at small n_kv + for (int64_t n_kv : {256, 1024, 4096}) { + for (int64_t n_q : {1, 2, 3, 4, 8}) { + test_cases.emplace_back(new test_flash_attn_ext_banded_sinks(128, 24, 8, n_q, n_kv, 1024, 3, GGML_TYPE_F16, GGML_TYPE_F32, 1)); + } + } + // Inkling-2-Mini decode: banded over a padded n_kv vs flash attention with a dense bias mask { const char * env = std::getenv("GGML_TEST_BANDED_PERF_KV"); From e67909e253f62e5f4df92bc321a8465a709da656 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 26 Nov 2026 14:18:06 -0800 Subject: [PATCH 105/115] tests : run the padded F16 K layout cases on banded FA only (plain CUDA FA asserts on them since ggml-org#32901) --- tests/test-backend-ops.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index db241a32f8fa..ad966060de71 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -15038,14 +15038,17 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_banded( 64, 8, 2, 33, n_kv, 32, 4, GGML_TYPE_Q8_0, GGML_TYPE_F32)); } // layouts and masks backends may refuse: K/V rows padded off a 4-element boundary, a mask wider than K, and (banded) - // K/V head counts that differ. Left out: plain FA with padded F16/F16 rows, which CUDA FA reads in place and gets wrong + // K/V head counts that differ. Left out: plain FA with a padded F16 K or V, which CUDA FA reads in place: wrong for + // F16/F16, and an abort on rows off a 4-byte boundary since the FA loads take half2 strides (ggml-org#32901) // banded, d, nh, n_q, n_kv, type_k, type_v, hk, hv, pad, mask_cols for (int64_t n_q : { 1, 33 }) { test_cases.emplace_back(new test_flash_attn_ext_kv_layout(true, 128, 4, n_q, 64, GGML_TYPE_F16, GGML_TYPE_F16, 2, 2, 1, 64)); } for (bool banded : { false, true }) { - test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 1, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); - test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 33, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + if (banded) { + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 1, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 33, 64, GGML_TYPE_F16, GGML_TYPE_Q8_0, 2, 2, 1, 64)); + } test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 128)); test_cases.emplace_back(new test_flash_attn_ext_kv_layout(banded, 128, 4, 20, 64, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, 2, 2, 0, 64)); } From b71fd1ac06bbac30658fb414b589a23f811f6ceb Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 26 Nov 2026 16:40:52 -0800 Subject: [PATCH 106/115] Inkling 2: build the log-scaled positions at their first use, so they stay on the GPU --- src/models/inkling2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index f3746b6d0acf..64f7e4da8898 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -445,7 +445,8 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { 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); - ggml_build_forward_expand(gf, tau); + // not expanded here: as the first nodes of the graph, before any weight, the scheduler would run this chain on the + // CPU every ubatch (next to the CPU embedding lookup); expanded at the first full-attention layer it stays on the GPU ggml_tensor * cur = build_inp_embd(model.tok_embd); From 17826c8fe3cc0fd835c84f28e5444461d0409600 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 27 Nov 2026 01:20:31 -0800 Subject: [PATCH 107/115] ggml : accept the banded flash attention in the indexed-bias check, so its CPU and CUDA paths do not assert ggml-org#33063 asserts that the op is FLASH_ATTN_EXT in ggml_validate_flash_attn_ext_indexed_bias, which the CPU flash attention and the CUDA FA alloc size call. FLASH_ATTN_EXT_BANDED shares both paths and never carries an indexed bias, so Inkling (CUDA) and CPU-only Inkling 2 aborted at the first banded attention. --- ggml/src/ggml.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 4a560eb49685..0a7436e8ea1b 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5603,6 +5603,10 @@ bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { } bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a) { + // the banded op shares the FA paths and never carries an indexed bias + if (a->op == GGML_OP_FLASH_ATTN_EXT_BANDED) { + return true; + } GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); const struct ggml_tensor * table = a->src[6]; const struct ggml_tensor * indices = a->src[7]; From 731e35efb00d773f2f3ddfa4f621a2b16a4bcf09 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Fri, 27 Nov 2026 16:38:36 -0800 Subject: [PATCH 108/115] Inkling 2: keep 2 to 8 token ubatches on the dense attention with the indexed bias The FA tile kernel with the indexed relative bias is faster than the banded op plus its merge for few-token ubatches (speculative verify, prompt tails): +6..+18% pp2-pp8 up to d32768 and +29..+52% pp8 at d64K-d128K on a B200. 16 tokens lose from 64K cells, so larger ubatches stay banded. LLAMA_INKLING_DENSE_NMAX / LLAMA_INKLING_DENSE_KV_MAX override the limits. --- src/models/inkling2.cpp | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 64f7e4da8898..896dc52d7522 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -23,6 +23,28 @@ static bool inkling2_banded_causal_enabled() { return enabled; } +// ubatches of 2 to this many tokens over at most n_kv_dense_max cells take the dense attention with the indexed +// relative bias (one FA tile kernel), not the banded op and its merge. On a B200 the dense path is faster for 2 to 8 +// tokens up to 128K cells; 16 tokens lose from 64K cells. LLAMA_INKLING_DENSE_NMAX and LLAMA_INKLING_DENSE_KV_MAX +// override them (for sweeps; NMAX=1 restores the banded path for every ubatch of 2+ tokens) +static constexpr int64_t n_tokens_dense_max = 8; +static constexpr int64_t n_kv_dense_max = INT64_MAX; + +static int64_t inkling2_env_i64(const char * name, int64_t def) { + const char * env = getenv(name); + return env == nullptr ? def : std::max(0, atoll(env)); +} + +static int64_t inkling2_dense_n_max() { + static const int64_t v = inkling2_env_i64("LLAMA_INKLING_DENSE_NMAX", n_tokens_dense_max); + return v; +} + +static int64_t inkling2_dense_kv_max() { + static const int64_t v = inkling2_env_i64("LLAMA_INKLING_DENSE_KV_MAX", n_kv_dense_max); + return v; +} + static int inkling2_banded_pos_mode() { static const int mode = [] { const char * env = getenv("LLAMA_INKLING_BANDED_POS"); @@ -379,10 +401,16 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { const auto * base = attn->mctx->get_base(); const ggml_type tk = base->type_k(); const ggml_type tv = base->type_v(); - decode_banded = n_tokens == 1 && cparams.n_seq_max == 1 && (tk == tv ? + const bool kv_converted = tk == tv ? tk == GGML_TYPE_Q4_1 || tk == GGML_TYPE_Q5_0 || tk == GGML_TYPE_Q5_1 : - tk == GGML_TYPE_Q8_0 && (tv == GGML_TYPE_Q4_0 || tv == GGML_TYPE_F16)); - inp->banded = cparams.flash_attn && (n_tokens > 1 || decode_banded); + tk == GGML_TYPE_Q8_0 && (tv == GGML_TYPE_Q4_0 || tv == GGML_TYPE_F16); + decode_banded = n_tokens == 1 && cparams.n_seq_max == 1 && kv_converted; + // a few-token ubatch (speculative verify, prompt tails) over a short enough cache stays dense too: the FA tile + // kernel with the indexed bias beats the banded op plus its merge there. n_kv is part of can_reuse(), so a reused + // graph made the same choice + const bool small_dense = n_tokens > 1 && n_tokens <= inkling2_dense_n_max() && !kv_converted && + (int64_t) base->get_n_kv() <= inkling2_dense_kv_max(); + inp->banded = cparams.flash_attn && ((n_tokens > 1 && !small_dense) || decode_banded); inp->banded_pad = n_tokens <= n_tokens_banded_min; // the cells of several sequences, or of a wrapped cache, are not the positions: the banded attention then // takes the distances from the positions of the cells and the queries; disabled, those ubatches are dense From cd788402779d9c08ceac2e419896d18ef491313c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 28 Nov 2026 21:46:47 -0800 Subject: [PATCH 109/115] inkling2 : dense few-token attention by default on CUDA only The dense FA path for 2-8 token ubatches was tuned on a B200. On an M5 Max (Metal) it is 2-3% slower at pp3 / pp8 / pp16 and 10-12% at 32K cells, and other GPU backends were not measured, so they keep the banded path. Layers on the CPU keep the CUDA choice, and LLAMA_INKLING_DENSE_NMAX still overrides. --- src/models/inkling2.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 324f567fda32..fc883b6f9b09 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -35,9 +35,11 @@ static int64_t inkling2_env_i64(const char * name, int64_t def) { return env == nullptr ? def : std::max(0, atoll(env)); } -static int64_t inkling2_dense_n_max() { - static const int64_t v = inkling2_env_i64("LLAMA_INKLING_DENSE_NMAX", n_tokens_dense_max); - return v; +// the default holds on CUDA only: on Metal (M5 Max) the dense path is 2-3% slower at 3-16 tokens and 10-12% at 32K +// cells, and other backends were not measured, so they keep the banded path unless LLAMA_INKLING_DENSE_NMAX is set +static int64_t inkling2_dense_n_max(bool cuda) { + static const int64_t v = inkling2_env_i64("LLAMA_INKLING_DENSE_NMAX", -1); + return getenv("LLAMA_INKLING_DENSE_NMAX") ? v : (cuda ? n_tokens_dense_max : 1); } static int64_t inkling2_dense_kv_max() { @@ -408,7 +410,14 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { // a few-token ubatch (speculative verify, prompt tails) over a short enough cache stays dense too: the FA tile // kernel with the indexed bias beats the banded op plus its merge there. n_kv is part of can_reuse(), so a reused // graph made the same choice - const bool small_dense = n_tokens > 1 && n_tokens <= inkling2_dense_n_max() && !kv_converted && + // layers left on the CPU keep the CUDA choice of a partly offloaded model; any other GPU backend turns it off + bool dense_cuda = true; + for (uint32_t il = 0; il < hparams.n_layer() && dense_cuda; ++il) { + ggml_backend_dev_t dev = model.dev_layer(il); + const char * reg = dev ? ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)) : "CPU"; + dense_cuda = strcmp(reg, "CUDA") == 0 || strcmp(reg, "CPU") == 0; + } + const bool small_dense = n_tokens > 1 && n_tokens <= inkling2_dense_n_max(dense_cuda) && !kv_converted && (int64_t) base->get_n_kv() <= inkling2_dense_kv_max(); inp->banded = cparams.flash_attn && ((n_tokens > 1 && !small_dense) || decode_banded); inp->banded_pad = n_tokens <= n_tokens_banded_min; From eacd17dfc4881ef9516f53267526265f87fe52d5 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 30 Nov 2026 18:44:22 -0800 Subject: [PATCH 110/115] inkling : keep the dense relative bias in F32 on the non-FA attention path Since the FA bias cleanup (b12859) a dense KQ bias is cast to the mask type and added to the mask, and the mask is F16 whenever flash attention is enabled. Inkling routes multi-sequence ubatches through this path with an F32 bias, so rounding it to F16 moved its outputs (Inkling-Small wikitext-2 -c 512: KLD 0.196, top-1 83.5%). Cast the mask to F32 instead for Inkling, which restores the previous numbers exactly. --- src/llama-graph.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 61a00ce306a1..c4b41451e28a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -3249,6 +3249,10 @@ ggml_tensor * llm_graph_context::build_attn_mha( bias_dense = ggml_reshape_4d(ctx0, bias_dense, q->ne[2], bias_idxs->ne[0], q->ne[1], n_stream); bias_dense = ggml_permute(ctx0, bias_dense, 2, 0, 1, 3); } + if (model.arch == LLM_ARCH_INKLING && kq_mask->type != GGML_TYPE_F32) { + // the Inkling relative bias stays F32 (the F16 mask of flash attention would round it) + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } bias_dense = ggml_cast(ctx0, bias_dense, kq_mask->type); cb(bias_dense, "kq_bias", il); kq_mask = ggml_add(ctx0, bias_dense, kq_mask); From 874f2ae07183b63edf35afc39cbc4b832f2d2de3 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Mon, 30 Nov 2026 19:14:22 -0800 Subject: [PATCH 111/115] inkling : keep the 8-wide MoE router soft_max on the CUDA block kernel From ggml-org b12878 (one thread per row for soft_max on short rows) CUDA computes rows of up to 8 on a new kernel whose rounding differs from the block kernel by an ulp. Inkling's router softmax over 6 routed + 2 shared experts is 8 wide, and on Inkling-Small IQ1_S that ulp grows to KLD 0.17 over the layers. Append a -inf column on CUDA layers so the row stays on the block kernel, which then returns the same bits as before; other backends and models are unchanged. --- src/models/inkling.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 3cfb293b2959..0753576ce2d1 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -7,6 +7,8 @@ #include "../llama-memory-recurrent.h" #include +#include +#include void llama_model_inkling::load_arch_hparams(llama_model_loader & ml) { ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); @@ -580,7 +582,17 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * all_logits = ggml_concat(ctx0, topk_logits, shared_logits, 0); ggml_tensor * w = ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, all_logits))); - w = ggml_soft_max(ctx0, w); + ggml_backend_dev_t dev = model.dev_layer(il); + const int64_t n_w = w->ne[0]; + if (n_w <= 8 && dev && strcmp(ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)), "CUDA") == 0) { + // CUDA runs rows of up to 8 on a one-thread-per-row soft_max (ggml-org b12878), which rounds differently from + // the block kernel: a -inf column keeps the row on the block kernel, which then gives the same bits as before + w = ggml_concat(ctx0, w, ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_tokens), -INFINITY), 0); + w = ggml_soft_max(ctx0, w); + w = ggml_cont(ctx0, ggml_view_2d(ctx0, w, n_w, n_tokens, w->nb[1], 0)); + } else { + w = ggml_soft_max(ctx0, w); + } w = ggml_scale(ctx0, w, hparams.expert_weights_scale); w = ggml_mul(ctx0, w, layer.ffn_gscale); cb(w, "inkling_moe_weights", il); From 9dd84c2ea1d62725ca91798a461f7666395da9db Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 2 Dec 2026 05:59:06 -0800 Subject: [PATCH 112/115] inkling : also keep the router soft_max off the short-row kernel on ROCm, MUSA and Vulkan ggml-org b12916 (#33197) gave Vulkan the same one-thread-per-row soft_max for rows of up to 8 that CUDA got in b12878, and the CUDA kernel is also built for ROCm and MUSA. Pad the router row on those backends too, so their results stay the same as before the short-row kernels. --- src/models/inkling.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index 0753576ce2d1..a3a89015ea1e 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -584,9 +584,13 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_tensor * w = ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, all_logits))); ggml_backend_dev_t dev = model.dev_layer(il); const int64_t n_w = w->ne[0]; - if (n_w <= 8 && dev && strcmp(ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)), "CUDA") == 0) { - // CUDA runs rows of up to 8 on a one-thread-per-row soft_max (ggml-org b12878), which rounds differently from - // the block kernel: a -inf column keeps the row on the block kernel, which then gives the same bits as before + const char * reg_name = dev ? ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)) : ""; + const bool short_row_sm = strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || + strcmp(reg_name, "MUSA") == 0 || strcmp(reg_name, "Vulkan") == 0; + if (n_w <= 8 && short_row_sm) { + // CUDA/ROCm/MUSA (ggml-org b12878) and Vulkan (b12916) run rows of up to 8 on a one-thread-per-row soft_max, + // which rounds differently from the block kernel: a -inf column keeps the row on the block kernel, which then + // gives the same bits as before w = ggml_concat(ctx0, w, ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_tokens), -INFINITY), 0); w = ggml_soft_max(ctx0, w); w = ggml_cont(ctx0, ggml_view_2d(ctx0, w, n_w, n_tokens, w->nb[1], 0)); From 4a8e8b94727afdd28f317e4b82391df7038b601d Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Wed, 2 Dec 2026 08:33:32 -0800 Subject: [PATCH 113/115] inkling : keep the router soft_max on the Metal kernel it used before b12878 ggml-org#33187 (b12878) also gave Metal a one-thread-per-row soft_max for rows of up to 8 columns. Before it, Metal ran the 8-wide router row on its float4 kernel, which it only picks when the width is a multiple of 4, so a single -inf column would move it to the scalar kernel and still change the sum order. Pad to 12 on Metal (9 when the width is not a multiple of 4); the other backends keep the single -inf column and an unchanged graph. --- src/models/inkling.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/models/inkling.cpp b/src/models/inkling.cpp index a3a89015ea1e..4d134fdeb60f 100644 --- a/src/models/inkling.cpp +++ b/src/models/inkling.cpp @@ -585,13 +585,16 @@ llama_model_inkling::graph::graph(const llama_model & model, const llm_graph_par ggml_backend_dev_t dev = model.dev_layer(il); const int64_t n_w = w->ne[0]; const char * reg_name = dev ? ggml_backend_reg_name(ggml_backend_dev_backend_reg(dev)) : ""; + const bool is_metal = strcmp(reg_name, "MTL") == 0; const bool short_row_sm = strcmp(reg_name, "CUDA") == 0 || strcmp(reg_name, "ROCm") == 0 || - strcmp(reg_name, "MUSA") == 0 || strcmp(reg_name, "Vulkan") == 0; + strcmp(reg_name, "MUSA") == 0 || strcmp(reg_name, "Vulkan") == 0 || is_metal; if (n_w <= 8 && short_row_sm) { - // CUDA/ROCm/MUSA (ggml-org b12878) and Vulkan (b12916) run rows of up to 8 on a one-thread-per-row soft_max, - // which rounds differently from the block kernel: a -inf column keeps the row on the block kernel, which then - // gives the same bits as before - w = ggml_concat(ctx0, w, ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_tokens), -INFINITY), 0); + // CUDA/ROCm/MUSA/Metal (ggml-org b12878) and Vulkan (b12916) run rows of up to 8 on a one-thread-per-row + // soft_max, which rounds differently from the block kernel: -inf columns keep the row on the block kernel, + // which then gives the same bits as before. Metal picks its float4 kernel only when the width is a multiple + // of 4, so it is padded to 12 there (9 otherwise) to stay on the kernel it used before. + const int64_t n_pad = is_metal ? (n_w % 4 == 0 ? 12 : 9) - n_w : 1; + w = ggml_concat(ctx0, w, ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_pad, n_tokens), -INFINITY), 0); w = ggml_soft_max(ctx0, w); w = ggml_cont(ctx0, ggml_view_2d(ctx0, w, n_w, n_tokens, w->nb[1], 0)); } else { From b699fb7018112b25db4dacebad15e0ba57740e94 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 3 Dec 2026 15:21:54 -0800 Subject: [PATCH 114/115] inkling2 : use ggml_flash_attn_ext_set_sinks instead of the deprecated add_sinks add_sinks is a deprecated wrapper that calls set_sinks, so behavior is identical; the deprecated call fails macOS builds with -Werror -Wdeprecated-declarations. --- src/models/inkling2.cpp | 4 ++-- tests/test-backend-ops.cpp | 6 +++--- tests/test-flash-attn-banded-causal.cpp | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 288ae549a29c..ced16500f22a 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -380,7 +380,7 @@ bool llama_model_inkling2::graph::use_banded(int il, bool swa) { ggml_tensor * pm = ggml_new_tensor_4d(ctx0, GGML_TYPE_F16, 1, 1, 1, 1); ggml_tensor * pr = ggml_new_tensor_4d(ctx0, GGML_TYPE_F32, 1, nh, 1, 1); ggml_tensor * op = ggml_flash_attn_ext_banded(ctx0, pq, pk, pv, pm, pr, 1.0f, 1); - ggml_flash_attn_ext_add_sinks(op, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, nh, 1, 1)); + ggml_flash_attn_ext_set_sinks(op, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, nh, 1, 1)); if (inp->self_k_pos[swa]) { ggml_flash_attn_ext_banded_set_pos(op, ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1), ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1)); } @@ -645,7 +645,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens ggml_tensor * rel_b = ggml_mul_mat(ctx0, rel_bias, Rcur); rel_b = ggml_reshape_4d(ctx0, rel_b, rel_b->ne[0], n_head, n_tokens, 1); cur = ggml_flash_attn_ext_banded(ctx0, q_fa, k_fa, v_fa, m, rel_b, 1.0f/sqrtf(n_embd_head), rel_b->ne[0]); - ggml_flash_attn_ext_add_sinks(cur, ggml_reshape_3d(ctx0, sinks, n_head, n_tokens, 1)); + ggml_flash_attn_ext_set_sinks(cur, ggml_reshape_3d(ctx0, sinks, n_head, n_tokens, 1)); if (inp->self_k_pos[is_swa]) { ggml_flash_attn_ext_banded_set_pos(cur, inp->self_k_pos[is_swa], q_pos_banded); } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index d662d9cf6cf6..1f9181ed34d5 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10655,7 +10655,7 @@ struct test_flash_attn_ext_banded_sinks : public test_flash_attn_ext_banded { ggml_tensor * out = test_flash_attn_ext_banded::build_graph(ctx); ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, sinks == 2 ? n_q : 1); ggml_set_name(s, "sinks"); - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); return out; } @@ -10793,7 +10793,7 @@ struct test_flash_attn_ext_banded_pos : public test_case { ggml_set_name(qp, "q_pos"); ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); ggml_flash_attn_ext_banded_set_pos(out, kp, qp); ggml_prec_set_acc(out, GGML_PREC_F32); ggml_set_name(out, "out"); @@ -12567,7 +12567,7 @@ struct test_flash_attn_ext_banded_causal_pos : public test_flash_attn_ext_banded ggml_set_name(qp, "q_pos"); ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, nullptr, r, 1.0f/float(d), rel_extent); - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); ggml_flash_attn_ext_banded_set_pos(out, kp, qp); ggml_flash_attn_ext_banded_set_causal(out, true); ggml_prec_set_acc(out, GGML_PREC_F32); diff --git a/tests/test-flash-attn-banded-causal.cpp b/tests/test-flash-attn-banded-causal.cpp index ede964635f5c..b187bfb859d7 100644 --- a/tests/test-flash-attn-banded-causal.cpp +++ b/tests/test-flash-attn-banded-causal.cpp @@ -111,7 +111,7 @@ static bool run(ggml_backend_t backend, const causal_config & c, const causal_da ggml_tensor * out = ggml_flash_attn_ext_banded(ctx.get(), q, k, v, m, r, 1.0f/float(c.d), c.extent); if (s) { - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); } if (kp) { ggml_flash_attn_ext_banded_set_pos(out, kp, qp); From 551bc36c41d096e4fda466e6f6001b21e7e606ce Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Thu, 3 Dec 2026 15:42:03 -0800 Subject: [PATCH 115/115] tests : use ggml_flash_attn_ext_set_sinks instead of the deprecated add_sinks --- tests/test-backend-ops.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5e34f4dba8c2..e3297090d5b6 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10712,7 +10712,7 @@ struct test_flash_attn_ext_banded_layout : public test_flash_attn_ext_banded { if (sinks) { ggml_tensor * s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_head, sinks == 2 ? n_q : 1); ggml_set_name(s, "sinks"); - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); } ggml_prec_set_acc(out, GGML_PREC_F32); ggml_set_name(out, "out"); @@ -10797,7 +10797,7 @@ struct test_flash_attn_ext_banded_shapes : public test_case { ggml_set_name(sk, "sinks"); ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); - ggml_flash_attn_ext_add_sinks(out, sk); + ggml_flash_attn_ext_set_sinks(out, sk); ggml_prec_set_acc(out, GGML_PREC_F32); ggml_set_name(out, "out"); return out; @@ -10954,7 +10954,7 @@ struct test_flash_attn_ext_banded_kv2 : public test_case { ggml_set_name(s, "sinks"); ggml_tensor * out = ggml_flash_attn_ext_banded(ctx, q, k, v, m, r, 1.0f/float(d), rel_extent); - ggml_flash_attn_ext_add_sinks(out, s); + ggml_flash_attn_ext_set_sinks(out, s); ggml_prec_set_acc(out, GGML_PREC_F32); ggml_set_name(out, "out"); return out;