Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[workspace]
members = ["src/frontend", "src/runtime", "src/models/clm", "src/models/cua_s1/native", "src/models/qwen3_5/native", "src/models/open_jev/native", "src/models/jev_vl/native", "src/models/omnijev/native", "src/models/laya", "src/backends/cuda", "src/models/decider/native", "src/models/jemm/native", "src/models/startlux/native", "src/models/clef/native", "src/models/kev/native"]
members = ["src/frontend", "src/runtime", "src/models/clm", "src/models/cua_s1/native", "src/models/qwen3_5/native", "src/models/open_jev/native", "src/models/jev_vl/native", "src/models/omnijev/native", "src/models/laya", "src/backends/cuda", "src/models/decider/native", "src/models/jemm/native", "src/models/startlux/native", "src/models/clef/native", "src/models/kev/native", "src/models/lfm2/native"]
resolver = "3"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ checkpoint. Public231 concurrency-1 latency for heads `1ba07d1`, `f968e576`,
| StartLux-Decision v1.1 4B Instant | [Native Rust/CUDA text worker](recipe/startlux/README.md); `choice` / `noul` / `score`; weights CC BY-NC 4.0; Instant only (no AutoThink, no 27B); GPU parity unverified; [L20X latency recipe](recipe/startlux/latency.md) |
| autotrust/JEV-27B-VL | [Experimental Rust/CUDA worker](recipe/jev_vl/README.md); single-question text, online inline PNG/JPEG and offline-preencoded image inputs; [validation scope and limits](recipe/jev_vl/validation.md) |
| CLM-v0.1-8B | [External worker with a CPU stub encoder](recipe/clm/README.md); contract checks only, real Qwen3-8B decisions unverified by this recipe |
| LFM2.5-350M | [Transformers worker](recipe/lfm2/README.md); text state and independent choice questions |
| LFM2.5-350M | [Transformers Choice worker](recipe/lfm2/README.md) and [Rust preparation with F32 export](recipe/lfm2/native.md) |
| OmniJev-4B v1.1 | [Native Rust/CUDA worker](recipe/omnijev/native.md), eager: one image, Choice, Noul and Score; [reference comparison on sm_89](recipe/omnijev/native.md#comparison-with-the-reference) |
| Kev-4B | [Pinned CPU export and Rust pointer head](recipe/kev/README.md); no worker or full-model parity yet ([#27](https://github.com/InferMatrixLab/system1-omni/issues/27)) |
| D3 (Decision 3.0) | [Python reference worker](recipe/d3/reference.md) on the checkpoint's pinned runtime; `choice`/`noul`/`score` over text, image and video state; author-run on A100 for text and media serving (see the integration and media PRs) |
Expand Down
2 changes: 2 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ the Rust `omni-clef` worker. It admits one complete text request through
process runs the checkpoint's joint schema head on its main thread, which is
the thread that initialized CUDA. The joint head is still that Python module.
Clef does not use the shared Qwen CUDA executor.
[LFM2.5-350M Rust preparation](../recipe/lfm2/native.md) produces Choice token
plans and verifies the F32 artifact for a future executor.

The shared Qwen executor also exposes a single-row eager
`forward_prompt_prefix_bidirectional` prerequisite: state queries read state
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ nav:
- OmniJev native worker: recipe/omnijev/native.md
- CLM stub-encoder contract: recipe/clm/README.md
- LFM2.5-350M choice worker: recipe/lfm2/README.md
- LFM2.5-350M Rust preparation: recipe/lfm2/native.md
- D3 reference worker: recipe/d3/reference.md
- Vela 2.0 reference workers: recipe/vela/reference.md
- Clef reference worker: recipe/clef/reference.md
Expand Down
2 changes: 2 additions & 0 deletions recipe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ For a first real decision, follow the [complete CPU walkthrough](../docs/getting

- [LFM2.5-350M choice worker](lfm2/README.md): score text decisions with independent
questions, hybrid cache branching and configurable candidate batches.
The [Rust preparation recipe](lfm2/native.md) covers Choice token plans,
same-score replay, and CPU F32 export.

Recipes contain setup, launch commands and examples. Reusable implementation code
belongs under `src/`.
Expand Down
3 changes: 3 additions & 0 deletions recipe/lfm2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ This recipe covers text `state` and `choice` questions only. Each public
question is evaluated independently; only candidates within one question share a
prefill. Question IDs are never placed in the prompt.

The [Rust preparation recipe](native.md) covers token plans, frozen-score replay,
CPU F32 export, and the opt-in Q12 Transformers reference.

## Pinned artifacts

| Artifact | Pin |
Expand Down
163 changes: 163 additions & 0 deletions recipe/lfm2/export_f32.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""Widen the pinned LFM2.5-350M BF16 checkpoint into a local F32 artifact."""

import argparse
import hashlib
import json
import os
import shutil
import struct
import tempfile
from pathlib import Path

import numpy as np
from safetensors import safe_open

ROOT = Path(__file__).resolve().parents[2]
PROFILE = ROOT / "src/models/lfm2/native/profile.json"
SOURCE = "model.safetensors"
WEIGHTS = "weights.f32.safetensors"
FORMAT = "omni-lfm2-f32-v1"
CHUNK = 1 << 20


def identity(path):
with path.open("rb") as handle:
return {"bytes": path.stat().st_size,
"sha256": hashlib.file_digest(handle, "sha256").hexdigest()}


def require(condition, message):
if not condition:
raise ValueError(message)


def check_source(checkpoint, profile):
files = {name: identity(checkpoint / name) for name in profile["checkpoint"]}
for name, info in files.items():
require(info["sha256"] == profile["checkpoint"][name], f"wrong source hash: {name}")
return files


def widen(source, output):
"""Write a deterministic safetensors header and widen unsigned BF16 bits."""
with source.open("rb") as handle:
header_bytes, = struct.unpack("<Q", handle.read(8))
require(0 < header_bytes <= 32768, "unexpected BF16 header length")
header = json.loads(handle.read(header_bytes))
header.pop("__metadata__", None)
names = sorted(header)
require(len(names) == 148 and "lm_head.weight" not in header
and "model.embed_tokens.weight" in header, "wrong inventory or broken tied LM head")

out_header = {"__metadata__": {"format": "pt"}}
cursor = 0
with safe_open(source, framework="pt", device="cpu") as tensors:
require(tensors.keys() == names, "BF16 safetensors index mismatch")
for name in names:
entry = header[name]
start, end = entry["data_offsets"]
shape = tensors.get_slice(name).get_shape()
require(entry["dtype"] == "BF16" and shape == entry["shape"],
f"unexpected source dtype or shape: {name}")
byte_count = (end - start) * 2
out_header[name] = {"dtype": "F32", "shape": shape,
"data_offsets": [cursor, cursor + byte_count]}
cursor += byte_count
encoded = json.dumps(out_header, separators=(",", ":")).encode("ascii")
encoded += b" " * (-len(encoded) % 8)
with output.open("xb") as handle:
handle.write(struct.pack("<Q", len(encoded)))
handle.write(encoded)
for name in names:
start, end = header[name]["data_offsets"]
values = np.memmap(source, dtype="<u2", mode="r",
offset=8 + header_bytes + start, shape=((end - start) // 2,))
for offset in range(0, values.size, CHUNK):
widened = np.left_shift(values[offset:offset + CHUNK].astype("<u4"), 16)
handle.write(widened.astype("<u4", copy=False).tobytes())
del values
handle.flush()
os.fsync(handle.fileno())


def verify_values(checkpoint, artifact):
"""Independently compare all F32 bits to PyTorch CPU widening."""
import torch

with safe_open(checkpoint / SOURCE, framework="pt", device="cpu") as src, \
safe_open(artifact / WEIGHTS, framework="pt", device="cpu") as dst:
require(src.keys() == dst.keys(), "tensor names changed during export")
parameters = 0
for name in src.keys():
original = src.get_tensor(name)
result = dst.get_tensor(name)
require(original.dtype == torch.bfloat16 and result.dtype == torch.float32
and original.shape == result.shape, f"dtype or shape mismatch: {name}")
original = original.flatten()
result = result.flatten()
for start in range(0, original.numel(), CHUNK):
expected = original[start:start + CHUNK].float()
actual = result[start:start + CHUNK]
require(torch.equal(actual.view(torch.int32), expected.view(torch.int32)),
f"F32 widening mismatch: {name} from element {start}")
require(torch.isfinite(actual).all().item(), f"non-finite weight: {name}")
parameters += original.numel()
return {"tensors": len(src.keys()), "parameters_bitwise_checked": parameters}


def verify(checkpoint, artifact, profile, files):
manifest = json.loads((artifact / "manifest.json").read_text(encoding="utf-8"))
require(manifest["format"] == FORMAT and manifest["profile"] == profile,
"artifact profile or schema mismatch")
expected = {WEIGHTS: identity(artifact / WEIGHTS)}
expected.update({name: info for name, info in files.items() if name != SOURCE})
require(manifest["files"] == expected, "artifact inventory mismatch")
for name, info in expected.items():
if name != WEIGHTS:
require(identity(artifact / name) == info, f"changed checkpoint file: {name}")
report = verify_values(checkpoint, artifact)
report.update({"manifest": identity(artifact / "manifest.json"), "files": expected})
return report


def export(checkpoint, output, profile, files):
require(not output.exists(), f"output already exists: {output}")
staging = Path(tempfile.mkdtemp(prefix=f".{output.name}.", dir=output.parent))
try:
manifest_files = {name: info for name, info in files.items() if name != SOURCE}
needed = files[SOURCE]["bytes"] * 2 + sum(info["bytes"] for info in manifest_files.values())
require(shutil.disk_usage(staging).free >= needed, "insufficient storage for F32 export")
for name in manifest_files:
shutil.copyfile(checkpoint / name, staging / name)
widen(checkpoint / SOURCE, staging / WEIGHTS)
manifest_files[WEIGHTS] = identity(staging / WEIGHTS)
manifest = {"format": FORMAT, "profile": profile, "files": manifest_files}
with (staging / "manifest.json").open("x", encoding="utf-8", newline="\n") as handle:
json.dump(manifest, handle, ensure_ascii=False, indent=2, sort_keys=True)
handle.write("\n")
report = verify(checkpoint, staging, profile, files)
require(not output.exists(), f"output already exists: {output}")
staging.rename(output)
return report
except BaseException as error:
error.add_note(f"Partial export retained at {staging}")
raise


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("checkpoint", type=Path, help="local pinned LFM2.5-350M snapshot")
parser.add_argument("artifact", type=Path, help="output directory (or existing directory with --verify)")
parser.add_argument("--verify", action="store_true", help="verify an existing export without writing it")
args = parser.parse_args()
profile = json.loads(PROFILE.read_text(encoding="utf-8"))
files = check_source(args.checkpoint, profile)
if args.verify:
report = verify(args.checkpoint, args.artifact, profile, files)
else:
report = export(args.checkpoint, args.artifact, profile, files)
print(json.dumps(report, indent=2, sort_keys=True))


if __name__ == "__main__":
main()
153 changes: 153 additions & 0 deletions recipe/lfm2/native.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# LFM2.5-350M Rust preparation

The **omni-lfm2-native** CLI validates and prepares the Choice contract,
interprets supplied sequence scores, and inspects an F32 weight package. It runs
on CPU. The [Transformers recipe](README.md) supplies the runnable worker.
See the [model contract](../../src/models/lfm2/README.md) for API semantics and
the [executor boundary](../../src/models/lfm2/README.md#rust-preparation-and-executor-boundary)
for device state and readout ownership.

## Checkpoint and CPU export

Run from the repository root. Use an existing local snapshot of
[LiquidAI/LFM2.5-350M at the pinned revision](https://huggingface.co/LiquidAI/LFM2.5-350M/tree/9e6c6ccf47cd318696e137d381a7ded8fe4df09f)
under the upstream LFM Open License. The recipe requires its config, tokenizer,
tokenizer config, chat template, license and single BF16 safetensors file. The
[profile](../../src/models/lfm2/native/profile.json) pins each source file's SHA-256.
Use Python 3.12, NumPy 2.4.6, safetensors 0.8.0 and PyTorch 2.14.0 as in the
[reference lock](../../src/models/lfm2/requirements.lock.txt). The recorded CPU
export used the existing Q12 environment with GPU visibility empty. Allow about
1.5 GB of free output space and 3 GiB of available memory for export plus
verification. The output parent must already exist.

~~~sh
export CHECKPOINT=/absolute/path/to/pinned/snapshot
export ARTIFACT=/absolute/path/to/new/lfm2-f32
CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 \
python recipe/lfm2/export_f32.py "$CHECKPOINT" "$ARTIFACT"
CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 \
python recipe/lfm2/export_f32.py "$CHECKPOINT" "$ARTIFACT" --verify
cargo build --locked --release -p omni-lfm2-native
./target/release/omni-lfm2-native inspect "$ARTIFACT"
~~~

Export widens BF16 bits into little-endian F32. An independent PyTorch CPU check
compares every F32 bit and checks finiteness before publishing the directory.
The manifest records the source profile and the byte size and SHA-256 of every
artifact file. The original config and tokenizer files are copied byte for byte.
The config's BF16 dtype describes the source snapshot. The manifest and
safetensors header describe the F32 package. The LM head aliases the input
embedding tensor, with one physical copy. An interrupted export leaves a staging
directory for inspection. Choose a new output path for a retry.

| Artifact inventory | Verified value |
| --- | --- |
| Manifest schema | omni-lfm2-f32-v1 |
| Weight file | weights.f32.safetensors |
| Unique tensors / elements | 148 / 354,483,968 |
| Weight file size | 1,417,952,352 bytes |
| Weight SHA-256 | 4757f9b07ce4eb8540130f40cd1607f0c953ef8d8f53768ddfb6b782db420fb8 |
| Manifest SHA-256 | 591a567ab5af3bb4d0d4e037599ab1fb2af6f3bd54018984325cfb2ffcc10cd4 |

Rust inspection checks the profile, file hashes and tensor inventory including
dtype, geometry and offsets. Keep weight packages outside the source tree.

## Prepare a request and replay captured scores

Use a public Choice request from the [frozen fixture](../../tests/lfm2/fixtures/q12_replay.json)
or supply your own. This example extracts a real request and its original
uncached F32 sequence totals. The finish step takes scores in the question and
candidate order emitted by prepare.

~~~sh
export BIN=./target/release/omni-lfm2-native
python - <<'PY'
import json
from pathlib import Path

with open("tests/lfm2/fixtures/q12_replay.json", encoding="utf-8") as handle:
case = json.load(handle)["public"][0]
Path("request.json").write_text(json.dumps(case["request"]), encoding="utf-8")
scores = [question["plan"]["fields"][0]["scores"] for question in case["questions"]]
Path("scores.json").write_text(json.dumps(scores), encoding="utf-8")
PY
"$BIN" validate request.json
"$BIN" render request.json
"$BIN" prepare "$ARTIFACT/tokenizer.json" request.json
"$BIN" finish "$ARTIFACT/tokenizer.json" request.json scores.json
~~~

Render emits the literal prompt, field suffix and JSON candidate plus newline.
Prepare emits their independently encoded IDs in the same order, along with
unpadded usage, candidate targets and half-open continuation and full-sequence
logit intervals. A single request or score input can use standard input via the
path "-". Validation errors include the request status and detail on stderr.
Malformed-input text comes from the Rust JSON parser, which accepts Unicode
scalar text and bounds JSON nesting at 512 levels.

## Verify the preparation contract

~~~sh
cargo test --locked -p omni-lfm2-native -- --list
cargo test --locked -p omni-lfm2-native
LFM2_TOKENIZER_JSON="$ARTIFACT/tokenizer.json" LFM2_ARTIFACT_DIR="$ARTIFACT" \
cargo test --release --locked -p omni-lfm2-native -- --ignored
~~~

The default suite replays frozen token fragments and F32 scores for five public
requests, six questions and 266 candidate branches, plus the original 17
internal schema cases. It verifies exact text hashes, order, readout intervals,
choice and usage. Same-score probabilities and confidence use the Python
verifier's 1e-6 absolute tolerance. Opt-in tests use the actual tokenizer and
inspect the full artifact. The
[fixture extractor](../../tests/lfm2/freeze_native_contract.py) consumes the
frozen captures and pinned tokenizer without running a forward. From the
repository root with the Q12 environment, reproduce it with
`python tests/lfm2/freeze_native_contract.py "$CAPTURE_ROOT" "$CHECKPOINT" replay.json`,
where `CAPTURE_ROOT` is the verified Q12 archive extraction. The
[profile file](../../src/models/lfm2/native/profile.json) identifies the
approved original public capture and its Python and RLCD source revisions.
The historical FP16 runs compare their respective profiles separately.

## Explicit Q12 Transformers reference

The approved numerical reference used an NVIDIA L20 (sm_89, driver 580.178.04)
with CPython 3.12.13, Torch 2.14.0+cu130, Transformers 5.17.0 and cuDNN 9.24.0.43.
It loaded the same BF16 checkpoint directly as CUDA FP32 and used eager
attention and PyTorch convolution. Run the original verifier from the repo
root in that environment with one allocated GPU visible, the pinned RLCD code
available locally and the pinned checkpoint already in the HF cache. The
standard worker still defaults to FP16.

~~~sh
HF_HUB_OFFLINE=1 python - .local/lfm/reference .local/lfm/q12.verify.json <<'PY'
import runpy
import sys
from importlib.util import find_spec

import torch

torch.set_float32_matmul_precision("highest")
torch.backends.cudnn.allow_tf32 = False
assert torch.cuda.device_count() == 1
assert not torch.backends.cuda.matmul.allow_tf32
assert torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction
assert torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction
assert torch.backends.cudnn.enabled
assert not torch.backends.cudnn.benchmark and not torch.backends.cudnn.deterministic
assert not torch.are_deterministic_algorithms_enabled()
assert not torch.is_autocast_enabled("cuda")
assert find_spec("causal_conv1d") is None and find_spec("fla") is None
reference, output = sys.argv[1:]
sys.path.insert(0, "recipe/lfm2")
sys.argv = ["recipe/lfm2/verify.py", "--reference-dir", reference,
"--device", "cuda", "--dtype", "float32",
"--batch-sizes", "1,8,16,32,64,all", "--output", output]
runpy.run_path(sys.argv[0], run_name="__main__")
PY
~~~

L20 executor acceptance requires exact choices, per-candidate absolute score
error below 0.15 against the independent, uncached F32 reference and the original
cache checks (atol 0.015, rtol 0.08, argmax and isolation). Actual native
execution, HTTP readiness and device limits are pending for #159.
Loading
Loading