laya-coreml README

The project's README from github.com/mizorewww/laya-coreml. As one markdown file: README.md.

Laya Core ML playing Snake with real local model probabilities

Version 0.4.0 aligns the host inference contract directly with official Laya v0.4.1 (1adc59f), replacing the earlier selective port. Batch/long-text prediction, hooks, structured decisions, calibration, HTTP/MCP, evaluation and Router behavior now share the official host semantics. See the migration guide for changed defaults, validation evidence and the remaining Core ML boundaries.

Laya-CoreML

Open-weight typed decisions on Apple Silicon. Core ML, Neural Engine, zero generated tokens.

PyPI · Hugging Face weights · 中文

A real Laya model plays Snake locally, with visible probabilities, score, length, latency and safety interventions. The GIF replays a recorded Core ML run at 1× speed. The game uses explicit planner features and a visible cycle safety layer.

The complete active Snake loop sustained 49.1–50.0 decisions/s across three uncapped 600-step episodes, with zero deaths and two safety interventions. Game-loop timings and paced-rate limits include rendering serialization; terminal painting is excluded.

One short multilingual decision: 4.98 ms P50 / 5.31 ms P95 on M3 Max with ANE FP16. The same experiment measured 2.78× better whole-system energy per decision than compiled MLX FP16. A separately validated W8 palette variant reached 4.88 ms and 3.19× energy improvement. These are single-question results, not full Snake frame times; the requested 10× improvement was not achieved.

Run the demo

Apple Silicon · macOS 15+ · Python 3.11–3.13.

pip install 'laya-coreml[demo]'
hf download aac6fef/laya-multilingual-coreml-ane --local-dir models/snake
laya-coreml-snake --model ./models/snake

Download once, then play offline. No PyTorch, Transformers or MLX is needed for inference. The terminal needs 104 columns × 35 rows. Space pauses; ↑/↓ changes speed; R resets; Q quits. First-time Core ML initialization can take tens of seconds.

Controls, recording and video export · Measured stable decision rates · Shareable video and recording provenance

Ask for a decision

pip install laya-coreml
import laya_coreml as laya

agent = laya.load("aac6fef/laya-multilingual-coreml-ane")
result = agent.predict(
    "The customer requests a refund of a duplicate payment.",
    {
        "refund": {
            "type": "noul",
            "instructions": "Does the customer request a refund?",
        }
    },
)
print(result["answers"]["refund"])

Laya returns probabilities for choice, ordinal score, and boolean noul questions. There is no autoregressive decoding or generated JSON to parse. Hub models download before initialization; subsequent predictions stay local. Pass local_files_only=True to require an existing cache, or load a local directory.

Following upstream v0.3.5, fitted calibration temperatures are clamped to [0.5, 5.0] before use: the shipped choice:11+ bucket is 0.1006, which would sharpen logits ~10x and report a coin flip as near-certainty. The checkpoint's raw values remain available as agent.temperature_raw and agent.temperature_by_options_raw, and a RuntimeWarning names every clamped bucket at load.

The ANE bundle has a 96-token total limit, including question, options and state. State truncation and long-text scanning use that actual budget; oversized question heads or option sets still fail. Use aac6fef/laya-multilingual-coreml for the general-purpose 1024-token model. Full API, model selection and offline usage.

Measured on M3 Max

Performance figures below come from the linked original benchmark runs. Version 0.4.0 validates fidelity; it makes no new throughput or energy claim.

40-core GPU, 128 GiB, macOS 27.2. One 91-token question padded to 96, including prompt preparation, tokenization, arrays, synchronous inference, calibration and formatting. Loading and warmup are excluded. MLX enables compile, prefix caching and shape buckets. Six alternating 20-second blocks per implementation produced 65,598 stable calls.

Metric Compiled MLX FP16 Core ML ANE FP16 Core ML ANE W8
P50 / P95 6.94 / 7.39 ms 4.98 / 5.31 ms 4.88 / 5.23 ms
Mean system power estimate 61.39 W 30.75 W 27.39 W
System energy / decision 0.4288 J 0.1540 J 0.1344 J
Speed gain 1× 1.39× 1.42×
System energy gain 1× 2.78× 3.19×

Energy uses direct SMC PSTR sensor readings, with raw samples and explicit anomaly rejection. This is an estimate with sensor and background-load uncertainty. Speed gain × average power ratio = energy gain; multiplying energy by speed again would double-count time. The W8 variant compresses weights while retaining FP16 compute. It is approximate, and its package-size reduction is not a speed ratio.

Speed, energy and hardware evidence · Raw measurements.

Available checkpoints

Hugging Face bundle Default engine Capacity Purpose
Laya 421M CPU + GPU 512 tokens Original English model
Multilingual 322M CPU + GPU 1024 tokens General multilingual decisions
Typed Decisions 421M CPU + GPU 1024 tokens Original specialized checkpoint
Snake GPU CPU + GPU B3 / L64 Batches the three compact game questions
Multilingual ANE CPU + ANE B1 / L96 Short decisions, FP16
Multilingual ANE W8 CPU + ANE B1 / L96 Optional approximate palette compression

Every bundle includes tokenizer/configuration, model card, provenance, checksums and packaging-time validation. ANE bundles also include the exact original host embedding/action tensors they need. No original training checkout is required.

Port fidelity and limits

The three general-purpose FP16 checkpoints match upstream selected answers on 189/189 validation questions. Each passes 100 repeated calls. ANE FP16 L96 passes 59/59 fitting questions, with maximum calibrated-probability drift 0.002925; W8 passes the same subset with drift 0.014393 under an unchanged 0.02 gate. Six- and four-bit experiments failed that gate and are not published weights. These are conversion-fidelity fixtures, not proof of general task accuracy.

A separately exported FP16 ANE L1024 graph passes the complete 63/63 fixture, but an actual 1024-token request takes about 91.7 ms in its serial screen. The short ANE result does not establish a long-context advantage. A 600-step paired Snake check matches 600/600 actions, with zero deaths and zero shield interventions; the current ANE adapter's three sequential calls do not establish a consistent full-game speedup over compiled MLX.

The ordinary SDPA Core ML export and the ANE graph are different implementations. The ordinary export defaults to CPU+GPU after unrestricted RangeDim GPU shapes failed local fidelity checks. Changing its device setting alone does not reproduce the ANE result. The ANE rewrite uses BC1L activations, 1×1 projections and per-head attention; its plan and a separate Instruments trace support Neural Engine work. CPU still handles input/output boundaries.

Documentation and reproducibility

To export yourself, install laya-coreml[convert] and run laya-coreml convert laya-multilingual models/custom. ANE research conversion, compression and benchmark scripts live in the Git checkout. The inference wheel contains the portable runtime and optional terminal demo.

Apache-2.0. Independent port of Laya, by Convai Innovations and contributors, building on the MLX sibling project. Not an official Convai Innovations or Apple release. See NOTICE.

Official v0.4.1 host compatibility (v0.4.0)

This release ports host behavior directly from upstream 1adc59f to Core ML. Model weights remain separate downloads. The runtime still needs no PyTorch, Transformers, or MLX. Optional temperature fitting, training helpers and conversion use PyTorch. Migration and complete compatibility scope.

import laya_coreml as laya

router = laya.Router(max_loaded=2)
result = router.predict(state, questions, min_confidence=0.7)
router.register("local", "./models/my-coreml-bundle", description="Custom classifier")
result = router.predict(state, questions, model="local")
router.unload("local")
router.unregister("local")

Router() uses the published English, multilingual and typed-decisions Core ML bundles. It defaults to two resident models and to multilingual when the language is undecided. Use Router(default="english") to choose English as the fallback. route() inspects a request without loading weights; explicit model, task, and lang override inference from the input. Automatic typed-workflow detection is opt-in through auto_task_detection=True. Language detection includes the upstream acronym, capitalization and mixed-script fixes.

Pass models={"custom": "./bundle"} at construction, or use register, registered, attach, preload, and unload. Sources are local Core ML bundles or Hub repository IDs. compute_units, revision, and local_files_only are passed to bundle loading. An attached ANE bundle uses its usual CPU+NE default when compute_units is omitted. Resident-model access and status reads remain available during a cold load; duplicate loads share construction. Replacing/unregistering a source waits for its in-flight build, then removes the old resident entry, following official synchronization. Unload drops router references without invalidating agents held by callers or ongoing predictions. Core ML manages native caches; the router collects unreachable Python objects and never deletes cached model files.

Agent, ANEAgent, and Router accept min_confidence=0.7 or a bucket mapping such as {"choice:2": 0.8, "choice:3-5": 0.7, "default": 0.6}. Answers gain abstention, abstention_threshold, and, when below threshold, low_confidence. The gate preserves the answer and does not automatically call a fallback. Shipped confidence values still require held-out calibration for any correctness-probability interpretation.

result = laya.predict_tournament(router, state, questions, group_size=16)
# Optional external embedder: maps a list of strings to an (N, D) numeric array.
result = laya.predict_shortlist(router, state, questions, embed_fn, k=16)

Tournament elimination handles large choice sets without an embedding model. result["tournament"] records finalists, original counts, and rounds. Probabilities and usage describe the final pass only. Choose group_size / shortlist k within the bundle's exported option capacity. shortlist_choice is also available for caller-managed ranking; the Core ML graph does not expose an encoder embedder.

Email helpers (laya_coreml.email.clean_email_body, email_state, email_questions) include English, Portuguese, Spanish and French cleanup, including the French device footer fix. Cleaning is explicit and never silently applied to ordinary input.

Parallel option layout

The converter supports checkpoints trained with "option_layout": "parallel": shared option positions, option-isolating encoder masks, local attention measured in position IDs, and the position-free decision head. Preparation, fixed/enumerated shapes, conversion and runtime use matching position_ids and option_ids inputs. Missing configuration means sequential; unknown layouts and configuration/export mismatches raise an error. Do not switch an existing bundle to parallel by editing its JSON: the graph and trained weights must match the layout.

FP32 and FP16 exports are tested on CPU and CPU+GPU, with varying input lengths and option order, against upstream v0.4.1. Legacy ANE exports have sequential RoPE baked into the graph and reject parallel configurations; use the general convert path for parallel checkpoints. Existing ANE packages receive the shared prompt, gating, routing and decision-helper features without requiring reconversion. No new parallel pretrained weights or parallel ANE acceleration claim is made by this release.

Validation covers all 24 permutations of four options, a sequential sensitivity control, pinned upstream numerical parity, real Core ML export/load execution, registry races, routing and helper semantics. CI runs portable tests on Linux and actual Core ML tests on macOS. Reproduce with:

uv sync --extra convert --extra dev --extra demo --extra publish --extra reference
# Check out upstream 1adc59f into .upstream for reference parity.
uv run --no-sync pytest -q

The three general-purpose bundles match all 189/189 selected answers from the original FP32 golden fixture. The fixed L96 ANE bundle matches all 59/59 questions that fit its capacity (four long questions are excluded). Each bundle passes 100 identical repeated calls: 248/248 agreements and 400 stability calls in total. This measures port fidelity on the fixture, not general task accuracy. See the release validation report.

laya-coreml (mizorewww/laya-coreml)

Searching Database…

这是什么东西?它是 Laya 的开放权重 Python 移植版,用来回答选择题——从选项里挑一个、给出等级评分,或回答是/否——在 Apple Silicon 上通过 Core ML 和神经网络引擎本地运行,完全不生成文本 token。
那它是我写代码调用的 Python 库,还是我直接运行的应用?是一个 Python 库:从 PyPI 安装 laya-coreml,然后在代码里调用它的 Agent、ANEAgent 和 Router 类(也附带一个命令行工具)。还有一个可选的终端演示,用模型玩贪吃蛇。
我该怎么把它跑起来?在一台 Apple Silicon Mac(macOS 15+,Python 3.11–3.13)上运行 pip install laya-coreml;模型权重会从 Hugging Face 下载一次。可选的贪吃蛇演示需要 104 列 × 35 行的终端窗口。
我还需要另外装 PyTorch 或 Transformers 吗?不需要。推理本身不依赖 PyTorch、Transformers 或 MLX——这些重型框架只用于可选的附加功能,比如温度拟合、训练辅助工具,以及转换你自己的检查点。
那个高速的神经网络引擎模式有什么限制?ANE 的模型包把单次请求限制在总共 96 个 token——包括问题、选项和状态——超长的输入会直接失败。长文本要用 1024 token 的 CPU+GPU 模型包;1024 token 的 ANE 导出版每次请求大约耗时 91.7 毫秒,所以 ANE 适合短决策。
所以它只能在 Mac 上运行吗?实际上是的:推理走的是 Core ML 和神经网络引擎,所以需要一台运行 macOS 15+ 的 Apple Silicon Mac。仓库的可移植测试能在 Linux CI 上跑,但真正的 Core ML 推理只能在 macOS 上进行。
它能离线工作吗,还是会把我的问题发送到别处?首次从 Hugging Face 下载模型之后就能完全离线运行;之后的每一次预测都留在你自己的电脑上。传入 localfilesonly=True 可以强制只使用已有的缓存。
许可证宽松吗?这是 Apple 或 Convai 的官方发布吗?是 Apache-2.0,可以商用。它是 Laya(原作者是 Convai Innovations 及其贡献者)的独立社区移植版,并非 Convai 或 Apple 的官方发布。
它到底有多快?在 M3 Max 上,ANE FP16 模型回答一个短问题的耗时为 4.98 毫秒 P50 / 5.31 毫秒 P95,W8 版本为 4.88 毫秒,而编译后的 MLX FP16 是 6.94 毫秒。每次决策的整机能耗比 MLX 低 2.78 倍(W8 版为 3.19 倍)。这些是单个问题的数据,不是贪吃蛇整帧的耗时。
我可以从 Hugging Face 拉取哪些模型包?一共六个:原始英文 421M(512 token 上下文)、一个 322M 多语言模型和一个 421M 类型化决策模型(各 1024 token)、一个贪吃蛇 GPU 包,以及两个神经网络引擎多语言版本——FP16 和一个近似 W8 调色版。每个包都自带分词器、配置、模型卡、校验和以及所需的张量。
Core ML 移植版的回答和原模型完全一致吗?在验证测试集上是的:三个通用 FP16 检查点在 189 道题上与上游结果完全一致,各自还通过了 100 次相同的重复调用。ANE FP16 版本在校准概率上最多偏差约 0.003,W8 约 0.014,都在 0.02 的门槛之内——不过这只是测试集上的保真度,并不代表真实任务准确率已得到验证。
Router 类有什么用?它会把多个 Core ML 模型包常驻内存,并把每个请求路由到合适的那一个;语言未确定时默认用多语言模型;route() 可以在不加载权重的情况下检查请求。调用方可以设置一个 minconfidence 门槛(默认 0.7),把低置信度的结果标记为弃权,而庞大的选项集则通过锦标赛淘汰法处理。
Creator
mizorewww
Size
6.2 MB
Stars
1.6K
Age
28d
Commits · 90 Days