From e3cbc34552f9c53c703ed01f91911e1066aa5638 Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 14:01:14 -0700 Subject: [PATCH 1/8] LFM3: an XNNPACK export path, because ExecuTorch 1.5.1 has no LFM3 definition and its transformer cannot express one LiquidAI's LFM3-1.7B keeps LFM2's gated short convolutions and adds windowed attention layers, a second RoPE (theta 1e6 zero-tail partial on the global layers, 1e4 full on the windowed ones), a per-head sigmoid output gate, sandwich norms and a width-7 convolution. pipeline/lfm3_model.py builds it from ExecuTorch's own parts (RMSNorm, FeedForward, the KV cache and SDPA that export_llm swaps for its custom ops) and keeps the windowed layers' keys in a ring of window + prefill chunk slots. On the real checkpoint it matches the remote modeling_lfm3.py exactly on fp32 logits without a cache, and to 1.8e-4 with the custom ops, chunked prefill over the ring, 40 decode steps and a reset. - families/convert: the lfm3 family (XNNPACK only) and its tensor names - naming/eligibility: families exported ahead of the app's chat template (the app has none for LFM3 yet and refuses such files by name); the Kotlin port is unchanged - solve/hub: the fp32 teacher loads remote code for LFM3, downloaded at the pinned revision - transformers 5.22.1: LFM3's remote config does not load under 5.17.0 (KeyError: 'conv') Co-Authored-By: Claude Opus 5.5 --- pipeline/convert.py | 32 ++- pipeline/eligibility.py | 9 +- pipeline/export_with_codes.py | 13 +- pipeline/export_xnnpack.py | 15 +- pipeline/families.py | 83 +++++++ pipeline/hub.py | 5 + pipeline/lfm3_model.py | 336 +++++++++++++++++++++++++++ pipeline/manifest.py | 21 ++ pipeline/naming.py | 25 +- pipeline/solve.py | 22 +- requirements/export-xnnpack.txt | 7 +- tests/fixtures/lfm3-1.7b.config.json | 68 ++++++ tests/test_lfm3.py | 158 +++++++++++++ 13 files changed, 774 insertions(+), 20 deletions(-) create mode 100644 pipeline/lfm3_model.py create mode 100644 tests/fixtures/lfm3-1.7b.config.json create mode 100644 tests/test_lfm3.py diff --git a/pipeline/convert.py b/pipeline/convert.py index 0ddd055..9b165fb 100644 --- a/pipeline/convert.py +++ b/pipeline/convert.py @@ -69,9 +69,32 @@ "conv.out_proj.weight": "conv.out_proj.weight", "conv.in_proj.weight": "conv.in_proj.weight", } +# LFM3 (pipeline/lfm3_model.py): LFM2's operator and feed-forward names, Llama's attention +# names, plus a per-head output gate and the sandwich norms after each operator and each +# feed-forward. HF's post_operator_norm is post_attention_norm here for both layer kinds. +_LFM3_LAYER_KEYS = { + "self_attn.q_proj.weight": "attention.wq.weight", + "self_attn.k_proj.weight": "attention.wk.weight", + "self_attn.v_proj.weight": "attention.wv.weight", + "self_attn.o_proj.weight": "attention.wo.weight", + "self_attn.q_norm.weight": "attention.q_norm_fn.weight", + "self_attn.k_norm.weight": "attention.k_norm_fn.weight", + "self_attn.gate_proj.weight": "attention.gate_proj.weight", + "operator_norm.weight": "attention_norm.weight", + "post_operator_norm.weight": "post_attention_norm.weight", + "ffn_norm.weight": "ffn_norm.weight", + "post_ffn_norm.weight": "post_ffn_norm.weight", + "feed_forward.w1.weight": "feed_forward.w1.weight", + "feed_forward.w2.weight": "feed_forward.w2.weight", + "feed_forward.w3.weight": "feed_forward.w3.weight", + "conv.conv.weight": "conv.conv.weight", + "conv.out_proj.weight": "conv.out_proj.weight", + "conv.in_proj.weight": "conv.in_proj.weight", +} # One HF tensor that becomes three: the short convolution's fused input projection is stored # as B, C and x stacked on dim 0, and ExecuTorch's ShortConv reads them apart. -SPLIT_THREE = {"lfm2": ("conv.in_proj.weight", ("conv.B_proj.weight", "conv.C_proj.weight", "conv.x_proj.weight"))} +_IN_PROJ = ("conv.in_proj.weight", ("conv.B_proj.weight", "conv.C_proj.weight", "conv.x_proj.weight")) +SPLIT_THREE = {"lfm2": _IN_PROJ, "lfm3": _IN_PROJ} # Buffers some checkpoints carry that the model recomputes. _IGNORED = re.compile(r"(rotary_emb\.inv_freq|\.masked_bias|\.attn\.bias)$") @@ -83,12 +106,13 @@ # LFM2 shares none of the per-layer names, so its map replaces rather than extends the # common one; every layer is a short convolution or an attention block, never both. "lfm2": (_LFM2_LAYER_KEYS, False), + "lfm3": (_LFM3_LAYER_KEYS, False), } # Converters whose per-layer map stands alone instead of extending _LAYER_KEYS. -_STANDALONE = {"lfm2"} +_STANDALONE = {"lfm2", "lfm3"} # A conv layer and an attention layer carry different tensors, so the per-layer count that # the other families check cannot apply; LFM2 is checked by total instead. -_MIXED_LAYERS = {"lfm2"} +_MIXED_LAYERS = {"lfm2", "lfm3"} def unpermute(weight, n_heads: int): @@ -118,7 +142,7 @@ def _shards(model_dir: Path) -> list[Path]: def map_key(hf_key: str, converter: str) -> str | None: """ExecuTorch name for an HF tensor, None for ignorable buffers, KeyError if unknown.""" extra, _ = CONVERTERS[converter] - top = _LFM2_TOP_KEYS if converter == "lfm2" else _TOP_KEYS + top = _LFM2_TOP_KEYS if converter in ("lfm2", "lfm3") else _TOP_KEYS if hf_key in top: return top[hf_key] if _IGNORED.search(hf_key): diff --git a/pipeline/eligibility.py b/pipeline/eligibility.py index f2bac9d..2cc5010 100644 --- a/pipeline/eligibility.py +++ b/pipeline/eligibility.py @@ -20,6 +20,8 @@ # class but reads as no app family at all, so it is refused below rather than exported # into a file the app cannot render. "lfm2": {"lfm25"}, + # Ahead of the app (naming.AHEAD_OF_APP): it has no LFM3 template yet. + "lfm3": {"lfm3"}, } # What a release of each family is called. The architecture class alone is not enough: a # later generation can keep the class (a text-only "Qwen3.8" on Qwen3ForCausalLM would pass @@ -28,6 +30,7 @@ "qwen3": re.compile(r"qwen3(?![.\d])", re.IGNORECASE), "qwen2_5": re.compile(r"qwen2\.5(?![.\d])", re.IGNORECASE), "lfm2": re.compile(r"lfm2\.5(?![.\d])", re.IGNORECASE), + "lfm3": re.compile(r"lfm3(?![.\d])", re.IGNORECASE), "llama": re.compile(r"llama-?3\.2(?![.\d])|smollm2(?!\d)", re.IGNORECASE), "gemma3": re.compile(r"gemma-?3(?![.\dn])", re.IGNORECASE), "smollm3": re.compile(r"smollm3(?!\d)", re.IGNORECASE), @@ -37,7 +40,7 @@ # Qwen3 does this throughout. LFM2.5 does it unevenly: the 1.2B is LFM2.5-1.2B-Instruct # against LFM2.5-1.2B-Base, but the 2.6B is plain LFM2.5-2.6B against LFM2.5-2.6B-Base, so # reading the bare name as a base model gets that one backwards. -_CHAT_WITHOUT_A_SUFFIX = {"qwen3", "lfm2"} +_CHAT_WITHOUT_A_SUFFIX = {"qwen3", "lfm2", "lfm3"} @dataclass @@ -97,7 +100,7 @@ def name_reasons(model_id: str, settings: Settings) -> list[str]: elif nominal > settings.max_nominal_billions: reasons.append(f"named size {nominal:g}B is above {settings.max_nominal_billions:g}B") output_repo = naming.output_repo(model_id, settings.hub_org, settings.repo_suffix) - if naming.app_family(naming.app_model_name(output_repo, "x.pte")) is None: + if naming.pipeline_family(naming.app_model_name(output_repo, "x.pte")) is None: reasons.append(f"the app has no chat template for {name!r} (or refuses it by name)") return reasons @@ -131,7 +134,7 @@ def evaluate(source: SourceModel, settings: Settings) -> Verdict: reasons.append(f"{source.total_params:,} parameters is not below {settings.max_params:,}") output_repo = naming.output_repo(source.id, settings.hub_org, settings.repo_suffix) - app_token = naming.app_family(naming.app_model_name(output_repo, "x.pte")) + app_token = naming.pipeline_family(naming.app_model_name(output_repo, "x.pte")) if family is not None and app_token is None: # The app reads the chat template from the name, so a file it cannot place is a file # it refuses to load after the download. LFM2 without the .5 is the live case. diff --git a/pipeline/export_with_codes.py b/pipeline/export_with_codes.py index 3f3a55a..e8cfa83 100644 --- a/pipeline/export_with_codes.py +++ b/pipeline/export_with_codes.py @@ -1,7 +1,7 @@ """Run ``export_llm`` with the graph fixes a published file needs, and optionally with solved int4 codes in place of its own rounding. - python -m pipeline.export_with_codes --config [--codes ] [--lfm2-state-fix] + python -m pipeline.export_with_codes --config [--codes ] [--lfm2-state-fix] [--lfm3] A separate entry point, invoked as a subprocess like plain ``export_llm``, so the exporter keeps measuring a child's peak RSS and an out-of-memory export still fails as a process @@ -72,6 +72,11 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help="clear the short convolution's state at position zero (pipeline/lfm2_state.py)", ) + parser.add_argument( + "--lfm3", + action="store_true", + help="build LFM3 params with pipeline/lfm3_model.py, the definition ExecuTorch 1.5.1 lacks", + ) args = parser.parse_args(argv) import torch @@ -82,6 +87,12 @@ def main(argv: list[str] | None = None) -> int: lfm2_state.apply() print("applied the LFM2 short-convolution state fix") + if args.lfm3: + from pipeline import lfm3_model + + lfm3_model.apply() + print("applied the LFM3 model definition (pipeline/lfm3_model.py)") + if args.codes: from executorch.examples.models.llama.source_transformation import quantize as quantize_module diff --git a/pipeline/export_xnnpack.py b/pipeline/export_xnnpack.py index 2212784..598c387 100644 --- a/pipeline/export_xnnpack.py +++ b/pipeline/export_xnnpack.py @@ -75,7 +75,7 @@ def export_llm_config( backend: str = BACKEND, ) -> dict: extra = {} - if plan.model_class.startswith("lfm2"): + if plan.state_reset_at_zero: # Set only when the export applies the state fix, because the app reads it to decide # whether it can keep its cheap reset or must reopen the file between prompts. extra["get_state_reset_at_zero"] = 1 @@ -286,14 +286,21 @@ def run( # LFM2 needs its short-convolution state cleared in the graph, and solved codes need to # replace torchao's rounding; either sends the export through the wrapper, which is the # same export_llm with those two patches applied inside the subprocess. - state_fix = plan.model_class.startswith("lfm2") - if codes is not None or state_fix: + # LFM3's model is this repository's (pipeline/lfm3_model.py), so its export always goes + # through the wrapper too; its convolution clears its own state at position zero. + state_fix = plan.converter == "lfm2" + if codes is not None or state_fix or plan.lfm3: command = [sys.executable, "-m", "pipeline.export_with_codes", "--config", str(config_path)] if codes is not None: command += ["--codes", str(codes)] if state_fix: command += ["--lfm2-state-fix"] - print(f"==> export_llm (codes: {'gptq' if codes else 'round to nearest'}, state fix: {state_fix})") + if plan.lfm3: + command += ["--lfm3"] + print( + f"==> export_llm (codes: {'gptq' if codes else 'round to nearest'}, state fix: {state_fix}, " + f"lfm3: {plan.lfm3})" + ) else: command = [sys.executable, "-m", "executorch.extension.llm.export.export_llm", "--config", str(config_path)] print("==> export_llm") diff --git a/pipeline/families.py b/pipeline/families.py index f07cb51..ff6852f 100644 --- a/pipeline/families.py +++ b/pipeline/families.py @@ -65,6 +65,12 @@ def supports(self, backend: str) -> bool: "lowers to it segfaults in the 1.4.0 runtime at the first prefill" ) _LFM2_NO_QNN = "not in ExecuTorch 1.5.1's Qualcomm SUPPORTED_LLM_MODELS registry" +# LFM3 runs on pipeline/lfm3_model.py, a definition this repository adds to export_llm's +# transformer. The vendor paths each build their own model and have none for it, and the +# Vulkan recipe has no kernel for LFM2's short convolution, which LFM3 keeps. +_LFM3_NO_VULKAN = "the Vulkan delegate has no kernel for the short convolution (as for LFM2)" +_LFM3_NO_QNN = "not in ExecuTorch 1.5.1's Qualcomm SUPPORTED_LLM_MODELS registry" +_LFM3_NO_MTK = "no LFM3 definition in ExecuTorch 1.5.1's examples/mediatek" FAMILIES: tuple[Family, ...] = ( Family("qwen3", ("Qwen3ForCausalLM",)), @@ -76,6 +82,13 @@ def supports(self, backend: str) -> bool: ("Lfm2ForCausalLM",), {"vulkan": _LFM2_NO_VULKAN, "qnn": _LFM2_NO_QNN}, ), + # LFM3: LFM2's hybrid with windowed attention layers, two RoPEs, a per-head output gate + # and sandwich norms. XNNPACK only, through pipeline/lfm3_model.py. + Family( + "lfm3", + ("Lfm3ForCausalLM",), + {"vulkan": _LFM3_NO_VULKAN, "qnn": _LFM3_NO_QNN, "mtk": _LFM3_NO_MTK}, + ), Family("qwen2_5", ("Qwen2ForCausalLM",), {"mtk": _MTK_QWEN2_MASK}), Family("llama", ("LlamaForCausalLM",)), Family( @@ -334,6 +347,16 @@ class XnnpackPlan: params: dict converter: str # key into pipeline.convert.CONVERTERS + @property + def lfm3(self) -> bool: + """The model is built by pipeline/lfm3_model.py, which every process tracing it applies.""" + return self.converter == "lfm3" + + @property + def state_reset_at_zero(self) -> bool: + """A short-convolution hybrid whose export clears its state at position zero.""" + return self.converter in ("lfm2", "lfm3") + def xnnpack_plan(family: Family, config: dict) -> XnnpackPlan: """ExecuTorch params and model class for this checkpoint, or UnsupportedModel.""" @@ -341,6 +364,9 @@ def xnnpack_plan(family: Family, config: dict) -> XnnpackPlan: raise UnsupportedModel(family.unsupported["xnnpack"]) c = text_config(config) _check_common(c) + if family.key == "lfm3": + # Two RoPE thetas, so no top-level rope_theta for _common_params to read. + return _lfm3_plan(c) params = _common_params(c) if family.key == "qwen3": @@ -403,3 +429,60 @@ def xnnpack_plan(family: Family, config: dict) -> XnnpackPlan: return XnnpackPlan("llama3_2", params, "llama") raise UnsupportedModel(f"no XNNPACK recipe for family {family.key}") + + +def _lfm3_plan(c: dict) -> XnnpackPlan: + """LFM3's params for pipeline/lfm3_model.py, from the fields of ExecuTorch's ModelArgs. + + ``rope_theta`` is the global layers' and ``local_rope_theta`` the windowed layers' (the + field 1.5.1 declares for Gemma 3 and never reads); ``partial_rotary_factor`` applies to + the global layers only, as in the checkpoint's rope_parameters. The convolution width + rides in ``attention_kwargs``, which upstream passes to attention constructors and + ignores: without pipeline/lfm3_model.py the width-7 convolution weights do not fit + upstream's width-3 block, so the load fails instead of building another model. + """ + layer_types = c.get("layer_types") or [] + _require(bool(layer_types), "LFM3 config has no layer_types") + _require(len(layer_types) == int(c["num_hidden_layers"]), "layer_types does not match num_hidden_layers") + _require( + set(layer_types) <= {"conv", "full_attention", "sliding_attention"}, + f"unknown LFM3 layer types: {sorted(set(layer_types))}", + ) + _require("sliding_attention" in layer_types, "an LFM3 config without windowed layers is not validated") + _require(not c.get("conv_bias"), "LFM3 with a convolution bias is not supported") + _require(bool(c.get("tie_word_embeddings", True)), "LFM3 with untied embeddings is not supported") + _require(bool(c.get("use_sandwich_norm")), "LFM3 without sandwich norms is not validated") + window = c.get("sliding_window") + _require(isinstance(window, int) and window > 0, f"sliding_window {window!r}") + rope = c.get("rope_parameters") or {} + full, local = rope.get("full_attention") or {}, rope.get("sliding_attention") or {} + for name, block in (("full_attention", full), ("sliding_attention", local)): + _require(block.get("rope_type", "default") == "default", f"{name} RoPE {block.get('rope_type')!r}") + _require("rope_theta" in block, f"{name} has no rope_theta") + _require(float(local.get("partial_rotary_factor", 1.0)) == 1.0, "partial RoPE on the windowed layers") + n_heads = int(c["num_attention_heads"]) + dim = int(c["hidden_size"]) + params = { + "dim": dim, + "ffn_dim_multiplier": 1, + "hidden_dim": int(c["intermediate_size"]), + "n_heads": n_heads, + "head_dim": int(c.get("head_dim") or dim // n_heads), + "n_kv_heads": int(c.get("num_key_value_heads") or n_heads), + "n_layers": int(c["num_hidden_layers"]), + "norm_eps": float(c["norm_eps"]), + "rope_theta": float(full["rope_theta"]), + "local_rope_theta": float(local["rope_theta"]), + "partial_rotary_factor": float(full.get("partial_rotary_factor", 1.0)), + "vocab_size": int(c["vocab_size"]), + "use_hf_rope": True, + "use_qk_norm": True, + "qk_norm_before_rope": True, + "layer_types": list(layer_types), + "sliding_window": window, + "post_attention_norm": True, + "post_ffn_norm": True, + "attention_kwargs": {"conv_L_cache": int(c.get("conv_L_cache") or 3)}, + } + # model_class only picks export_llm's example directory; LFM2's is the nearest relative. + return XnnpackPlan("lfm2_5_1_2b", params, "lfm3") diff --git a/pipeline/hub.py b/pipeline/hub.py index f5b74ab..3dcee38 100644 --- a/pipeline/hub.py +++ b/pipeline/hub.py @@ -141,6 +141,11 @@ def download( from huggingface_hub import snapshot_download patterns = (WEIGHT_PATTERNS if weights else []) + SIDE_FILES + source.license_files + list(extra) + if source.config.get("auto_map"): + # A family transformers does not implement ships its modeling code (LFM3), which the + # solve's fp32 teacher loads with trust_remote_code. Only top-level .py files, at the + # same pinned revision as the weights; nothing here runs them unless asked to. + patterns.append("*.py") snapshot_download( source.id, revision=source.sha, diff --git a/pipeline/lfm3_model.py b/pipeline/lfm3_model.py new file mode 100644 index 0000000..bf63f86 --- /dev/null +++ b/pipeline/lfm3_model.py @@ -0,0 +1,336 @@ +"""LFM3 for ExecuTorch's ``export_llm``: the model definition ExecuTorch 1.5.1 does not have. + +LiquidAI's LFM3-1.7B (2026-10-23) is LFM2's hybrid grown three ways, none of which the +1.5.1 transformer can express (examples/models/llama/llama_transformer.py, model_args.py): + +* A third layer type. Of 24 layers, 13 are gated short convolutions, 6 attend globally and + 5 attend over a sliding window of 256 tokens. ``construct_transformer`` knows ``conv`` and + treats anything else as global attention, so the windowed layers would see everything. +* Two RoPEs. Global layers rotate a quarter of each head at theta 1e6 ("zero-tail" partial + RoPE: the first ``partial_rotary_factor * head_dim / 2`` frequencies follow the full head + dimension's progression and the rest are zero), windowed layers rotate all of it at theta + 1e4. ExecuTorch computes one table for the whole model. +* Per-layer extras: a sigmoid output gate per head (``gate_proj``, hidden -> n_heads; 1.5.1's + ``use_attn_o_gate`` is per element), RMSNorm after each operator and after each feed-forward + ("sandwich" norms; 1.5.1 declares ``post_attention_norm`` and never reads it), and a + width-7 convolution (``ShortConvBlock`` hard-codes 3). + +Everything else is LFM2's, and the parts are ExecuTorch's own where they exist: RMSNorm, +FeedForward, the KV cache and SDPA modules that ``export_llm`` swaps for its custom ops, the +ring-buffer bookkeeping it uses for Gemma 3. Reference: modeling_lfm3.py in the checkpoint +(``trust_remote_code``; transformers has no LFM3 yet). + +The windowed layers keep their keys in a ring, not a full-length cache: ``window + prefill +chunk`` slots, which is what a chunk of up to ``max_seq_len`` tokens needs to still see the +256 before it (ExecuTorch's own ``RingKVCache`` has ``2 * window`` and asserts the chunk fits +in it, which a 2048-token prefill does not). At 32k that is 2,304 slots instead of 32,768 for +5 of the 11 attending layers, and no window-squared mask anywhere. + +The short convolution's state is cleared in the graph at position zero, as for LFM2 +(pipeline/lfm2_state.py, and the export says so with ``get_state_reset_at_zero``). + +``apply()`` makes ``construct_transformer`` build this model when the params say LFM3 (a +``sliding_attention`` layer type), and leaves every other model to upstream. It must run in +any process that builds the model: ``pipeline.export_with_codes --lfm3`` and the solve. +""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import nn + +LAYER_TYPES = ("conv", "full_attention", "sliding_attention") + + +def is_lfm3(args) -> bool: + return bool(args.layer_types) and "sliding_attention" in args.layer_types + + +def rope_tables(head_dim: int, theta: float, partial: float, length: int) -> tuple[torch.Tensor, torch.Tensor]: + """cos and sin, [length, head_dim / 2], as Lfm3RotaryEmbedding computes them. + + The zero-tail layout (compute_default_rope_parameters): ``partial * head_dim // 2`` + frequencies over the full ``head_dim``, then zeros, so those dimensions get cos 1, sin 0. + """ + # device="cpu" throughout: Llama2Model builds the module under torch.device("meta"), and + # a non-persistent buffer is never loaded from the checkpoint, so a meta one stays empty. + angles = int(partial * head_dim) // 2 + inv = 1.0 / (theta ** (torch.arange(0, 2 * angles, 2, dtype=torch.float, device="cpu") / head_dim)) + inv = torch.cat((inv, torch.zeros(head_dim // 2 - angles, dtype=torch.float, device="cpu"))) + freqs = torch.outer(torch.arange(length, dtype=torch.float, device="cpu"), inv) + return freqs.cos(), freqs.sin() + + +def rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor: + """HF's rotate_half RoPE on ``x`` [B, S, H, D] with cos/sin [S, D/2].""" + cos = torch.cat((cos, cos), -1)[None, :, None, :] + sin = torch.cat((sin, sin), -1)[None, :, None, :] + half = x.shape[-1] // 2 + rotated = torch.cat((-x[..., half:], x[..., :half]), -1) + return x * cos + rotated * sin + + +class RingCache(nn.Module): + """K and V of one windowed layer in ``window + chunk`` slots, on ExecuTorch's custom ops. + + The bookkeeping is ExecuTorch's (attention.py CachePositionsManager and + _create_causal_mask_for_ring_buffer, as CustomRingKVCache uses them); only the size + differs. A position-zero call resets every slot to empty, so a new prompt never sees the + last one. Not a KVCache or CustomKVCache subclass on purpose: ``export_llm``'s + replace_kv_cache_with_custom_kv_cache would otherwise swap it for a plain cache. + """ + + def __init__(self, n_kv_heads: int, head_dim: int, window: int, chunk: int): + super().__init__() + from executorch.examples.models.llama.attention import CachePositionsManager + from executorch.extension.llm.custom_ops import custom_ops # noqa: F401 (llama:: ops) + + self.window = window + self.capacity = window + chunk + shape = (1, self.capacity, n_kv_heads, head_dim) + self.register_buffer("k_cache", torch.zeros(shape, dtype=torch.float32, device="cpu")) + self.register_buffer("v_cache", torch.zeros(shape, dtype=torch.float32, device="cpu")) + self.positions = CachePositionsManager(self.capacity) + + def attend(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor: + """q [B, S, H, D], k and v [B, S, KV, D] -> [B, S, H, D].""" + from executorch.examples.models.llama.attention import _create_causal_mask_for_ring_buffer + + seqlen = q.shape[1] + start = input_pos[0].item() + torch._check_is_size(start) + indices = self.positions.calculate_positions_and_update_indices(input_pos, seqlen).unsqueeze(0) + torch.ops.llama.update_cache_with_indices(k, self.k_cache, start, indices) + torch.ops.llama.update_cache_with_indices(v, self.v_cache, start, indices) + mask = _create_causal_mask_for_ring_buffer(self.positions.cache_positions, self.window, start, seqlen) + return torch.ops.llama.custom_sdpa(q, self.k_cache, self.v_cache, 0, mask, 0, False) + + +class Lfm3Attention(nn.Module): + """Lfm3Attention: QK RMSNorm before RoPE, a sigmoid gate per head, a window or not.""" + + def __init__(self, args, layer_id: int, sliding: bool): + super().__init__() + from executorch.examples.models.llama.attention import SDPA, KVCache + from executorch.examples.models.llama.norm import RMSNorm + + self.layer_id = layer_id + self.sliding = sliding + self.n_heads = args.n_heads + self.n_kv_heads = args.n_kv_heads + self.n_rep = self.n_heads // self.n_kv_heads + self.head_dim = args.head_dim + self.dim = args.dim + self.window = int(args.sliding_window) + self.max_context_len = args.max_context_len + self.use_kv_cache = args.use_kv_cache + self.enable_dynamic_shape = args.enable_dynamic_shape + q_dim, kv_dim = self.n_heads * self.head_dim, self.n_kv_heads * self.head_dim + self.wq = nn.Linear(args.dim, q_dim, bias=False) + self.wk = nn.Linear(args.dim, kv_dim, bias=False) + self.wv = nn.Linear(args.dim, kv_dim, bias=False) + self.wo = nn.Linear(q_dim, args.dim, bias=False) + self.gate_proj = nn.Linear(args.dim, self.n_heads, bias=False) + self.q_norm_fn = RMSNorm(self.head_dim, eps=args.norm_eps) + self.k_norm_fn = RMSNorm(self.head_dim, eps=args.norm_eps) + # Which of Rope's two tables this layer rotates with. + self.rope_index = Rope.LOCAL if sliding else Rope.GLOBAL + if self.use_kv_cache: + if sliding: + self.ring = RingCache(self.n_kv_heads, self.head_dim, self.window, args.max_seq_len) + else: + # ExecuTorch's own modules, so export_llm swaps them for CustomKVCache and + # SDPACustom (causal from start_pos) exactly as for every other model. + self.kv_cache = KVCache( + args.max_batch_size, + self.max_context_len, + self.n_kv_heads, + self.head_dim, + args.enable_dynamic_shape, + ) + self.SDPA = SDPA(q_dim, self.head_dim, self.n_rep, self.max_context_len) + + def forward(self, x: torch.Tensor, input_pos: torch.Tensor | None, freqs_cos, freqs_sin) -> torch.Tensor: + bsz, seqlen, _ = x.shape + q = self.q_norm_fn(self.wq(x).view(bsz, seqlen, self.n_heads, self.head_dim)) + k = self.k_norm_fn(self.wk(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim)) + v = self.wv(x).view(bsz, seqlen, self.n_kv_heads, self.head_dim) + cos, sin = freqs_cos[self.rope_index], freqs_sin[self.rope_index] + q, k = rotate(q, cos, sin), rotate(k, cos, sin) + + if not self.use_kv_cache: + out = self._attend_whole(q, k, v) + elif self.sliding: + out = self.ring.attend(q, k, v, input_pos) + else: + out = self._attend_cached(q, k, v, input_pos, bsz, seqlen) + + gate = torch.sigmoid(self.gate_proj(x)).unsqueeze(-1) + out = (out.reshape(bsz, seqlen, self.n_heads, self.head_dim) * gate).reshape(bsz, seqlen, -1) + return self.wo(out) + + def _attend_cached(self, q, k, v, input_pos, bsz, seqlen): + from executorch.examples.models.llama.attention import SDPA + + q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) + k, v = self.kv_cache.update(input_pos, k, v) + mask = None + if isinstance(self.SDPA, SDPA): + # Only the eager module reads a mask; SDPACustom is causal from start_pos. Built + # here rather than kept as a context-squared buffer per layer. + start = input_pos[0].item() + rows = start + torch.arange(seqlen, dtype=torch.long).view(-1, 1) + mask = torch.arange(self.max_context_len, dtype=torch.long).view(1, -1) <= rows + return self.SDPA(input_pos, q, k, v, bsz, seqlen, mask) + + def _attend_whole(self, q, k, v): + """No cache (the solve): the whole sequence at once, causal and maybe windowed.""" + seqlen = q.shape[1] + i = torch.arange(seqlen).view(-1, 1) + j = torch.arange(seqlen).view(1, -1) + mask = j <= i + if self.sliding: + mask = mask & (j > i - self.window) + q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2) + k = k.repeat_interleave(self.n_rep, dim=1) + v = v.repeat_interleave(self.n_rep, dim=1) + out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) + return out.transpose(1, 2) + + +class ShortConv(nn.Module): + """LFM2's gated short convolution, any width, its state cleared at position zero.""" + + def __init__(self, dim: int, width: int): + super().__init__() + self.width = width + self.B_proj = nn.Linear(dim, dim, bias=False) + self.C_proj = nn.Linear(dim, dim, bias=False) + self.x_proj = nn.Linear(dim, dim, bias=False) + self.out_proj = nn.Linear(dim, dim, bias=False) + self.conv = nn.Conv1d(dim, dim, kernel_size=width, padding=0, groups=dim, bias=False) + self.register_buffer("conv_state", torch.zeros(1, dim, width - 1, device="cpu")) + + def forward(self, x: torch.Tensor, input_pos: torch.Tensor | None) -> torch.Tensor: + B = self.B_proj(x).transpose(-1, -2) + C = self.C_proj(x).transpose(-1, -2) + Bx = B * self.x_proj(x).transpose(-1, -2) + if input_pos is None: + state = torch.zeros_like(self.conv_state) + else: + # min(position, 1): zeros for a prompt that starts at 0, the carried state for a + # continuation (pipeline/lfm2_state.py has why it is a clamp, not a comparison). + keep = torch.clamp(input_pos.reshape(-1)[:1], max=1).to(self.conv_state.dtype).view(1, 1, 1) + state = self.conv_state * keep + Bx = torch.cat([state, Bx], dim=-1) + with torch.no_grad(): + self.conv_state.copy_(Bx[..., -(self.width - 1) :]) + y = C * self.conv(Bx)[..., : x.size(1)] + return self.out_proj(y.transpose(-1, -2).contiguous()) + + +class Block(nn.Module): + """Lfm3DecoderLayer: operator (convolution or attention), feed-forward, sandwich norms.""" + + def __init__(self, args, layer_id: int, layer_type: str, conv_width: int, sandwich: bool): + super().__init__() + from executorch.examples.models.llama.feed_forward import FeedForward + from executorch.examples.models.llama.norm import RMSNorm + + if layer_type == "conv": + self.conv = ShortConv(args.dim, conv_width) + else: + self.attention = Lfm3Attention(args, layer_id, sliding=layer_type == "sliding_attention") + self.feed_forward = FeedForward(dim=args.dim, hidden_dim=args.hidden_dim) + # attention_norm / ffn_norm: the names ExecuTorch's blocks use (operator_norm in HF). + self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps) + self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps) + self.sandwich = sandwich + if sandwich: + self.post_attention_norm = RMSNorm(args.dim, eps=args.norm_eps) + self.post_ffn_norm = RMSNorm(args.dim, eps=args.norm_eps) + + def forward(self, x, freqs_cos=None, freqs_sin=None, attn_options=None): + input_pos = attn_options.get("input_pos") if attn_options else None + if hasattr(self, "conv"): + h = self.conv(self.attention_norm(x), input_pos) + else: + h = self.attention(self.attention_norm(x), input_pos, freqs_cos, freqs_sin) + if self.sandwich: + h = self.post_attention_norm(h) + h = x + h + ffn = self.feed_forward(self.ffn_norm(h)) + if self.sandwich: + ffn = self.post_ffn_norm(ffn) + return h + ffn, None + + +class Rope(nn.Module): + """Both RoPEs in one table, [2, context, head_dim / 2]: index GLOBAL or LOCAL. + + In the Transformer's RoPE slot, so the tables are stored once and sliced once per call + (Transformer.forward hands the same freqs to every layer, which picks its own row) rather + than once per attending layer: 11 copies would add ~176 MB to a 32k file. + """ + + GLOBAL, LOCAL = 0, 1 + + def __init__(self, args): + super().__init__() + self.use_kv_cache = args.use_kv_cache + self.max_context_len = args.max_context_len + tables = ( + rope_tables(args.head_dim, float(args.rope_theta), float(args.partial_rotary_factor), args.max_context_len), + rope_tables(args.head_dim, float(args.local_rope_theta), 1.0, args.max_context_len), + ) + self.register_buffer("freqs_cos", torch.stack([t[0] for t in tables]), persistent=False) + self.register_buffer("freqs_sin", torch.stack([t[1] for t in tables]), persistent=False) + + def get_freqs(self, input_pos, seq_len: int): + if not self.use_kv_cache or input_pos is None: + return self.freqs_cos[:, :seq_len], self.freqs_sin[:, :seq_len] + # As upstream's Rope.get_freqs with a dynamic shape. + start = input_pos[-1].item() + torch._check_is_size(start) + torch._check(start < self.max_context_len) + return self.freqs_cos.narrow(1, start, seq_len), self.freqs_sin.narrow(1, start, seq_len) + + +def construct(args): + from executorch.examples.models.llama.llama_transformer import Transformer + + unknown = set(args.layer_types) - set(LAYER_TYPES) + if unknown: + raise ValueError(f"LFM3 layer types {sorted(unknown)} are not implemented") + if len(args.layer_types) != args.n_layers: + raise ValueError(f"{len(args.layer_types)} layer types for {args.n_layers} layers") + extra = args.attention_kwargs or {} + conv_width = int(extra.get("conv_L_cache", 3)) + sandwich = bool(args.post_attention_norm and args.post_ffn_norm) + layers = nn.ModuleList( + Block(args, i, layer_type, conv_width, sandwich) for i, layer_type in enumerate(args.layer_types) + ) + return Transformer(args, layers, Rope(args)) + + +_APPLIED = False + + +def apply() -> None: + """Route ``construct_transformer`` to LFM3 for LFM3 params. Idempotent.""" + global _APPLIED + if _APPLIED: + return + from executorch.examples.models.llama import llama_transformer + from executorch.examples.models.llama import model as llama_model + + upstream = llama_transformer.construct_transformer + + def construct_transformer(model_args): + return construct(model_args) if is_lfm3(model_args) else upstream(model_args) + + llama_transformer.construct_transformer = construct_transformer + # model.py imported the name, so its binding is the one Llama2Model calls. + llama_model.construct_transformer = construct_transformer + _APPLIED = True diff --git a/pipeline/manifest.py b/pipeline/manifest.py index 3b8e993..5b1e7c2 100644 --- a/pipeline/manifest.py +++ b/pipeline/manifest.py @@ -163,6 +163,27 @@ def readme(repo_id: str, reports: list[dict], hub_tags: list[str], license_files "[openweights](https://github.com/alpharomercoma/openweights) Android app or any " f"ExecuTorch {reports[0]['toolchain']['executorch']} runtime.", "", + ] + if naming.ahead_of_app(naming.source_name(source["id"])): + # The app picks the chat template from the name and has none for this family yet, so + # it refuses these files until it gains one; the card says so instead of implying + # they run there today. + out += [ + "The openweights app has no chat template for this model family yet, so it does not " + "load these files until it gains one. Any ExecuTorch runtime with the LLM runner's " + "custom ops runs them today; render prompts with the model's own `chat_template.jinja`.", + "", + ] + if any(r["recipe"].get("converter") == "lfm3" for r in reports): + out += [ + "ExecuTorch has no LFM3 definition of its own yet. These files are traced from " + "[ExecuPack](https://github.com/ExperimentalMachines/execupack)'s " + "(`pipeline/lfm3_model.py`), which matches the checkpoint's own `modeling_lfm3.py` " + "on fp32 logits, with ExecuTorch's custom KV-cache and SDPA ops: the windowed layers " + "keep a ring of their last 256 tokens plus one prefill chunk instead of the full window.", + "", + ] + out += [ "## Files", "", f"Windows in this repo: {window_spans(reports)}. " diff --git a/pipeline/naming.py b/pipeline/naming.py index 7fc9220..e2ab9ae 100644 --- a/pipeline/naming.py +++ b/pipeline/naming.py @@ -32,6 +32,13 @@ # template for it; the app has had Qwen35Template since, and keeping the refusal meant this # repository skipped a family the app can run. APP_EXCLUDED = ("vl", "vision", "coder", "guard") + +# Families this pipeline exports before the app has a chat template for them. Not part of +# the Kotlin port: the app reads these names as no family at all and refuses the file +# (PromptTemplates.forModel returns null, loudly), so a published file waits for the +# template without breaking anything. Each needs its own exporter support first; LFM3 has +# pipeline/lfm3_model.py. +AHEAD_OF_APP = ("lfm3",) _KEPT_PUNCTUATION = "-_." _SIZE_HINT = re.compile(r"(? str | None: return None +def pipeline_family(name: str) -> str | None: + """The app's family for ``name``, or a family exported ahead of its template.""" + token = app_family(name) + if token is not None: + return token + n = normalise(name) + if any(excluded in n for excluded in APP_EXCLUDED): + return None + return next((token for token in AHEAD_OF_APP if token in n), None) + + +def ahead_of_app(name: str) -> bool: + """A family this pipeline exports but the app has no chat template for yet.""" + return app_family(name) is None and pipeline_family(name) is not None + + def app_backend(text: str) -> str: name = text.lower() if "xnnpack" in name: @@ -166,7 +189,7 @@ def check_app_rules(repo_id: str, weights_path: str, backend: str) -> list[str]: if detected != expected: problems.append(f"{repo_id}/{weights_path} reads as backend {detected!r}, not {expected!r}") installed = app_model_name(repo_id, weights_path) - if app_family(installed) is None: + if pipeline_family(installed) is None: problems.append(f"installed name {installed!r} matches no chat template the app knows") if app_size_hint(repo_name) is None: problems.append(f"repo name {repo_name!r} carries no size hint like 1.7B") diff --git a/pipeline/solve.py b/pipeline/solve.py index 1037f55..4fbf9c8 100644 --- a/pipeline/solve.py +++ b/pipeline/solve.py @@ -138,7 +138,9 @@ def dequantise(codes, scales, group: int = GROUP): ) -def eager_model(model_class: str, params: dict, checkpoint: Path, work_dir: Path, max_seq_len: int = 2048): +def eager_model( + model_class: str, params: dict, checkpoint: Path, work_dir: Path, max_seq_len: int = 2048, lfm3: bool = False +): """The module ``export_llm`` traces, in fp32 with no KV cache. Built through the same entry point the exporter uses, so the linears solved here are the @@ -156,6 +158,12 @@ def eager_model(model_class: str, params: dict, checkpoint: Path, work_dir: Path lfm2_state.apply() + if lfm3: + # The definition the export applies too (pipeline/lfm3_model.py); the solve has to + # solve the linears of the module that is lowered later. + from pipeline import lfm3_model + + lfm3_model.apply() params_path = work_dir / "solve-params.json" params_path.write_text(json.dumps(params)) cfg = LlmConfig() @@ -190,7 +198,7 @@ def int4_linears(model) -> dict: return found -def teacher(src_dir: Path): +def teacher(src_dir: Path, trust_remote_code: bool = False): """The fp32 Hugging Face model as a greedy continuation function, and the model itself. The replies are what GPTQ is asked to protect, so they come from the unquantised model, @@ -203,7 +211,11 @@ def teacher(src_dir: Path): import torch from transformers import AutoModelForCausalLM - model = AutoModelForCausalLM.from_pretrained(str(src_dir), dtype=torch.float32).eval() + # trust_remote_code only for a family transformers does not implement (LFM3: the + # checkpoint's modeling_lfm3.py), downloaded at the pinned revision with the weights. + model = AutoModelForCausalLM.from_pretrained( + str(src_dir), dtype=torch.float32, trust_remote_code=trust_remote_code + ).eval() # Several families set eos_token_id to a list of stop tokens. generate() takes a list # there but pad_token_id has to be one integer, so the first is the one to pad with. eos = model.config.eos_token_id @@ -360,7 +372,7 @@ def run( from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(str(src_dir)) - fp32, generate = teacher(src_dir) + fp32, generate = teacher(src_dir, trust_remote_code=plan.lfm3) rows = calibration.sequences(generate, tokenizer) # While the unquantised model is still loaded: what it would decide on the gate's # prompts, which is what the exported file has to agree with before anything publishes. @@ -383,7 +395,7 @@ def run( } print("==> building the eager model") - model = eager_model(plan.model_class, plan.params, checkpoint, work_dir) + model = eager_model(plan.model_class, plan.params, checkpoint, work_dir, lfm3=plan.lfm3) print(f"==> solving {len(int4_linears(model))} linears") started = time.time() diff --git a/requirements/export-xnnpack.txt b/requirements/export-xnnpack.txt index 519b60f..4bf1254 100644 --- a/requirements/export-xnnpack.txt +++ b/requirements/export-xnnpack.txt @@ -6,8 +6,11 @@ torchao==0.18.0 executorch==1.5.1 pytorch-tokenizers==1.5.0 # executorch.extension.llm.runner imports transformers at package import time; the smoke -# test needs that package for TextLLMRunner. -transformers==5.17.0 +# test needs that package for TextLLMRunner. 5.22.1, not 5.17.0: LFM3 has no transformers +# implementation, and its remote code (configuration_lfm3.py) fails to load under 5.17.0, +# where standardize_rope_params looks up a RoPE block for every layer type, "conv" included +# (KeyError: 'conv'). 5.22.1 loads it, and pipeline/lfm3_model.py matches it on fp32 logits. +transformers==5.22.1 huggingface_hub==1.31.0 safetensors==0.8.0 jinja2==3.1.6 diff --git a/tests/fixtures/lfm3-1.7b.config.json b/tests/fixtures/lfm3-1.7b.config.json new file mode 100644 index 0000000..99c8788 --- /dev/null +++ b/tests/fixtures/lfm3-1.7b.config.json @@ -0,0 +1,68 @@ +{ + "architectures": [ + "Lfm3ForCausalLM" + ], + "auto_map": { + "AutoConfig": "configuration_lfm3.Lfm3Config", + "AutoModel": "modeling_lfm3.Lfm3Model", + "AutoModelForCausalLM": "modeling_lfm3.Lfm3ForCausalLM" + }, + "bos_token_id": 124894, + "conv_L_cache": 7, + "conv_bias": false, + "dtype": "bfloat16", + "eos_token_id": 124900, + "head_dim": 128, + "hidden_size": 2048, + "intermediate_size": 7680, + "layer_types": [ + "conv", + "conv", + "full_attention", + "conv", + "sliding_attention", + "conv", + "full_attention", + "conv", + "sliding_attention", + "conv", + "full_attention", + "conv", + "sliding_attention", + "conv", + "full_attention", + "conv", + "sliding_attention", + "conv", + "full_attention", + "conv", + "sliding_attention", + "conv", + "full_attention", + "conv" + ], + "max_position_embeddings": 262144, + "model_type": "lfm3", + "norm_eps": 1e-05, + "num_attention_heads": 16, + "num_hidden_layers": 24, + "num_key_value_heads": 4, + "pad_token_id": 124893, + "rope_parameters": { + "full_attention": { + "partial_rotary_factor": 0.5, + "rope_theta": 1000000.0, + "rope_type": "default" + }, + "sliding_attention": { + "rope_theta": 10000, + "rope_type": "default" + } + }, + "sliding_window": 256, + "tie_word_embeddings": true, + "transformers_version": "5.12.1", + "use_cache": true, + "use_sandwich_norm": true, + "vocab_size": 128000 +} diff --git a/tests/test_lfm3.py b/tests/test_lfm3.py new file mode 100644 index 0000000..6a3c3d6 --- /dev/null +++ b/tests/test_lfm3.py @@ -0,0 +1,158 @@ +"""LFM3: the family, its params for pipeline/lfm3_model.py, the converter, and its names. + +tests/fixtures/lfm3-1.7b.config.json is LiquidAI/LFM3-1.7B's config.json at ac2586a3. The +model definition itself is checked against the checkpoint's modeling_lfm3.py on real +weights, which needs the 3.4 GB download and the remote code, so it is not a unit test: +docs/PLAN.md has the numbers (identical fp32 logits without a cache; 1.8e-4 with the custom +KV-cache ops, chunked prefill over the ring and 40 decode steps). +""" + +from __future__ import annotations + +import pytest +from conftest import load_json, make_source + +from pipeline import convert, eligibility, families, naming, settings + +LFM3_PARAMS = 1_728_801_536 + + +def lfm3_config(**overrides) -> dict: + config = load_json("lfm3-1.7b.config.json") + config.update(overrides) + return config + + +def test_lfm3_is_its_own_family_with_xnnpack_only(): + family = families.family_for(lfm3_config()) + assert family.key == "lfm3" + assert family.supports("xnnpack") + for backend in ("vulkan", "qnn", "mtk"): + assert not family.supports(backend) + + +def test_lfm3_plan_carries_both_ropes_the_window_and_the_convolution_width(): + plan = families.xnnpack_plan(families.family_for(lfm3_config()), lfm3_config()) + assert plan.converter == "lfm3" and plan.lfm3 and plan.state_reset_at_zero + p = plan.params + # Global layers: theta 1e6 on a zero-tail half of the rotary frequencies. + assert p["rope_theta"] == 1_000_000.0 and p["partial_rotary_factor"] == 0.5 + # Windowed layers: theta 1e4, fully rotated. + assert p["local_rope_theta"] == 10_000.0 + assert p["sliding_window"] == 256 + assert p["attention_kwargs"] == {"conv_L_cache": 7} + assert p["hidden_dim"] == 7680 and p["head_dim"] == 128 and p["n_kv_heads"] == 4 + assert p["layer_types"].count("conv") == 13 + assert p["layer_types"].count("full_attention") == 6 + assert p["layer_types"].count("sliding_attention") == 5 + assert p["post_attention_norm"] and p["post_ffn_norm"] + + +def test_lfm3_attends_on_eleven_of_twenty_four_layers(): + assert families.attending_layers(lfm3_config()) == 11 + + +@pytest.mark.parametrize( + "overrides, reason", + [ + ({"conv_bias": True}, "convolution bias"), + ({"use_sandwich_norm": False}, "sandwich"), + ({"tie_word_embeddings": False}, "untied"), + ({"sliding_window": None}, "sliding_window"), + ( + { + "rope_parameters": { + "full_attention": {"rope_type": "yarn", "rope_theta": 1e6, "factor": 4.0}, + "sliding_attention": {"rope_type": "default", "rope_theta": 1e4}, + } + }, + "RoPE", + ), + ], +) +def test_lfm3_refuses_what_the_definition_does_not_implement(overrides, reason): + with pytest.raises(families.UnsupportedModel, match=reason): + families.xnnpack_plan(families.family_for(lfm3_config()), lfm3_config(**overrides)) + + +# Every tensor name in LFM3-1.7B's model.safetensors (layer 0 is a convolution, layer 2 +# global attention, layer 4 windowed attention). +LFM3_KEYS = { + "model.embed_tokens.weight": "tok_embeddings.weight", + "model.embedding_norm.weight": "norm.weight", + "model.layers.0.conv.conv.weight": "layers.0.conv.conv.weight", + "model.layers.0.conv.in_proj.weight": "layers.0.conv.in_proj.weight", + "model.layers.0.conv.out_proj.weight": "layers.0.conv.out_proj.weight", + "model.layers.0.feed_forward.w1.weight": "layers.0.feed_forward.w1.weight", + "model.layers.0.feed_forward.w2.weight": "layers.0.feed_forward.w2.weight", + "model.layers.0.feed_forward.w3.weight": "layers.0.feed_forward.w3.weight", + "model.layers.0.ffn_norm.weight": "layers.0.ffn_norm.weight", + "model.layers.0.operator_norm.weight": "layers.0.attention_norm.weight", + "model.layers.0.post_ffn_norm.weight": "layers.0.post_ffn_norm.weight", + "model.layers.0.post_operator_norm.weight": "layers.0.post_attention_norm.weight", + "model.layers.2.self_attn.gate_proj.weight": "layers.2.attention.gate_proj.weight", + "model.layers.2.self_attn.k_norm.weight": "layers.2.attention.k_norm_fn.weight", + "model.layers.2.self_attn.k_proj.weight": "layers.2.attention.wk.weight", + "model.layers.2.self_attn.o_proj.weight": "layers.2.attention.wo.weight", + "model.layers.2.self_attn.q_norm.weight": "layers.2.attention.q_norm_fn.weight", + "model.layers.2.self_attn.q_proj.weight": "layers.2.attention.wq.weight", + "model.layers.4.self_attn.v_proj.weight": "layers.4.attention.wv.weight", +} + + +def test_every_lfm3_tensor_has_an_executorch_name(): + for hf, et in LFM3_KEYS.items(): + assert convert.map_key(hf, "lfm3") == et, hf + + +def test_lfm3_does_not_borrow_lfm2s_attention_names(): + # LFM2 says out_proj and q_layernorm; an LFM3 checkpoint carrying them is not LFM3. + for key in ("model.layers.2.self_attn.out_proj.weight", "model.layers.2.self_attn.q_layernorm.weight"): + with pytest.raises(KeyError): + convert.map_key(key, "lfm3") + + +def test_lfm3_splits_the_fused_convolution_projection_like_lfm2(): + assert convert.SPLIT_THREE["lfm3"] == convert.SPLIT_THREE["lfm2"] + + +def test_lfm3_is_exported_ahead_of_the_apps_template(): + name = naming.app_model_name("experimentalmachines/LFM3-1.7B-ExecuTorch", "xnnpack/LFM3-1.7B-8da4w-gptq-2k.pte") + # The Kotlin port stays the app's: no LFM3 template there yet. + assert naming.app_family(name) is None + assert naming.pipeline_family(name) == "lfm3" + assert naming.ahead_of_app("LFM3-1.7B") + assert not naming.ahead_of_app("LFM2.5-1.2B-Instruct") + repo, path = "experimentalmachines/LFM3-1.7B-ExecuTorch", "xnnpack/LFM3-1.7B-8da4w-gptq-32k.pte" + assert naming.check_app_rules(repo, path, "xnnpack") == [] + + +def test_the_vision_model_stays_out(): + assert naming.pipeline_family("LFM3-VL-2B-ExecuTorch") is None + + +def test_lfm3_chat_model_is_eligible_for_xnnpack_only(): + cfg = settings.load() + verdict = eligibility.evaluate(make_source("LiquidAI/LFM3-1.7B", lfm3_config(), total_params=LFM3_PARAMS), cfg) + assert verdict.reasons == [] + assert verdict.variant == "instruct" + assert verdict.backends["xnnpack"] is None + assert all(verdict.backends[b] for b in ("vulkan", "qnn", "mtk")) + + +def test_lfm3_base_is_a_base_checkpoint(): + cfg = settings.load() + verdict = eligibility.evaluate(make_source("LiquidAI/LFM3-1.7B-Base", lfm3_config(), total_params=LFM3_PARAMS), cfg) + assert any("base checkpoint" in r for r in verdict.reasons) + + +def test_rope_tables_leave_the_tail_unrotated(): + torch = pytest.importorskip("torch") + pytest.importorskip("executorch") + from pipeline import lfm3_model + + cos, sin = lfm3_model.rope_tables(128, 1e6, 0.5, 8) + assert cos.shape == (8, 64) + # 32 rotated frequencies from the full 128-dim progression, then 32 at zero. + assert torch.all(cos[:, 32:] == 1) and torch.all(sin[:, 32:] == 0) + assert torch.isclose(sin[1, 1], torch.sin(torch.tensor(1e6 ** (-2 / 128)))) From 05b6965172a9411797b558f1bd4dfebd6830ca5a Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 14:07:13 -0700 Subject: [PATCH 2/8] LFM3: run remote code only from LiquidAI's own repos, and record the definition as finding 42 A finetune with LFM3's auto_map would otherwise have its own modeling code executed by the solve's fp32 teacher. remote_code_allowed admits a trusted publisher whose every auto_map entry is a module in the pinned snapshot (no repo--module references), and the teacher loads with local_files_only. PLAN's XNNPACK table and research finding 42 carry the measurements against modeling_lfm3.py. Co-Authored-By: Claude Opus 5.5 --- docs/PLAN.md | 1 + docs/research/README.md | 1 + pipeline/hub.py | 23 ++++++++++++++++++++--- pipeline/solve.py | 10 ++++++++-- tests/test_lfm3.py | 11 +++++++++++ 5 files changed, 41 insertions(+), 5 deletions(-) diff --git a/docs/PLAN.md b/docs/PLAN.md index 234c906..9afeb07 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -107,6 +107,7 @@ converted to ExecuTorch's checkpoint layout by `pipeline/convert.py`. | Qwen2.5 | `Qwen2ForCausalLM` | yes | | Llama 3.2, SmolLM2 | `LlamaForCausalLM` | yes (q/k un-permuted for Meta RoPE) | | Gemma 3, SmolLM3 | `Gemma3ForCausalLM`, `SmolLM3ForCausalLM` | not yet: not in `export_llm`'s model list; needs a validated path (optimum-executorch or params support) | +| LFM3 | `Lfm3ForCausalLM` (remote code) | through `pipeline/lfm3_model.py`: ExecuTorch has no definition, and 1.5.1's transformer cannot express windowed layers, two RoPEs, a per-head gate or sandwich norms (finding 42) | Smoke test: the Linux wheel ships `TextLLMRunner`, the same C++ runner the app calls through `LlmModule`. Greedy generation of a short prompt must produce non-degenerate text diff --git a/docs/research/README.md b/docs/research/README.md index d876fc6..a787be3 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -67,3 +67,4 @@ Findings from building and running this pipeline, each kept with its evidence. C | 39 | 2026-10-04 | MediaTek | At 16k, LFM2.5 built once no chunk held more than one attention layer; a 4-chunk build with two in some chunks did not. LFM2.5-1.2B-Instruct (attention at layers 2, 5, 8, 10, 12, 14 of 16) at 16k in 4 chunks lost MediaTek's local compiler service while compiling chunk 2, after calibration had finished; its heretic finetune, the same architecture, in 8 chunks (two layers, at most one attention layer each) built and was published: 3,235 s, peak 14,361,923,584 B in use on a 16 vCPU runner. LFM2.5-2.6B (attention at 2, 5, 9, 13, 17, 21, 24, 27 of 30) needs 10 chunks for one attention layer each, and its heretic finetune built at 16k that way: 5,891 s, peak 26,554,892,288 B. Two successes and one failure, so one attention layer per chunk is a working heuristic for these architectures; that it is necessary, and why the compiler service died, are not shown. 32k was started for all three LFM2.5 models (8 and 10 chunks) and cancelled mid-calibration for budget. | measured + inference | run 35994412279 (4 chunks, failed at chunk 2), run 37171790063 (8 chunks, published), run 37176914465 (2.6B-heretic, 10 chunks, 16k published, 32k cancelled); `mtk/mt6991/export-report-16k.json` in `experimentalmachines/LFM2.5-1.2B-Instruct-heretic-ExecuTorch` and `…/LFM2.5-2.6B-heretic-ExecuTorch` | Dispatch 16k with `max_chunks` at the smallest count that leaves one attention layer per chunk (8 for the 1.2B, 10 for the 2.6B); `mtk.max_chunks` stays 4 for the windows that build at it. The successful builds peaked at 13.4 and 24.7 GiB; what killed the failed run's compiler service is not known. LFM2.5-2.6B (base) at 16k and every 32k remain unbuilt. | | 40 | 2026-10-07 | Runner | The Namespace profile `namespace-profile-execupack` has 4 x86_64 CPUs, MemTotal 16,438,740 kB (15.7 GiB), a 101 GB overlay disk shared by / and /mnt, and no swap: `swapon` on a swap file is refused ("Operation not permitted"), so the 24 to 96 GiB the Blacksmith jobs added cannot be had. Against `sizing.host_need_bytes` and `export_mtk.calibration_bytes` that leaves: Vulkan up to 8k for the 0.1B to 1.2B models (Qwen3-0.6B, Qwen2.5-0.5B, SmolLM2, Llama-3.2-1B) and up to 16k for LFM2.5-1.2B, 2k-4k for Qwen2.5-1.5B, Qwen3-1.7B and LFM2.5-2.6B, nothing at 3B and above; XNNPACK up to 8k for the sub-1B models, 2k-4k for Llama-3.2-1B and LFM2.5-1.2B, nothing from 1.5B up; MediaTek Qwen3-0.6B at 512 only, Llama-3.2-1B to 2k, SmolLM2-135M to 4k, and no LFM2.5 at any window by the current estimate (about 17.4 GiB for the 1.2B). Of the windows built before, every 32k window and every 16k except LFM2.5-1.2B's on Vulkan now fall outside it, as do the MediaTek 16k builds of finding 39. That last is the estimate's call, not a measured limit: `calibration_bytes` puts the 1.2B at about 17.4 GiB from the 14.4 to 15.7 bytes per parameter measured on 4-chunk builds, while the 8-chunk 16k build peaked at 13.4 GiB, which this RAM would hold; refitting the estimate for more chunks could bring the 1.2B back. | measured + estimate | CI run 37606922033 (the runner step); `tests/test_namespace_runner.py` pins the tier and the windows; the coverage is the sizing model's, not exports run on the profile | `config/pipeline.yaml` has the one tier with swap_gib 0; `prepare-host.sh` carries on without swap where it is refused; a model no window fits stops at the targets job instead of failing an empty matrix. The wider windows need a larger Namespace profile added as a second tier. QNN has no tier: its export peaked at 15.6 GB of RSS for Qwen3-0.6B (finding 8), at the edge of this profile. | | 41 | 2026-10-07 | Runner | Modal runs the XNNPACK and Vulkan exports and the solve. A Sandbox may ask for at most 344064 MiB (336 GiB) and 64 physical cores: larger requests are refused at creation with InvalidError ("memory request must be <= 344064 MiB", "CPU request must be <= 64000 mCPU"), so every window ever built fits, Qwen3-4B at 32k (about 134 GiB) included. Inside a Sandbox /proc/meminfo shows the host's memory (680 GiB to 1.3 TiB), not the request, so the export's own memory gate passes there and the request computed from `sizing.host_need_bytes` is what sizes the run; nproc does reflect the request. SmolLM2-135M at 2k: the Vulkan file came out byte-identical to the published one (sha256 0de5a249...), peaking at 1.9 GiB of a 6.1 GiB request; the XNNPACK file exported and passed the smoke test ("The capital of France is Paris") in the same Sandbox. Both were slower than on Blacksmith: 361 s against 145 s for Vulkan and 1,308 s against 348 s for XNNPACK, though the published files were built with ExecuTorch 1.4.0 and these with 1.5.1, so the runner is not the only difference. | measured | `pipeline/remote.py` runs from this workstation, 2026-10-07 (the sandbox limits probed by request; the two exports with their export reports); the published reports in `experimentalmachines/SmolLM2-135M-Instruct-ExecuTorch` | xnnpack and vulkan runner_tiers are one `modal` tier at Modal's ceiling, each window's memory_mib is its need times modal.memory_margin, and the XNNPACK export, smoke test and decision gate share one Sandbox, so the separate verify job is gone. Per-export time is the open cost question: modal.cpu is 8 cores, and whether more cores or a 1.5.1-to-1.4.0 difference explains the gap is not measured. | +| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. `sizing` still counts the 5 windowed layers at a full-window KV cache (about 0.6 GB over at 32k): the phone estimate is pessimistic, the host one conservative. | diff --git a/pipeline/hub.py b/pipeline/hub.py index 3dcee38..c84faa5 100644 --- a/pipeline/hub.py +++ b/pipeline/hub.py @@ -21,6 +21,23 @@ "README.md", ] LICENSE_PREFIXES = ("license", "use_policy", "notice") +# Publishers whose own modeling code the solve may run (trust_remote_code), for a family +# transformers does not implement: LiquidAI's LFM3. A finetune elsewhere with the same +# auto_map is refused rather than having its code executed on the runner. +TRUSTED_REMOTE_CODE_ORGS = ("LiquidAI",) + + +def remote_code_allowed(source: SourceModel) -> bool: + """The repo is a trusted publisher's, and every auto_map entry names a module in it. + + A ``repo--module.Class`` entry would make transformers fetch code from another repo, + outside the pinned snapshot; those are refused. + """ + auto_map = source.config.get("auto_map") or {} + if not auto_map or source.id.split("/", 1)[0] not in TRUSTED_REMOTE_CODE_ORGS: + return False + refs = [v for value in auto_map.values() for v in (value if isinstance(value, list) else [value]) if v] + return all("--" not in ref and "/" not in ref for ref in refs) @dataclass @@ -141,10 +158,10 @@ def download( from huggingface_hub import snapshot_download patterns = (WEIGHT_PATTERNS if weights else []) + SIDE_FILES + source.license_files + list(extra) - if source.config.get("auto_map"): + if remote_code_allowed(source): # A family transformers does not implement ships its modeling code (LFM3), which the - # solve's fp32 teacher loads with trust_remote_code. Only top-level .py files, at the - # same pinned revision as the weights; nothing here runs them unless asked to. + # solve's fp32 teacher loads with trust_remote_code. Only from a trusted publisher, + # at the same pinned revision as the weights; nothing here runs them. patterns.append("*.py") snapshot_download( source.id, diff --git a/pipeline/solve.py b/pipeline/solve.py index 4fbf9c8..37248ad 100644 --- a/pipeline/solve.py +++ b/pipeline/solve.py @@ -212,9 +212,11 @@ def teacher(src_dir: Path, trust_remote_code: bool = False): from transformers import AutoModelForCausalLM # trust_remote_code only for a family transformers does not implement (LFM3: the - # checkpoint's modeling_lfm3.py), downloaded at the pinned revision with the weights. + # checkpoint's modeling_lfm3.py) from a trusted publisher (hub.remote_code_allowed), + # downloaded at the pinned revision with the weights; local_files_only so nothing else + # is fetched while loading it. model = AutoModelForCausalLM.from_pretrained( - str(src_dir), dtype=torch.float32, trust_remote_code=trust_remote_code + str(src_dir), dtype=torch.float32, trust_remote_code=trust_remote_code, local_files_only=True ).eval() # Several families set eos_token_id to a list of stop tokens. generate() takes a list # there but pad_token_id has to be one integer, so the first is the one to pad with. @@ -372,6 +374,10 @@ def run( from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(str(src_dir)) + if plan.lfm3 and not hub.remote_code_allowed(source): + raise ExportError( + f"{model_id} needs its own modeling code, which only {hub.TRUSTED_REMOTE_CODE_ORGS} repos may run here" + ) fp32, generate = teacher(src_dir, trust_remote_code=plan.lfm3) rows = calibration.sequences(generate, tokenizer) # While the unquantised model is still loaded: what it would decide on the gate's diff --git a/tests/test_lfm3.py b/tests/test_lfm3.py index 6a3c3d6..2f341f4 100644 --- a/tests/test_lfm3.py +++ b/tests/test_lfm3.py @@ -156,3 +156,14 @@ def test_rope_tables_leave_the_tail_unrotated(): # 32 rotated frequencies from the full 128-dim progression, then 32 at zero. assert torch.all(cos[:, 32:] == 1) and torch.all(sin[:, 32:] == 0) assert torch.isclose(sin[1, 1], torch.sin(torch.tensor(1e6 ** (-2 / 128)))) + + +def test_remote_code_runs_only_for_a_trusted_publisher_and_local_modules(): + from pipeline import hub + + official = make_source("LiquidAI/LFM3-1.7B", lfm3_config(), total_params=LFM3_PARAMS) + assert hub.remote_code_allowed(official) + finetune = make_source("someone/LFM3-1.7B-finetune", lfm3_config(), total_params=LFM3_PARAMS) + assert not hub.remote_code_allowed(finetune) + elsewhere = lfm3_config(auto_map={"AutoModelForCausalLM": "other/repo--modeling_lfm3.Lfm3ForCausalLM"}) + assert not hub.remote_code_allowed(make_source("LiquidAI/LFM3-1.7B", elsewhere, total_params=LFM3_PARAMS)) From 6ee6b3602950b947906414ac6931f0732a2a7578 Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 14:41:06 -0700 Subject: [PATCH 3/8] gate: ask with the reasoning switched off, because a thinking model's first token is not its decision The gate reads one token. LFM3's template opens in the generation prompt, so that token was the first word of the reasoning ("The" or "We", fp32 at 0.52 to 0.73), and the 4-bit LFM3 files failed on quiet rows where they opened the reasoning with the other word and called nothing. Qwen3's gates were blind the other way: at 0.9999 on every row. With enable_thinking=False the prompt ends in and the next token is the answer or (LFM3 fp32: at 1.000 on all 12 search rows). Templates without the switch render as before; calibration is unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/research/README.md | 2 +- pipeline/calibration.py | 13 ++++++++++--- pipeline/gate.py | 18 +++++++++++++++--- 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/docs/research/README.md b/docs/research/README.md index a787be3..dfa451b 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -67,4 +67,4 @@ Findings from building and running this pipeline, each kept with its evidence. C | 39 | 2026-10-04 | MediaTek | At 16k, LFM2.5 built once no chunk held more than one attention layer; a 4-chunk build with two in some chunks did not. LFM2.5-1.2B-Instruct (attention at layers 2, 5, 8, 10, 12, 14 of 16) at 16k in 4 chunks lost MediaTek's local compiler service while compiling chunk 2, after calibration had finished; its heretic finetune, the same architecture, in 8 chunks (two layers, at most one attention layer each) built and was published: 3,235 s, peak 14,361,923,584 B in use on a 16 vCPU runner. LFM2.5-2.6B (attention at 2, 5, 9, 13, 17, 21, 24, 27 of 30) needs 10 chunks for one attention layer each, and its heretic finetune built at 16k that way: 5,891 s, peak 26,554,892,288 B. Two successes and one failure, so one attention layer per chunk is a working heuristic for these architectures; that it is necessary, and why the compiler service died, are not shown. 32k was started for all three LFM2.5 models (8 and 10 chunks) and cancelled mid-calibration for budget. | measured + inference | run 35994412279 (4 chunks, failed at chunk 2), run 37171790063 (8 chunks, published), run 37176914465 (2.6B-heretic, 10 chunks, 16k published, 32k cancelled); `mtk/mt6991/export-report-16k.json` in `experimentalmachines/LFM2.5-1.2B-Instruct-heretic-ExecuTorch` and `…/LFM2.5-2.6B-heretic-ExecuTorch` | Dispatch 16k with `max_chunks` at the smallest count that leaves one attention layer per chunk (8 for the 1.2B, 10 for the 2.6B); `mtk.max_chunks` stays 4 for the windows that build at it. The successful builds peaked at 13.4 and 24.7 GiB; what killed the failed run's compiler service is not known. LFM2.5-2.6B (base) at 16k and every 32k remain unbuilt. | | 40 | 2026-10-07 | Runner | The Namespace profile `namespace-profile-execupack` has 4 x86_64 CPUs, MemTotal 16,438,740 kB (15.7 GiB), a 101 GB overlay disk shared by / and /mnt, and no swap: `swapon` on a swap file is refused ("Operation not permitted"), so the 24 to 96 GiB the Blacksmith jobs added cannot be had. Against `sizing.host_need_bytes` and `export_mtk.calibration_bytes` that leaves: Vulkan up to 8k for the 0.1B to 1.2B models (Qwen3-0.6B, Qwen2.5-0.5B, SmolLM2, Llama-3.2-1B) and up to 16k for LFM2.5-1.2B, 2k-4k for Qwen2.5-1.5B, Qwen3-1.7B and LFM2.5-2.6B, nothing at 3B and above; XNNPACK up to 8k for the sub-1B models, 2k-4k for Llama-3.2-1B and LFM2.5-1.2B, nothing from 1.5B up; MediaTek Qwen3-0.6B at 512 only, Llama-3.2-1B to 2k, SmolLM2-135M to 4k, and no LFM2.5 at any window by the current estimate (about 17.4 GiB for the 1.2B). Of the windows built before, every 32k window and every 16k except LFM2.5-1.2B's on Vulkan now fall outside it, as do the MediaTek 16k builds of finding 39. That last is the estimate's call, not a measured limit: `calibration_bytes` puts the 1.2B at about 17.4 GiB from the 14.4 to 15.7 bytes per parameter measured on 4-chunk builds, while the 8-chunk 16k build peaked at 13.4 GiB, which this RAM would hold; refitting the estimate for more chunks could bring the 1.2B back. | measured + estimate | CI run 37606922033 (the runner step); `tests/test_namespace_runner.py` pins the tier and the windows; the coverage is the sizing model's, not exports run on the profile | `config/pipeline.yaml` has the one tier with swap_gib 0; `prepare-host.sh` carries on without swap where it is refused; a model no window fits stops at the targets job instead of failing an empty matrix. The wider windows need a larger Namespace profile added as a second tier. QNN has no tier: its export peaked at 15.6 GB of RSS for Qwen3-0.6B (finding 8), at the edge of this profile. | | 41 | 2026-10-07 | Runner | Modal runs the XNNPACK and Vulkan exports and the solve. A Sandbox may ask for at most 344064 MiB (336 GiB) and 64 physical cores: larger requests are refused at creation with InvalidError ("memory request must be <= 344064 MiB", "CPU request must be <= 64000 mCPU"), so every window ever built fits, Qwen3-4B at 32k (about 134 GiB) included. Inside a Sandbox /proc/meminfo shows the host's memory (680 GiB to 1.3 TiB), not the request, so the export's own memory gate passes there and the request computed from `sizing.host_need_bytes` is what sizes the run; nproc does reflect the request. SmolLM2-135M at 2k: the Vulkan file came out byte-identical to the published one (sha256 0de5a249...), peaking at 1.9 GiB of a 6.1 GiB request; the XNNPACK file exported and passed the smoke test ("The capital of France is Paris") in the same Sandbox. Both were slower than on Blacksmith: 361 s against 145 s for Vulkan and 1,308 s against 348 s for XNNPACK, though the published files were built with ExecuTorch 1.4.0 and these with 1.5.1, so the runner is not the only difference. | measured | `pipeline/remote.py` runs from this workstation, 2026-10-07 (the sandbox limits probed by request; the two exports with their export reports); the published reports in `experimentalmachines/SmolLM2-135M-Instruct-ExecuTorch` | xnnpack and vulkan runner_tiers are one `modal` tier at Modal's ceiling, each window's memory_mib is its need times modal.memory_margin, and the XNNPACK export, smoke test and decision gate share one Sandbox, so the separate verify job is gone. Per-export time is the open cost question: modal.cpu is 8 cores, and whether more cores or a 1.5.1-to-1.4.0 difference explains the gap is not measured. | -| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. `sizing` still counts the 5 windowed layers at a full-window KV cache (about 0.6 GB over at 32k): the phone estimate is pessimistic, the host one conservative. | +| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. `sizing` still counts the 5 windowed layers at a full-window KV cache (about 0.6 GB over at 32k): the phone estimate is pessimistic, the host one conservative. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. | diff --git a/pipeline/calibration.py b/pipeline/calibration.py index a4c255b..c2333c7 100644 --- a/pipeline/calibration.py +++ b/pipeline/calibration.py @@ -265,10 +265,17 @@ def render(tokenizer, prompt: str) -> str: ) -def render_app(tokenizer, user_turn: str) -> str: - """The same, under the app's system text, tool schema and opening exchange.""" +def render_app(tokenizer, user_turn: str, thinking: bool = True) -> str: + """The same, under the app's system text, tool schema and opening exchange. + + ``thinking=False`` asks a reasoning template to close its think block in the generation + prompt (``enable_thinking``, which Qwen3's and LFM3's templates read and the others + ignore), so the next token is the answer or the tool call itself. Calibration leaves it + at the template's default and renders exactly as before. + """ messages = [{"role": "system", "content": APP_SYSTEM}, *APP_PRIMER, {"role": "user", "content": user_turn}] - return tokenizer.apply_chat_template(messages, tools=APP_TOOLS, tokenize=False, add_generation_prompt=True) + extra = {} if thinking else {"enable_thinking": False} + return tokenizer.apply_chat_template(messages, tools=APP_TOOLS, tokenize=False, add_generation_prompt=True, **extra) def app_head(tokenizer) -> str: diff --git a/pipeline/gate.py b/pipeline/gate.py index dbce4a5..ed345ee 100644 --- a/pipeline/gate.py +++ b/pipeline/gate.py @@ -85,11 +85,23 @@ def prompts(tokenizer) -> dict[str, str]: - """Every gate question in the app's own prompt, ready for the assistant's turn.""" + """Every gate question in the app's own prompt, ready for the assistant's turn. + + With the template's reasoning switched off. The gate reads one token, so that token has + to be the decision, and a reasoning model's first token is not: Qwen3's template lets it + open ````, which every published Qwen3 gate graded at 0.9999 on every row, and + LFM3's opens the block itself, leaving the first word of the reasoning ("We", "The"), a + near tie that a 4-bit file broke the other way on two quiet rows without calling + anything (2026-10-31). With the block closed in the prompt, the next token is the answer + or the tool call, for every family; templates without the switch render as before. + """ from pipeline import calibration - out = {q: calibration.render_app(tokenizer, f"{q}\n\n{calibration.TRAILER.format(subject=s)}") for q, s in SEARCH} - out.update({q: calibration.render_app(tokenizer, q) for q in QUIET}) + def app(turn: str) -> str: + return calibration.render_app(tokenizer, turn, thinking=False) + + out = {q: app(f"{q}\n\n{calibration.TRAILER.format(subject=s)}") for q, s in SEARCH} + out.update({q: app(q) for q in QUIET}) return out From eba9368d1bf1ec48fe89ba5660a499025d4761e4 Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 14:46:14 -0700 Subject: [PATCH 4/8] sizing: an LFM3 window's KV cache is its global layers plus a fixed ring, not eleven full caches LFM3's five sliding-window layers keep window + prefill chunk slots (pipeline/lfm3_model.py) at any context, so the first reports put the 32k cache at 1.48 GB where it is 0.85. The per-token figure now counts the six full caches (24,576 B), the ring is its own report field (kv_cache_ring_bytes, 47 MB), and the card states both. Only LFM3 is sized this way: Gemma 3's configs name sliding layers too, and nothing here rings them. correct-reports fixes the published reports' figures in place, refusing any it cannot reproduce from the old sizing. Co-Authored-By: Claude Opus 5.5 --- pipeline/__main__.py | 3 +- pipeline/correct.py | 68 +++++++++++++++++++++++++++++++++++--- pipeline/export_xnnpack.py | 5 ++- pipeline/families.py | 10 ++++++ pipeline/manifest.py | 10 ++++-- pipeline/sizing.py | 35 ++++++++++++++++++-- tests/test_lfm3.py | 64 +++++++++++++++++++++++++++++++++++ 7 files changed, 184 insertions(+), 11 deletions(-) diff --git a/pipeline/__main__.py b/pipeline/__main__.py index 4c6e33a..b7b28c0 100644 --- a/pipeline/__main__.py +++ b/pipeline/__main__.py @@ -563,7 +563,8 @@ def main(argv: list[str] | None = None) -> int: watch.set_defaults(func=_watch) fix = commands.add_parser( - "correct-reports", help="rewrite fp32 reports' recipe and sizing fields on the Hub; never touches a .pte" + "correct-reports", + help="rewrite fp32 reports' recipe fields and windowed models' KV sizing on the Hub; never touches a .pte", ) fix.add_argument( "repos", nargs="+", help="output repos, e.g. experimentalmachines/SmolLM2-360M-Instruct-ExecuTorch" diff --git a/pipeline/correct.py b/pipeline/correct.py index cc8e652..22fc1b8 100644 --- a/pipeline/correct.py +++ b/pipeline/correct.py @@ -88,6 +88,63 @@ def corrected(report: dict, arch: sizing.Architecture, cfg, commit: str, today: return new +KV_FIELDS = ( + "window.kv_cache_bytes_per_token", + "window.kv_cache_ring_bytes", + "window.device_resident_bytes", + "window.fits_phone_budget", + "window.table[].kv_cache_bytes", + "window.table[].device_resident_bytes", + "window.table[].fits_device", +) + + +def corrected_kv(report: dict, arch: sizing.Architecture, cfg, commit: str, today: str) -> dict | None: + """A windowed model's KV figures with the sliding layers counted as the ring they are. + + LFM3's first reports counted all 11 attending layers at the full window, where 5 keep a + ring of window + prefill chunk slots (pipeline/lfm3_model.py); at 32k that put the cache + at 1.48 GB against 0.85. Like the fp32 correction, the old figures must reproduce exactly + from the full-cache sizing before anything is replaced. The export-time host estimates + (``export_peak_bytes``, ``estimates``) are a record of what the build was sized with and + stay as they are. + """ + recipe = report.get("recipe") or {} + if report.get("backend") != "xnnpack" or not arch.windowed_layers: + return None + window = report["window"] + if "kv_cache_ring_bytes" in window: + return None + full = dataclasses.replace(arch, windowed_layers=0, window=0) + qmode = recipe.get("qmode", "8da4w").split("-")[0] + overhead = cfg.runtime_overhead_bytes + if window["kv_cache_bytes_per_token"] != sizing.kv_bytes_per_token(full): + raise CannotCorrect(f"{report['files'][0]['path']}: per-token KV is not the full-cache figure") + for row in (window, *window["table"]): + if row["device_resident_bytes"] != sizing.device_resident_bytes(full, row["context"], overhead, qmode): + raise CannotCorrect(f"{report['files'][0]['path']}: resident bytes at {row['context']} do not reproduce") + new = copy.deepcopy(report) + chunk = recipe.get("prefill_chunk") or sizing.PREFILL_CHUNK + budget = window["phone_budget_bytes"] + new["window"]["kv_cache_bytes_per_token"] = sizing.kv_bytes_per_token(arch) + new["window"]["kv_cache_ring_bytes"] = sizing.kv_ring_bytes(arch, window["context"], chunk) + for row in (new["window"], *new["window"]["table"]): + row["device_resident_bytes"] = sizing.device_resident_bytes(arch, row["context"], overhead, qmode) + new["window"]["fits_phone_budget"] = new["window"]["device_resident_bytes"] <= budget + for row in new["window"]["table"]: + row["kv_cache_bytes"] = sizing.kv_cache_bytes(arch, row["context"]) + row["fits_device"] = row["device_resident_bytes"] <= budget + new.setdefault("corrections", []).append( + { + "date": today, + "by": f"execupack {commit}", + "fields": list(KV_FIELDS), + "reason": "sliding-window layers sized as full caches; they keep a fixed ring. The .pte is unchanged", + } + ) + return new + + def correct_repo(repo_id: str, commit: str, dry_run: bool = True) -> dict: """Correct every fp32 report in one Hub repo; return what changed (and the commit URL).""" from huggingface_hub import CommitOperationAdd, hf_hub_download @@ -106,11 +163,14 @@ def correct_repo(repo_id: str, commit: str, dry_run: bool = True) -> dict: archs: dict[tuple, sizing.Architecture] = {} for path, report in reports.items(): key = (report["source"]["id"], report["source"]["sha"]) - if report.get("recipe", {}).get("qmode") == "fp32" and key not in archs: + if report.get("backend") == "xnnpack" and key not in archs: source = hub.fetch(*key) archs[key] = families.architecture(source.config, source.total_params) - fixed = corrected(report, archs[key], cfg, commit, today) if key in archs else None - if fixed is not None: + if key not in archs: + continue + fixed = corrected(report, archs[key], cfg, commit, today) or report + fixed = corrected_kv(fixed, archs[key], cfg, commit, today) or fixed + if fixed is not report: changed[path] = fixed result = {"repo": repo_id, "revision": info.sha, "corrected": sorted(changed), "commit_url": None} if not changed or dry_run: @@ -131,7 +191,7 @@ def correct_repo(repo_id: str, commit: str, dry_run: bool = True) -> dict: commit_info = hf.create_commit( repo_id, operations, - commit_message=f"correct fp32 report fields ({len(changed)} reports); no .pte changed", + commit_message=f"correct report fields ({len(changed)} reports); no .pte changed", parent_commit=info.sha, ) result["commit_url"] = commit_info.commit_url diff --git a/pipeline/export_xnnpack.py b/pipeline/export_xnnpack.py index 598c387..69bc2ae 100644 --- a/pipeline/export_xnnpack.py +++ b/pipeline/export_xnnpack.py @@ -348,7 +348,8 @@ def run( ) print(f" reply: {smoke_result['reply']!r}") - kv_per_token = sizing.kv_cache_bytes(arch, 1) + kv_per_token = sizing.kv_bytes_per_token(arch) + kv_ring = sizing.kv_ring_bytes(arch, window, cfg.prefill_chunk) report = { "backend": backend, "target": None, @@ -368,6 +369,8 @@ def run( "context": window, "reason": window_reason, "kv_cache_bytes_per_token": kv_per_token, + # A windowed layer's ring, the same size at every window (LFM3); 0 otherwise. + "kv_cache_ring_bytes": kv_ring, "device_resident_bytes": resident, "phone_budget_bytes": cfg.device_budget_bytes, "fits_phone_budget": resident <= cfg.device_budget_bytes, diff --git a/pipeline/families.py b/pipeline/families.py index ff6852f..7a90f89 100644 --- a/pipeline/families.py +++ b/pipeline/families.py @@ -271,9 +271,19 @@ def architecture(config: dict, total_params: int) -> Architecture: # transformers' PretrainedConfig default, the same one convert.py assumes. tied_embeddings=bool(c.get("tie_word_embeddings", True)), attention_layers=attending_layers(c), + # Only LFM3's exporter keeps its windowed layers in a ring (pipeline/lfm3_model.py); + # Gemma 3's configs name sliding layers too, and no path here rings them. + **_windowed(c), ) +def _windowed(c: dict) -> dict: + if c.get("model_type") != "lfm3": + return {} + layer_types = c.get("layer_types") or [] + return {"windowed_layers": layer_types.count("sliding_attention"), "window": int(c.get("sliding_window") or 0)} + + def attending_layers(c: dict) -> int | None: """How many layers attend, or None when every one of them does. diff --git a/pipeline/manifest.py b/pipeline/manifest.py index 5b1e7c2..fe1c175 100644 --- a/pipeline/manifest.py +++ b/pipeline/manifest.py @@ -231,10 +231,16 @@ def readme(repo_id: str, reports: list[dict], hub_tags: list[str], license_files kv = r["window"].get("kv_cache_bytes_per_token") if kv: ctx = r["window"]["context"] + ring = r["window"].get("kv_cache_ring_bytes") or 0 + whole = ( + f"{kv * ctx + ring:,} bytes for the whole window ({ring:,} of them the sliding-window " + "layers' fixed ring)" + if ring + else f"{kv * ctx:,} bytes for the whole window" + ) out.append( f"- {BACKEND_TITLES[r['backend']]} at {ctx:,} tokens: the KV cache costs {kv:,} bytes per " - f"token (fp32), {kv * ctx:,} bytes for the whole window, allocated in full when the " - "model loads." + f"token (fp32), {whole}, allocated in full when the model loads." ) out += ["", "## How it was made", ""] described = set() diff --git a/pipeline/sizing.py b/pipeline/sizing.py index c2a31a1..5cc7318 100644 --- a/pipeline/sizing.py +++ b/pipeline/sizing.py @@ -49,11 +49,21 @@ class Architecture: # the export peak enough to refuse a window that fits, and the masks are the dominant # term at 32k. attention_layers: int | None = None + # Of those, how many attend over a fixed window and keep only a ring of keys: LFM3's + # five sliding-window layers hold window + one prefill chunk slots at any context + # (pipeline/lfm3_model.py RingCache). Zero for every family exported with full caches, + # including ones whose config names sliding layers but whose exporter does not ring them. + windowed_layers: int = 0 + window: int = 0 @property def attending(self) -> int: return self.n_layers if self.attention_layers is None else self.attention_layers + @property + def full_cache_layers(self) -> int: + return self.attending - self.windowed_layers + @property def embedding_params(self) -> int: return self.vocab_size * self.dim @@ -72,9 +82,28 @@ def linear_params(self) -> int: return self.n_layers * (attention + mlp) + self.vocab_size * self.dim -def kv_cache_bytes(arch: Architecture, context: int) -> int: - """K and V for every attending layer, every KV head, every position, fp32.""" - return arch.attending * 2 * arch.n_kv_heads * arch.head_dim * context * FP32_BYTES +# The export's prefill chunk (max_seq_len) when a caller does not say: pipeline.yaml's +# export.prefill_chunk. Only a windowed layer's ring depends on it. +PREFILL_CHUNK = 2048 + + +def kv_bytes_per_token(arch: Architecture) -> int: + """What one more token of window costs: K and V in every layer with a full-length cache.""" + return arch.full_cache_layers * 2 * arch.n_kv_heads * arch.head_dim * FP32_BYTES + + +def kv_ring_bytes(arch: Architecture, context: int, prefill_chunk: int = PREFILL_CHUNK) -> int: + """K and V in the windowed layers' rings: window + max_seq_len slots, whatever the window.""" + if not arch.windowed_layers: + return 0 + slots = arch.window + min(prefill_chunk, context) + return arch.windowed_layers * 2 * arch.n_kv_heads * arch.head_dim * slots * FP32_BYTES + + +def kv_cache_bytes(arch: Architecture, context: int, prefill_chunk: int = PREFILL_CHUNK) -> int: + """K and V for every attending layer and KV head, fp32: every position of the window in a + full cache, the ring's slots in a windowed layer.""" + return kv_bytes_per_token(arch) * context + kv_ring_bytes(arch, context, prefill_chunk) def linear_bytes_per_param(qmode: str) -> float: diff --git a/tests/test_lfm3.py b/tests/test_lfm3.py index 2f341f4..f0d6442 100644 --- a/tests/test_lfm3.py +++ b/tests/test_lfm3.py @@ -167,3 +167,67 @@ def test_remote_code_runs_only_for_a_trusted_publisher_and_local_modules(): assert not hub.remote_code_allowed(finetune) elsewhere = lfm3_config(auto_map={"AutoModelForCausalLM": "other/repo--modeling_lfm3.Lfm3ForCausalLM"}) assert not hub.remote_code_allowed(make_source("LiquidAI/LFM3-1.7B", elsewhere, total_params=LFM3_PARAMS)) + + +def test_the_windowed_layers_cost_a_fixed_ring_not_the_window(): + from pipeline import sizing + + arch = families.architecture(lfm3_config(), LFM3_PARAMS) + assert (arch.windowed_layers, arch.window, arch.full_cache_layers) == (5, 256, 6) + # Six global layers grow with the window: 2 x 4 KV heads x 128 x 4 bytes each. + assert sizing.kv_bytes_per_token(arch) == 6 * 2 * 4 * 128 * 4 == 24_576 + # Five rings of 256 + 2,048 slots, the same at 8k and 32k. + assert sizing.kv_ring_bytes(arch, 32768) == sizing.kv_ring_bytes(arch, 8192) == 5 * 2 * 4 * 128 * 2304 * 4 + assert sizing.kv_cache_bytes(arch, 32768) == 24_576 * 32768 + 47_185_920 == 852_492_288 + + +def test_gemma3s_sliding_layers_are_not_sized_as_rings(): + from conftest import hf_config + + arch = families.architecture(hf_config("google/gemma-3-1b-it"), 999_885_952) + assert arch.windowed_layers == 0 + + +def test_a_report_sized_with_full_caches_is_corrected_to_the_ring(): + import dataclasses + + from pipeline import correct, sizing + + cfg = settings.load() + arch = families.architecture(lfm3_config(), LFM3_PARAMS) + full = dataclasses.replace(arch, windowed_layers=0, window=0) + overhead = cfg.runtime_overhead_bytes + rows = [ + { + "context": c, + "kv_cache_bytes": sizing.kv_cache_bytes(full, c), + "device_resident_bytes": sizing.device_resident_bytes(full, c, overhead), + "export_peak_bytes": 1, + "fits_device": True, + "fits_host": True, + } + for c in (32768, 2048) + ] + report = { + "backend": "xnnpack", + "files": [{"path": "xnnpack/LFM3-1.7B-8da4w-gptq-32k.pte"}], + "recipe": {"qmode": "8da4w-gptq", "prefill_chunk": 2048}, + "window": { + "context": 32768, + "kv_cache_bytes_per_token": 45_056, + "device_resident_bytes": rows[0]["device_resident_bytes"], + "phone_budget_bytes": cfg.device_budget_bytes, + "fits_phone_budget": True, + "table": rows, + }, + } + new = correct.corrected_kv(report, arch, cfg, "abc1234", "2026-10-31") + assert new["window"]["kv_cache_bytes_per_token"] == 24_576 + assert new["window"]["kv_cache_ring_bytes"] == 47_185_920 + saved = report["window"]["device_resident_bytes"] - new["window"]["device_resident_bytes"] + assert saved == 1_476_395_008 - 852_492_288 + assert new["window"]["table"][0]["kv_cache_bytes"] == 852_492_288 + assert new["window"]["table"][0]["export_peak_bytes"] == 1 # the build's own estimate stays + assert new["corrections"][-1]["fields"] == list(correct.KV_FIELDS) + # Already corrected: nothing more to do. + assert correct.corrected_kv(new, arch, cfg, "abc1234", "2026-10-31") is None From 4e5b2a8d8306399bc0afa261a035355aaa011aaf Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 14:57:01 -0700 Subject: [PATCH 5/8] research: finding 42 records the ring sizing and the Hub correction, which superseded its full-cache caveat Co-Authored-By: Claude Opus 5.5 --- docs/research/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/research/README.md b/docs/research/README.md index dfa451b..9d81f76 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -67,4 +67,4 @@ Findings from building and running this pipeline, each kept with its evidence. C | 39 | 2026-10-04 | MediaTek | At 16k, LFM2.5 built once no chunk held more than one attention layer; a 4-chunk build with two in some chunks did not. LFM2.5-1.2B-Instruct (attention at layers 2, 5, 8, 10, 12, 14 of 16) at 16k in 4 chunks lost MediaTek's local compiler service while compiling chunk 2, after calibration had finished; its heretic finetune, the same architecture, in 8 chunks (two layers, at most one attention layer each) built and was published: 3,235 s, peak 14,361,923,584 B in use on a 16 vCPU runner. LFM2.5-2.6B (attention at 2, 5, 9, 13, 17, 21, 24, 27 of 30) needs 10 chunks for one attention layer each, and its heretic finetune built at 16k that way: 5,891 s, peak 26,554,892,288 B. Two successes and one failure, so one attention layer per chunk is a working heuristic for these architectures; that it is necessary, and why the compiler service died, are not shown. 32k was started for all three LFM2.5 models (8 and 10 chunks) and cancelled mid-calibration for budget. | measured + inference | run 35994412279 (4 chunks, failed at chunk 2), run 37171790063 (8 chunks, published), run 37176914465 (2.6B-heretic, 10 chunks, 16k published, 32k cancelled); `mtk/mt6991/export-report-16k.json` in `experimentalmachines/LFM2.5-1.2B-Instruct-heretic-ExecuTorch` and `…/LFM2.5-2.6B-heretic-ExecuTorch` | Dispatch 16k with `max_chunks` at the smallest count that leaves one attention layer per chunk (8 for the 1.2B, 10 for the 2.6B); `mtk.max_chunks` stays 4 for the windows that build at it. The successful builds peaked at 13.4 and 24.7 GiB; what killed the failed run's compiler service is not known. LFM2.5-2.6B (base) at 16k and every 32k remain unbuilt. | | 40 | 2026-10-07 | Runner | The Namespace profile `namespace-profile-execupack` has 4 x86_64 CPUs, MemTotal 16,438,740 kB (15.7 GiB), a 101 GB overlay disk shared by / and /mnt, and no swap: `swapon` on a swap file is refused ("Operation not permitted"), so the 24 to 96 GiB the Blacksmith jobs added cannot be had. Against `sizing.host_need_bytes` and `export_mtk.calibration_bytes` that leaves: Vulkan up to 8k for the 0.1B to 1.2B models (Qwen3-0.6B, Qwen2.5-0.5B, SmolLM2, Llama-3.2-1B) and up to 16k for LFM2.5-1.2B, 2k-4k for Qwen2.5-1.5B, Qwen3-1.7B and LFM2.5-2.6B, nothing at 3B and above; XNNPACK up to 8k for the sub-1B models, 2k-4k for Llama-3.2-1B and LFM2.5-1.2B, nothing from 1.5B up; MediaTek Qwen3-0.6B at 512 only, Llama-3.2-1B to 2k, SmolLM2-135M to 4k, and no LFM2.5 at any window by the current estimate (about 17.4 GiB for the 1.2B). Of the windows built before, every 32k window and every 16k except LFM2.5-1.2B's on Vulkan now fall outside it, as do the MediaTek 16k builds of finding 39. That last is the estimate's call, not a measured limit: `calibration_bytes` puts the 1.2B at about 17.4 GiB from the 14.4 to 15.7 bytes per parameter measured on 4-chunk builds, while the 8-chunk 16k build peaked at 13.4 GiB, which this RAM would hold; refitting the estimate for more chunks could bring the 1.2B back. | measured + estimate | CI run 37606922033 (the runner step); `tests/test_namespace_runner.py` pins the tier and the windows; the coverage is the sizing model's, not exports run on the profile | `config/pipeline.yaml` has the one tier with swap_gib 0; `prepare-host.sh` carries on without swap where it is refused; a model no window fits stops at the targets job instead of failing an empty matrix. The wider windows need a larger Namespace profile added as a second tier. QNN has no tier: its export peaked at 15.6 GB of RSS for Qwen3-0.6B (finding 8), at the edge of this profile. | | 41 | 2026-10-07 | Runner | Modal runs the XNNPACK and Vulkan exports and the solve. A Sandbox may ask for at most 344064 MiB (336 GiB) and 64 physical cores: larger requests are refused at creation with InvalidError ("memory request must be <= 344064 MiB", "CPU request must be <= 64000 mCPU"), so every window ever built fits, Qwen3-4B at 32k (about 134 GiB) included. Inside a Sandbox /proc/meminfo shows the host's memory (680 GiB to 1.3 TiB), not the request, so the export's own memory gate passes there and the request computed from `sizing.host_need_bytes` is what sizes the run; nproc does reflect the request. SmolLM2-135M at 2k: the Vulkan file came out byte-identical to the published one (sha256 0de5a249...), peaking at 1.9 GiB of a 6.1 GiB request; the XNNPACK file exported and passed the smoke test ("The capital of France is Paris") in the same Sandbox. Both were slower than on Blacksmith: 361 s against 145 s for Vulkan and 1,308 s against 348 s for XNNPACK, though the published files were built with ExecuTorch 1.4.0 and these with 1.5.1, so the runner is not the only difference. | measured | `pipeline/remote.py` runs from this workstation, 2026-10-07 (the sandbox limits probed by request; the two exports with their export reports); the published reports in `experimentalmachines/SmolLM2-135M-Instruct-ExecuTorch` | xnnpack and vulkan runner_tiers are one `modal` tier at Modal's ceiling, each window's memory_mib is its need times modal.memory_margin, and the XNNPACK export, smoke test and decision gate share one Sandbox, so the separate verify job is gone. Per-export time is the open cost question: modal.cpu is 8 cores, and whether more cores or a 1.5.1-to-1.4.0 difference explains the gap is not measured. | -| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. `sizing` still counts the 5 windowed layers at a full-window KV cache (about 0.6 GB over at 32k): the phone estimate is pessimistic, the host one conservative. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. | +| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. The first published reports counted the 5 windowed layers at a full-window KV cache (1,476,395,008 B at 32k); since eba9368 `sizing` counts them as their fixed ring (852,492,288 B at 32k, 47,185,920 B of it the rings), and `correct-reports` rewrote the five published reports, `config.json` and README in Hub commit fd07e07 without touching a `.pte`. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. | From cd9090a707499391a84ab909df35b7fb16775dc9 Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 15:04:07 -0700 Subject: [PATCH 6/8] gate and eligibility: grade only the quiet rows fp32 is sure of, and let a named base checkpoint through on request Quiet rows now follow the rule the calling rows already had: a row fp32 itself splits says nothing about a regression (LFM3-1.7B on Pride and Prejudice at 0.27; LFM3-1.7B-Base on three of four at 0.09 to 0.39). verify marks a base checkpoint's gate as not measuring tool calling: LFM3-1.7B-Base puts a newline, not a call, first on every calling row. --allow-base on solve and export-xnnpack publishes a base checkpoint someone asked for by name; the watcher never passes it, so the chat-only default stands for everything it finds. Co-Authored-By: Claude Opus 5.5 --- pipeline/__main__.py | 13 ++++++++++++- pipeline/eligibility.py | 6 ++++-- pipeline/export_xnnpack.py | 3 ++- pipeline/gate.py | 13 +++++++++---- pipeline/solve.py | 10 ++++++++-- pipeline/verify.py | 4 ++++ tests/test_gate.py | 19 +++++++++++++++++++ tests/test_lfm3.py | 5 +++++ 8 files changed, 63 insertions(+), 10 deletions(-) diff --git a/pipeline/__main__.py b/pipeline/__main__.py index b7b28c0..daed58a 100644 --- a/pipeline/__main__.py +++ b/pipeline/__main__.py @@ -8,6 +8,8 @@ import sys from pathlib import Path +ALLOW_BASE = "a base checkpoint asked for by name: publish it although only chat models are by default" + def _plan(args) -> int: from pipeline import eligibility, families, hub, settings, sizing @@ -82,7 +84,13 @@ def _solve(args) -> int: from pipeline import solve as solve_module report = solve_module.run( - args.model, args.revision, Path(args.out), Path(args.work), damp=args.damp, reference_only=args.reference_only + args.model, + args.revision, + Path(args.out), + Path(args.work), + damp=args.damp, + reference_only=args.reference_only, + allow_base=args.allow_base, ) print(json.dumps(report, indent=2)) return 0 @@ -102,6 +110,7 @@ def _export_xnnpack(args) -> int: skip_smoke=args.skip_smoke, codes=Path(args.codes) if args.codes else None, qmode=args.qmode or None, + allow_base=args.allow_base, ) ) @@ -425,6 +434,7 @@ def main(argv: list[str] | None = None) -> int: help="codes.pt from `solve`; without it the int4 weights are rounded to nearest", ) export.add_argument("--qmode", default="", help="recipe: 8da4w (config default) or fp32 (linears not quantized)") + export.add_argument("--allow-base", action="store_true", help=ALLOW_BASE) export.set_defaults(func=_export_xnnpack) verify = commands.add_parser("verify", help="smoke-test an exported .pte on a host whose runner works") @@ -456,6 +466,7 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help="write only the gate's fp32 reference (gate.json), no codes: for a recipe that is not solved", ) + solve.add_argument("--allow-base", action="store_true", help=ALLOW_BASE) solve.set_defaults(func=_solve) vulkan = commands.add_parser("export-vulkan", help="download, convert, export a Vulkan (GPU) .pte") diff --git a/pipeline/eligibility.py b/pipeline/eligibility.py index 2cc5010..487ab3c 100644 --- a/pipeline/eligibility.py +++ b/pipeline/eligibility.py @@ -105,7 +105,9 @@ def name_reasons(model_id: str, settings: Settings) -> list[str]: return reasons -def evaluate(source: SourceModel, settings: Settings) -> Verdict: +def evaluate(source: SourceModel, settings: Settings, allow_base: bool = False) -> Verdict: + """``allow_base`` admits a base checkpoint someone asked for by name (``--allow-base``); + the watcher never passes it, so nothing it finds on its own is published as a base.""" name = naming.source_name(source.id) family = families.family_for(source.config) if source.config else None family_key = family.key if family else None @@ -114,7 +116,7 @@ def evaluate(source: SourceModel, settings: Settings) -> Verdict: if source.pipeline_tag not in (None, settings.pipeline_tag): reasons.append(f"pipeline tag {source.pipeline_tag!r} is not {settings.pipeline_tag!r}") - if verdict.variant == "base": + if verdict.variant == "base" and not allow_base: # Base checkpoints are not published. They have no chat template, so the app -- which # renders one from the name and refuses a file it cannot place -- cannot run them, # and a completion model in a chat app reads as a broken chat model. diff --git a/pipeline/export_xnnpack.py b/pipeline/export_xnnpack.py index 69bc2ae..286f2af 100644 --- a/pipeline/export_xnnpack.py +++ b/pipeline/export_xnnpack.py @@ -196,12 +196,13 @@ def run( backend: str = BACKEND, codes: Path | None = None, qmode: str | None = None, + allow_base: bool = False, ) -> dict: if backend not in BACKEND_CONFIG: raise ExportError(f"unknown backend {backend!r}; this exporter builds {sorted(BACKEND_CONFIG)}") cfg = settings.load() source = hub.fetch(model_id, revision) - verdict = eligibility.evaluate(source, cfg) + verdict = eligibility.evaluate(source, cfg, allow_base=allow_base) if verdict.reasons: raise ExportError(f"{model_id} is not eligible: {'; '.join(verdict.reasons)}") if verdict.backends[backend] is not None: diff --git a/pipeline/gate.py b/pipeline/gate.py index ed345ee..87675a6 100644 --- a/pipeline/gate.py +++ b/pipeline/gate.py @@ -174,7 +174,11 @@ def check(ref: dict, measured: dict) -> dict: agreed = sum(1 for q in search if measured[q]["top"] == ref["rows"][q]["token"]) # A quiet row is one where fp32 answers instead of calling. The export must do the same: # picking fp32's token there means it answered, and any other top token is worth seeing. - quiet_followed = sum(1 for q in QUIET if measured[q]["top"] == ref["rows"][q]["token"]) + # Graded only where fp32 is sure of its answer, as the calling rows are: a quiet row fp32 + # itself splits (LFM3-1.7B on Pride and Prejudice at 0.27, its base model on three of four + # at 0.09 to 0.39) cannot tell a regression from the coin landing the other way. + quiet = [q for q in QUIET if ref["rows"][q]["p"] > CONFIDENT] + quiet_followed = sum(1 for q in quiet if measured[q]["top"] == ref["rows"][q]["token"]) # Whether this model tool-calls at all. LFM2.5-2.6B answers "The" at probability 1.0 to # every row here, trailered or not: it is not tool-trained, so fp32's chosen token is the # same on the search rows as on the quiet ones and the gate cannot see a tool-calling @@ -192,9 +196,9 @@ def check(ref: dict, measured: dict) -> dict: ) if agreed < MIN_AGREEMENT * len(search): problems.append(f"kept fp32's choice on {agreed} of {len(search)} calling rows, under {MIN_AGREEMENT:.0%}") - if quiet_followed < len(QUIET) - 1: + if quiet_followed < len(quiet) - 1: problems.append( - f"answered like fp32 on only {quiet_followed} of {len(QUIET)} quiet rows: it is reaching for a tool " + f"answered like fp32 on only {quiet_followed} of {len(quiet)} quiet rows: it is reaching for a tool " "on questions the unquantised model answers itself" ) return { @@ -207,7 +211,8 @@ def check(ref: dict, measured: dict) -> dict: "shortfall": round(fp32_mean - export_mean, 4), "quiet_rows_answered_like_fp32": quiet_followed, "measures_tool_calling": informative, - "quiet_rows": len(QUIET), + "quiet_rows": len(quiet), + "fp32_undecided_quiet_rows": [q for q in QUIET if q not in quiet], "fp32_undecided_rows": undecided, "rows": { q: {"fp32": round(ref["rows"][q]["p"], 4), "export": round(measured[q]["p"], 4), "kind": kind} diff --git a/pipeline/solve.py b/pipeline/solve.py index 37248ad..ae527a2 100644 --- a/pipeline/solve.py +++ b/pipeline/solve.py @@ -336,7 +336,13 @@ def accumulate(mod, args, name=name, hess=hess, counts=counts): def run( - model_id: str, revision: str, out: Path, work_dir: Path, damp: float = 0.01, reference_only: bool = False + model_id: str, + revision: str, + out: Path, + work_dir: Path, + damp: float = 0.01, + reference_only: bool = False, + allow_base: bool = False, ) -> dict: """Solve one model's int4 codes and write them to ``out``. @@ -351,7 +357,7 @@ def run( cfg = settings.load() source = hub.fetch(model_id, revision) - verdict = eligibility.evaluate(source, cfg) + verdict = eligibility.evaluate(source, cfg, allow_base=allow_base) if verdict.reasons: raise ExportError(f"{model_id} is not eligible: {'; '.join(verdict.reasons)}") if verdict.backends["xnnpack"] is not None: diff --git a/pipeline/verify.py b/pipeline/verify.py index 7dc9e56..02c0467 100644 --- a/pipeline/verify.py +++ b/pipeline/verify.py @@ -82,6 +82,10 @@ def run(out_dir: Path, backend: str, work_dir: Path, gate_reference: Path | None tokenizer = AutoTokenizer.from_pretrained(str(src_dir)) print("==> decision gate") verdict = gate.check(reference, gate.measure(pte, out_dir / report["tokenizer"], tokenizer, reference)) + if report["source"].get("variant") == "base": + # Not tool-trained: its first token on a calling row is not a call (LFM3-1.7B-Base + # puts a newline there), so the gate tracks fp32 and measures no tool calling. + verdict["measures_tool_calling"] = False print( f" fp32 {verdict['fp32_mean']} against the export's {verdict['export_mean']} " f"on {verdict['graded']} rows, same choice on {verdict['agreed']}" diff --git a/tests/test_gate.py b/tests/test_gate.py index 031b174..25dd268 100644 --- a/tests/test_gate.py +++ b/tests/test_gate.py @@ -61,6 +61,25 @@ def test_reaching_for_a_tool_on_quiet_rows_fails(): assert any("quiet rows" in p for p in verdict["problems"]) +def test_a_quiet_row_fp32_itself_splits_is_not_graded(): + # LFM3-1.7B's fp32 answers "Who wrote Pride and Prejudice?" at 0.27; an export that lands + # on another token there has not regressed. Undecided quiet rows are left out, as the + # undecided calling rows are, and the rest are held to the same rule. + ref = reference() + undecided = gate.QUIET[2] + ref["rows"][undecided]["p"] = 0.27 + rows = measured(0.80, len(gate.SEARCH)) + rows[undecided]["top"] = 999 + other = gate.QUIET[0] + verdict = gate.check(ref, rows) + assert verdict["passed"] and verdict["quiet_rows"] == len(gate.QUIET) - 1 + assert verdict["fp32_undecided_quiet_rows"] == [undecided] + # Two misses among the confident rows still fail. + rows[other]["top"] = 999 + rows[gate.QUIET[1]]["top"] = 999 + assert not gate.check(ref, rows)["passed"] + + def test_a_model_fp32_never_calls_on_is_not_graded_as_a_pass(): # If fp32 is undecided everywhere, there is nothing to compare against and the gate has # to say so. Passing quietly here would wave through every export of that family. diff --git a/tests/test_lfm3.py b/tests/test_lfm3.py index f0d6442..a029bab 100644 --- a/tests/test_lfm3.py +++ b/tests/test_lfm3.py @@ -144,6 +144,11 @@ def test_lfm3_base_is_a_base_checkpoint(): cfg = settings.load() verdict = eligibility.evaluate(make_source("LiquidAI/LFM3-1.7B-Base", lfm3_config(), total_params=LFM3_PARAMS), cfg) assert any("base checkpoint" in r for r in verdict.reasons) + # Asked for by name, it is exported like the chat model (and still reads as a base). + asked = eligibility.evaluate( + make_source("LiquidAI/LFM3-1.7B-Base", lfm3_config(), total_params=LFM3_PARAMS), cfg, allow_base=True + ) + assert asked.reasons == [] and asked.variant == "base" and asked.backends["xnnpack"] is None def test_rope_tables_leave_the_tail_unrotated(): From 4a5b84bf44677fef7af620fe76fb359c8e0987af Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 15:19:19 -0700 Subject: [PATCH 7/8] research: finding 42 adds ExecuTorch 1.6.0-rc1, where the LFM3 definition matches and exports but nothing ships until the apps move Co-Authored-By: Claude Opus 5.5 --- docs/research/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/research/README.md b/docs/research/README.md index 9d81f76..32cb2ab 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -67,4 +67,4 @@ Findings from building and running this pipeline, each kept with its evidence. C | 39 | 2026-10-04 | MediaTek | At 16k, LFM2.5 built once no chunk held more than one attention layer; a 4-chunk build with two in some chunks did not. LFM2.5-1.2B-Instruct (attention at layers 2, 5, 8, 10, 12, 14 of 16) at 16k in 4 chunks lost MediaTek's local compiler service while compiling chunk 2, after calibration had finished; its heretic finetune, the same architecture, in 8 chunks (two layers, at most one attention layer each) built and was published: 3,235 s, peak 14,361,923,584 B in use on a 16 vCPU runner. LFM2.5-2.6B (attention at 2, 5, 9, 13, 17, 21, 24, 27 of 30) needs 10 chunks for one attention layer each, and its heretic finetune built at 16k that way: 5,891 s, peak 26,554,892,288 B. Two successes and one failure, so one attention layer per chunk is a working heuristic for these architectures; that it is necessary, and why the compiler service died, are not shown. 32k was started for all three LFM2.5 models (8 and 10 chunks) and cancelled mid-calibration for budget. | measured + inference | run 35994412279 (4 chunks, failed at chunk 2), run 37171790063 (8 chunks, published), run 37176914465 (2.6B-heretic, 10 chunks, 16k published, 32k cancelled); `mtk/mt6991/export-report-16k.json` in `experimentalmachines/LFM2.5-1.2B-Instruct-heretic-ExecuTorch` and `…/LFM2.5-2.6B-heretic-ExecuTorch` | Dispatch 16k with `max_chunks` at the smallest count that leaves one attention layer per chunk (8 for the 1.2B, 10 for the 2.6B); `mtk.max_chunks` stays 4 for the windows that build at it. The successful builds peaked at 13.4 and 24.7 GiB; what killed the failed run's compiler service is not known. LFM2.5-2.6B (base) at 16k and every 32k remain unbuilt. | | 40 | 2026-10-07 | Runner | The Namespace profile `namespace-profile-execupack` has 4 x86_64 CPUs, MemTotal 16,438,740 kB (15.7 GiB), a 101 GB overlay disk shared by / and /mnt, and no swap: `swapon` on a swap file is refused ("Operation not permitted"), so the 24 to 96 GiB the Blacksmith jobs added cannot be had. Against `sizing.host_need_bytes` and `export_mtk.calibration_bytes` that leaves: Vulkan up to 8k for the 0.1B to 1.2B models (Qwen3-0.6B, Qwen2.5-0.5B, SmolLM2, Llama-3.2-1B) and up to 16k for LFM2.5-1.2B, 2k-4k for Qwen2.5-1.5B, Qwen3-1.7B and LFM2.5-2.6B, nothing at 3B and above; XNNPACK up to 8k for the sub-1B models, 2k-4k for Llama-3.2-1B and LFM2.5-1.2B, nothing from 1.5B up; MediaTek Qwen3-0.6B at 512 only, Llama-3.2-1B to 2k, SmolLM2-135M to 4k, and no LFM2.5 at any window by the current estimate (about 17.4 GiB for the 1.2B). Of the windows built before, every 32k window and every 16k except LFM2.5-1.2B's on Vulkan now fall outside it, as do the MediaTek 16k builds of finding 39. That last is the estimate's call, not a measured limit: `calibration_bytes` puts the 1.2B at about 17.4 GiB from the 14.4 to 15.7 bytes per parameter measured on 4-chunk builds, while the 8-chunk 16k build peaked at 13.4 GiB, which this RAM would hold; refitting the estimate for more chunks could bring the 1.2B back. | measured + estimate | CI run 37606922033 (the runner step); `tests/test_namespace_runner.py` pins the tier and the windows; the coverage is the sizing model's, not exports run on the profile | `config/pipeline.yaml` has the one tier with swap_gib 0; `prepare-host.sh` carries on without swap where it is refused; a model no window fits stops at the targets job instead of failing an empty matrix. The wider windows need a larger Namespace profile added as a second tier. QNN has no tier: its export peaked at 15.6 GB of RSS for Qwen3-0.6B (finding 8), at the edge of this profile. | | 41 | 2026-10-07 | Runner | Modal runs the XNNPACK and Vulkan exports and the solve. A Sandbox may ask for at most 344064 MiB (336 GiB) and 64 physical cores: larger requests are refused at creation with InvalidError ("memory request must be <= 344064 MiB", "CPU request must be <= 64000 mCPU"), so every window ever built fits, Qwen3-4B at 32k (about 134 GiB) included. Inside a Sandbox /proc/meminfo shows the host's memory (680 GiB to 1.3 TiB), not the request, so the export's own memory gate passes there and the request computed from `sizing.host_need_bytes` is what sizes the run; nproc does reflect the request. SmolLM2-135M at 2k: the Vulkan file came out byte-identical to the published one (sha256 0de5a249...), peaking at 1.9 GiB of a 6.1 GiB request; the XNNPACK file exported and passed the smoke test ("The capital of France is Paris") in the same Sandbox. Both were slower than on Blacksmith: 361 s against 145 s for Vulkan and 1,308 s against 348 s for XNNPACK, though the published files were built with ExecuTorch 1.4.0 and these with 1.5.1, so the runner is not the only difference. | measured | `pipeline/remote.py` runs from this workstation, 2026-10-07 (the sandbox limits probed by request; the two exports with their export reports); the published reports in `experimentalmachines/SmolLM2-135M-Instruct-ExecuTorch` | xnnpack and vulkan runner_tiers are one `modal` tier at Modal's ceiling, each window's memory_mib is its need times modal.memory_margin, and the XNNPACK export, smoke test and decision gate share one Sandbox, so the separate verify job is gone. Per-export time is the open cost question: modal.cpu is 8 cores, and whether more cores or a 1.5.1-to-1.4.0 difference explains the gap is not measured. | -| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. The first published reports counted the 5 windowed layers at a full-window KV cache (1,476,395,008 B at 32k); since eba9368 `sizing` counts them as their fixed ring (852,492,288 B at 32k, 47,185,920 B of it the rings), and `correct-reports` rewrote the five published reports, `config.json` and README in Hub commit fd07e07 without touching a `.pte`. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. | +| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. The first published reports counted the 5 windowed layers at a full-window KV cache (1,476,395,008 B at 32k); since eba9368 `sizing` counts them as their fixed ring (852,492,288 B at 32k, 47,185,920 B of it the rings), and `correct-reports` rewrote the five published reports, `config.json` and README in Hub commit fd07e07 without touching a `.pte`. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. ExecuTorch 1.6.0-rc1 (tagged 2026-10-30, wheel on PyTorch's test channel, torch 2.15.0) has no LFM3 model either, though its `ShortConv` takes a width: under it the same module matches Hugging Face (identical logits without a cache, 2.1e-4 with the custom-op cache and the ring), and a 2k 8da4w export (1,239,187,968 B, 597 s with the base model's solve on the same CPUs) answers the smoke test through 1.6.0's own runner. Nothing was published from it: the apps ship the 1.5.1 runtime, which `EXECUTORCH_VERSION` keeps every export on. | From e452850b0b694fb0242f45127140d9b39c95ce0c Mon Sep 17 00:00:00 2001 From: Alpha Romer Coma Date: Sat, 31 Oct 2026 15:50:29 -0700 Subject: [PATCH 8/8] manifest: a base checkpoint's card says it is a completion model, and finding 42 records LFM3-1.7B-Base The card told a reader of LFM3-1.7B-Base to render prompts with its chat template, which is the wrong advice for a model not trained on chat turns. It now opens by saying what a base checkpoint is; the published card was regenerated from its reports (Hub commit c2e3f94). Co-Authored-By: Claude Opus 5.5 --- docs/research/README.md | 2 +- pipeline/manifest.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/research/README.md b/docs/research/README.md index 32cb2ab..3107277 100644 --- a/docs/research/README.md +++ b/docs/research/README.md @@ -67,4 +67,4 @@ Findings from building and running this pipeline, each kept with its evidence. C | 39 | 2026-10-04 | MediaTek | At 16k, LFM2.5 built once no chunk held more than one attention layer; a 4-chunk build with two in some chunks did not. LFM2.5-1.2B-Instruct (attention at layers 2, 5, 8, 10, 12, 14 of 16) at 16k in 4 chunks lost MediaTek's local compiler service while compiling chunk 2, after calibration had finished; its heretic finetune, the same architecture, in 8 chunks (two layers, at most one attention layer each) built and was published: 3,235 s, peak 14,361,923,584 B in use on a 16 vCPU runner. LFM2.5-2.6B (attention at 2, 5, 9, 13, 17, 21, 24, 27 of 30) needs 10 chunks for one attention layer each, and its heretic finetune built at 16k that way: 5,891 s, peak 26,554,892,288 B. Two successes and one failure, so one attention layer per chunk is a working heuristic for these architectures; that it is necessary, and why the compiler service died, are not shown. 32k was started for all three LFM2.5 models (8 and 10 chunks) and cancelled mid-calibration for budget. | measured + inference | run 35994412279 (4 chunks, failed at chunk 2), run 37171790063 (8 chunks, published), run 37176914465 (2.6B-heretic, 10 chunks, 16k published, 32k cancelled); `mtk/mt6991/export-report-16k.json` in `experimentalmachines/LFM2.5-1.2B-Instruct-heretic-ExecuTorch` and `…/LFM2.5-2.6B-heretic-ExecuTorch` | Dispatch 16k with `max_chunks` at the smallest count that leaves one attention layer per chunk (8 for the 1.2B, 10 for the 2.6B); `mtk.max_chunks` stays 4 for the windows that build at it. The successful builds peaked at 13.4 and 24.7 GiB; what killed the failed run's compiler service is not known. LFM2.5-2.6B (base) at 16k and every 32k remain unbuilt. | | 40 | 2026-10-07 | Runner | The Namespace profile `namespace-profile-execupack` has 4 x86_64 CPUs, MemTotal 16,438,740 kB (15.7 GiB), a 101 GB overlay disk shared by / and /mnt, and no swap: `swapon` on a swap file is refused ("Operation not permitted"), so the 24 to 96 GiB the Blacksmith jobs added cannot be had. Against `sizing.host_need_bytes` and `export_mtk.calibration_bytes` that leaves: Vulkan up to 8k for the 0.1B to 1.2B models (Qwen3-0.6B, Qwen2.5-0.5B, SmolLM2, Llama-3.2-1B) and up to 16k for LFM2.5-1.2B, 2k-4k for Qwen2.5-1.5B, Qwen3-1.7B and LFM2.5-2.6B, nothing at 3B and above; XNNPACK up to 8k for the sub-1B models, 2k-4k for Llama-3.2-1B and LFM2.5-1.2B, nothing from 1.5B up; MediaTek Qwen3-0.6B at 512 only, Llama-3.2-1B to 2k, SmolLM2-135M to 4k, and no LFM2.5 at any window by the current estimate (about 17.4 GiB for the 1.2B). Of the windows built before, every 32k window and every 16k except LFM2.5-1.2B's on Vulkan now fall outside it, as do the MediaTek 16k builds of finding 39. That last is the estimate's call, not a measured limit: `calibration_bytes` puts the 1.2B at about 17.4 GiB from the 14.4 to 15.7 bytes per parameter measured on 4-chunk builds, while the 8-chunk 16k build peaked at 13.4 GiB, which this RAM would hold; refitting the estimate for more chunks could bring the 1.2B back. | measured + estimate | CI run 37606922033 (the runner step); `tests/test_namespace_runner.py` pins the tier and the windows; the coverage is the sizing model's, not exports run on the profile | `config/pipeline.yaml` has the one tier with swap_gib 0; `prepare-host.sh` carries on without swap where it is refused; a model no window fits stops at the targets job instead of failing an empty matrix. The wider windows need a larger Namespace profile added as a second tier. QNN has no tier: its export peaked at 15.6 GB of RSS for Qwen3-0.6B (finding 8), at the edge of this profile. | | 41 | 2026-10-07 | Runner | Modal runs the XNNPACK and Vulkan exports and the solve. A Sandbox may ask for at most 344064 MiB (336 GiB) and 64 physical cores: larger requests are refused at creation with InvalidError ("memory request must be <= 344064 MiB", "CPU request must be <= 64000 mCPU"), so every window ever built fits, Qwen3-4B at 32k (about 134 GiB) included. Inside a Sandbox /proc/meminfo shows the host's memory (680 GiB to 1.3 TiB), not the request, so the export's own memory gate passes there and the request computed from `sizing.host_need_bytes` is what sizes the run; nproc does reflect the request. SmolLM2-135M at 2k: the Vulkan file came out byte-identical to the published one (sha256 0de5a249...), peaking at 1.9 GiB of a 6.1 GiB request; the XNNPACK file exported and passed the smoke test ("The capital of France is Paris") in the same Sandbox. Both were slower than on Blacksmith: 361 s against 145 s for Vulkan and 1,308 s against 348 s for XNNPACK, though the published files were built with ExecuTorch 1.4.0 and these with 1.5.1, so the runner is not the only difference. | measured | `pipeline/remote.py` runs from this workstation, 2026-10-07 (the sandbox limits probed by request; the two exports with their export reports); the published reports in `experimentalmachines/SmolLM2-135M-Instruct-ExecuTorch` | xnnpack and vulkan runner_tiers are one `modal` tier at Modal's ceiling, each window's memory_mib is its need times modal.memory_margin, and the XNNPACK export, smoke test and decision gate share one Sandbox, so the separate verify job is gone. Per-export time is the open cost question: modal.cpu is 8 cores, and whether more cores or a 1.5.1-to-1.4.0 difference explains the gap is not measured. | -| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. The first published reports counted the 5 windowed layers at a full-window KV cache (1,476,395,008 B at 32k); since eba9368 `sizing` counts them as their fixed ring (852,492,288 B at 32k, 47,185,920 B of it the rings), and `correct-reports` rewrote the five published reports, `config.json` and README in Hub commit fd07e07 without touching a `.pte`. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. ExecuTorch 1.6.0-rc1 (tagged 2026-10-30, wheel on PyTorch's test channel, torch 2.15.0) has no LFM3 model either, though its `ShortConv` takes a width: under it the same module matches Hugging Face (identical logits without a cache, 2.1e-4 with the custom-op cache and the ring), and a 2k 8da4w export (1,239,187,968 B, 597 s with the base model's solve on the same CPUs) answers the smoke test through 1.6.0's own runner. Nothing was published from it: the apps ship the 1.5.1 runtime, which `EXECUTORCH_VERSION` keeps every export on. | +| 42 | 2026-10-31 | XNNPACK | LiquidAI's LFM3-1.7B (`Lfm3ForCausalLM`, remote code only: transformers has no LFM3 and ExecuTorch 1.5.1 none either, the newest release on 2026-10-31) cannot be described by ExecuTorch 1.5.1's transformer: of 24 layers 13 are width-7 gated short convolutions (`ShortConvBlock` hard-codes 3), 6 attend globally with a zero-tail partial RoPE (the first quarter of each head rotated at theta 1e6, frequencies over the full head dimension) and 5 attend over a 256-token window with full RoPE at theta 1e4 (one RoPE table per model upstream; `sliding_window` and `local_rope_theta` are declared in `ModelArgs` and never read), every attention output is gated per head by `sigmoid(gate_proj(x))` (hidden to 16; upstream's `use_attn_o_gate` is per element), and each operator and feed-forward is followed by its own RMSNorm (`post_attention_norm` is declared and never read). `pipeline/lfm3_model.py` builds it from ExecuTorch's parts and is applied in every process that builds the model, as the LFM2 state fix is. The windowed layers keep a ring of window + prefill chunk slots on `update_cache_with_indices` and a masked `custom_sdpa` (upstream's `RingKVCache` holds 2 x window and asserts a chunk fits, which a 2,048-token prefill does not), so no layer holds a full-window cache it cannot use and no window-squared mask exists. On the real checkpoint (ac2586a3) against the checkpoint's own `modeling_lfm3.py`, fp32: without a cache, identical logits over a 559-token app prompt and a 17-token one (max difference 0, top-1 100%); with the cache and export_llm's custom-op transforms, 96-token prefill chunks (the ring wraps), 40 decode steps and a second prompt at position zero, max logit difference 1.8e-4, top-1 100%, KL under 4e-7. The remote config does not load under transformers 5.17.0 (`standardize_rope_params` looks up a RoPE block for every layer type, `conv` included: KeyError); 5.22.1 loads it. | measured + source | `lfm3_check.py` harness (HF fp32 vs the module, no cache and cached); `examples/models/llama/{llama_transformer,model_args,attention}.py` and `examples/models/lfm2/short_conv.py` at v1.5.1 | XNNPACK only (Vulkan has no short-convolution kernel; neither vendor path has a definition). The app has no LFM3 chat template, so the family is exported ahead of it (`naming.AHEAD_OF_APP`) and the model card says so; `-Base` stays unpublished under the chat-only rule, LFM3-VL and the audio models are multimodal. The first published reports counted the 5 windowed layers at a full-window KV cache (1,476,395,008 B at 32k); since eba9368 `sizing` counts them as their fixed ring (852,492,288 B at 32k, 47,185,920 B of it the rings), and `correct-reports` rewrote the five published reports, `config.json` and README in Hub commit fd07e07 without touching a `.pte`. The decision gate first failed all three GPTQ windows on quiet rows: it reads one token, and LFM3's template opens a `` block in the generation prompt, so that token is the first word of the reasoning (fp32 'The' at 0.52 to 0.73 against 'We'), which the 4-bit file tipped the other way on two of four rows without calling anything. Qwen3's published gates had the same blind spot (`` at 0.9999 on every row, `measures_tool_calling` false). With `enable_thinking=False` the prompt ends in ``, and fp32's first token is `` at 1.000 on all 12 search rows and the answer on the quiet ones (0.98, 0.99, 0.95; 'Who wrote Pride and Prejudice?' undecided at 0.27); the 32k GPTQ file then keeps 12 of 12 calls at 0.9991 against 0.9998 and 3 of 4 quiet rows, `measures_tool_calling` true. `gate.prompts` now renders with the reasoning switched off for every family; templates without the switch are unchanged, and calibration still renders at the template's default. ExecuTorch 1.6.0-rc1 (tagged 2026-10-30, wheel on PyTorch's test channel, torch 2.15.0) has no LFM3 model either, though its `ShortConv` takes a width: under it the same module matches Hugging Face (identical logits without a cache, 2.1e-4 with the custom-op cache and the ring), and a 2k 8da4w export (1,239,187,968 B, 597 s with the base model's solve on the same CPUs) answers the smoke test through 1.6.0's own runner. Nothing was published from it: the apps ship the 1.5.1 runtime, which `EXECUTORCH_VERSION` keeps every export on. LFM3-1.7B-Base (545fc8f4) was published on request (`--allow-base`; the chat-only default stands for the watcher): its fp32 model puts a newline first on all 12 calling rows (0.71 to 0.86) and is undecided on three of four quiet rows, so its gate tracks fp32 without measuring tool calling, and every window kept 12 of 12 (0.9786 against 0.76) and completed the smoke prefix with ' Paris'. Both repos' ten files match their reports' sha256 on the Hub. | diff --git a/pipeline/manifest.py b/pipeline/manifest.py index fe1c175..cc78886 100644 --- a/pipeline/manifest.py +++ b/pipeline/manifest.py @@ -164,6 +164,13 @@ def readme(repo_id: str, reports: list[dict], hub_tags: list[str], license_files f"ExecuTorch {reports[0]['toolchain']['executorch']} runtime.", "", ] + if source.get("variant") == "base": + # Published only on request (--allow-base): say what it is before anything else. + out += [ + "This is the base checkpoint, a completion model: it continues text and is not trained to " + "follow chat turns or call tools. Give it a prefix to continue rather than a chat prompt.", + "", + ] if naming.ahead_of_app(naming.source_name(source["id"])): # The app picks the chat template from the name and has none for this family yet, so # it refuses these files until it gains one; the card says so instead of implying @@ -171,7 +178,12 @@ def readme(repo_id: str, reports: list[dict], hub_tags: list[str], license_files out += [ "The openweights app has no chat template for this model family yet, so it does not " "load these files until it gains one. Any ExecuTorch runtime with the LLM runner's " - "custom ops runs them today; render prompts with the model's own `chat_template.jinja`.", + "custom ops runs them today" + + ( + "." + if source.get("variant") == "base" + else "; render prompts with the model's own `chat_template.jinja`." + ), "", ] if any(r["recipe"].get("converter") == "lfm3" for r in reports):