This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
DokterSmol 6997f8da14 tests, docs: lfm3 in the family tests, with its golden and declare cases
A tiny LFM3 (conv, full attention, conv, sliding attention; window 8, conv
width 7) joins the engine tests every family runs: the golden against the
reference implementation, chunking and batching, libavx against libref,
decode against prefill, concurrent requests and speculation by prompt lookup.
Its golden is made by mklfm3golden.py from the modelling code LiquidAI ships
with the checkpoint, since transformers has no LFM3 class.

arch_test covers what the plugin declares for each layer kind, what it
refuses, and a step through both attention groups.
2026-11-17 18:12:32 +01:00

74 lines
3.4 KiB
Python

"""mklfm3golden.py CKPTDIR CODEDIR OUT.h -- the LFM3 golden for tests/engine_e2e_test.cpp.
transformers has no LFM3 model class; the reference is the modelling code LiquidAI ships with the
checkpoint (configuration_lfm3.py, modeling_lfm3.py, lfm3_conv.py; Apache-2.0). CODEDIR is a
directory holding those files, for example a download of LiquidAI/LFM3-1.7B: its classes are
built over the tiny random checkpoint tests/tiny_model.h writes and run in float32, as
mktinygolden.py does for the other families. Nothing of CODEDIR's weights is read.
CKPTDIR holds the tiny checkpoints: run `RAD_E2E_KEEP=1 build/tests/engine_e2e_test` and pass the
directory it prints. The header records the FNV-1a hash of lfm3/model.safetensors (the test
refuses a golden made from other weights), the sha256 of the modelling file, and at every
position of mktinygolden.py's prompt the four most likely next tokens with their
log-probabilities."""
import hashlib, json, os, re, sys
import torch
from safetensors.torch import load_file
import transformers
from transformers.dynamic_module_utils import get_class_from_dynamic_module
ckpt_dir, code_dir, out = sys.argv[1], sys.argv[2], sys.argv[3]
torch.manual_seed(0)
here = os.path.dirname(os.path.abspath(__file__))
PROMPT = json.loads(re.search(r"kTinyGoldPrompt\[\] = (\".*\");",
open(os.path.join(here, "tiny_golden.h")).read()).group(1))
ids = list(PROMPT.encode())
TOP = 4
def fnv(path):
h = 0xcbf29ce484222325
for b in open(path, "rb").read():
h = ((h ^ b) * 0x100000001b3) & (2**64 - 1)
return h
d = os.path.join(ckpt_dir, "lfm3")
cfg = json.load(open(os.path.join(d, "config.json")))
for k in ("architectures", "model_type"):
cfg.pop(k, None)
# The release's pad and bos ids lie outside the tiny vocabulary.
cfg["pad_token_id"] = None
cfg["bos_token_id"] = None
Config = get_class_from_dynamic_module("configuration_lfm3.Lfm3Config", code_dir)
Model = get_class_from_dynamic_module("modeling_lfm3.Lfm3ForCausalLM", code_dir)
model = Model(Config(**cfg))
sd = {k: v.float() for k, v in load_file(os.path.join(d, "model.safetensors")).items()}
missing, unexpected = model.load_state_dict(sd, strict=False)
# A tied head is the embedding; anything else missing is a naming error.
missing = [k for k in missing if k != "lm_head.weight"]
if missing or unexpected:
raise SystemExit(f"lfm3: missing {missing}, unexpected {unexpected}")
model = model.float().eval()
with torch.no_grad():
lp = torch.log_softmax(model(torch.tensor([ids])).logits[0].float(), dim=-1)
v, i = torch.topk(lp, TOP, dim=-1)
code_sha = hashlib.sha256(open(os.path.join(code_dir, "modeling_lfm3.py"), "rb").read()).hexdigest()
def rows(t, fmt):
return ", ".join("{ " + ", ".join(fmt(x) for x in row) + " }" for row in t)
L = ["/* lfm3_golden.h -- GENERATED by mklfm3golden.py from LiquidAI's modeling_lfm3.py (sha256",
f" * {code_sha}) under transformers {transformers.__version__};",
" * do not edit. */", "#pragma once", '#include "tiny_golden.h"', "",
f"static_assert(kTinyGoldPositions == {len(ids)} && kTinyGoldTop == {TOP}, "
'"lfm3_golden.h was made for another prompt");',
"static const TinyGold kLfm3Gold = {",
f" \"lfm3\", 0x{fnv(os.path.join(d, 'model.safetensors')):016x}ull,",
" { " + rows(i, lambda x: str(int(x))) + " },",
" { " + rows(v, lambda x: f"{float(x):.6g}f") + " } };"]
open(out, "w").write("\n".join(L) + "\n")