From 47f7bbeba6610d9de4ea7fb157a2c5dee9b2ffe7 Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Mon, 29 Jun 2026 17:00:12 +0100 Subject: [PATCH 1/7] convert : add Laguna (LagunaForCausalLM) support HF->GGUF conversion for poolside's Laguna (XS.2 and M.1): per-expert MoE tensor stacking, sigmoid routing with a score-correction bias and a shared expert, the attention output gate (per-head on XS.2, per-element on M.1), QK-norm, and per-layer-type RoPE (YaRN on full-attention layers, plain RoPE on sliding-window layers; M.1 is full-attention only). - conversion/laguna.py: LagunaModel converter. eos_token_id is a list [2, 24]; token 2 (which also serves as BOS) is kept as eos and token 24 (, the chat turn-end) is registered as eot so generation halts natively. - gguf-py: MODEL_ARCH.LAGUNA plus its tensor list and the attention-gate / expert-score-correction tensor mappings. - convert_hf_to_gguf_update.py: register the laguna BPE pre-tokenizer. The gate type (per-head vs per-element) is resolved from the config and cross-checked against the g_proj weight width; a contradiction fails the conversion rather than silently mis-encoding the gate. (cherry picked from commit e457ddf7d5260d7a61083cefa6b3d1ae58f9b2ae) --- conversion/__init__.py | 1 + conversion/base.py | 3 + conversion/laguna.py | 254 +++++++++++++++++++++++++++++++++ convert_hf_to_gguf_update.py | 1 + gguf-py/gguf/constants.py | 27 ++++ gguf-py/gguf/tensor_mapping.py | 1 + 6 files changed, 287 insertions(+) create mode 100644 conversion/laguna.py diff --git a/conversion/__init__.py b/conversion/__init__.py index 00192cf33a8c..c0b1c14791c5 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -18,6 +18,7 @@ TEXT_MODEL_MAP: dict[str, str] = { "AfmoeForCausalLM": "afmoe", + "LagunaForCausalLM": "laguna", "ApertusForCausalLM": "llama", "ArceeForCausalLM": "llama", "ArcticForCausalLM": "arctic", diff --git a/conversion/base.py b/conversion/base.py index c872bcbb3c4b..09324985acfd 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -1396,6 +1396,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: # NOTE: if you get an error here, you need to update the convert_hf_to_gguf_update.py script # or pull the latest version of the model from Huggingface # don't edit the hashes manually! + if chkhsh == "972da7b59cec44d1f0a490a86c96df53859e486e481563e5dddac155013d87ac": + # ref: https://huggingface.co/poolside/Laguna-XS.2 + res = "laguna" if chkhsh == "b6e8e1518dc4305be2fe39c313ed643381c4da5db34a98f6a04c093f8afbe99b": # ref: https://huggingface.co/THUDM/glm-4-9b-chat res = "chatglm-bpe" diff --git a/conversion/laguna.py b/conversion/laguna.py new file mode 100644 index 000000000000..fc2e90bc009e --- /dev/null +++ b/conversion/laguna.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import re +import logging +from collections.abc import Iterable +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, TextModel, gguf + +logger = logging.getLogger("hf-to-gguf") + + +@ModelBase.register("LagunaForCausalLM") +class LagunaModel(TextModel): + model_arch = gguf.MODEL_ARCH.LAGUNA + _experts: list[dict] | None = None + _gate_types: list[str] | None = None + + # --- vocab --------------------------------------------------------------- + + def set_vocab(self) -> None: + # Laguna ships a GPT-2 byte-level BPE tokenizer. The BPE pre-tokenizer + # variant ("laguna") is registered via get_vocab_base_pre()'s hash + # dispatcher; that table is regenerated by convert_hf_to_gguf_update.py + # before merging upstream. + self._set_vocab_gpt2() + + # Laguna's eos_token_id is a LIST: token 2 (the EOS marker, which also + # serves as BOS) and token 24 (, the chat turn-end). + # _set_vocab_gpt2 records only the scalar eos (2), so the GGUF never + # learns that ends generation. Register the remaining + # eos id(s) as the end-of-turn token; llama.cpp folds eot into its EOG + # set unconditionally, so the model halts on natively + # without client-side stop strings. See config.json eos_token_id=[2, 24]. + eos_ids = self.hparams.get("eos_token_id") + if isinstance(eos_ids, list): + bos_id = self.hparams.get("bos_token_id") + extra = [e for e in eos_ids if e != bos_id] + if extra: + self.gguf_writer.add_eot_token_id(extra[0]) + logger.info( + f"gguf: registered eot_token_id={extra[0]} from eos list {eos_ids}" + ) + + # Inline the chat template. The HF repo ships chat_template.jinja + # separately and tokenizer_config.json references it via + # "chat_template": "{% include 'chat_template.jinja' %}" + # llama.cpp's embedded Jinja renderer does not resolve {% include %} at + # runtime, so write the file's resolved contents into the GGUF directly. + chat_template_path = self.dir_model / "chat_template.jinja" + if chat_template_path.is_file(): + tmpl = chat_template_path.read_text(encoding="utf-8") + self.gguf_writer.add_chat_template(tmpl) + logger.info(f"gguf: inlined chat_template.jinja ({len(tmpl)} chars)") + + # --- hparams ------------------------------------------------------------- + + def set_gguf_parameters(self) -> None: + # Don't call super().set_gguf_parameters() — TextModel emits a scalar + # head_count from hparams["num_attention_heads"], but Laguna varies + # head count per layer and we want it as an ARRAY. We re-emit the + # other base keys explicitly below. + hparams = self.hparams + + self.gguf_writer.add_block_count(hparams["num_hidden_layers"]) + self.gguf_writer.add_context_length(hparams["max_position_embeddings"]) + self.gguf_writer.add_embedding_length(hparams["hidden_size"]) + self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"]) # dense layers + self.gguf_writer.add_vocab_size(hparams["vocab_size"]) + self.gguf_writer.add_layer_norm_rms_eps(hparams["rms_norm_eps"]) + self.gguf_writer.add_file_type(self.ftype) + + # Per-layer head count — emit as ARRAY. XS.2 varies heads per layer + # (full=48, SWA=64) and ships num_attention_heads_per_layer; M.1 is + # uniform and omits it, so fall back to a constant list built from the + # scalar num_attention_heads. + per_layer_heads = hparams.get("num_attention_heads_per_layer") + if not per_layer_heads: + per_layer_heads = [hparams["num_attention_heads"]] * hparams["num_hidden_layers"] + assert len(per_layer_heads) == hparams["num_hidden_layers"], ( + f"num_attention_heads_per_layer length {len(per_layer_heads)} != " + f"num_hidden_layers {hparams['num_hidden_layers']}" + ) + self.gguf_writer.add_head_count(per_layer_heads) + self.gguf_writer.add_head_count_kv(hparams["num_key_value_heads"]) + + head_dim = hparams["head_dim"] + self.gguf_writer.add_key_length(head_dim) + self.gguf_writer.add_value_length(head_dim) + + # Resolve + validate the attention gate type now, so an inconsistent + # `gating` field fails at conversion time rather than silently. See + # _attn_gate_types. + self._attn_gate_types() + + # SWA: scalar window size. M.1 has no sliding window (sliding_window=0), + # so the key is omitted and the loader leaves swa_type = NONE. For XS.2 + # the full/sliding interleave (full attention every 4th layer, dense + # first) is applied by the graph builder's sliding-window period. + sliding_window = hparams.get("sliding_window") or 0 + if sliding_window > 0: + self.gguf_writer.add_sliding_window(sliding_window) + + # MoE + self.gguf_writer.add_expert_count(self.find_hparam(["num_experts", "num_local_experts"])) + self.gguf_writer.add_expert_used_count(hparams["num_experts_per_tok"]) + self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"]) + self.gguf_writer.add_expert_shared_feed_forward_length(hparams["shared_expert_intermediate_size"]) + self.gguf_writer.add_expert_weights_norm(True) # HF reference always sum-normalises after top-k + self.gguf_writer.add_expert_weights_scale(float(hparams["moe_routed_scaling_factor"])) + self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SIGMOID) + + # Dense-vs-MoE structure: a run of leading dense layers (XS.2 has 1, + # M.1 has 3) followed by MoE layers. `leading_dense_block_count` is what + # the loader reads to decide which layers are dense. + mlp_layer_types: list[str] = hparams["mlp_layer_types"] + leading_dense = 0 + for t in mlp_layer_types: + if t == "dense": + leading_dense += 1 + else: + break + self.gguf_writer.add_leading_dense_block_count(leading_dense) + + # Per-layer-type RoPE. XS.2 has both full_attention and sliding_attention + # rope configs; M.1 has only full_attention (no SWA). The _swa mirrors are + # emitted only when a sliding config exists. + rope_params = hparams["rope_parameters"] + full_rope = rope_params["full_attention"] + swa_rope = rope_params.get("sliding_attention") + + # `partial_rotary_factor` differs per layer type (XS.2 full=0.5 rotates + # the first 64 of 128 dims, swa=1.0 rotates all 128; M.1 full=1.0). + full_rot = int(head_dim * float(full_rope.get("partial_rotary_factor", 1.0))) + self.gguf_writer.add_rope_dimension_count(full_rot) + self.gguf_writer.add_rope_freq_base(float(full_rope["rope_theta"])) + if swa_rope is not None: + swa_rot = int(head_dim * float(swa_rope.get("partial_rotary_factor", 1.0))) + self.gguf_writer.add_rope_dimension_count_swa(swa_rot) + self.gguf_writer.add_rope_freq_base_swa(float(swa_rope["rope_theta"])) + + # YaRN scaling on full layers. SWA layers use rope_type="default"; + # the C++ graph builder hardcodes "no YaRN on SWA layers" — we don't + # emit any *_swa variants of YaRN params. (If a future variant + # applies YaRN to SWA, we'd add `_swa` mirrors of these keys then.) + rope_type = full_rope.get("rope_type", "default") + if rope_type == "yarn": + self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.YARN) + self.gguf_writer.add_rope_scaling_factor(float(full_rope["factor"])) + self.gguf_writer.add_rope_scaling_orig_ctx_len(int(full_rope["original_max_position_embeddings"])) + self.gguf_writer.add_rope_scaling_yarn_attn_factor(float(full_rope.get("attention_factor", 1.0))) + self.gguf_writer.add_rope_scaling_yarn_beta_fast(float(full_rope.get("beta_fast", 32.0))) + self.gguf_writer.add_rope_scaling_yarn_beta_slow(float(full_rope.get("beta_slow", 1.0))) + elif rope_type != "default": + raise NotImplementedError( + f"Unsupported rope_type for full_attention: {rope_type!r}. " + f"Only 'yarn' and 'default' are recognised." + ) + + def _attn_gate_types(self) -> list[str]: + """Per-layer attention output gate type: "per_head" or "per_element". + + `gating_types` (per layer) is authoritative when present; otherwise the + scalar `gating` field is used (the "per-element"/"per-head" string, or + the legacy boolean True == per-head, as in Laguna-XS.2). + + Fails loudly when the model is per-element but the `gating` field does + not declare that as a string: runtimes that key off `gating` (vLLM, + transformers) ignore gating_types and read a bare boolean True as + per-head, silently corrupting the model. Surfacing it here keeps a + broken checkpoint from being packaged as if it were fine. + """ + if self._gate_types is not None: + return self._gate_types + hparams = self.hparams + n_layer = hparams["num_hidden_layers"] + gating = hparams.get("gating") + gating_types = hparams.get("gating_types") + + def _norm(t: object) -> str: + sval = str(t).replace("-", "_") + if sval in ("per_element", "per_head"): + return sval + raise ValueError(f"Laguna: unrecognised attention gate type {t!r}") + + if gating_types: + assert len(gating_types) == n_layer, ( + f"gating_types length {len(gating_types)} != num_hidden_layers {n_layer}") + types = [_norm(t) for t in gating_types] + elif isinstance(gating, str): + types = [_norm(gating)] * n_layer + elif gating is True: + types = ["per_head"] * n_layer + else: + raise ValueError( + f"Laguna: cannot determine attention gate type " + f"(gating={gating!r}, gating_types={gating_types!r})") + + if any(t == "per_element" for t in types) and not ( + isinstance(gating, str) and _norm(gating) == "per_element"): + raise ValueError( + f"Laguna config declares a per-element attention gate but " + f"`gating`={gating!r} is not the string \"per-element\". Runtimes that " + f"read `gating` (vLLM, transformers) will mis-handle this checkpoint as " + f"per-head. Set gating=\"per-element\" in the source config.") + + self._gate_types = types + return types + + # --- tensor handling ----------------------------------------------------- + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + # Per-expert MoE weights: model.layers.{bid}.mlp.experts.{xid}.{w}.weight. + # Only the NUMBERED per-expert weights are stacked; the router bias + # (mlp.experts.e_score_correction_bias) takes the normal mapping path. + if re.search(r"mlp\.experts\.\d+\.", name): + n_experts = self.find_hparam(["num_local_experts", "num_experts"]) + assert bid is not None + if self._experts is None: + self._experts = [{} for _ in range(self.block_count)] + self._experts[bid][name] = data_torch + needed = [f"model.layers.{bid}.mlp.experts.{x}.{w}.weight" + for x in range(n_experts) for w in ("gate_proj", "up_proj", "down_proj")] + if all(e in self._experts[bid] for e in needed): + for w_name in ["gate_proj", "up_proj", "down_proj"]: + datas = [self._experts[bid][f"model.layers.{bid}.mlp.experts.{x}.{w_name}.weight"] + for x in range(n_experts)] + stacked = torch.stack(datas, dim=0) + merged = f"model.layers.{bid}.mlp.experts.{w_name}.weight" + yield from TextModel.modify_tensors(self, stacked, merged, bid) + self._experts[bid].clear() + return + return + # Cross-check the gate projection width against the declared gate type; + # a mismatch means the weights and config disagree -> fail, do not guess. + if bid is not None and name.endswith("self_attn.g_proj.weight"): + heads = (self.hparams.get("num_attention_heads_per_layer") + or [self.hparams["num_attention_heads"]] * self.hparams["num_hidden_layers"]) + n_head = heads[bid] + head_dim = self.hparams["head_dim"] + gate_type = self._attn_gate_types()[bid] + expected = n_head * head_dim if gate_type == "per_element" else n_head + out_features = int(data_torch.shape[0]) + if out_features != expected: + raise ValueError( + f"Laguna layer {bid}: g_proj output width {out_features} contradicts the " + f"declared {gate_type} gate (expected {expected}); weights and config disagree.") + + yield from TextModel.modify_tensors(self, data_torch, name, bid) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index 91c006278f14..028160edffea 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -172,6 +172,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/THUDM/glm-4-9b-hf", "chkhsh": "a1336059768a55c99a734006ffb02203cd450fed003e9a71886c88acf24fdbc2"}, {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/zai-org/GLM-4.5-Air", "chkhsh": "9ca2dd618e8afaf09731a7cf6e2105b373ba6a1821559f258b272fe83e6eb902"}, {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/zai-org/GLM-4.7-Flash", "chkhsh": "cdf5f35325780597efd76153d4d1c16778f766173908894c04afc20108536267"}, + {"name": "laguna", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/poolside/Laguna-XS.2", "chkhsh": "972da7b59cec44d1f0a490a86c96df53859e486e481563e5dddac155013d87ac"}, {"name": "minerva-7b", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sapienzanlp/Minerva-7B-base-v1.0", "chkhsh": "1431a23e583c97432bc230bff598d103ddb5a1f89960c8f1d1051aaa944d0b35"}, {"name": "hunyuan", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-A13B-Instruct", "chkhsh": "7e57df22b1fe23a7b1e1c7f3dc4e3f96d43a4eb0836d0c6bdc3436d7b2f1c664"}, {"name": "hunyuan-dense", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-4B-Instruct", "chkhsh": "bba3b3366b646dbdded5dbc42d59598b849371afc42f7beafa914afaa5b70aa6"}, diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index c435f2659e47..a092e324e2e8 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -494,6 +494,7 @@ class MODEL_ARCH(IntEnum): DOTS1 = auto() ARCEE = auto() AFMOE = auto() + LAGUNA = auto() ERNIE4_5 = auto() ERNIE4_5_MOE = auto() HUNYUAN_MOE = auto() @@ -1050,6 +1051,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.DOTS1: "dots1", MODEL_ARCH.ARCEE: "arcee", MODEL_ARCH.AFMOE: "afmoe", + MODEL_ARCH.LAGUNA: "laguna", MODEL_ARCH.ERNIE4_5: "ernie4_5", MODEL_ARCH.ERNIE4_5_MOE: "ernie4_5-moe", MODEL_ARCH.FALCON_H1: "falcon-h1", @@ -3718,6 +3720,31 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_POST_NORM, MODEL_TENSOR.FFN_EXP_PROBS_B, ], + MODEL_ARCH.LAGUNA: [ + MODEL_TENSOR.TOKEN_EMBD, + 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_OUT, + MODEL_TENSOR.ATTN_Q_NORM, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_SHEXP, + MODEL_TENSOR.FFN_UP_SHEXP, + MODEL_TENSOR.FFN_DOWN_SHEXP, + ], MODEL_ARCH.ERNIE4_5: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index b95ad0b4a0cd..23179488768f 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -479,6 +479,7 @@ class TensorNameMap: "model.layers.{bid}.mlp.e_score_correction", # exaone-moe "model.layers.{bid}.block_sparse_moe.gate.e_score_correction", # kimi "model.layers.{bid}.moe.router_bias", # step3.5 expert selection bias + "model.layers.{bid}.mlp.experts.e_score_correction", # laguna ), # Feed-forward up From adf4760baa3413b79fa17684f97abc9f87896cb9 Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Sat, 27 Jun 2026 10:52:51 +0000 Subject: [PATCH 2/7] chat : add Laguna tool-call and reasoning parser PEG/autoparser chat handler for Laguna (XS.2 and M.1 share the format). GLM-4-MoE-style tool calls: {name} {k} {v} ... with string args emitted raw and all other args as JSON, plus ... reasoning; the turn ends with . An optional exit marker in the trigger rule lets the lazy grammar complete after the tool call(s), so the model terminates cleanly instead of looping additional calls under parallel_tool_calls. Detection keys on / together with the role tags. Adds a test-chat case (models/templates/laguna.jinja). (cherry picked from commit d211291ea0cc8838db219f3b27129f419fba45b0) --- common/chat.cpp | 195 ++++++++++++++++++++++++++++++++++ models/templates/laguna.jinja | 132 +++++++++++++++++++++++ tests/test-chat.cpp | 82 ++++++++++++++ 3 files changed, 409 insertions(+) create mode 100644 models/templates/laguna.jinja diff --git a/common/chat.cpp b/common/chat.cpp index 61062e6de126..5f472d98eaa5 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -2198,6 +2198,191 @@ static json common_chat_extra_context() { return ctx; } +// Laguna (poolside) — GLM-4-MoE-style tool calls + reasoning. +// Tool call wire format: +// {name} +// {k} +// {v} +// ... +// +// String-typed args are emitted raw between ...; all other +// args are JSON literals. Reasoning is ...; the turn ends with +// . Both Laguna-XS.2 and Laguna-M.1 share this format. +static common_chat_params common_chat_params_init_laguna(const common_chat_template & tmpl, + const autoparser::generation_params & inputs) { + common_chat_params data; + + 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 = ""; + data.thinking_end_tag = ""; + data.preserved_tokens = { + "", "", + "", "", + "", "", + "", "", + "", "", + }; + + // ends the assistant turn. The single eot token (24) handles + // this when sampled directly, but the model occasionally emits the + // multi-token spelling; register it as a stop so generation always halts. + data.additional_stops.push_back(""); + + const std::string THINK_START = ""; + const std::string THINK_END = ""; + const std::string CALL_START = ""; + const std::string CALL_END = ""; + const std::string KEY_START = ""; + const std::string KEY_END = ""; + const std::string VAL_START = ""; + const std::string VAL_END = ""; + + auto has_tools = inputs.tools.is_array() && !inputs.tools.empty(); + auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; + auto include_grammar = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE; + + auto parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + auto end = p.end(); + + // The framework prepends data.generation_prompt to the parsed output: + // "\n" followed by the opening (thinking enabled) or + // (disabled). Consume it, then capture reasoning. The model's + // output therefore starts with the reasoning text (no leading ). + const std::string GEN_PROMPT = "\n"; + auto head = p.eps(); + if (extract_reasoning && inputs.enable_thinking) { + // The model normally closes reasoning with before a tool + // call, but sometimes emits directly without it. + // Terminate reasoning on whichever marker comes first so the call is + // not swallowed into reasoning_content; consume if present. + head = p.literal(GEN_PROMPT + THINK_START) + + p.reasoning(p.until_one_of({ THINK_END, CALL_START })) + + p.optional(p.literal(THINK_END)); + } else if (extract_reasoning) { + head = p.literal(GEN_PROMPT + THINK_END); + } else { + head = p.literal(GEN_PROMPT) + + p.optional(p.literal(THINK_START)) + p.optional(p.literal(THINK_END)); + } + + if (!has_tools || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) { + return head + p.content(p.until_one_of({ "" })) + + p.optional(p.literal("")) + p.space() + end; + } + + auto tool_choice = p.choice(); + foreach_function(inputs.tools, [&](const json & tool) { + const auto & function = tool.at("function"); + std::string name = function.at("name"); + auto params = function.contains("parameters") ? function.at("parameters") : json::object(); + const auto & props = params.contains("properties") ? params.at("properties") : json::object(); + + std::set required; + if (params.contains("required")) { + params.at("required").get_to(required); + } + auto schema_info = common_schema_info(); + schema_info.resolve_refs(params); + + std::vector required_parsers; + std::vector optional_parsers; + for (const auto & [param_name, param_schema] : props.items()) { + bool is_required = required.find(param_name) != required.end(); + bool is_string = schema_info.resolves_to_string(param_schema); + + // name\nVALUE + auto arg = p.tool_arg( + p.tool_arg_open( + p.literal(KEY_START) + p.tool_arg_name(p.literal(param_name)) + p.literal(KEY_END) + + p.space() + p.literal(VAL_START)) + + (is_string + ? p.tool_arg_string_value(p.until(VAL_END)) + : p.tool_arg_json_value(p.schema(p.json(), + "tool-" + name + "-arg-" + param_name + "-schema", + param_schema, false))) + + p.tool_arg_close(p.literal(VAL_END))); + + auto named_arg = p.rule("tool-" + name + "-arg-" + param_name, arg); + if (is_required) { + required_parsers.push_back(named_arg); + } else { + optional_parsers.push_back(named_arg); + } + } + + common_peg_parser args_seq = p.eps(); + for (size_t i = 0; i < required_parsers.size(); i++) { + if (i > 0) { + args_seq = args_seq + p.space(); + } + args_seq = args_seq + required_parsers[i]; + } + if (!optional_parsers.empty()) { + common_peg_parser any_opt = p.choice(); + for (const auto & opt : optional_parsers) { + any_opt |= opt; + } + args_seq = args_seq + p.repeat(p.space() + any_opt, 0, -1); + } + + // name\n {args} + auto func_parser = p.tool( + p.tool_open(p.literal(CALL_START) + p.tool_name(p.literal(name)) + p.literal("\n")) + + args_seq + p.space() + + p.tool_close(p.literal(CALL_END))); + + tool_choice |= p.rule("tool-" + name, func_parser); + }); + + auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0; + auto max_calls = inputs.parallel_tool_calls ? -1 : 1; + // Mirror the kimi_k2 structure: each tool is followed by optional + // whitespace, and the trigger rule ends with an optional + // exit marker. This lets the (lazy) trigger rule COMPLETE once the model + // emits the turn-end, so the grammar disengages instead of offering + // another indefinitely (the parallel=true / max_calls=-1 + // loop). Space is a suffix (not prefix) to avoid ambiguity with the exit. + auto tool_calls = p.rule("tool-calls", + p.trigger_rule("tool-call", + p.repeat(tool_choice + p.space(), min_calls, max_calls) + + p.optional(p.literal("")))); + + auto content_before_tools = p.content(p.until(CALL_START)); + + // After the tool call(s) the model may emit trailing text (Laguna is + // wrapper-less, so a repetitive model can ramble past the final call). + // Absorb anything up to the turn-end as content so a stray trailing + // fragment does not fail the whole parse — mirrors the reference + // implementation, which extracts the calls and ignores the remainder. + auto trailing = p.content(p.until_one_of({ "" })); + + return head + content_before_tools + tool_calls + trailing + + p.optional(p.literal("")) + p.space() + end; + }); + + data.parser = parser.save(); + + if (include_grammar) { + data.grammar_lazy = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO; + data.grammar = build_grammar([&](const common_grammar_builder & builder) { + foreach_function(inputs.tools, [&](const json & tool) { + const auto & function = tool.at("function"); + auto schema = function.at("parameters"); + builder.resolve_refs(schema); + }); + parser.build_grammar(builder, data.grammar_lazy); + }); + data.grammar_triggers = { + { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "" } + }; + } + + return data; +} + std::optional common_chat_try_specialized_template( const common_chat_template & tmpl, const std::string & src, @@ -2210,6 +2395,16 @@ std::optional common_chat_try_specialized_template( return common_chat_params_init_ministral_3(tmpl, params); } + // Laguna (poolside) — GLM-4-MoE-style tool calls with / + // pairs, plus / role tags (distinct from GLM's + // <|assistant|>). Covers both Laguna-XS.2 and Laguna-M.1. + if (src.find("") != std::string::npos && + src.find("") != std::string::npos && + src.find("") != std::string::npos) { + LOG_DBG("Using specialized template: Laguna\n"); + return common_chat_params_init_laguna(tmpl, params); + } + // GPT-OSS - has unique channel-based structure that needs dedicated handler if (src.find("<|channel|>") != std::string::npos) { LOG_DBG("Using specialized template: GPT-OSS\n"); diff --git a/models/templates/laguna.jinja b/models/templates/laguna.jinja new file mode 100644 index 000000000000..4baa3fded6d2 --- /dev/null +++ b/models/templates/laguna.jinja @@ -0,0 +1,132 @@ +{#- Iteration on laguna_glm_thinking_v5/chat_template.jinja -#} +{#- Adds a default system message (used when no system message is provided in `messages`). -#} +{{- "〈|EOS|〉" -}} +{%- set enable_thinking = enable_thinking | default(false) -%} +{%- set render_assistant_messages_raw = render_assistant_messages_raw | default(false) -%} +{%- set add_generation_prompt = add_generation_prompt | default(false) -%} + +{#- ───── header (system message) ───── -#} +{%- set system_message = "You are a helpful, conversationally-fluent assistant made by Poolside. You are here to be helpful to users through natural language conversations." -%} +{%- if messages and messages[0].role == "system" -%} + {%- set system_message = messages[0].content -%} +{%- endif -%} + +{%- if (system_message and system_message.strip()) or tools -%} + {{- "\n" -}} + + {%- if system_message and system_message.strip() -%} + {{- "\n" -}} + {{- system_message.rstrip() -}} + {%- endif -%} + + {%- if tools -%} + {{- "\n\n### Tools\n\n" -}} + {%- set ns = namespace(tool_string="You may call functions to assist with the user query.\n" + ~ "All available function signatures are listed below:\n" + ~ "\n") -%} + {%- for tool in tools -%} + {%- set ns.tool_string = ns.tool_string ~ (tool | tojson) ~ "\n" -%} + {%- endfor -%} + {%- if enable_thinking -%} + {%- set tool_string = ns.tool_string + "\n\n" ~ + "Wrap your thinking in '', '' tags, followed by a function call. For each function call, return an unescaped XML-like object with function name and arguments within '' and '' tags, like here:\n" ~ + " your thoughts here \n" ~ + "function-name\nargument-key\nvalue-of-argument-key\n" ~ + "" -%} + {%- else -%} + {%- set tool_string = ns.tool_string + "\n\n" ~ + "For each function call, return an unescaped XML-like object " ~ + "with function name and arguments within '' and '' tags, like here:\n" ~ + "function-name\nargument-key\nvalue-of-argument-key\n" ~ + "" -%} + {%- endif -%} + {{- tool_string -}} + {%- endif -%} + + {{- "\n\n" -}} +{%- endif -%} + +{#- ───── main loop ───── -#} +{%- for message in messages -%} + {%- set content = message.content if message.content is string else "" -%} + {%- if message.role == "user" -%} + {{- "\n" + content + "\n\n" -}} + {%- elif message.role == "assistant" -%} + {%- generation -%} + {{- "\n" -}} + {%- if render_assistant_messages_raw -%} + {#- Raw mode: prepend the generation prompt token, then dump content verbatim. -#} + {#- The generation prompt is when enable_thinking, otherwise. -#} + {#- Only prepend if content doesn't already start with it. -#} + {%- if enable_thinking -%} + {%- if not content.startswith('') -%} + {{- '' -}} + {%- endif -%} + {%- else -%} + {%- if not content.startswith('') -%} + {{- '' -}} + {%- endif -%} + {%- endif -%} + {{- content -}} + {#- Append closing tag if content doesn't already end with it. -#} + {%- if not content.endswith('\n') and not content.endswith('') -%} + {{- '\n' -}} + {%- endif -%} + {{- "\n" -}} + {%- else -%} + {#- Extract reasoning content from message.reasoning (vLLM field name) or message.reasoning_content, or from tags -#} + {%- set reasoning_content = '' %} + {%- if message.reasoning is string %} + {%- set reasoning_content = message.reasoning %} + {%- elif message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- endif %} + {#- Always strip tags from content if present to avoid duplication -#} + {%- if '' in content %} + {%- if not reasoning_content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- endif %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {#- Display reasoning content for all messages -#} + {%- if reasoning_content -%} + {{- '\n' + reasoning_content.strip() + '\n\n' -}} + {%- else -%} + {{- '\n' -}} + {%- endif -%} + {#- Display main content -#} + {%- if content.strip() -%} + {{- content.strip() ~ "\n" -}} + {%- endif -%} + {%- if message.tool_calls -%} + {%- for tool_call in message.tool_calls -%} + {%- set function_data = tool_call.function -%} + {{- '' + function_data.name }} + {% set _args = function_data.arguments %} + {%- for k, v in _args.items() -%} + {{- "" ~ k ~ "\n" -}} + {{- ""}}{{ v | tojson(ensure_ascii=False) if v is not string else v }}{{ "\n" -}} + {%- endfor -%} + {{- "\n" -}} + {%- endfor -%} + {%- endif -%} + {{- "\n" -}} + {%- endif -%} + {%- endgeneration -%} + {%- elif message.role == "tool" -%} + {{- "\n" + content + "\n\n" -}} + {%- elif message.role == "system" and loop.index0 != 0 -%} + {#- Render additional system messages (skip the first one which is handled separately in the header) -#} + {{- "\n" + content + "\n\n" -}} + {%- endif -%} +{%- endfor -%} +{#- ───── generation prompt ───── -#} +{%- if add_generation_prompt -%} + {{- "\n" -}} + {#- ───── Include reasoning mode directive ───── -#} + {%- if not enable_thinking %} + {{- '' -}} + {%- else %} + {{- '' -}} + {%- endif %} +{%- endif -%} diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index c1be9eb5a99f..788198843c1c 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -1825,6 +1825,84 @@ static void test_convert_responses_to_chatcmpl() { } } +// Laguna (poolside) — GLM-4-MoE tool calls + reasoning, turn ends with . +static void test_laguna_parser(const std::string & template_path, bool detailed_debug) { + auto tst = peg_tester(template_path, detailed_debug); + + // Reasoning + content (no tools). Generation prompt emits the opening , + // so the parsed output starts with reasoning text and no leading . + tst.test("I'm\nthinkingHello, world!\nWhat's up?") + .enable_thinking(true) + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .expect(message_assist_thoughts) + .run(); + + // Reasoning + single tool call (string param). The grammar covers the + // tool-call region; the turn-end is post-grammar (handled by + // additional_stops at runtime), so the parsed/grammar-checked text ends at + // — mirroring the deepseek_v3_2 cases. + tst.test( + "Let me check the weather\n" + "get_weather\n" + "city\n" + "Paris\n" + "") + .enable_thinking(true) + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ get_weather_tool }) + .expect(message_with_tool_calls_and_reasoning("get_weather", R"({"city": "Paris"})", "Let me check the weather")) + .run(); + + // Non-thinking mode + non-string (integer) arg. Generation prompt is + // "\n"; the integer is a raw JSON value, not quoted. + tst.test( + "special_function\n" + "arg1\n" + "1\n" + "") + .enable_thinking(false) + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ special_function_tool }) + .expect(message_assist_call) + .run(); + + // Thinking mode where the model omits the closing and goes straight + // into the tool call. The reasoning region terminates at (not only + // at ), so the call is still extracted instead of being swallowed into + // reasoning_content. + tst.test( + "Let me check the weather\n" + "get_weather\n" + "city\n" + "Paris\n" + "") + .enable_thinking(true) + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .tools({ get_weather_tool }) + .expect(message_with_tool_calls_and_reasoning("get_weather", R"({"city": "Paris"})", "Let me check the weather")) + .run(); + + // Parallel tool calls with reasoning. + tst.test( + "Calling both\n" + "get_time\n" + "city\n" + "Paris\n" + "\n" + "get_weather\n" + "city\n" + "Paris\n" + "") + .enable_thinking(true) + .reasoning_format(COMMON_REASONING_FORMAT_DEEPSEEK) + .parallel_tool_calls(true) + .tools({ get_time_tool, get_weather_tool }) + .expect(message_with_reasoning_content_and_multiple_tool_calls( + "Calling both", "", + { { "get_time", R"({"city": "Paris"})" }, { "get_weather", R"({"city": "Paris"})" } })) + .run(); +} + // Shared LFM2 parser cases - all variants use one output format and parser static void test_lfm2_parser(const std::string & template_path, bool detailed_debug) { auto tst = peg_tester(template_path, detailed_debug); @@ -4144,6 +4222,10 @@ static void test_template_output_peg_parsers(bool detailed_debug) { test_lfm2_parser(tmpl, detailed_debug); } + { + test_laguna_parser("models/templates/laguna.jinja", detailed_debug); + } + // Thinking cases only apply to LFM2.5-8B-A1B, the one LFM2 template that emits { auto tst = peg_tester("models/templates/LFM2.5-8B-A1B.jinja", detailed_debug); From b06461599e041991ae11ab8605a441d6162ab0fc Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Tue, 30 Jun 2026 16:43:16 +0100 Subject: [PATCH 3/7] conversion : address review feedback (logger + set_gguf_parameters) - Use the shared logger from .base instead of a local logging.getLogger. - Call super().set_gguf_parameters() and override only head_count with the per-layer array, instead of re-emitting the base keys by hand (overwriting an already-set value is fine). Keep vocab_size, which the base does not emit for the gpt2 vocab path. Addresses @CISC review comments on conversion/laguna.py. (cherry picked from commit ea288fadcdcbdaf573e319fd3edab6b0bce813e6) --- conversion/laguna.py | 32 +++++++++----------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/conversion/laguna.py b/conversion/laguna.py index fc2e90bc009e..28c76d7b5c61 100644 --- a/conversion/laguna.py +++ b/conversion/laguna.py @@ -1,7 +1,6 @@ from __future__ import annotations import re -import logging from collections.abc import Iterable from typing import TYPE_CHECKING @@ -10,9 +9,7 @@ if TYPE_CHECKING: from torch import Tensor -from .base import ModelBase, TextModel, gguf - -logger = logging.getLogger("hf-to-gguf") +from .base import ModelBase, TextModel, gguf, logger @ModelBase.register("LagunaForCausalLM") @@ -61,24 +58,18 @@ def set_vocab(self) -> None: # --- hparams ------------------------------------------------------------- def set_gguf_parameters(self) -> None: - # Don't call super().set_gguf_parameters() — TextModel emits a scalar - # head_count from hparams["num_attention_heads"], but Laguna varies - # head count per layer and we want it as an ARRAY. We re-emit the - # other base keys explicitly below. + super().set_gguf_parameters() hparams = self.hparams - self.gguf_writer.add_block_count(hparams["num_hidden_layers"]) - self.gguf_writer.add_context_length(hparams["max_position_embeddings"]) - self.gguf_writer.add_embedding_length(hparams["hidden_size"]) - self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"]) # dense layers + # super() covers the standard keys (block/context/embedding/ffn length, + # head_count_kv, key/value_length from the explicit head_dim, rms_eps, + # file_type). It does not emit vocab_size for the gpt2 vocab path, so set + # it here, and override the scalar head_count with a per-layer ARRAY: + # XS.2 varies heads per layer (full=48, SWA=64) via + # num_attention_heads_per_layer; M.1 is uniform and omits it, so build a + # constant list from the scalar num_attention_heads. self.gguf_writer.add_vocab_size(hparams["vocab_size"]) - self.gguf_writer.add_layer_norm_rms_eps(hparams["rms_norm_eps"]) - self.gguf_writer.add_file_type(self.ftype) - # Per-layer head count — emit as ARRAY. XS.2 varies heads per layer - # (full=48, SWA=64) and ships num_attention_heads_per_layer; M.1 is - # uniform and omits it, so fall back to a constant list built from the - # scalar num_attention_heads. per_layer_heads = hparams.get("num_attention_heads_per_layer") if not per_layer_heads: per_layer_heads = [hparams["num_attention_heads"]] * hparams["num_hidden_layers"] @@ -87,11 +78,6 @@ def set_gguf_parameters(self) -> None: f"num_hidden_layers {hparams['num_hidden_layers']}" ) self.gguf_writer.add_head_count(per_layer_heads) - self.gguf_writer.add_head_count_kv(hparams["num_key_value_heads"]) - - head_dim = hparams["head_dim"] - self.gguf_writer.add_key_length(head_dim) - self.gguf_writer.add_value_length(head_dim) # Resolve + validate the attention gate type now, so an inconsistent # `gating` field fails at conversion time rather than silently. See From 821e3f8ffee00576326cf5f78f34c81ed656c016 Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Wed, 1 Jul 2026 10:00:19 +0100 Subject: [PATCH 4/7] conversion : address review feedback (chat_template.jinja + dedupe set_gguf_parameters) Signed-off-by: Joe Rowell (cherry picked from commit 588d27aafbed126725442c67d296e456d3c0527b) --- conversion/laguna.py | 96 ++++++++++---------------------------------- 1 file changed, 21 insertions(+), 75 deletions(-) diff --git a/conversion/laguna.py b/conversion/laguna.py index 28c76d7b5c61..b7d627393eff 100644 --- a/conversion/laguna.py +++ b/conversion/laguna.py @@ -21,39 +21,19 @@ class LagunaModel(TextModel): # --- vocab --------------------------------------------------------------- def set_vocab(self) -> None: - # Laguna ships a GPT-2 byte-level BPE tokenizer. The BPE pre-tokenizer - # variant ("laguna") is registered via get_vocab_base_pre()'s hash - # dispatcher; that table is regenerated by convert_hf_to_gguf_update.py - # before merging upstream. self._set_vocab_gpt2() - # Laguna's eos_token_id is a LIST: token 2 (the EOS marker, which also - # serves as BOS) and token 24 (, the chat turn-end). - # _set_vocab_gpt2 records only the scalar eos (2), so the GGUF never - # learns that ends generation. Register the remaining - # eos id(s) as the end-of-turn token; llama.cpp folds eot into its EOG - # set unconditionally, so the model halts on natively - # without client-side stop strings. See config.json eos_token_id=[2, 24]. + # eos_token_id is a list [2, 24]: token 2 (EOS, also BOS) and token 24 + # (, the turn-end). _set_vocab_gpt2 only records the scalar + # eos, so register the extra id as eot; llama.cpp folds eot into its EOG + # set, so the model halts on natively. eos_ids = self.hparams.get("eos_token_id") if isinstance(eos_ids, list): bos_id = self.hparams.get("bos_token_id") extra = [e for e in eos_ids if e != bos_id] if extra: self.gguf_writer.add_eot_token_id(extra[0]) - logger.info( - f"gguf: registered eot_token_id={extra[0]} from eos list {eos_ids}" - ) - - # Inline the chat template. The HF repo ships chat_template.jinja - # separately and tokenizer_config.json references it via - # "chat_template": "{% include 'chat_template.jinja' %}" - # llama.cpp's embedded Jinja renderer does not resolve {% include %} at - # runtime, so write the file's resolved contents into the GGUF directly. - chat_template_path = self.dir_model / "chat_template.jinja" - if chat_template_path.is_file(): - tmpl = chat_template_path.read_text(encoding="utf-8") - self.gguf_writer.add_chat_template(tmpl) - logger.info(f"gguf: inlined chat_template.jinja ({len(tmpl)} chars)") + logger.info(f"gguf: registered eot_token_id={extra[0]} from eos list {eos_ids}") # --- hparams ------------------------------------------------------------- @@ -61,13 +41,9 @@ def set_gguf_parameters(self) -> None: super().set_gguf_parameters() hparams = self.hparams - # super() covers the standard keys (block/context/embedding/ffn length, - # head_count_kv, key/value_length from the explicit head_dim, rms_eps, - # file_type). It does not emit vocab_size for the gpt2 vocab path, so set - # it here, and override the scalar head_count with a per-layer ARRAY: - # XS.2 varies heads per layer (full=48, SWA=64) via - # num_attention_heads_per_layer; M.1 is uniform and omits it, so build a - # constant list from the scalar num_attention_heads. + # super() does not emit vocab_size for the gpt2 vocab path; head_count is + # overridden with a per-layer array (XS.2 varies heads per layer via + # num_attention_heads_per_layer; M.1 is uniform and omits it). self.gguf_writer.add_vocab_size(hparams["vocab_size"]) per_layer_heads = hparams.get("num_attention_heads_per_layer") @@ -79,15 +55,11 @@ def set_gguf_parameters(self) -> None: ) self.gguf_writer.add_head_count(per_layer_heads) - # Resolve + validate the attention gate type now, so an inconsistent - # `gating` field fails at conversion time rather than silently. See - # _attn_gate_types. + # Resolve + validate the attention gate type now so an inconsistent + # `gating` field fails at conversion time. See _attn_gate_types. self._attn_gate_types() - # SWA: scalar window size. M.1 has no sliding window (sliding_window=0), - # so the key is omitted and the loader leaves swa_type = NONE. For XS.2 - # the full/sliding interleave (full attention every 4th layer, dense - # first) is applied by the graph builder's sliding-window period. + # SWA window size (M.1 has none -> key omitted, swa_type stays NONE). sliding_window = hparams.get("sliding_window") or 0 if sliding_window > 0: self.gguf_writer.add_sliding_window(sliding_window) @@ -101,9 +73,7 @@ def set_gguf_parameters(self) -> None: self.gguf_writer.add_expert_weights_scale(float(hparams["moe_routed_scaling_factor"])) self.gguf_writer.add_expert_gating_func(gguf.ExpertGatingFuncType.SIGMOID) - # Dense-vs-MoE structure: a run of leading dense layers (XS.2 has 1, - # M.1 has 3) followed by MoE layers. `leading_dense_block_count` is what - # the loader reads to decide which layers are dense. + # Leading dense layers (XS.2 has 1, M.1 has 3) before the MoE layers. mlp_layer_types: list[str] = hparams["mlp_layer_types"] leading_dense = 0 for t in mlp_layer_types: @@ -113,40 +83,16 @@ def set_gguf_parameters(self) -> None: break self.gguf_writer.add_leading_dense_block_count(leading_dense) - # Per-layer-type RoPE. XS.2 has both full_attention and sliding_attention - # rope configs; M.1 has only full_attention (no SWA). The _swa mirrors are - # emitted only when a sliding config exists. - rope_params = hparams["rope_parameters"] - full_rope = rope_params["full_attention"] - swa_rope = rope_params.get("sliding_attention") - - # `partial_rotary_factor` differs per layer type (XS.2 full=0.5 rotates - # the first 64 of 128 dims, swa=1.0 rotates all 128; M.1 full=1.0). - full_rot = int(head_dim * float(full_rope.get("partial_rotary_factor", 1.0))) - self.gguf_writer.add_rope_dimension_count(full_rot) - self.gguf_writer.add_rope_freq_base(float(full_rope["rope_theta"])) + # Per-layer-type RoPE dimension count (partial rotary). base emits + # rope_freq_base(_swa) and the YaRN params from self.rope_parameters. + head_dim = hparams["head_dim"] + full_rope = self.rope_parameters["full_attention"] + self.gguf_writer.add_rope_dimension_count( + int(head_dim * float(full_rope.get("partial_rotary_factor", 1.0)))) + swa_rope = self.rope_parameters.get("sliding_attention") if swa_rope is not None: - swa_rot = int(head_dim * float(swa_rope.get("partial_rotary_factor", 1.0))) - self.gguf_writer.add_rope_dimension_count_swa(swa_rot) - self.gguf_writer.add_rope_freq_base_swa(float(swa_rope["rope_theta"])) - - # YaRN scaling on full layers. SWA layers use rope_type="default"; - # the C++ graph builder hardcodes "no YaRN on SWA layers" — we don't - # emit any *_swa variants of YaRN params. (If a future variant - # applies YaRN to SWA, we'd add `_swa` mirrors of these keys then.) - rope_type = full_rope.get("rope_type", "default") - if rope_type == "yarn": - self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.YARN) - self.gguf_writer.add_rope_scaling_factor(float(full_rope["factor"])) - self.gguf_writer.add_rope_scaling_orig_ctx_len(int(full_rope["original_max_position_embeddings"])) - self.gguf_writer.add_rope_scaling_yarn_attn_factor(float(full_rope.get("attention_factor", 1.0))) - self.gguf_writer.add_rope_scaling_yarn_beta_fast(float(full_rope.get("beta_fast", 32.0))) - self.gguf_writer.add_rope_scaling_yarn_beta_slow(float(full_rope.get("beta_slow", 1.0))) - elif rope_type != "default": - raise NotImplementedError( - f"Unsupported rope_type for full_attention: {rope_type!r}. " - f"Only 'yarn' and 'default' are recognised." - ) + self.gguf_writer.add_rope_dimension_count_swa( + int(head_dim * float(swa_rope.get("partial_rotary_factor", 1.0)))) def _attn_gate_types(self) -> list[str]: """Per-layer attention output gate type: "per_head" or "per_element". From fa3f5c2968901729e86d70cf0a28eb9e5957df6b Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Mon, 29 Jun 2026 17:00:13 +0100 Subject: [PATCH 5/7] llama : add Laguna model architecture Graph builder for poolside's Laguna (XS.2 and M.1). Softplus attention output gate (per-head or per-element, taken from the g_proj tensor width and required to be exactly one of the two valid widths), QK-RMSNorm, optional hybrid full / sliding-window attention with per-layer head counts, partial-rotary YaRN on full-attention layers and plain RoPE on sliding-window layers, and sigmoid-routed MoE with a score-correction bias, sum-normalization, a routed scaling factor and an always-on shared expert. Validated on Laguna-XS.2 (4-shot GSM8K in line with the reference implementation) and Laguna-M.1. (cherry picked from commit b0c66b6f5fc81dfd4ffb39d169c9b9f4d854e759) --- src/llama-arch.cpp | 1 + src/llama-arch.h | 1 + src/llama-model.cpp | 3 + src/llama-vocab.cpp | 3 +- src/models/laguna.cpp | 321 ++++++++++++++++++++++++++++++++++++++++++ src/models/models.h | 13 ++ 6 files changed, 341 insertions(+), 1 deletion(-) create mode 100644 src/models/laguna.cpp diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 4a52d977297c..492a7d54a8c6 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -107,6 +107,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_DOTS1, "dots1" }, { LLM_ARCH_ARCEE, "arcee" }, { LLM_ARCH_AFMOE, "afmoe" }, + { LLM_ARCH_LAGUNA, "laguna" }, { LLM_ARCH_ERNIE4_5, "ernie4_5" }, { LLM_ARCH_ERNIE4_5_MOE, "ernie4_5-moe" }, { LLM_ARCH_HUNYUAN_MOE, "hunyuan-moe" }, diff --git a/src/llama-arch.h b/src/llama-arch.h index 989da06d8d51..74411281e5d6 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -112,6 +112,7 @@ enum llm_arch { LLM_ARCH_DOTS1, LLM_ARCH_ARCEE, LLM_ARCH_AFMOE, + LLM_ARCH_LAGUNA, LLM_ARCH_ERNIE4_5, LLM_ARCH_ERNIE4_5_MOE, LLM_ARCH_HUNYUAN_MOE, diff --git a/src/llama-model.cpp b/src/llama-model.cpp index c52875533905..41c801bd6044 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -247,6 +247,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_arcee(params); case LLM_ARCH_AFMOE: return new llama_model_afmoe(params); + case LLM_ARCH_LAGUNA: + return new llama_model_laguna(params); case LLM_ARCH_ERNIE4_5: return new llama_model_ernie4_5(params); case LLM_ARCH_ERNIE4_5_MOE: @@ -2484,6 +2486,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_COGVLM: case LLM_ARCH_PANGU_EMBED: case LLM_ARCH_AFMOE: + case LLM_ARCH_LAGUNA: case LLM_ARCH_QWEN3NEXT: case LLM_ARCH_MIMO2: case LLM_ARCH_STEP35: diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index ffd1607831e1..dd464835baec 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2331,7 +2331,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2; clean_spaces = false; } else if ( - tokenizer_pre == "afmoe") { + tokenizer_pre == "afmoe" || + tokenizer_pre == "laguna") { pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE; clean_spaces = false; } else if ( diff --git a/src/models/laguna.cpp b/src/models/laguna.cpp new file mode 100644 index 000000000000..ee37c68b86df --- /dev/null +++ b/src/models/laguna.cpp @@ -0,0 +1,321 @@ +// Laguna (poolside): sigmoid-routed MoE with a score-correction bias, one shared +// expert, a softplus attention output gate, QK-norm, and per-layer-type RoPE +// (YaRN on full-attention layers, plain RoPE on sliding-window layers). XS.2 is +// hybrid full/SWA with a per-head gate; M.1 is full-attention with a per-element +// gate. Shares the MoE/gate structure with afmoe. + +#include "models.h" + +void llama_model_laguna::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead); + ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm); + + // Laguna ships exactly one shared expert; the size lives in the + // expert_shared_feed_forward_length key. afmoe stores a count and derives + // size = count * n_ff_exp, but Laguna's shared and routed experts can in + // principle have different sizes, so we read the size directly. + hparams.n_expert_shared = 1; + ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp); + + // Sliding-window attention is OPTIONAL. XS.2 is hybrid (full / SWA / SWA / + // SWA repeating, period 4 starting with full); M.1 has no sliding window + // (all layers full attention). When sliding_window is absent or zero we + // leave swa_type = NONE and skip the SWA-specific per-layer-type RoPE. + hparams.n_swa = 0; + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa, false); + if (hparams.n_swa > 0) { + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + + uint32_t swa_period = 4; + ml.get_key_or_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, swa_period, false); + hparams.set_swa_pattern(swa_period, /*dense_first=*/true); // XS.2: FULL at il%4==0 + + // Per-layer-type RoPE: full layers use YaRN θ=500000 over 64 dims; + // SWA layers use default RoPE θ=10000 over 128 dims. Base load_hparams + // already reads ROPE_FREQ_BASE and ROPE_DIMENSION_COUNT into the + // non-SWA fields; we explicitly pull the SWA mirrors here. + hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; + hparams.rope_freq_scale_train_swa = 1.0f; // SWA uses plain RoPE (no YaRN scaling); do NOT inherit full layers 1/factor + ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false); + ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT_SWA, hparams.n_rot_swa, false); + } + + // Default the expert gating function to SIGMOID when the key is absent + // (matches the HF reference). + if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_NONE) { + hparams.expert_gating_func = LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID; + } + + switch (hparams.n_layer()) { + case 40: type = LLM_TYPE_30B_A3B; break; // Laguna-XS.2 + case 70: type = LLM_TYPE_230B_A10B; break; // Laguna-M.1 + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_laguna::load_arch_tensors(llama_model_loader & ml) { + LLAMA_LOAD_LOCALS; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + if (output == NULL) { + // tied embeddings fallback + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } + + const int64_t n_ff_exp = hparams.n_ff_exp; + const int64_t n_ff_shexp = hparams.n_ff_shexp; + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + // Per-layer head count — Laguna varies n_head between full and SWA + // layers (48 vs 64 in XS.2). KV head count is uniform. + const int64_t n_head_il = hparams.n_head(i); + const int64_t n_head_kv_il = hparams.n_head_kv(i); + const int64_t n_embd_q_il = n_embd_head_k * n_head_il; + const int64_t n_embd_k_il = n_embd_head_k * n_head_kv_il; + const int64_t n_embd_v_il = n_embd_head_v * n_head_kv_il; + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + + create_tensor_qkv(layer, i, n_embd, n_embd_q_il, n_embd_k_il, n_embd_v_il, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_q_il, n_embd}, 0); + + layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head_k}, 0); + layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_k}, 0); + + // Attention output gate. XS.2 is per-head (g_proj -> n_head, one scalar + // per head broadcast over head_dim at multiply time); M.1 is per-element + // (g_proj -> n_head*head_dim, like afmoe). Detect from the stored tensor + // shape so a single arch handles both; the graph mirrors this check. + // Gate width selects per-head vs per-element. Read it from the tensor and + // require EXACTLY one of the two valid widths -- never silently fall back. + // (The converter also cross-checks this against the config's declared + // `gating` type and fails at conversion time on a mismatch.) + const int64_t n_gate_per_head = n_head_il; + const int64_t n_gate_per_elem = n_embd_head_k * n_head_il; + const ggml_tensor * gate_meta = ml.get_tensor_meta(tn(LLM_TENSOR_ATTN_GATE, "weight", i).str().c_str()); + GGML_ASSERT(gate_meta != nullptr && "Laguna: missing attention gate tensor"); + const int64_t n_gate_out = gate_meta->ne[1]; + if (n_gate_out != n_gate_per_head && n_gate_out != n_gate_per_elem) { + GGML_ABORT("Laguna: unexpected attention gate width %lld at layer %d " + "(expected %lld per-head or %lld per-element)", + (long long) n_gate_out, i, (long long) n_gate_per_head, (long long) n_gate_per_elem); + } + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_gate_out}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + + if ((uint32_t)i >= hparams.n_layer_dense_lead) { + // MoE layer + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + layer.ffn_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); + + // Always-on shared expert. + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0); + } else { + // Dense layer (the leading n_layer_dense_lead layers) + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } + } +} + +std::unique_ptr llama_model_laguna::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(*this, params); +} + +llama_model_laguna::graph::graph(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) { + const int64_t n_embd_head = hparams.n_embd_head_v(); + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); + + ggml_tensor * cur; + ggml_tensor * inpL; + + inpL = build_inp_embd(model.tok_embd); + // No MuP embedding scale (laguna omits this; afmoe scales by sqrt(hidden)). + + ggml_tensor * inp_pos = build_inp_pos(); + // XS.2 is hybrid SWA -> interleaved-SWA KV input; M.1 is all-full -> plain + // KV input. Pick the matching input (and build_attn overload) per swa_type. + const bool has_swa = hparams.swa_type != LLAMA_SWA_TYPE_NONE; + llm_graph_input_attn_kv * inp_attn_kv = has_swa ? nullptr : build_attn_inp_kv(); + llm_graph_input_attn_kv_iswa * inp_attn_iswa = has_swa ? build_attn_inp_kv_iswa() : nullptr; + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + const float kq_scale = 1.0f / sqrtf(float(n_embd_head)); + + for (int il = 0; il < n_layer; ++il) { + const bool is_swa_il = hparams.is_swa(il); + const int64_t n_head_il = hparams.n_head(il); + const int64_t n_head_kv_il = hparams.n_head_kv(il); + + // Per-layer-type RoPE config. SWA layers run plain rope (no YaRN), + // achieved by zeroing the YaRN ext/beta params for those layers. + const int n_rot_l = is_swa_il ? hparams.n_rot_swa : n_rot; + const float freq_base_l = is_swa_il ? hparams.rope_freq_base_train_swa : freq_base; + const float freq_scale_l = is_swa_il ? hparams.rope_freq_scale_train_swa : freq_scale; + const float ext_factor_l = is_swa_il ? 0.0f : ext_factor; + // YaRN magnitude scaling (mscale) is already handled by the framework: + // llama_context pre-divides cparams.yarn_attn_factor by (1 + 0.1*ln(factor)) + // to cancel ggml rope_yarn's internal mscale *= 1 + 0.1*ln(1/freq_scale). + // Pass attn_factor straight through (like every other arch); SWA layers run + // plain RoPE (ext_factor 0, no mscale) so force 1.0 there. + const float attn_factor_l = is_swa_il ? 1.0f : attn_factor; + const float beta_fast_l = is_swa_il ? 0.0f : beta_fast; + const float beta_slow_l = is_swa_il ? 0.0f : beta_slow; + const int n_ctx_orig_l = is_swa_il ? hparams.n_ctx_train : n_ctx_orig; + + ggml_tensor * inpSA = inpL; + + // Pre-norm + cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + // Self-attention + { + ggml_tensor * attn_inp = cur; // saved for the gate projection + + auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, + n_embd_head, n_head_il, n_head_kv_il, il); + + // g_proj on the *pre-attention* hidden state (matches HF + // reference: gate is computed from the same `hidden_states` + // input as q/k/v, not from the attn output). + ggml_tensor * gate = build_lora_mm(model.layers[il].wqkv_gate, attn_inp); + cb(gate, "attn_gate_proj", il); + + // QK RMSNorm at head_dim level (Qwen3 style) + Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il); + Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + cb(Kcur, "Kcur_normed", il); + + Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, + n_rot_l, rope_type, n_ctx_orig_l, freq_base_l, freq_scale_l, + ext_factor_l, attn_factor_l, beta_fast_l, beta_slow_l); + Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, + n_rot_l, rope_type, n_ctx_orig_l, freq_base_l, freq_scale_l, + ext_factor_l, attn_factor_l, beta_fast_l, beta_slow_l); + cb(Qcur, "Qcur_rope", il); + cb(Kcur, "Kcur_rope", il); + + cur = has_swa + ? build_attn(inp_attn_iswa, + NULL, NULL, NULL, // o_proj deferred until after gating + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il) + : build_attn(inp_attn_kv, + NULL, NULL, NULL, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il); + cb(cur, "attn_out", il); + + // Softplus output gate (the unary kernel computes softplus in fp32 + // and casts back). Two shapes, distinguished by the g_proj output + // dim (matching the load-time detection): + // XS.2 per-head : gate [n_head_il, n_tokens] -> reshape to + // [1, n_head_il, n_tokens] and broadcast over + // head_dim against cur [head_dim, n_head, T]. + // M.1 per-element : gate [n_head_il*head_dim, n_tokens] spans the + // full attention output -> direct ggml_mul. + gate = ggml_softplus(ctx0, gate); + cb(gate, "attn_gate_softplus", il); + + const int64_t n_tokens = cur->ne[1]; + if (model.layers[il].wqkv_gate->ne[1] == n_head_il) { + cur = ggml_reshape_3d(ctx0, cur, n_embd_head, n_head_il, n_tokens); + gate = ggml_reshape_3d(ctx0, gate, 1, n_head_il, n_tokens); + cur = ggml_mul(ctx0, cur, gate); + cur = ggml_reshape_2d(ctx0, cur, n_embd_head * n_head_il, n_tokens); + } else { + cur = ggml_mul(ctx0, cur, gate); + } + cb(cur, "attn_gated", il); + + cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s); + cb(cur, "attn_o_proj", il); + } + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); + cb(ffn_inp, "ffn_inp", il); + + // Pre-norm only (no post-attn norm) + cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + if ((uint32_t)il >= hparams.n_layer_dense_lead) { + // MoE: sigmoid routing + score-correction bias + sum-norm + + // routed_scaling_factor (all handled by build_moe_ffn). + ggml_tensor * moe_out = build_moe_ffn(cur, + model.layers[il].ffn_gate_inp, + model.layers[il].ffn_up_exps, + model.layers[il].ffn_gate_exps, + model.layers[il].ffn_down_exps, + model.layers[il].ffn_exp_probs_b, + n_expert, n_expert_used, + LLM_FFN_SILU, + hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il); + cb(moe_out, "ffn_moe_out", il); + + // Always-on shared expert, summed in parallel. + ggml_tensor * ffn_shexp = build_ffn(cur, + model.layers[il].ffn_up_shexp, NULL, NULL, + model.layers[il].ffn_gate_shexp, NULL, NULL, + model.layers[il].ffn_down_shexp, NULL, NULL, + NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(ffn_shexp, "ffn_shexp", il); + + cur = ggml_add(ctx0, moe_out, ffn_shexp); + cb(cur, "ffn_out", il); + } else { + // Dense FFN for the leading n_layer_dense_lead layers (XS.2: 1, M.1: 3) + 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); + cb(cur, "ffn_out", il); + } + + // No post-ffn norm + cur = ggml_add(ctx0, cur, ffn_inp); + cur = build_cvec(cur, il); + cb(cur, "l_out", il); + + inpL = cur; + } + + cur = inpL; + cur = build_norm(cur, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; + + ggml_build_forward_expand(gf, cur); +} diff --git a/src/models/models.h b/src/models/models.h index 2ac8415a3639..f202400a534b 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -1549,6 +1549,19 @@ struct llama_model_afmoe : public llama_model_base { }; +struct llama_model_laguna : public llama_model_base { + llama_model_laguna(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_ernie4_5 : public llama_model_base { llama_model_ernie4_5(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; From 027c4b108c7afaa5560ff7609329a5a86e7ec288 Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Wed, 1 Jul 2026 15:51:28 +0100 Subject: [PATCH 6/7] laguna : address review (dedicated vocab pre-type, converter registration, optional expert_shared_count) (cherry picked from commit 348fd3e6aef225b8e24c599fff19ac0b0ca0b7e9) --- conversion/base.py | 6 +++--- conversion/laguna.py | 4 +--- convert_hf_to_gguf_update.py | 2 +- src/llama-vocab.cpp | 13 +++++++++++-- src/llama-vocab.h | 1 + src/models/laguna.cpp | 8 ++++---- 6 files changed, 21 insertions(+), 13 deletions(-) diff --git a/conversion/base.py b/conversion/base.py index 09324985acfd..d94039432ca5 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -1396,9 +1396,6 @@ def get_vocab_base_pre(self, tokenizer) -> str: # NOTE: if you get an error here, you need to update the convert_hf_to_gguf_update.py script # or pull the latest version of the model from Huggingface # don't edit the hashes manually! - if chkhsh == "972da7b59cec44d1f0a490a86c96df53859e486e481563e5dddac155013d87ac": - # ref: https://huggingface.co/poolside/Laguna-XS.2 - res = "laguna" if chkhsh == "b6e8e1518dc4305be2fe39c313ed643381c4da5db34a98f6a04c093f8afbe99b": # ref: https://huggingface.co/THUDM/glm-4-9b-chat res = "chatglm-bpe" @@ -1675,6 +1672,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "9dcf830ee9990cdbf78cc523a5f7bd9ad8f3f9890c2d3581d2785ad10f07049d": # ref: https://huggingface.co/JetBrains/Mellum2-12B-A2.5B-Base res = "mellum2" + if chkhsh == "972da7b59cec44d1f0a490a86c96df53859e486e481563e5dddac155013d87ac": + # ref: https://huggingface.co/poolside/Laguna-XS.2 + res = "laguna" if res is None: logger.warning("\n") diff --git a/conversion/laguna.py b/conversion/laguna.py index b7d627393eff..9a9567e14e0a 100644 --- a/conversion/laguna.py +++ b/conversion/laguna.py @@ -64,9 +64,7 @@ def set_gguf_parameters(self) -> None: if sliding_window > 0: self.gguf_writer.add_sliding_window(sliding_window) - # MoE - self.gguf_writer.add_expert_count(self.find_hparam(["num_experts", "num_local_experts"])) - self.gguf_writer.add_expert_used_count(hparams["num_experts_per_tok"]) + # MoE (expert_count / expert_used_count come from super().set_gguf_parameters()) self.gguf_writer.add_expert_feed_forward_length(hparams["moe_intermediate_size"]) self.gguf_writer.add_expert_shared_feed_forward_length(hparams["shared_expert_intermediate_size"]) self.gguf_writer.add_expert_weights_norm(True) # HF reference always sum-normalises after top-k diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index 028160edffea..e5d3196efe41 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -162,6 +162,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "granite-embed-multi-97m", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ibm-granite/granite-embedding-97m-multilingual-r2", }, {"name": "granite-embed-multi-311m", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/ibm-granite/granite-embedding-311m-multilingual-r2", }, {"name": "mellum2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/JetBrains/Mellum2-12B-A2.5B-Base"}, + {"name": "laguna", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/poolside/Laguna-XS.2", }, ] # some models are known to be broken upstream, so we will skip them as exceptions @@ -172,7 +173,6 @@ class TOKENIZER_TYPE(IntEnum): {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/THUDM/glm-4-9b-hf", "chkhsh": "a1336059768a55c99a734006ffb02203cd450fed003e9a71886c88acf24fdbc2"}, {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/zai-org/GLM-4.5-Air", "chkhsh": "9ca2dd618e8afaf09731a7cf6e2105b373ba6a1821559f258b272fe83e6eb902"}, {"name": "glm4", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/zai-org/GLM-4.7-Flash", "chkhsh": "cdf5f35325780597efd76153d4d1c16778f766173908894c04afc20108536267"}, - {"name": "laguna", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/poolside/Laguna-XS.2", "chkhsh": "972da7b59cec44d1f0a490a86c96df53859e486e481563e5dddac155013d87ac"}, {"name": "minerva-7b", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/sapienzanlp/Minerva-7B-base-v1.0", "chkhsh": "1431a23e583c97432bc230bff598d103ddb5a1f89960c8f1d1051aaa944d0b35"}, {"name": "hunyuan", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-A13B-Instruct", "chkhsh": "7e57df22b1fe23a7b1e1c7f3dc4e3f96d43a4eb0836d0c6bdc3436d7b2f1c664"}, {"name": "hunyuan-dense", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/tencent/Hunyuan-4B-Instruct", "chkhsh": "bba3b3366b646dbdded5dbc42d59598b849371afc42f7beafa914afaa5b70aa6"}, diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index dd464835baec..054aa23ff8ca 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -496,6 +496,12 @@ struct llm_tokenizer_bpe : llm_tokenizer { "[!\"#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_`{|}~][A-Za-z]+|[^\\r\\n\\p{L}\\p{P}\\p{S}]?[\\p{L}\\p{M}]+| ?[\\p{P}\\p{S}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; + case LLAMA_VOCAB_PRE_TYPE_LAGUNA: + regex_exprs = { + "[^\\n]+|[\\n]+", + "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + }; + break; case LLAMA_VOCAB_PRE_TYPE_EXAONE_MOE: regex_exprs = { // original regex from tokenizer.json @@ -2331,10 +2337,13 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { pre_type = LLAMA_VOCAB_PRE_TYPE_GROK_2; clean_spaces = false; } else if ( - tokenizer_pre == "afmoe" || - tokenizer_pre == "laguna") { + tokenizer_pre == "afmoe") { pre_type = LLAMA_VOCAB_PRE_TYPE_AFMOE; clean_spaces = false; + } else if ( + tokenizer_pre == "laguna") { + pre_type = LLAMA_VOCAB_PRE_TYPE_LAGUNA; + clean_spaces = false; } else if ( tokenizer_pre == "minimax-m2") { pre_type = LLAMA_VOCAB_PRE_TYPE_MINIMAX_M2; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 707cd4bac4bf..b7c28926338b 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_LAGUNA = 56, }; struct LLM_KV; diff --git a/src/models/laguna.cpp b/src/models/laguna.cpp index ee37c68b86df..e274739395ea 100644 --- a/src/models/laguna.cpp +++ b/src/models/laguna.cpp @@ -14,11 +14,11 @@ void llama_model_laguna::load_arch_hparams(llama_model_loader & ml) { ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm); - // Laguna ships exactly one shared expert; the size lives in the - // expert_shared_feed_forward_length key. afmoe stores a count and derives - // size = count * n_ff_exp, but Laguna's shared and routed experts can in - // principle have different sizes, so we read the size directly. + // Laguna ships one shared expert and stores its size directly (routed and + // shared experts may differ), so read the size from expert_shared_feed_forward_length. + // The count is not in the config; default to 1 but read the key if present. hparams.n_expert_shared = 1; + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared, false); ml.get_key(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, hparams.n_ff_shexp); // Sliding-window attention is OPTIONAL. XS.2 is hybrid (full / SWA / SWA / From 61ee3eb9db31f8ac36435ffd85dd99014b1f0a75 Mon Sep 17 00:00:00 2001 From: Joe Rowell Date: Tue, 30 Jun 2026 14:53:31 +0100 Subject: [PATCH 7/7] ggml-cuda : fix flash-attn MMA GQA ncols2 dispatch for non-power-of-2 ratios The non-Volta MMA path in ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2 chose the GQA head-packing factor (ncols2) by threshold (gqa_ratio > 4 -> 8, > 2 -> 4, > 1 -> 2) rather than by divisibility. When gqa_ratio is not a multiple of the chosen factor, the kernel packs more query heads per KV head than actually share one, giving wrong KV indexing and corrupted output -- but only when the GQA optimization is active (padded K/V during decode), which is why prefill looked correct. E.g. 48 query / 8 KV heads (gqa_ratio = 6) hits 6 > 4 -> ncols2 = 8, packing 8 where only 6 share. Switch the non-Volta branch to divisibility (% 8 == 0 -> 8, % 4 == 0 -> 4, % 2 == 0 -> 2), matching the Volta branch above; gqa_ratio = 6 now correctly selects ncols2 = 2. Power-of-two ratios are unchanged. (cherry picked from commit c4aa4af5d0a816c9a3a806ecbb5cfaaa0f4558b3) --- ggml/src/ggml-cuda/fattn.cu | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 39aeb8cef362..2a10b5485768 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -89,16 +89,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con } } - if (use_gqa_opt && gqa_ratio > 4) { + if (use_gqa_opt && gqa_ratio % 8 == 0) { ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } - if (use_gqa_opt && gqa_ratio > 2) { + if (use_gqa_opt && gqa_ratio % 4 == 0) { ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } + if (use_gqa_opt && gqa_ratio % 2 == 0) { + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + return; + } + if constexpr (DKQ <= 256) { if (use_gqa_opt && gqa_ratio > 1) { ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst);