Локальный движок типизированных решений · Local typed-decision engine
Go + ONNX Runtime · ~322M параметров · GPU или CPU · без Python в рантайме · один forward pass на запрос · без генерации текста
Представьте, что у большой языковой модели есть быстрый помощник, который отвечает не текстом, а конкретным решением: «какой это тип задачи?», «насколько это опасно?», «верно ли утверждение?». Laya Engine — это такой помощник, работающий на вашем компьютере: ~322 млн параметров вместо сотен миллиардов, десятки-сотни миллисекунд вместо секунд, ноль обращений в интернет.
Три ключевые идеи:
- Не генерация, а решение. Модель за один forward pass выдаёт вероятности по
вашим вариантам (
choice), оценку по шкале (score) или P(истина) для утверждения (noul). Она не пишет код и не «рассуждает» — она быстро отвечает на узкие вопросы о коротком тексте. - Один сервис на всю машину. Всё живёт на
127.0.0.1:8095: ассистенты, скрипты, задачи обработки данных ходят в один процесс, а не поднимают каждый свои копии весов. - Где дешевле вычислить, чем рассуждать. Типизация задачи, оценка риска действия, триаж лога, ранжирование контекста — на это большая модель тратит секунды и токены, а локальный движок — десятки миллисекунд и ноль токенов.
flowchart LR
C["Клиент (ассистент, скрипт,<br/>плагин ZCode)"] -->|POST /decide| A["HTTP API<br/>127.0.0.1:8095"]
A --> B["Сборка входа<br/>вопрос + варианты + состояние"]
B --> T["Токенизатор mmBERT<br/>(на Go, сверен с эталоном)"]
T --> O["ONNX Runtime<br/>CUDA или CPU"]
O -->|"logits → softmax<br/>с температурой"| R["Ответ: выбор, вероятности,<br/>уверенность, бюджет, чекпоинт"]
R --> C
- Один запрос — один проход модели. Все вопросы батча считаются вместе: «цена» запроса зависит от числа вопросов и длины состояния, а не от параллелизма (≈1 мс на входной токен на GTX 1650).
- Чекпоинт — часть контракта. Каждый ответ несёт sha256 весов
(
multilingual-fp16-0b095e005a4c): пороги и замеры нельзя перенести на другие веса незаметно. - Обрезка видна клиенту. Если состояние не влезло, ответ помечается
(
state_truncated,collapsed) — клиент обязан считать такой ответ недостоверным, а не «уверенным».
Три сценария на одном и том же типе задачи (разбор лога, медианы контрольных прогонов A/B, лог 358 КБ / 7 000 строк):
| Сценарий | Сумма входных токенов | Что это |
|---|---|---|
| Без движка | 2 800 000 | замер пользователя; условия с A/B не сопоставлялись |
| Без плагина | 992 037 | базовая линия A/B проекта (артефакт читается целиком) |
| Движок + плагин v2 | 513 614 | триаж, дедупликация и отбор контекста до чтения |
- −48 % — относительно базовой линии A/B (992 037 → 513 614): та же задача, те же условия, те же субагенты.
- −81,7 % — относительно 2 800 000: арифметика по двум разным замерам, где сопоставимость условий не проверена; число приведено как ориентир масштаба, а не как измеренный эффект.
- Пик контекста в том же A/B: 223 663 → 94 455 (−58 %), время вызовов модели не изменилось (23,8 → 23,5 с), полнота ответов 26/26.
Честные оговорки, без которых график обманчив: проценты относятся к входным токенам, а не к счёту (денежная экономия зависит от кэша, выходных токенов и тарифа); на маленьком логе (влезает в одно чтение) инструмент добавляет round-trip и проигрывает (+73 %), а поиск по 20 попаданиям даёт паритет. Правило окупаемости: отбор контекста оправдан, только если он заменяет чтение целиком. Полная методика, сырые журналы и формулы — docs/BENCHMARKS.md.
Сценарий целиком: 1) запустить движок → 2) подключить плагин ZCode →
3) проверить состояние → 4) заменить лишнее чтение инструментами отбора.
Команды: /laya-status, /laya-all on (включить активные режимы осознанно),
/laya-triage (ошибки лога), /laya-search (релевантные попадания),
/laya-review (приоритеты diff), /laya-bench (задержка).
| Платформа | Одна команда |
|---|---|
| Windows 10/11 x64 | install.cmd (GPU) · install.cmd -Cpu · install.cmd -Prebuilt · install.cmd -Service -Plugin |
| Linux | ./scripts/install.sh · --cpu · --prebuilt · --service --plugin |
| macOS | xcode-select --install && ./scripts/install.sh --cpu |
| Docker | ./scripts/fetch-model.sh && docker compose up --build laya-cpu |
Что происходит: скачиваются веса (617 МБ, SHA-256), ONNX Runtime 1.25.0, при необходимости CUDA 12/cuDNN 9; собирается сервис (или берётся готовый бинарник); запускается self-test. Дальше:
./scripts/laya.sh start | status | logs | stop # Linux/macOS
start-laya.cmd | stop-laya.cmd :: WindowsБез видеокарты всё работает: --cpu / /cpu (медленнее, но без NVIDIA-стека).
Полный гид по платформам, автозапуску (Task Scheduler / systemd / launchd) и
диагностике — docs/INSTALL.md.
Плагин davinci-laya-decisions встраивает движок в агентный цикл ZCode:
гейт риска перед опасными вызовами (по умолчанию shadow — только метрики),
ledger изменений, проверка доказательств завершения, ранжирование контекста и
10 MCP-инструментов. Вместе с плагином устанавливается навык
laya-decision-workflow — правило, когда инструменты окупаются.
Settings → Plugin Management → Discover → «+» → GitHub repository
→ Ydjin1984/davinci-laya-zcode → включить «DaVinci × Laya: локальные решения»
→ новая сессия ZCode → /laya-status
Или скриптом: ./scripts/install-plugin.sh (Linux/macOS) /
powershell -ExecutionPolicy Bypass -File scripts\windows\install-plugin.ps1.
Репозиторий плагина: https://github.com/Ydjin1984/laya-zcode-stack.
Подробности: integrations/zcode/README.md.
| Метод | Путь | Назначение |
|---|---|---|
| POST | /decide |
батч вопросов choice / score / noul по одному состоянию |
| POST | /count |
бюджеты без инференса (~1 мс): влезает ли состояние |
| GET | /info |
устройство, чекпоинт, лимиты, счётчики |
| GET | /ready · /health |
готовность / живость |
| POST | /benchmark |
p50/p95/p99 на вашей машине |
| GET/POST | /v1/models · /v1/systemone |
Jev-совместимый фасад |
| GET | /work |
панель фактических решений, ответов, политики и проверок |
curl -s http://127.0.0.1:8095/decide -H 'Content-Type: application/json' -d '{
"state": "удали файл D:\\tmp\\old.txt и покажи список",
"questions": {
"route": {"type":"choice","instructions":"Какой набор инструментов нужен?",
"criteria":{"dialog":"ответить словами","files_write":"изменить или удалить файл","console":"выполнить команду"}},
"data_loss": {"type":"noul","instructions":"Уничтожит ли это действие несохранённые или невосстановимые данные пользователя (сброс изменений, удаление файлов, перезапись без копии)?"}
}}'
# → route: files_write (0.985) · data_loss: 0.912 · checkpoint: multilingual-fp16-0b095e005a4cПолный контракт, семантика полей (answer_confidence — калиброванная величина,
порог — по ней) и правила формулировки вопросов (модель 322M чувствительна к
формулировке: короткое «изменяет ли запрос состояние?» даёт ложный ноль, полное
утверждение о действии — 0.912): docs/API.md.
http://127.0.0.1:8095/work показывает реальные вызовы Laya: вход, вопросы,
ответы, политику плагина, задержки, проверки и ручную разметку. Данные — в
локальном SQLite data/work.db; hook пишет события в data/work-spool и не
ждёт сеть, поэтому панель не замедляет быстрые вызовы. Точность считается
только по размеченным вопросам; уверенность модели и успешность npm test —
не одно и то же. Подробности, безопасность и откат: docs/WORK.md.
| Нагрузка | p50 | p95 |
|---|---|---|
| RTX 3060, 6 вопросов/запрос (исторический замер) | 46–56 мс | 77 мс |
| GTX 1650, 3 вопроса/запрос (текущая тестовая машина) | 154 мс | 257 мс |
Время линейно по входным токенам (≈1 мс/токен на GTX 1650), все операторы — на
CUDA. Проверить на своей машине: POST /benchmark.
Модель: fp16, ~322M параметров (энкодер mmBERT + голова типизированных решений),
max_len=1024, head_max_len=256.
Скриншот ниже — не рендер, а Диспетчер задач тестовой машины во время работы сервиса: 2,1 из 4,0 ГБ выделенной видеопамяти, загрузка 3D 9 %, 49 °C. Это ответ на главный вопрос про требования: один экземпляр движка с fp16-моделью укладывается в 4 ГБ видеопамяти и не занимает карту целиком — рядом продолжают работать другие задачи. (Шесть экземпляров, как в демо-аркаде, в 4 ГБ не влезут — см. laya_arcade/README.md.)
01..05_*.png иллюстрации серии (в корне, по одной на раздел)
+ скриншот Диспетчера задач: движок на GTX 1650
cmd/laya-server/ точка входа сервиса (флаги, прогрев, логи)
engine/ ONNX-сессия, сборка входа, вопросы, CUDA-окружение
tokenizer/ токенизатор mmBERT на Go (сверен с HuggingFace)
server/ HTTP API, бенчмарк, Jev-фасад
scripts/ кросс-платформенные скрипты (install, fetch-*, laya.sh, плагин)
tools/ инструменты разработки: эталоны, диагностика, профилирование
docs/ INSTALL · API · BENCHMARKS · ARCHITECTURE · ENGINE.ru · ТЗ интеграции
examples/ примеры клиентов: curl, PowerShell, Python, Node
docker/ образы CPU и GPU + compose
integrations/zcode/ плагин и навык ZCode: установка и измеренный эффект
laya_arcade/ демо: три игры, в которые играет Laya, и нейроэволюция рядом
models/ third_party/ пусто в git: веса и библиотеки скачивают скрипты (SHA-256)
- Большие артефакты — через триаж. Лог в мегабайты целиком не влезет; отбор окупается на порядки (см. −48 %/−58 %).
- Маленькие файлы — читайте напрямую. Если артефакт влезает в одно чтение, отбор добавляет round-trip, который нечем оплатить.
- Несколько решений — один batch. Независимые вопросы в один вызов: один forward pass вместо N.
- Решающие факты — в начало состояния. Состояние режется справа; хвост модель может не увидеть.
- Порог — по
answer_confidence, и он привязан к чекпоинту. - Вероятность ≠ доказательство. Ответы модели не расширяют разрешения и не
заменяют факты (
git status, коды возврата тестов). - Калибруйте на своих данных. Чужие пороги — стартовая точка, не истина.
| Документ | О чём |
|---|---|
| docs/INSTALL.md | установка на Windows/Linux/macOS/Docker, автозапуск, удаление, диагностика |
| docs/API.md | полный контракт HTTP API, семантика полей, формулировки вопросов |
| docs/BENCHMARKS.md | латентность, модель стоимости, A/B экономии токенов, чего числа не показывают |
| docs/ARCHITECTURE.md | устройство: слои, поток одного /decide, CUDA-окружение, интеграция |
| docs/ENGINE.ru.md | глубокая техническая справка по движку (RU) |
| docs/TZ-ZCode-Laya-Integration.md | ТЗ интеграции ZCode × Laya (архитектура решения) |
| integrations/zcode/README.md | плагин: компоненты, установка, измеренный эффект |
| AGENTS.md | правила для coding-агентов, работающих в этом репозитории |
| CONTRIBUTING.md · SECURITY.md | вклад и безопасность |
Код этого репозитория — Apache-2.0 (LICENSE). Модель Laya —
Apache-2.0 (convaiinnovations/laya); ONNX Runtime — MIT. CUDA/cuDNN не
распространяются: скрипты скачивают их из публичных колёс NVIDIA, условия —
NVIDIA CUDA Toolkit EULA. Полный список — NOTICE.
A big LLM sometimes needs a fast assistant that answers not with text, but with a concrete decision: "what kind of task is this?", "how risky is this action?", "is this statement true?". Laya Engine is that assistant, running on your own machine: ~322M parameters instead of hundreds of billions, tens of milliseconds instead of seconds, zero network calls.
Three core ideas:
- Decisions, not generation. In one forward pass the model returns
probabilities over your options (
choice), a level on an ordered scale (score), or P(true) for a statement (noul). No code writing, no reasoning — just fast, typed answers about short text. - One service per machine. Everything lives on
127.0.0.1:8095: assistants, scripts and data jobs share a single process instead of loading their own copies of the weights. - Cheaper to compute than to reason about. Task classification, action-risk scoring, log triage, context ranking: a big model spends seconds and tokens on this; the local engine spends tens of milliseconds and zero tokens.
flowchart LR
C["Client (assistant, script,<br/>ZCode plugin)"] -->|POST /decide| A["HTTP API<br/>127.0.0.1:8095"]
A --> B["Input assembly<br/>question + options + state"]
B --> T["mmBERT tokenizer<br/>(Go, reference-verified)"]
T --> O["ONNX Runtime<br/>CUDA or CPU"]
O -->|"logits → temperature-scaled<br/>softmax"| R["Answer: choice, probabilities,<br/>confidence, budget, checkpoint"]
R --> C
- One request — one model pass. All questions in a batch are computed together; cost is driven by the number of questions and the state length, not concurrency (≈1 ms per input token on a GTX 1650).
- The checkpoint is part of the contract. Every answer carries the weights
sha256 (
multilingual-fp16-0b095e005a4c): thresholds and measurements cannot be silently carried over to different weights. - Truncation is explicit. If the state did not fit, the answer is flagged
(
state_truncated,collapsed) and must be treated as unreliable.
Three scenarios for the same task type (log analysis; medians of the project's A/B runs, 358 KB / 7,000-line log):
| Scenario | Sum of input tokens | What it is |
|---|---|---|
| No engine | 2,800,000 | a user measurement; conditions were not matched to the A/B |
| No plugin | 992,037 | the project's A/B baseline (artifact read whole) |
| Engine + plugin v2 | 513,614 | triage, dedup and context selection before reading |
- −48 % against the A/B baseline (992,037 → 513,614): same task, same conditions, same subagents.
- −81.7 % against 2,800,000: arithmetic across two different measurements whose conditions were not verified to be comparable — a scale indicator, not a measured effect.
- Peak context in the same A/B: 223,663 → 94,455 (−58 %); model time unchanged (23.8 → 23.5 s); answer completeness 26/26.
Honest caveats: the percentages are about input tokens, not about the bill (pricing depends on cache, output tokens and tariff); on a small log (fits in one read) the tool adds a round-trip and loses (+73 %); repository search over ~20 hits is at parity. Payoff rule: selection is worth it only when it replaces a full read. Full method, raw journals and formulas: docs/BENCHMARKS.md.
The full scenario: 1) start the engine → 2) connect the ZCode plugin →
3) check status → 4) replace unnecessary reading with selection tools.
Commands: /laya-status, /laya-all on (enable active modes deliberately),
/laya-triage (log errors), /laya-search (relevant hits), /laya-review
(diff priorities), /laya-bench (latency).
| Platform | One command |
|---|---|
| Windows 10/11 x64 | install.cmd · install.cmd -Cpu · install.cmd -Prebuilt · install.cmd -Service -Plugin |
| Linux | ./scripts/install.sh · --cpu · --prebuilt · --service --plugin |
| macOS | xcode-select --install && ./scripts/install.sh --cpu |
| Docker | ./scripts/fetch-model.sh && docker compose up --build laya-cpu |
The installer downloads the weights (617 MB, SHA-256 checked), ONNX Runtime 1.25.0, and CUDA 12 / cuDNN 9 when needed; builds the service (or fetches the prebuilt binary) and runs a self-test. Then:
./scripts/laya.sh start | status | logs | stop # Linux/macOS
start-laya.cmd | stop-laya.cmd :: WindowsNo GPU? Everything works on CPU (--cpu / /cpu), just slower. Full guide with
autostart (Task Scheduler / systemd / launchd) and troubleshooting:
docs/INSTALL.md.
The davinci-laya-decisions plugin wires the engine into the agent cycle: a
risk gate before dangerous calls (shadow by default — metrics only), an evidence
ledger, a completion gate, context ranking, and 10 MCP tools. It ships a
skill (laya-decision-workflow) that teaches the model when those tools pay
off.
Settings → Plugin Management → Discover → "+" → GitHub repository
→ Ydjin1984/davinci-laya-zcode → enable "DaVinci × Laya: local decisions"
→ new ZCode session → /laya-status
Or scripted: ./scripts/install-plugin.sh /
powershell -ExecutionPolicy Bypass -File scripts\windows\install-plugin.ps1.
Plugin repository: https://github.com/Ydjin1984/davinci-laya-zcode.
Details: integrations/zcode/README.md.
| Method | Path | Purpose |
|---|---|---|
| POST | /decide |
batch of choice / score / noul questions over one state |
| POST | /count |
budgets without inference (~1 ms): does the state fit |
| GET | /info |
device, checkpoint, limits, counters |
| GET | /ready · /health |
readiness / liveness |
| POST | /benchmark |
p50/p95/p99 on your machine |
| GET/POST | /v1/models · /v1/systemone |
Jev-compatible facade |
Full contract, field semantics (answer_confidence is the calibrated value —
threshold on it) and question-wording rules (a 322M model is wording-sensitive:
"does the request modify state?" returns a false zero, a full concrete statement
returns 0.912): docs/API.md.
| Load | p50 | p95 |
|---|---|---|
| RTX 3060, 6 questions/request (historical) | 46–56 ms | 77 ms |
| GTX 1650, 3 questions/request (current test box) | 154 ms | 257 ms |
Time is linear in input tokens (≈1 ms/token on the GTX 1650); every operator runs
on CUDA. Measure your own box with POST /benchmark. Model: fp16, ~322M params
(mmBERT encoder + typed-decision head), max_len=1024, head_max_len=256.
The screenshot below is not a render — it is the test machine's Task Manager while the service was running: 2.1 of 4.0 GB dedicated GPU memory, 9 % 3D load, 49 °C. That answers the requirements question: one engine instance with the fp16 model fits into 4 GB of VRAM and does not pin the card — other workloads keep running next to it. (Six instances, as in the demo arcade, will not fit in 4 GB — see laya_arcade/README.md.)
01..05_*.png the illustration series (repo root, one per section)
+ the Task Manager screenshot: the engine on a GTX 1650
cmd/laya-server/ service entry point (flags, warm-up, logging)
engine/ ONNX session, input assembly, questions, CUDA environment
tokenizer/ mmBERT tokenizer in Go (verified against HuggingFace)
server/ HTTP API, benchmark, Jev facade
scripts/ cross-platform scripts (install, fetch-*, laya.sh, plugin)
tools/ developer tooling: references, diagnostics, profiling
docs/ INSTALL · API · BENCHMARKS · ARCHITECTURE · ENGINE.ru · integration spec
examples/ clients: curl, PowerShell, Python, Node
docker/ CPU and GPU images + compose
integrations/zcode/ ZCode plugin and skill: install and measured effect
laya_arcade/ demo: three games Laya plays, plus neuroevolution alongside
models/ third_party/ empty in git: scripts fetch weights and libraries (SHA-256)
- Large artifacts → triage. A multi-megabyte log will not fit; selection pays off by orders of magnitude (−48 %/−58 % above).
- Small files → read directly. If it fits in one read, selection adds a round-trip nobody pays for.
- Several decisions → one batch call. One forward pass instead of N.
- Decision-critical facts go first. The state is cut from the right.
- Threshold on
answer_confidence, and bind it to the checkpoint. - Probability is not proof. Model answers never widen permissions and never
replace facts (
git status, test exit codes). - Calibrate on your own data. Someone else's thresholds are a starting point.
| Document | About |
|---|---|
| docs/INSTALL.md | install on Windows/Linux/macOS/Docker, autostart, uninstall, troubleshooting |
| docs/API.md | full HTTP contract, field semantics, question wording |
| docs/BENCHMARKS.md | latency, cost model, token-saving A/B, what the numbers do not show |
| docs/ARCHITECTURE.md | internals: layers, one /decide flow, CUDA environment, integration |
| docs/ENGINE.ru.md | deep technical reference (Russian) |
| integrations/zcode/README.md | the plugin: components, install, measured effect |
| AGENTS.md | rules for coding agents working in this repository |
| CONTRIBUTING.md · SECURITY.md | contributions and security |
Repository code: Apache-2.0 (LICENSE). Laya model: Apache-2.0
(convaiinnovations/laya); ONNX Runtime: MIT. CUDA/cuDNN are not redistributed —
scripts download them from public NVIDIA wheels under the NVIDIA CUDA Toolkit
EULA. Full list: NOTICE.
#LayaEngine #ONNXRuntime #GoLang #CUDA #cuDNN #SystemOne
#DecisionEngine #LocalAI #LocalLLM #TokenEfficiency #ContextEngineering
#ZCode #MCP #ModelContextProtocol #CodeAgents #DeveloperTools
#AIAgents #mmBERT #BPE #ONNX #fp16 #CrossPlatform #Windows #Linux
#macOS #Docker #Apache2 #OpenSource #AgentSafety #TokenSavings
DaVinci Cyber Engineering · 2026



