Zero-Shot Classification
Laya
Safetensors
PyTorch
English
Spanish
intent-routing
tool-routing
semantic-router
zero-shot
bilingual
english
spanish
out-of-scope-detection
knowledge-distillation
modernbert
teacher-model
Eval Results (legacy)
Run this model with HF Jobs
Run lapislabsai/lapis-sal-421M on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/lapislabsai/lapis-sal-421M. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/lapislabsai/lapis-sal-421M on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use lapislabsai/lapis-sal-421M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Laya
How to use lapislabsai/lapis-sal-421M with Laya:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Release Lapis SAL: validated bilingual tool routing
Browse filesFiles changed (13)
- .gitattributes+2-34
- LICENSEAdded+202
- NOTICE.mdAdded+9
- README.mdAdded+216
- encoder/config.jsonAdded+84
- lapis_runtime.pyAdded+148
- laya_intent_router.pyAdded+265
- model.safetensorsAdded+3
- requirements.txtAdded+7
- rl_agent_config.jsonAdded+34
- third_party/ettin-LICENSE.txtAdded+21
- tokenizer/tokenizer.jsonAdded
- tokenizer/tokenizer_config.jsonAdded+14
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123*.safetensors filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.onnx.data filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
123456789# Upstream attribution
Lapis SAL uses the Laya DecisionModel design and the vendored [Laya intent router](https://github.com/vrajnotviraj/laya-intent-router) training/inference code, with Lapis-specific data preparation, fine-tuning, distillation, export fixes, and release tooling.
- Laya package: [NandhaKishorM/laya](https://github.com/NandhaKishorM/laya), pinned to `4066d5d5fbf08b66c6757ddeedbd797bd7655bc0`.- Teacher initialization: [convaiinnovations/laya](https://huggingface.co/convaiinnovations/laya), Apache-2.0; encoder family [answerdotai/ModernBERT-large](https://huggingface.co/answerdotai/ModernBERT-large), Apache-2.0.- Student encoder: [jhu-clsp/ettin-encoder-150m](https://huggingface.co/jhu-clsp/ettin-encoder-150m), MIT. Its upstream MIT notice is retained in `third_party/ettin-LICENSE.txt`, sourced from [the Ettin repository](https://github.com/jhu-clsp/ettin-encoder-vs-decoder/blob/main/LICENSE).
The Apache-2.0 license accompanying these packages does not remove the upstream MIT attribution or alter dataset terms. No dataset or raw user/evaluation messages are included in the Hugging Face packages. The locally supplied bilingual dataset is retained in the private reproducibility repository; it has no separate explicit license in its source metadata.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216---language:- en- eslicense: apache-2.0library_name: layapipeline_tag: zero-shot-classificationbase_model: convaiinnovations/layatags:- intent-routing- tool-routing- semantic-router- zero-shot- bilingual- english- spanish- out-of-scope-detection- knowledge-distillation- modernbert- teacher-model- pytorchmodel-index:- name: lapis-sal-421M results: - task: type: zero-shot-classification name: Dynamic tool routing dataset: type: custom name: Lapis bilingual tool-routing v4.1-refined (private synthetic test) split: test metrics: - type: accuracy value: 96.00 name: Routing accuracy (%)---# lapis-sal-421M
**The larger teacher checkpoint for bilingual tool routing, soft-label generation and further fine-tuning.**
Give the router a message and a menu of tools. It returns the best matching tool ID, or abstains with `None`.
[Quick start](#quick-start) · [Model family](#model-family) · [Tools](#tools-and-abstention) · [Training](#training) · [Evaluation](#evaluation) · [Limitations](#limitations)
## Model family
| Release | Format | Download | Best for ||---|---|---:|---|| [lapis-sal-150M](https://huggingface.co/lapislabsai/lapis-sal-150M) | PyTorch FP32 | ~658 MB | Fine-tuning, research and conversion || [lapis-sal-421M](https://huggingface.co/lapislabsai/lapis-sal-421M) | PyTorch FP32 | ~1.69 GB | Teacher inference and soft-label generation || [lapis-sal-150M-ONNX](https://huggingface.co/lapislabsai/lapis-sal-150M-ONNX) | ONNX INT8 | ~305 MB | CPU deployment || [lapis-sal-150M-MLX](https://huggingface.co/lapislabsai/lapis-sal-150M-MLX) | MLX FP16 / load-time INT8 | ~332 MB | Apple Silicon deployment |
Download sizes include the tokenizer and runtime. Each repository contains one checkpoint or backend; you do not need the full family to run one model. These are prepared release names; Hub links become available after publication.
## Quick start
Use Python 3.12. Download this repository and run from the downloaded folder:
```bashpython -m pip install 'huggingface_hub==1.33.0'hf download lapislabsai/lapis-sal-421M --local-dir lapis-sal-421Mcd lapis-sal-421Mpython -m pip install -r requirements.txt```
Run the following Python example from the downloaded folder. Replace the menu with the tools in your application:
```pythonfrom lapis_runtime import load_router
router = load_router('.', backend='torch', device='cpu', threads=4)paths = { 'WEATHER': ['Check weather conditions, forecasts and weather alerts'], 'CALENDAR': ['Create, read or update calendar events and meetings'],}result = router.route('Will it rain in Madrid tomorrow?', paths)print(result['match'], result['score'])```
`match` contains your tool ID, or `None` for abstention. `score` is the selected route's calibrated score; `probabilities` contains the option scores, including the internal `__none__` option. Evaluate calibration for your own menu and traffic.
For a CUDA deployment, pass `device='cuda'` to `load_router`. The checkpoint uses FP32 safetensors. This is a custom Laya DecisionModel; loading its encoder alone, `AutoModelForSequenceClassification`, or `pipeline()` will not reproduce routing. The bundled loader pins the validated Laya/PyTorch/Transformers stack. Accelerator performance beyond the reported measurements is not claimed.
## Why Lapis SAL?
A bilingual assistant needs to decide which tool to use before it can act. Lapis SAL makes that decision a dedicated, local step: pass the user's message and the tools currently available, then receive a tool ID or an abstention.
The project pairs a larger teacher with a smaller distilled student so applications can choose between a research checkpoint and compact deployment exports. The aim is practical English/Spanish routing with explicit tool descriptions and a way to say that none of the tools fits.
### What can you build?
- A personal assistant that routes requests to weather, calendars, reminders, email or search.- An agent or conversational workflow that chooses among the tools available for a particular request.- A local routing layer for desktop assistants, with CPU inference through ONNX or Apple Silicon inference through MLX.- Teacher-based soft-label generation, student distillation or further task-specific fine-tuning with the PyTorch checkpoints.
The router selects a tool; your application supplies tool arguments, permissions and execution.
## Tools and abstention
The adaptation and evaluation cover **13 tools plus `NONE`**:
| Tool | Intended route ||---|---|| `CALCULATOR` | Arithmetic and numerical calculations || `CALENDAR` | Calendar events, appointments and meetings || `CLOCK` | Time, timers, alarms and stopwatches || `CODE` | Programming questions and code assistance || `CONTACTS` | Contact lookup and contact management || `HEALTH` | Health, fitness and wellness information || `LOCATION` | Current location and location information || `MAIL` | Email search, reading and composition || `MAPS` | Maps, directions, places and navigation || `MESSAGES` | Instant messaging and text messages || `REMINDERS` | Reminders and personal tasks || `WEATHER` | Weather conditions, forecasts and alerts || `WEB_SEARCH` | Web information search || `NONE` | No appropriate tool or out-of-scope request |
These are the evaluated tool families, rather than a fixed output vocabulary. You provide IDs, descriptions and optional example phrasings at runtime. The router also considers its internal out-of-scope option; new tools and descriptions need independent evaluation.
## Architecture and size
| Property | Value ||---|---|| Encoder | ModernBERT-large / Laya || Encoder layers / hidden size / attention heads | 28 / 1,024 / 16 || Intermediate size / vocabulary | 2,624 / 50,368 || Encoder parameters | 394,781,696 || Complete learned parameters | 421,293,827 || Temperature-buffer elements | 3 || Decision head | Two norm-first transformer layers, typed embeddings and per-option scorer || Input budget | 512 tokens total; 384-token head budget || Release format | PyTorch FP32 |
The saved action head is retained for checkpoint compatibility; production tool routing reads the option logits. The teacher is named 421M from its measured complete parameter count.
## Training
The Lapis adaptation workflow was configured in an environment with **2 × NVIDIA T4 GPUs**, using **FP16 mixed precision**. The retained training implementation runs on a single device (`world_size: 1`); the release does not claim that both GPUs participated in distributed training.
1. **Adapt the teacher:** fine-tune the Laya / ModernBERT-large decision model on bilingual tool-routing episodes.2. **Create soft targets:** run the teacher over training episodes and retain probabilities for the candidate tools and `NONE`.3. **Distill the student:** train an Ettin-150M encoder with the Laya decision head, mixing teacher probabilities and gold labels with a teacher-target weight of 0.5.4. **Calibrate and export:** fit temperature buckets on held-out training/development data, then export and check the student backends on development episodes.
| Setting | Teacher | Student ||---|---|---|| Epochs | 1 | 2 || Micro batch / gradient accumulation | 2 / 16 | 8 / 6 || Encoder / head learning rate | 2.5e-5 / 1e-4 | 5e-5 / 3e-4 || Batch token budget | 4,096 | 4,096 || Prompt / total token limit / head budget | `compact_fill` / 512 / 384 | Same || Teacher-target weight | Gold labels | 0.5 || Training seed | 20260926 | 20260926 |
### Dataset
The privately supplied **Lapis bilingual tool-routing v4.1-refined** source has **10,000 synthetic examples**: 8,000 train, 1,000 validation and 1,000 final test. Deterministic preparation produces **100,000 training episodes** and **5,000 development episodes**, with seed 7, shuffled variable tool menus and nominal 5% gold-tool removal to exercise abstention. Only train/validation rows are expanded; the reserved test stays separate.
The source dataset and teacher soft labels are not redistributed. The author's private reproducibility repository retains preparation/training/export scripts, a dependency lock and source data. Original complete training logs and historical initialization revisions were not retained; exact reproduction of the original optimizer trajectory is not claimed. The released weights can be used for a new fine-tuning run, but original optimizer/scheduler state is not included.
## Evaluation
The reserved final test contains **1,000 examples: 500 English and 500 Spanish**. All 13 tools plus the internal `NONE` option are available, with shortlist disabled and threshold **0.625**. Test examples and tool descriptions were preserved. Development episodes were used for numerical checks and latency measurements.
| Backend | Correct / total | Accuracy | English | Spanish ||---|---:|---:|---:|---:|| PyTorch FP32 | 960 / 1000 | 96.00% | 99.20% | 92.80% |
Macro F1 for PyTorch FP32: **96.48%**. Class recall is the fraction of examples of that class routed correctly.
<details><summary>Per-class precision, recall and F1</summary>
| Class | Test examples | Precision | Recall | F1 ||---|---:|---:|---:|---:|| CALCULATOR | 60 | 100.00% | 100.00% | 100.00% || CALENDAR | 60 | 100.00% | 90.00% | 94.74% || CLOCK | 60 | 100.00% | 96.67% | 98.31% || CODE | 60 | 100.00% | 100.00% | 100.00% || CONTACTS | 60 | 100.00% | 95.00% | 97.44% || HEALTH | 60 | 100.00% | 91.67% | 95.65% || LOCATION | 60 | 100.00% | 100.00% | 100.00% || MAIL | 60 | 95.00% | 95.00% | 95.00% || MAPS | 60 | 100.00% | 98.33% | 99.16% || MESSAGES | 60 | 100.00% | 91.67% | 95.65% || NONE | 220 | 88.00% | 100.00% | 93.62% || REMINDERS | 60 | 88.33% | 88.33% | 88.33% || WEATHER | 60 | 100.00% | 86.67% | 92.86% || WEB_SEARCH | 60 | 100.00% | 100.00% | 100.00% |
</details>
The historical 63.80% reference used different tool descriptions and is not a controlled same-prompt baseline. No causal improvement claim is based on that comparison. Detailed audit records and file checksums are retained in the private reproducibility repository. No raw evaluation messages are shipped.
## Limitations
- Evaluation uses a small synthetic bilingual test. Its scores are not estimates for arbitrary real-world traffic; validate with your own held-out examples.- Only English and Spanish were evaluated. Health or code route selection does not validate the correctness of health advice or generated code.- Overlapping descriptions, implicit intent, long conversations and ambiguous messages can produce confident routing errors. Menus/history share a 512-token budget.- Thresholds and scores depend on the menu. Keep threshold tuning and model selection separate from your final test.- The model scores options; it does not generate text, extract tool arguments, execute actions or verify user authorization.- Apple MLX measurements cover macOS Apple Silicon. iPhone/iOS, other languages and unreported accelerators have not been validated.- This custom DecisionModel requires the included runtime. Standard Transformers pipelines and hosted inference providers are not advertised as supported.
## License and acknowledgements
The release is distributed under **Apache-2.0**, retaining applicable upstream notices. Ettin's MIT notice is included under `third_party/`. The model license does not grant rights to the private source dataset.
Built on [Laya DecisionModel](https://huggingface.co/convaiinnovations/laya), the [Laya intent-router implementation](https://github.com/vrajnotviraj/laya-intent-router), [ModernBERT-large](https://huggingface.co/answerdotai/ModernBERT-large), and [Ettin-encoder-150M](https://huggingface.co/jhu-clsp/ettin-encoder-150m). See `LICENSE` and `NOTICE.md` for attribution.
## Keywords
semantic routing, tool routing, intent classification, dynamic tool selection, abstention, out-of-scope detection, bilingual English Spanish, knowledge distillation, local inference, ModernBERT, Ettin, Laya123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384{ "architectures": [ "ModernBertForMaskedLM" ], "attention_bias": false, "attention_dropout": 0.0, "bos_token_id": 50281, "classifier_activation": "gelu", "classifier_bias": false, "classifier_dropout": 0.0, "classifier_pooling": "mean", "cls_token_id": 50281, "decoder_bias": true, "deterministic_flash_attn": false, "dtype": "float32", "embedding_dropout": 0.0, "eos_token_id": 50282, "global_attn_every_n_layers": 3, "gradient_checkpointing": false, "hidden_activation": "gelu", "hidden_size": 1024, "initializer_cutoff_factor": 2.0, "initializer_range": 0.02, "intermediate_size": 2624, "layer_norm_eps": 1e-05, "layer_types": [ "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention", "sliding_attention", "sliding_attention", "full_attention" ], "local_attention": 128, "max_position_embeddings": 8192, "mlp_bias": false, "mlp_dropout": 0.0, "model_type": "modernbert", "norm_bias": false, "norm_eps": 1e-05, "num_attention_heads": 16, "num_hidden_layers": 28, "pad_token_id": 50283, "position_embedding_type": "absolute", "repad_logits_with_grad": false, "rope_parameters": { "full_attention": { "rope_theta": 160000.0, "rope_type": "default" }, "sliding_attention": { "rope_theta": 10000.0, "rope_type": "default" } }, "sep_token_id": 50282, "sparse_pred_ignore_index": -100, "sparse_prediction": false, "tie_word_embeddings": true, "transformers_version": "5.17.0", "vocab_size": 50368}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Shared local loaders and provenance helpers; no downloads or publication."""from __future__ import annotations
import hashlibimport importlib.utilfrom importlib.metadata import distribution, version, PackageNotFoundErrorimport jsonfrom pathlib import Pathimport randomimport sys
def sha256(path): digest = hashlib.sha256() with Path(path).open('rb') as source: for block in iter(lambda: source.read(1024 * 1024), b''): digest.update(block) return digest.hexdigest()
def model_fingerprint(model_dir, backend): model_dir = Path(model_dir) names = { 'torch': ('model.safetensors', 'encoder/config.json', 'tokenizer/tokenizer.json', 'rl_agent_config.json'), 'onnx': ('laya.onnx', 'laya.onnx.data', 'tokenizer.json', 'rl_agent_config.json'), 'mlx': ('mlx/model.safetensors', 'mlx/config.json', 'tokenizer.json', 'rl_agent_config.json'), }[backend] return {name: sha256(model_dir / name) for name in names}
def versions(): result = {'python': sys.version.split()[0]} for name in ('torch', 'transformers', 'laya', 'mlx', 'onnxruntime', 'onnx', 'onnxscript', 'tokenizers', 'safetensors', 'numpy'): try: result[name] = version(name) except PackageNotFoundError: continue try: direct = distribution('laya').read_text('direct_url.json') if direct: result['laya_commit'] = json.loads(direct).get('vcs_info', {}).get('commit_id') except PackageNotFoundError: pass return result
def require_pinned_reference(): installed = versions() expected = {'torch': '2.14.0', 'transformers': '5.17.0', 'laya': '0.3.20'} wrong = {name: installed.get(name) for name, value in expected.items() if installed.get(name, '').split('+')[0] != value} commit = installed.get('laya_commit') if commit and commit != '4066d5d5fbf08b66c6757ddeedbd797bd7655bc0': wrong['laya_commit'] = commit if wrong: raise RuntimeError(f'Reference environment differs from the trained checkpoint: {wrong}. ' 'Use Python 3.12 and pip install -r requirements.txt.')
def load_module(path, name): spec = importlib.util.spec_from_file_location(name, str(path)) if spec is None or spec.loader is None: raise ImportError(f'Cannot load {path}') module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module
class TorchSession: """Same session interface as ONNX/MLX, with a strict local checkpoint load.""" def __init__(self, checkpoint, device='cpu', threads=4): require_pinned_reference() import torch from safetensors.torch import load_file from laya.common import build_model
checkpoint = Path(checkpoint) self.torch = torch self.device = torch.device(device) torch.set_num_threads(threads) cfg = json.loads((checkpoint / 'rl_agent_config.json').read_text()) self.model = build_model(cfg, encoder_dir=str(checkpoint / 'encoder')) self.model.encoder.config.reference_compile = False self.model.load_state_dict(load_file(str(checkpoint / 'model.safetensors')), strict=True) self.model.float().eval().to(self.device)
def run(self, names, feeds): if list(names) != ['logits']: raise ValueError(f'Unsupported outputs: {names}') torch = self.torch with torch.inference_mode(): f = {key: torch.as_tensor(value, device=self.device, dtype=torch.bool if key == 'marker_mask' else torch.long) for key, value in feeds.items()} return [self.model(**f)[0].float().cpu().numpy()]
def load_router(model_dir, backend='onnx', repo_dir=None, threads=4, device='cpu'): """Load checkpoint or deployment using identical production prompt/decision logic.""" model_dir = Path(model_dir).resolve() module_dir = Path(__file__).resolve().parent project_root = module_dir.parent if module_dir.name == 'scripts' else module_dir repo_dir = Path(repo_dir) if repo_dir else project_root / 'laya-intent-router' candidates = (repo_dir / 'laya_intent_router.py', Path(__file__).parent / 'laya_intent_router.py', model_dir / 'laya_intent_router.py') runtime = next((path for path in candidates if path.is_file()), None) if runtime is None: raise FileNotFoundError('laya_intent_router.py is missing; specify repo_dir or use a complete release package') mod = load_module(runtime, 'lapis_router_runtime') if backend != 'torch': return mod.LayaIntentRouter(str(model_dir), backend=backend, threads=threads, shortlist_k=0)
from tokenizers import Tokenizer router = mod.LayaIntentRouter.__new__(mod.LayaIntentRouter) router.cfg = json.loads((model_dir / 'rl_agent_config.json').read_text()) router.tok = Tokenizer.from_file(str(model_dir / 'tokenizer/tokenizer.json')) router.cls, router.sep, router.mask = (router.tok.token_to_id(t) for t in ('[CLS]', '[SEP]', '[MASK]')) router.backend = 'torch' router.sess = TorchSession(model_dir, device=device, threads=threads) router.threshold = router.cfg.get('match_threshold', 0.625) router.temps = router.cfg['temperature_by_options'] router.k, router.shortlist = 0, None return router
def load_episode_samples(path, n, seed): if n < 1: raise ValueError('Sample count must be positive') eps = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] if not eps: raise ValueError(f'No episodes in {path}') if any(str(ep.get('split', '')).lower() == 'test' for ep in eps): raise ValueError('Use development episodes, not the reserved test split') return random.Random(seed).sample(eps, min(n, len(eps)))
def episode_paths(ep): paths = ep['paths'] if isinstance(paths, dict): return {key: [value] if isinstance(value, str) else value for key, value in paths.items()} result = {} for path in paths: key = path.get('path_id') or path.get('id') or path.get('name') value = path.get('text') or path.get('texts') or path.get('descriptions') result[key] = [value] if isinstance(value, str) else list(value) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265"""Zero-shot intent router: pick which of your paths a message belongs to, or none of them.
from laya_intent_router import LayaIntentRouter r = LayaIntentRouter.from_pretrained() # or LayaIntentRouter("path/to/local/dir") r.route("i want to cancel my order 88213", { "order_status": ["Customer wants to know where their order is"], "cancel_order": ["Customer wants to cancel an existing order"], }) # {'match': 'cancel_order', 'score': 0.97, 'probabilities': {...}}
Needs: pip install onnxruntime tokenizers numpy huggingface_hubOn Apple Silicon, `pip install mlx` as well and the model runs on the GPU with backend="mlx" or "auto";laya_intent_router_mlx.py has the MLX code). The default is backend="onnx" (CPU), which never downloads mlx/."""
import hashlibimport jsonimport importlib.utilimport osimport platformimport reimport sysfrom collections import OrderedDict
import numpy as np
REPO_ID = "lapislabsai/lapis-sal-421M"INSTRUCTIONS = ( "A user sent this message to a conversational workflow that branches into the paths below. " "Which path is the message asking for?")HISTORY_HINT = ( " `history` holds the earlier turns of this conversation, oldest first; a short or elliptical " "message usually continues the intent of the most recent turns.")NO_MATCH_DESCRIPTION = "Gibberish, filler words, or a message unrelated to every other path."NONE = "__none__"BACKENDS = ("auto", "onnx", "mlx")SHARED_FILES = ["tokenizer.json", "rl_agent_config.json", "shortlist/*"]BACKEND_FILES = {"onnx": ["laya.onnx", "laya.onnx.data"], "mlx": ["mlx/*", "laya_intent_router_mlx.py"]}OPTION_CAP, MIN_HEAD_TOKENS, PHRASING_SEP = 96, 16, '" | "'
def _water_fill(lengths, budget, floor=4): open_ = list(range(len(lengths))) while open_: fair = budget // len(open_) short = [i for i in open_ if lengths[i] <= fair] if not short: break budget -= sum(lengths[i] for i in short) open_ = [i for i in open_ if lengths[i] > fair] alloc = list(lengths) for j, i in enumerate(open_): alloc[i] = max(floor, budget // len(open_) + (j < budget % len(open_))) return alloc
def _humanise(path_id): s = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", path_id) return re.sub(r"[_\-.:/]+", " ", s).strip().lower()
def _mlx_available(): if sys.platform != "darwin" or platform.machine() != "arm64": return False try: import mlx.core as mx
return bool(mx.metal.is_available()) # False in macOS VMs / CI runners without a Metal GPU except Exception: return False
def _has_mlx_weights(model_dir): weights_dir = os.path.join(model_dir, "mlx") if os.path.isfile(os.path.join(weights_dir, "model.safetensors")): return True try: with open(os.path.join(weights_dir, "config.json")) as source: config = json.load(source) weights_file = config.get("weights_file", "model.safetensors") return os.path.isfile(os.path.join(weights_dir, weights_file)) except (OSError, ValueError, TypeError): return False
def _mlx_session(model_dir): for d in (os.path.dirname(os.path.abspath(__file__)), model_dir): # next to this file, else the downloaded copy f = os.path.join(d, "laya_intent_router_mlx.py") if os.path.exists(f): spec = importlib.util.spec_from_file_location("laya_intent_router_mlx", f) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod.Session(os.path.join(model_dir, "mlx")) raise FileNotFoundError("laya_intent_router_mlx.py not found next to laya_intent_router.py or in " + model_dir)
def _session(path, threads): import onnxruntime as ort
o = ort.SessionOptions() o.intra_op_num_threads, o.inter_op_num_threads = threads, 1 return ort.InferenceSession(path, o, providers=["CPUExecutionProvider"])
class Shortlist: """bge-small embedder: keeps the k paths closest to the message (best phrasing wins). Cached per path set."""
def __init__(self, model_dir, threads=4, cache_size=512): from tokenizers import Tokenizer
self.tok = Tokenizer.from_file(os.path.join(model_dir, "tokenizer.json")) self.tok.enable_truncation(128) self.tok.enable_padding(pad_id=self.tok.token_to_id("[PAD]") or 0) self.sess = _session(os.path.join(model_dir, "model.onnx"), threads) self.cache, self.cache_size = OrderedDict(), cache_size
def _embed(self, texts): encs = self.tok.encode_batch(texts) ids = np.array([e.ids for e in encs], dtype=np.int64) mask = np.array([e.attention_mask for e in encs], dtype=np.int64) v = self.sess.run(None, {"input_ids": ids, "attention_mask": mask, "token_type_ids": np.zeros_like(ids)})[0][:, 0] return v / np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-8)
def top(self, message, paths, k): key = hashlib.blake2b(json.dumps(paths).encode(), digest_size=16).hexdigest() if key not in self.cache: texts, owner = [], [] for j, texts_j in enumerate(paths.values()): for t in list(texts_j) + [_humanise(list(paths)[j])]: texts.append(t) owner.append(j) self.cache[key] = (self._embed(texts), np.array(owner)) if len(self.cache) > self.cache_size: self.cache.popitem(last=False) self.cache.move_to_end(key) vecs, owner = self.cache[key] sims = vecs @ self._embed([message])[0] best = np.array([sims[owner == j].max() for j in range(len(paths))]) keep = set(np.argsort(-best, kind="stable")[:k].tolist()) return {p: t for j, (p, t) in enumerate(paths.items()) if j in keep}
class LayaIntentRouter: def __init__(self, model_dir, threads=4, shortlist_k=4, backend="onnx"): """backend: "onnx" (CPU, default), "mlx" (Apple GPU) or "auto" (mlx on Apple Silicon when mlx is installed and mlx/ weights are present, onnx otherwise). The chosen one is in self.backend.""" from tokenizers import Tokenizer
if backend not in BACKENDS: raise ValueError(f"backend must be one of {BACKENDS}, got {backend!r}") if backend == "auto": backend = "mlx" if _has_mlx_weights(model_dir) and _mlx_available() else "onnx"
self.cfg = json.load(open(os.path.join(model_dir, "rl_agent_config.json"))) self.tok = Tokenizer.from_file(os.path.join(model_dir, "tokenizer.json")) self.cls, self.sep, self.mask = (self.tok.token_to_id(t) for t in ("[CLS]", "[SEP]", "[MASK]")) self.backend = backend self.sess = _mlx_session(model_dir) if backend == "mlx" else _session(os.path.join(model_dir, "laya.onnx"), threads) self.threshold = self.cfg.get("match_threshold", 0.625) self.temps = self.cfg["temperature_by_options"] sl_dir = os.path.join(model_dir, "shortlist") self.k = shortlist_k if os.path.isdir(sl_dir) else 0 self.shortlist = Shortlist(sl_dir, threads) if self.k else None
@classmethod def from_pretrained(cls, repo_id=REPO_ID, backend="onnx", **kw): """Downloads only what the backend needs: ONNX never fetches mlx/, MLX never fetches laya.onnx.""" from huggingface_hub import snapshot_download
if backend not in BACKENDS: raise ValueError(f"backend must be one of {BACKENDS}, got {backend!r}") if backend == "auto": if _mlx_available(): d = snapshot_download(repo_id, allow_patterns=SHARED_FILES + BACKEND_FILES["mlx"]) if _has_mlx_weights(d): return cls(d, backend="mlx", **kw) backend = "onnx" if backend == "mlx" and not _mlx_available(): # fail before downloading 328 MB we can't use raise ImportError('backend="mlx" needs Apple Silicon and `pip install mlx`') return cls(snapshot_download(repo_id, allow_patterns=SHARED_FILES + BACKEND_FILES[backend]), backend=backend, **kw)
def _tokens(self, text): return self.tok.encode(text.replace("[MASK]", " "), add_special_tokens=False)
def _options(self, criteria, head_max_len): texts = [f" {k}: {d}".replace("[MASK]", " ") for k, d in criteria.items()] encs = [self.tok.encode(t, add_special_tokens=False) for t in texts] options = [[self.mask] + e.ids[:OPTION_CAP] for e in encs] if head_max_len - sum(map(len, options)) < MIN_HEAD_TOKENS: # too many paths: share the budget fairly alloc = _water_fill([len(o) for o in options], head_max_len - MIN_HEAD_TOKENS) for i, (t, e, a) in enumerate(zip(texts, encs, alloc)): n = a - 1 if n >= len(options[i]) - 1: continue ends, keep = [end for _, end in e.offsets], n p = t.find(PHRASING_SEP) while p >= 0: # prefer cutting between phrasings b = sum(x <= p + 1 for x in ends) if b > n: break if 4 * (n - b) <= a: keep = b p = t.find(PHRASING_SEP, p + 1) options[i] = [self.mask] + e.ids[:keep] return options
def _encode(self, message, criteria, history): max_len, head_max_len = self.cfg["max_len"], self.cfg["head_max_len"] options = self._options(criteria, head_max_len) instructions = INSTRUCTIONS + (HISTORY_HINT if history else "") head = self._tokens(f"choice question: {instructions}").ids[: max(8, head_max_len - sum(map(len, options)))] ids, markers = [self.cls, *head, self.sep], [] for o in options: markers.append(len(ids)) ids += o ids.append(self.sep) state = {"message": message, **({"history": list(history)} if history else {})} room = max(0, max_len - len(ids) - 1) ids = (ids + self._tokens(json.dumps(state, ensure_ascii=False)).ids[:room] + [self.sep])[:max_len] if any(m >= max_len for m in markers): raise ValueError("too many paths for 512 tokens; keep the shortlist on") return ids, markers
def _temperature(self, n): b = "2" if n <= 2 else "3-5" if n <= 5 else "6-10" if n <= 10 else "11+" return min(5.0, max(0.5, float(self.temps.get(f"choice:{b}", self.cfg["temperature"][0]))))
def route(self, message, paths, history=None, threshold=None): """paths: {path_id: [example phrasings or a description, ...]}. Returns the match (or None) and every probability.""" none_key = NONE while none_key in paths: none_key += "_" kept = self.shortlist.top(message, paths, self.k) if self.k and len(paths) > self.k else paths criteria = {p: " | ".join(f'"{t}"' for t in texts) for p, texts in kept.items()} criteria[none_key] = NO_MATCH_DESCRIPTION ids, markers = self._encode(message, criteria, history) logits = self.sess.run(["logits"], { "input_ids": np.array([ids], dtype=np.int64), "attention_mask": np.ones((1, len(ids)), dtype=np.int64), "marker_pos": np.array([markers], dtype=np.int64), "marker_mask": np.ones((1, len(markers)), dtype=bool), "qtype": np.zeros(1, dtype=np.int64)})[0][0] z = logits / self._temperature(len(criteria)) p = np.exp(z - z.max()) p /= p.sum() got = dict(zip(criteria, p.tolist())) probs = {k: got.get(k, 0.0) for k in paths} | {NONE: got[none_key]} best = max(paths, key=probs.get) ok = probs[best] > probs[NONE] and probs[best] >= (self.threshold if threshold is None else threshold) return {"match": best if ok else None, "score": probs[best], "probabilities": probs}
if __name__ == "__main__": here = os.path.dirname(os.path.abspath(__file__)) r = LayaIntentRouter(here) if os.path.exists(os.path.join(here, "laya.onnx")) else LayaIntentRouter.from_pretrained() paths = { "order_status": ["Customer wants to know the status or location of their order"], "cancel_order": ["Customer wants to cancel an existing order"], "return_order": ["Customer wants to return an order"], "wrong_item": ["Customer received an item different from what they ordered"], } print(f"backend: {r.backend}") for msg in sys.argv[1:] or ["where is my parcel #A-7721", "qwewqeqw", "i got blue shoes but ordered black"]: out = r.route(msg, paths) print(f"{msg!r:45} -> {out['match']} ({out['score']:.2f})")123version https://git-lfs.github.com/spec/v1oid sha256:1a9e199701060a0cf07e1f3a7a8153e01d99f86993b88b689ba2a284b1fd0ff8size 16851970881234567numpy==2.5.3tokenizers==0.23.2huggingface_hub==1.33.0torch==2.14.0transformers==5.17.0safetensors==0.8.0laya @ git+https://github.com/NandhaKishorM/laya@4066d5d5fbf08b66c6757ddeedbd797bd7655bc012345678910111213141516171819202122232425262728293031323334{ "encoder": "answerdotai/ModernBERT-large", "head_layers": 2, "max_len": 512, "head_max_len": 384, "max_prefixes": 6, "act_costs": { "escalate": 0.5 }, "cost_wrong_act": 3.0, "amp_dtype": "bf16", "model_name": "rl-agent", "temperature": [ 2.0630812644958496, 1.2514300346374512, 1.983399510383606 ], "temperature_by_options": { "score:3-5": 1.2514300346374512, "noul:2": 1.983399510383606, "choice:2": 2.0630812644958496, "choice:3-5": 1.0, "choice:6-10": 1.0, "choice:11+": 2.1076154708862305 }, "training": { "updates": 7313, "epochs_completed": 1, "hours": 1.96, "world_size": 1, "fine_tuned_from_checkpoint": true }, "option_format": "compact_fill"}123456789101112131415161718192021MIT License
Copyright (c) 2025 Johns Hopkins University Center for Language and Speech Processing
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE. 1234567891011121314{ "clean_up_tokenization_spaces": true, "cls_token": "[CLS]", "mask_token": "[MASK]", "model_input_names": [ "input_ids", "attention_mask" ], "model_max_length": 8192, "pad_token": "[PAD]", "sep_token": "[SEP]", "tokenizer_class": "PreTrainedTokenizerFast", "unk_token": "[UNK]"}.gitattributes+2-34
LICENSEAdded+202
NOTICE.mdAdded+9
README.mdAdded+216
encoder/config.jsonAdded+84
lapis_runtime.pyAdded+148
laya_intent_router.pyAdded+265
model.safetensorsAdded+3
requirements.txtAdded+7
rl_agent_config.jsonAdded+34
third_party/ettin-LICENSE.txtAdded+21
tokenizer/tokenizer.jsonAdded
tokenizer/tokenizer_config.jsonAdded+14