Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
laya

laya

> 后端框架
Free

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text

19.0K stars0 likes10 views
WebsiteGitHub

About

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text

Multilingual, non-autoregressive System 1 decision engine. Typed decisions over 100+ languages in a single forward pass — 33 ms — trained with reinforcement learning against strictly proper scoring rules (RLCD), with a router that picks the right checkpoint per request.

Installation

bash
python -m pip install laya

Python 3.10 or newer. Optional extras: laya[serve] (HTTP server), laya[mcp] (MCP server), laya[langchain] (LangChain and LangGraph), laya[onnx] (ONNX Runtime), laya[fast] (TileLang GPU fast path). Step-by-step setup for each platform, CPU-only or GPU PyTorch builds, and troubleshooting are in Installation details.

Quickstart

…

The same call works in any of 100+ languages. The Router detects the script and language and sends non-English text to laya-multilingual:

python
for text in ["मुझसे मार्च में दो बार शुल्क लिया गया, कृपया डुप्लिकेट राशि वापस करें।",
             "La aplicación se cierra cada vez que abro la configuración."]:
    r = router.predict(text, {"department": questions["department"]})
    print(r["routing"]["model"], r["answers"]["department"]["choice"])
# multilingual billing
# multilingual technical

From the command line, laya "My payment failed twice" --preset triage answers a ready-made question set. More in the full quickstart and the docs.

Fine-tune for better accuracy

The shipped checkpoints work zero-shot, but fine-tuning on decisions from your own domain is where accuracy jumps. On the typed-decisions benchmark (2,000 decisions across four workflows), the fine-tuned laya-typed-decisions checkpoint scores 0.766 accuracy, against 0.362 for the base English checkpoint on the same decisions.

Fine-tuning notebook: runs the whole loop on Kaggle's free 2x T4 GPUs (build the dataset, train, fit calibration temperatures, evaluate, and push the result to the Hub). Details in Fine-Tuning.

Documentation

nandhakishorm.github.io/laya: guides for prediction hooks, schema-driven decisions, Docker and LangChain and LangGraph, plus a full API reference.

What's new in 0.3.17

  • Installation, quickstart and documentation first. This README now opens with how to install Laya, runnable English and multilingual examples, how fine-tuning improves accuracy, and where the docs are.
  • Documentation site at nandhakishorm.github.io/laya, with an API reference generated from the docstrings.

The code is unchanged from the last runtime release, whose fixes are:

  • Sturdier fast path. After a CUDA out-of-memory error, the fallback to CPU switches the TileLang fast path off first instead of retrying on CUDA. A choice question with a single option no longer crashes it, requests longer than it was built for get a clear error, and concurrent calls can no longer overwrite each other's CUDA-graph buffers.
  • Server and runtime. laya-serve drains its inference pool on shutdown and returns 401 for a malformed bearer header, and ONNXAgent matches Agent on empty question sets and long conversation lists.
  • Smaller fixes. The laya command prints the right probability for a choice, LangChain remote calls refuse cross-origin or HTTPS-downgrade redirects, and AGENTS.md gives AI coding assistants the contribution rules.

Laya evaluates typed questions (choice, score, noul) over any state (text, email, ticket or JSON document) in a single forward pass — 33 ms for one question, 7.2 ms/question batched, measured on a T4. No text generation, so nothing to parse and nothing to hallucinate.

Three checkpoints, and a Router that picks between them per request:

encoder params context use it for
laya ModernBERT-large 421M 512 English
laya-multilingual mmBERT-base 322M 1024 100+ languages, 2x faster
laya-typed-decisions ModernBERT-large 421M 1024 the typed-decisions workflows

Installation details

Python 3.10 or newer. The dependencies set that floor: huggingface_hub 1.x, transformers 5.x and torch 2.14 all require 3.10.

Optional PyTorch build selection: If you need a CPU-only or GPU-specific PyTorch build, follow PyTorch's installation guide after creating your virtual environment and before installing Laya. Replace pip or pip3 in the selected command with the environment's Python executable followed by -m pip.

If you already use a virtual environment, install the PyPI release with:

bash
python -m pip install laya

For a new environment, choose the commands for your platform below. Run them from your project directory; the explicit Python paths keep installation and verification in the same environment.

macOS / Linux (with Python 3.10 or newer):

On Debian/Ubuntu, the system Python may require sudo apt install python3-venv before creating a virtual environment. If venv reports that ensurepip is unavailable, install that package and retry.

bash
python3 -m venv .venv
.venv/bin/python -m pip install laya
.venv/bin/python -I -c "import laya; print(laya.__version__)"

Windows PowerShell (this example uses an installed Python 3.11):

powershell
py -3.11 -m venv .venv
.\.venv\Scripts\python.exe -m pip install laya
.\.venv\Scripts\python.exe -I -c "import laya; print(laya.__version__)"

Both checks print the installed Laya version without loading a checkpoint. -I excludes the current directory from the import search path, so a local source copy cannot mask a missing installation. Keep using the same virtual environment's Python when running your application.

Install from GitHub

To use the development version instead of the PyPI release, create the virtual environment above and replace its installation command with the appropriate command below. Git must be installed.

bash
# macOS / Linux
.venv/bin/python -m pip install "git+https://github.com/NandhaKishorM/laya.git"
powershell
# Windows PowerShell
.\.venv\Scripts\python.exe -m pip install "git+https://github.com/NandhaKishorM/laya.git"

Run the same version check afterward. The GitHub version follows the repository's default branch and may differ from the published release.

Model setup and troubleshooting

Continue with the Router quickstart to run inference. Loading a Hub checkpoint requires access to Hugging Face on its first download; the quickstart's Router(preload=True) loads all three configured checkpoints at construction.

  • ModuleNotFoundError: No module named 'laya': run both installation and your script with the same virtual environment's Python executable shown above. In an editor, select that interpreter as well.
  • Missing rl_agent_config.json: this file ships with a Laya checkpoint alongside model.safetensors; it is not a configuration file you need to create in the source repository. For a local model, pass the directory containing those checkpoint files.

Command line

Installing the package also installs a laya command for quick local testing, no script needed:

bash
laya "I was charged twice, please refund"            # routing decision only; works offline, no download
laya "Refactor this service" --predict               # full answers (downloads the checkpoint on first use)
laya "Mein Konto wurde zweimal belastet" --lang de   # force a language instead of detecting it
laya "My payment failed twice" --preset triage       # answer a ready-made preset (triage, email, guard, moderation, router)
laya                                                 # interactive mode

Routing alone never downloads a checkpoint, so it returns in milliseconds. --predict loads the routed checkpoint, which needs network access to the Hugging Face hub the first time; if a checkpoint cannot be downloaded, the CLI says so instead of crashing.


Try it locally: web GUI + JSON API

examples/server.py is a self-contained FastAPI app for testing Laya without writing any code: a request builder (or a raw-JSON paste box) that renders choice/score/noul answers as 0-100 bars, plus a plain JSON API (/predict, /predict/batch) for scripting against.

bash
pip install "laya[serve]"
python examples/server.py               # http://127.0.0.1:8000

Open http://127.0.0.1:8000 in a browser for the builder UI, or hit it directly:

bash
curl -s localhost:8000/predict -H 'content-type: application/json' -d '{
  "state": {"body": "We were billed twice for March. Please refund it today."},
  "questions": {
    "department": {"type": "choice",
                   "instructions": "Which department should handle this?",
                   "criteria": {"billing": "invoices, payments, refunds", "other": "everything else"}},
    "urgency": {"type": "score",
                "instructions": "How urgent is this?",
                "criteria": ["not urgent", "soon", "critical"]}
  }
}' | python -m json.tool

--no-preload loads checkpoints lazily instead of all three up front; --device cuda|cpu|mps pins the device. See python examples/server.py --help for the rest.


Quickstart: Route Mode (Recommended)

To try the Python SDK in a CPU container, see the Docker Compose quickstart. It runs a sample request and keeps downloaded models between runs.

Laya ships three checkpoints. The built-in Router is the recommended entry point: it evaluates any state in any language, automatically detects scripts and languages in sub-milliseconds, and dispatches to the optimal checkpoint in a single forward pass.

…

Every result carries full routing metadata explaining why the choice was made:

python
res_hi["routing"]
# {
#   'model': 'multilingual',
#   'repo': 'convaiinnovations/laya/multilingual',
#   'reason': 'non-Latin script (devanagari, 100% of letters); the English checkpoint cannot read it'
# }

Inspect a routing decision without running any forward pass:

python
router.route({"body": "Der Kunde wurde zweimal belastet"}, questions).reason
# "Latin script but language looks like 'de', not English"

Very short Latin-script text often carries nothing that identifies its language ("Quero cancelar", "Esqueci minha senha"). Such text goes to default, which is "english" unless you change it. If most of your traffic is not English, set:

python
router = Router(default="multilingual")
router.route({"body": "Esqueci minha senha"}).model                 # -> multilingual
router.route({"body": "Please refund the duplicate charge"}).model  # -> english

Heterogeneous routed batches

If a lazy router receives an interleaved workload whose requests route to different checkpoints, calling predict() in a loop can still cause unnecessary checkpoint churn when the required checkpoints exceed the resident cache, for example with max_loaded=1 or when typed-decisions is also used.

Router.predict_batch() routes the full workload first, groups requests by checkpoint, then groups requests with the same question schema within each checkpoint. Each compatible group is dispatched to Agent.predict_batch() so states can share forward passes, and results are restored to t

Issues· 160 open

View all issuesOpen on GitHub
  • #805

    laya-serve: /v1/systemone/batch silently drops the request controls and skips the single endpoint's validation

    Updated Oct 1, 2026
  • #790

    export_onnx --quantize: per-channel dynamic INT8 collapses the model (32% agreement with eager); per-tensor is far better but int8 is lossy overall

    Updated Oct 1, 2026
  • #681

    fix(structured): score projection ignores minimum when probabilities are absent

    Updated Oct 1, 2026
  • #785

    [feature]: attribute shortlist evaluation errors to retrieval and decision stages

    enhancementUpdated Oct 1, 2026
  • #779

    [bug]:

    bugUpdated Sep 30, 2026
  • #782

    [bug]: Diarization ~10× slower after polyvoice 0.21 (tract embeddings, #358)

    bugUpdated Sep 30, 2026
  • #781

    [bug]: `guard`: `prompt_injection` scores 0.00 to 0.30 on instructions embedded in document-shaped text (3 cases, with a matched control)

    bugUpdated Sep 30, 2026
  • #637

    Fine-tune notebook fits temperatures outside the runtime clamp, so the served calibration differs from the fitted one

    Updated Sep 30, 2026
  • #780

    [bug]: load() does not resolve the checkpoint aliases Router accepts, so load("typed-decisions") 404s

    Updated Sep 30, 2026
  • #776

    Independent reproduction: all four published benchmark claims reproduce within 0.0003

    Updated Sep 30, 2026

> Tags

calibrationclassificationdecision-model

No comments yet. Be the first to share.

> Details

PublishedSep 23, 2026
UpdatedOct 1, 2026
Category后端框架
PricingFree

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架