Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(examples): fall back to the Hub when models/ is absent
thread3db584ba099f9a
diff --git a/examples/23_local_offline_models.py b/examples/23_local_offline_models.pyindex 3efdf90a..e46af8d9 100644--- a/examples/23_local_offline_models.py+++ b/examples/23_local_offline_models.py@@ -1,50 +1,53 @@-"""Example 23 -- running against ./models, fully offline.+"""Example 23 -- where the weights come from: ./models, or the Hub.-Shows that the local checkpoints need no network: prints the resolved paths, cross-checks-them against verify/checkpoints.json, and runs a prediction from disk.+Laya takes either a local directory (no network, no token) once `setup_laya.sh` has downloaded+one, or a Hub repo id. This prints what each name resolves to, cross-checks the local weights+against verify/checkpoints.json when they are there, and runs one prediction."""import jsonimport os-from _common import laya, MODELS, ROOT, STATE_EN, banner, describe, heading, load, router+from _common import (LOCAL_MODELS, MODELS, ROOT, STATE_EN, banner, describe, has_local, heading,+ laya, load, router)-banner("23", "Local, offline checkpoints", """- Every example here passes absolute paths from `models/` to `Agent`, so the first thing- `Agent` does is `os.path.exists` -- and it is true. No `snapshot_download`, no hub- call, no token. That is the difference from a stock `Router()`, which holds Hugging- Face repo ids and downloads the checkpoints into `HF_HOME` on first use.+banner("23", "Where the weights come from: ./models or the Hub", """+ `setup_laya.sh` downloads the three checkpoints into `models/`, and `_common` prefers them:+ an absolute directory means `Agent` stops at `os.path.exists`, so nothing touches the+ network and no token is needed.- This script proves the point from disk: it resolves each local path, checks the weight- file against the sizes recorded in `verify/checkpoints.json`, and then answers one- question without touching the network.+ Without `models/` the same code falls back to the Hub bundle (`convaiinnovations/laya`,+ with a subfolder per checkpoint), which downloads on first use. Same checkpoints either+ way; only where they are read from changes.""")print(" laya %s" % laya.__version__)-heading("resolved checkpoint paths")-for name, path in MODELS.items():- weights = os.path.join(path, "model.safetensors")- size = os.path.getsize(weights) if os.path.exists(weights) else 0- print(" %-16s %s" % (name, path))- print(" %-16s exists=%s model.safetensors=%d bytes" %- ("", os.path.isdir(path), size))+heading("what each name resolves to")+for name in MODELS:+ print(" %-16s %r" % (name, MODELS[name]))+ if has_local(name):+ weight = os.path.join(LOCAL_MODELS[name], "model.safetensors")+ print(" %-16s local: %d bytes" % ("", os.path.getsize(weight)))+ else:+ print(" %-16s no local copy: the Hub spec above is used" % "")heading("cross-check against verify/checkpoints.json")manifest_path = os.path.join(ROOT, "verify", "checkpoints.json")print(" manifest: %s" % manifest_path)if not os.path.exists(manifest_path):print(" (verify/checkpoints.json is not in this checkout; skipping the size cross-check)")+elif not all(has_local(name) for name in LOCAL_MODELS):+ print(" (some checkpoints are not local; skipping the size cross-check)")else:with open(manifest_path) as f:manifest = json.load(f)print(" repo=%s revision=%s" % (manifest["repo"], manifest["revision"][:12]))for cp in manifest["checkpoints"]:- local = MODELS[cp["name"]]- found = os.path.getsize(os.path.join(local, "model.safetensors"))+ found = os.path.getsize(os.path.join(LOCAL_MODELS[cp["name"]], "model.safetensors"))print(" %-16s expected=%d local=%d %s" %(cp["name"], cp["bytes"], found, "MATCH" if found == cp["bytes"] else "MISMATCH"))-heading("one prediction, straight from disk")+heading("one prediction")agent = load("english")result = agent.predict(STATE_EN, {"department": {@@ -63,14 +66,14 @@ print(" device: %s tokens: %d in, %d out" %(agent.device, result["usage"]["input_tokens"], result["usage"]["output_tokens"]))heading("Router(models=...) vs the default Router()")-local = router()-print(" local Router().models['english'] %r" % local.models["english"])-print(" default DEFAULT_MODELS['english'] %r" % (laya.DEFAULT_MODELS["english"],))-print(" local Router().models['multilingual'] %r" % local.models["multilingual"])-print(" default DEFAULT_MODELS['multilingual'] %r" % (laya.DEFAULT_MODELS["multilingual"],))+configured = router()+print(" Router().models['english'] %r" % (configured.models["english"],))+print(" DEFAULT_MODELS['english'] %r" % (laya.DEFAULT_MODELS["english"],))+print(" Router().models['multilingual'] %r" % (configured.models["multilingual"],))+print(" DEFAULT_MODELS['multilingual'] %r" % (laya.DEFAULT_MODELS["multilingual"],))print("""- The local values are absolute directories, so `Agent` never calls the hub. The default- values are a repo id plus an optional subfolder; `Agent` would call `snapshot_download`- and write the weights under `HF_HOME` (unset here, so ~/.cache/huggingface by default).- Offline inference is therefore not a special mode -- it is what passing local paths does.+ With a local copy the configured value is an absolute directory, so `Agent` never calls the+ hub. Without one it is the same Hub spec `DEFAULT_MODELS` uses, and the weights land in+ `HF_HOME` (~/.cache/huggingface by default). Passing a local path is still the only way to+ keep a run fully offline.""")diff --git a/examples/README.md b/examples/README.mdindex 90ea5a1e..c72c0cfb 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,13 +1,15 @@# Laya examples — a learning path41 runnable scripts arranged as eight stages. Each stage assumes the one before it and adds one-idea, so you can stop wherever you already have what you need. Every script runs against the-checkpoints in `../models` and prints real output — nothing here is a mock, and the numbers you-see come from the model on your machine.+idea, so you can stop wherever you already have what you need. Every script runs against the real+checkpoints and prints real output — nothing here is a mock, and the numbers you see come from the+model on your machine. `_common.py` prefers `../models` when `setup_laya.sh` has downloaded them+and otherwise loads the same checkpoints from the Hub (`convaiinnovations/laya`) on first use, so+these run after a plain `pip install laya`.```bashcd .. # repository root-./setup_laya.sh # once: venv + checkpoints+./setup_laya.sh # optional: venv + local checkpoints.venv/bin/python examples/01_first_call_minimal.py./examples/run_all.sh # all of them, pass/fail (non-zero exit on failure)./examples/run_all.sh 2[0-4] # just stage 5, by basename glob@@ -16,7 +18,8 @@ cd .. # repository root**Before you start*** Each example is its own process, so each loads its own checkpoints: 30-60 s on CPU, faster on- MPS, and the first MPS call pays ~13 s of Metal kernel compilation.+ MPS, and the first MPS call pays ~13 s of Metal kernel compilation. Without a local `../models`+ copy, the first run also downloads the checkpoint it needs into `HF_HOME`.* `device=None` lets Laya pick CUDA → MPS → CPU. `_common.load(name, device="cpu")` forces CPU.* `_common.py` holds the shared states, question sets and printing helpers. Examples import it, soyou can copy any example out and it keeps working.@@ -68,7 +71,7 @@ cd .. # repository root|---|---|| `16_many_questions_one_pass.py` | many questions, one pass: `input_tokens` is a batch total across the questions in the call. || `17_timing_a_call.py` | measuring honestly: load time vs inference, warm-up, and medians over several calls. |-| `18_confidence_gating.py` | the production pattern: automate on high confidence, escalate on low. |+| `18_confidence_gating.py` | the production pattern: gate on `answer_confidence`, the calibrated probability of the reported answer, and escalate on low. || `19_many_states_loop.py` | many states in your own loop — and why batching *questions* is the model's job while batching *states* is yours. |**You can now** size a workload, and branch on confidence instead of always acting.@@ -80,7 +83,7 @@ cd .. # repository root| `20_which_checkpoint.py` | what `english`, `multilingual` and `typed-decisions` each are good at, on the same input. || `21_routing_without_running.py` | `route()` alone: a checkpoint decision in microseconds, with the reason string, before any forward pass. || `22_route_and_predict_multilingual.py` | `predict()` routing and answering in one call, in several languages. |-| `23_local_offline_models.py` | running against local checkpoints with no network at all, and checking them. |+| `23_local_offline_models.py` | where the weights come from: local `../models` with no network at all when they are there, the Hub otherwise, and checking them against the manifest. || `24_preload_and_memory.py` | what stays resident: `preload`, `max_loaded`, LRU eviction, `attach`, `unload`. |**You can now** let the router choose, and control what is held in memory.diff --git a/examples/_common.py b/examples/_common.pyindex 57202001..960bb983 100644--- a/examples/_common.py+++ b/examples/_common.py@@ -7,9 +7,11 @@ Each example is a standalone script:Run it from anywhere -- paths resolve from this file, and Python puts the examples/ directoryon `sys.path` automatically, so `from _common import ...` just works.-Checkpoints live in `models/` (see `../setup_laya.sh` and `../verify/checkpoints.py`). Loading-one takes a few seconds, and the first MPS call pays Metal kernel compilation, so anything that-reports latency warms up first.+Checkpoints come from `models/` when `setup_laya.sh` has downloaded them, and from the Hub bundle+(`convaiinnovations/laya`, with a subfolder per checkpoint) otherwise, so the examples run after a+plain `pip install laya`. Loading one takes a few seconds -- plus the first download when there is+no local copy -- and the first MPS call pays Metal kernel compilation, so anything that reports+latency warms up first.This module also imports `laya` for you -- after setting `USE_TF=0`, because a stray TensorFlowinstall can deadlock model loading. Examples therefore do `from _common import laya, ...` rather@@ -30,12 +32,36 @@ sys.path.insert(0, ROOT) # repository root; <root>/laya/email.py must nimport laya # noqa: E402from laya.router import Router # noqa: E402-MODELS = {+BUNDLE_REPO = "convaiinnovations/laya"+_SUBFOLDER = {+ "english": None, # the bundle's root holds the English checkpoint+ "multilingual": "multilingual",+ "typed-decisions": "typed-decisions",+}++LOCAL_MODELS = {"english": os.path.join(ROOT, "models", "laya"),"multilingual": os.path.join(ROOT, "models", "laya-multilingual"),"typed-decisions": os.path.join(ROOT, "models", "laya-typed-decisions"),}++def has_local(name="english"):+ """True when setup_laya.sh has already downloaded this checkpoint into `models/`."""+ return os.path.exists(os.path.join(LOCAL_MODELS[name], "model.safetensors"))+++def checkpoint(name="english"):+ """A Router model spec: the local directory when there is one, else the Hub repo + subfolder."""+ if has_local(name):+ return LOCAL_MODELS[name]+ return (BUNDLE_REPO, _SUBFOLDER[name])+++# What `Router(models=...)` takes: absolute local paths in a checkout that ran setup_laya.sh,+# Hub specs otherwise.+MODELS = {name: checkpoint(name) for name in LOCAL_MODELS}+# ---------------------------------------------------------------- sample inputsSTATE_EN = {"from": "[email protected]",@@ -72,14 +98,6 @@ QUESTIONS = {}-def ensure_models():- """Exit with a useful message instead of a stack trace when the weights are missing."""- for name, path in MODELS.items():- if not os.path.exists(os.path.join(path, "model.safetensors")):- sys.exit("checkpoint %r is missing at %s\nRun ./setup_laya.sh first "- "(or verify with .venv/bin/python verify/checkpoints.py)." % (name, path))--def banner(number, title, blurb=""):"""Print the header every example starts with."""line = "=" * 74@@ -91,14 +109,17 @@ def banner(number, title, blurb=""):def load(name="english", device=None):- """Load one checkpoint. `device=None` lets Laya pick: CUDA, then MPS, then CPU."""- ensure_models()- return laya.load(MODELS[name], device=device)+ """Load one checkpoint: from `models/` when it is there, else from the Hub.++ `device=None` lets Laya pick: CUDA, then MPS, then CPU.+ """+ if has_local(name):+ return laya.load(LOCAL_MODELS[name], device=device)+ return laya.load(BUNDLE_REPO, subfolder=_SUBFOLDER[name], device=device)def router(device=None, **kwargs):- """A Router wired to the local checkpoints, so nothing touches the network."""- ensure_models()+ """A Router over the local checkpoints when they are there, else over the Hub bundle."""return Router(models=MODELS, device=device, **kwargs)