laya-mnn 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- laya_mnn-0.1.0/LICENSE +176 -0
- laya_mnn-0.1.0/NOTICE +14 -0
- laya_mnn-0.1.0/PKG-INFO +108 -0
- laya_mnn-0.1.0/README.md +84 -0
- laya_mnn-0.1.0/pyproject.toml +36 -0
- laya_mnn-0.1.0/setup.cfg +4 -0
- laya_mnn-0.1.0/src/laya_mnn/__init__.py +6 -0
- laya_mnn-0.1.0/src/laya_mnn/cli.py +78 -0
- laya_mnn-0.1.0/src/laya_mnn/download.py +118 -0
- laya_mnn-0.1.0/src/laya_mnn/runtime.py +204 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/PKG-INFO +108 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/SOURCES.txt +14 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/dependency_links.txt +1 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/entry_points.txt +2 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/requires.txt +3 -0
- laya_mnn-0.1.0/src/laya_mnn.egg-info/top_level.txt +1 -0
laya_mnn-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
laya_mnn-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
laya-mnn
|
|
2
|
+
Copyright 2026 yunfengwang
|
|
3
|
+
|
|
4
|
+
This product includes software and model weights derived from Laya
|
|
5
|
+
(https://github.com/NandhaKishorM/laya, https://huggingface.co/convaiinnovations/laya),
|
|
6
|
+
Copyright Convai Innovations, licensed under the Apache License, Version 2.0.
|
|
7
|
+
|
|
8
|
+
The prompt construction (build_sequence / render_options), confidence and
|
|
9
|
+
temperature handling in src/laya_mnn/runtime.py are ports of the reference
|
|
10
|
+
implementation in that project, kept numerically identical so that converted
|
|
11
|
+
models reproduce the original outputs. The converted MNN weights are a
|
|
12
|
+
quantized derivative of the published Laya checkpoint.
|
|
13
|
+
|
|
14
|
+
See LICENSE for the full Apache License, Version 2.0 text.
|
laya_mnn-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: laya-mnn
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run the Laya System 1 decision model locally on MNN (CPU, no PyTorch, no API)
|
|
5
|
+
Author: yunfengwang
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://huggingface.co/yunfengwang/laya-MNN-fp16
|
|
8
|
+
Project-URL: Source, https://huggingface.co/yunfengwang/laya-MNN-fp16
|
|
9
|
+
Keywords: mnn,onnx,decision-model,system-one,laya,calibration,edge-inference
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Operating System :: MacOS
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
License-File: NOTICE
|
|
20
|
+
Requires-Dist: mnn>=3.6.1
|
|
21
|
+
Requires-Dist: tokenizers>=0.15
|
|
22
|
+
Requires-Dist: numpy>=1.21
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# laya-mnn
|
|
26
|
+
|
|
27
|
+
Run the [Laya](https://huggingface.co/convaiinnovations/laya) System 1 decision model **locally on MNN** — no PyTorch, no GPU, no API key.
|
|
28
|
+
|
|
29
|
+
Laya takes a **state** (email, ticket, JSON) plus **typed questions** and returns typed answers with calibrated probabilities in one forward pass. It never generates text, so there is nothing to parse and nothing to hallucinate. This package runs a converted Laya checkpoint on Alibaba's [MNN](https://github.com/alibaba/MNN) runtime.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
uvx laya-mnn decide \
|
|
33
|
+
--state "Hi, we were billed twice for March. Please refund the duplicate or we will cancel our plan." \
|
|
34
|
+
--questions '{"department":{"type":"choice","instructions":"Which department should handle this?","criteria":{"billing":"invoices, payments, refunds","technical":"bugs, outages","other":"everything else"}},
|
|
35
|
+
"churn_risk":{"type":"noul","instructions":"Does the user threaten to cancel?"}}'
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"model": "laya-mnn",
|
|
41
|
+
"answers": {
|
|
42
|
+
"department": {
|
|
43
|
+
"type": "choice", "choice": "billing",
|
|
44
|
+
"probabilities": { "billing": 0.9631, "technical": 0.0165, "other": 0.0204 },
|
|
45
|
+
"confidence": 0.8067, "action": { "act_probability": 0.9977 }
|
|
46
|
+
},
|
|
47
|
+
"churn_risk": { "type": "noul", "noul": 0.9476, "confidence": 0.9476, "action": { "act_probability": 0.9977 } }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Weights download automatically on first use (about 850 MB for `fp16`).
|
|
53
|
+
|
|
54
|
+
## Question types
|
|
55
|
+
|
|
56
|
+
| type | answer | use for |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `choice` | one of the `criteria` keys, plus a probability per option | routing, intent, classification |
|
|
59
|
+
| `score` | expected value over ordered `criteria` levels (0-based) | severity, urgency, sentiment strength |
|
|
60
|
+
| `noul` | `P(true)` | yes/no judgements |
|
|
61
|
+
|
|
62
|
+
`criteria` is defined **at request time** — new schemas do not need retraining. Up to 64 options per question with the shipped checkpoints.
|
|
63
|
+
|
|
64
|
+
## CLI
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
laya-mnn decide --state S --questions Q [--precision fp16|int8] [--threads N] [--quiet]
|
|
68
|
+
laya-mnn download [--precision ...] # pre-fetch weights
|
|
69
|
+
laya-mnn info [--precision ...] # cache dir + manifest
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`--state` accepts literal text, inline JSON, or `@path`. `--questions` accepts inline JSON or `@path`.
|
|
73
|
+
|
|
74
|
+
## Python
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from laya_mnn import LayaMNN, ensure_model
|
|
78
|
+
|
|
79
|
+
model = LayaMNN(ensure_model("fp16"), threads=4)
|
|
80
|
+
result = model.system_one(
|
|
81
|
+
{"subject": "Duplicate charge", "body": "We were billed twice..."},
|
|
82
|
+
{"department": {"type": "choice", "instructions": "Which department?", "criteria": ["billing", "technical", "other"]}},
|
|
83
|
+
)
|
|
84
|
+
print(result["answers"]["department"]["choice"], result["answers"]["department"]["probabilities"])
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Checkpoints
|
|
88
|
+
|
|
89
|
+
| precision | size | notes |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| `fp16` | 846 MB | weights stored in half precision; probability deltas vs. the original PyTorch model are below 1e-3 |
|
|
92
|
+
| `int8` | 581 MB | weight-only 8-bit quantization; larger deltas, check it against your own eval |
|
|
93
|
+
|
|
94
|
+
Both are conversions of `convaiinnovations/laya` (English, ModernBERT-large backbone, 421M parameters). The model was exported to ONNX (`opset 17`, eager attention, static 512-token sequence) and converted with the MNN converter 3.6.1.
|
|
95
|
+
|
|
96
|
+
Hosted on [Hugging Face](https://huggingface.co/yunfengwang/laya-MNN-fp16) and [ModelScope](https://modelscope.cn/models/yunfeng/laya-MNN-fp16); `modelscope` is tried first, then Hugging Face (override with `HF_ENDPOINT`).
|
|
97
|
+
Set `LAYA_MNN_CACHE` to change the cache directory (default `~/.cache/laya-mnn`).
|
|
98
|
+
|
|
99
|
+
## Notes and limits
|
|
100
|
+
|
|
101
|
+
- **CPU is the supported backend.** The MNN Metal backend was measured to return all-zero logits for this graph in some builds of the 3.6.1 wheel; `--backend metal` is exposed but not recommended.
|
|
102
|
+
- A 512-token forward pass costs roughly 1.3 s on an Apple Silicon CPU. Shorter states are cheaper — the graph is exported at a fixed 512 tokens, so the CLI pads and masks.
|
|
103
|
+
- Max 64 options per question, 512 tokens of context, English only. The multilingual checkpoint (`mmBERT-base`) is not converted here.
|
|
104
|
+
- Percentile-latency and calibration in the upstream model card are for the original PyTorch model; quantized results will differ slightly.
|
|
105
|
+
|
|
106
|
+
## License and attribution
|
|
107
|
+
|
|
108
|
+
Apache-2.0. The model, its prompt format and the calibration scheme come from [NandhaKishorM/laya](https://github.com/NandhaKishorM/laya) by Convai Innovations (Apache-2.0); this package is an independent MNN port and is not affiliated with or endorsed by them. See `NOTICE`.
|
laya_mnn-0.1.0/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# laya-mnn
|
|
2
|
+
|
|
3
|
+
Run the [Laya](https://huggingface.co/convaiinnovations/laya) System 1 decision model **locally on MNN** — no PyTorch, no GPU, no API key.
|
|
4
|
+
|
|
5
|
+
Laya takes a **state** (email, ticket, JSON) plus **typed questions** and returns typed answers with calibrated probabilities in one forward pass. It never generates text, so there is nothing to parse and nothing to hallucinate. This package runs a converted Laya checkpoint on Alibaba's [MNN](https://github.com/alibaba/MNN) runtime.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
uvx laya-mnn decide \
|
|
9
|
+
--state "Hi, we were billed twice for March. Please refund the duplicate or we will cancel our plan." \
|
|
10
|
+
--questions '{"department":{"type":"choice","instructions":"Which department should handle this?","criteria":{"billing":"invoices, payments, refunds","technical":"bugs, outages","other":"everything else"}},
|
|
11
|
+
"churn_risk":{"type":"noul","instructions":"Does the user threaten to cancel?"}}'
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```json
|
|
15
|
+
{
|
|
16
|
+
"model": "laya-mnn",
|
|
17
|
+
"answers": {
|
|
18
|
+
"department": {
|
|
19
|
+
"type": "choice", "choice": "billing",
|
|
20
|
+
"probabilities": { "billing": 0.9631, "technical": 0.0165, "other": 0.0204 },
|
|
21
|
+
"confidence": 0.8067, "action": { "act_probability": 0.9977 }
|
|
22
|
+
},
|
|
23
|
+
"churn_risk": { "type": "noul", "noul": 0.9476, "confidence": 0.9476, "action": { "act_probability": 0.9977 } }
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Weights download automatically on first use (about 850 MB for `fp16`).
|
|
29
|
+
|
|
30
|
+
## Question types
|
|
31
|
+
|
|
32
|
+
| type | answer | use for |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| `choice` | one of the `criteria` keys, plus a probability per option | routing, intent, classification |
|
|
35
|
+
| `score` | expected value over ordered `criteria` levels (0-based) | severity, urgency, sentiment strength |
|
|
36
|
+
| `noul` | `P(true)` | yes/no judgements |
|
|
37
|
+
|
|
38
|
+
`criteria` is defined **at request time** — new schemas do not need retraining. Up to 64 options per question with the shipped checkpoints.
|
|
39
|
+
|
|
40
|
+
## CLI
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
laya-mnn decide --state S --questions Q [--precision fp16|int8] [--threads N] [--quiet]
|
|
44
|
+
laya-mnn download [--precision ...] # pre-fetch weights
|
|
45
|
+
laya-mnn info [--precision ...] # cache dir + manifest
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`--state` accepts literal text, inline JSON, or `@path`. `--questions` accepts inline JSON or `@path`.
|
|
49
|
+
|
|
50
|
+
## Python
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from laya_mnn import LayaMNN, ensure_model
|
|
54
|
+
|
|
55
|
+
model = LayaMNN(ensure_model("fp16"), threads=4)
|
|
56
|
+
result = model.system_one(
|
|
57
|
+
{"subject": "Duplicate charge", "body": "We were billed twice..."},
|
|
58
|
+
{"department": {"type": "choice", "instructions": "Which department?", "criteria": ["billing", "technical", "other"]}},
|
|
59
|
+
)
|
|
60
|
+
print(result["answers"]["department"]["choice"], result["answers"]["department"]["probabilities"])
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Checkpoints
|
|
64
|
+
|
|
65
|
+
| precision | size | notes |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `fp16` | 846 MB | weights stored in half precision; probability deltas vs. the original PyTorch model are below 1e-3 |
|
|
68
|
+
| `int8` | 581 MB | weight-only 8-bit quantization; larger deltas, check it against your own eval |
|
|
69
|
+
|
|
70
|
+
Both are conversions of `convaiinnovations/laya` (English, ModernBERT-large backbone, 421M parameters). The model was exported to ONNX (`opset 17`, eager attention, static 512-token sequence) and converted with the MNN converter 3.6.1.
|
|
71
|
+
|
|
72
|
+
Hosted on [Hugging Face](https://huggingface.co/yunfengwang/laya-MNN-fp16) and [ModelScope](https://modelscope.cn/models/yunfeng/laya-MNN-fp16); `modelscope` is tried first, then Hugging Face (override with `HF_ENDPOINT`).
|
|
73
|
+
Set `LAYA_MNN_CACHE` to change the cache directory (default `~/.cache/laya-mnn`).
|
|
74
|
+
|
|
75
|
+
## Notes and limits
|
|
76
|
+
|
|
77
|
+
- **CPU is the supported backend.** The MNN Metal backend was measured to return all-zero logits for this graph in some builds of the 3.6.1 wheel; `--backend metal` is exposed but not recommended.
|
|
78
|
+
- A 512-token forward pass costs roughly 1.3 s on an Apple Silicon CPU. Shorter states are cheaper — the graph is exported at a fixed 512 tokens, so the CLI pads and masks.
|
|
79
|
+
- Max 64 options per question, 512 tokens of context, English only. The multilingual checkpoint (`mmBERT-base`) is not converted here.
|
|
80
|
+
- Percentile-latency and calibration in the upstream model card are for the original PyTorch model; quantized results will differ slightly.
|
|
81
|
+
|
|
82
|
+
## License and attribution
|
|
83
|
+
|
|
84
|
+
Apache-2.0. The model, its prompt format and the calibration scheme come from [NandhaKishorM/laya](https://github.com/NandhaKishorM/laya) by Convai Innovations (Apache-2.0); this package is an independent MNN port and is not affiliated with or endorsed by them. See `NOTICE`.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "laya-mnn"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Run the Laya System 1 decision model locally on MNN (CPU, no PyTorch, no API)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [{ name = "yunfengwang" }]
|
|
13
|
+
keywords = ["mnn", "onnx", "decision-model", "system-one", "laya", "calibration", "edge-inference"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: Apache Software License",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
"Operating System :: MacOS",
|
|
19
|
+
"Operating System :: POSIX :: Linux",
|
|
20
|
+
"Operating System :: Microsoft :: Windows",
|
|
21
|
+
]
|
|
22
|
+
dependencies = [
|
|
23
|
+
"mnn>=3.6.1",
|
|
24
|
+
"tokenizers>=0.15",
|
|
25
|
+
"numpy>=1.21",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://huggingface.co/yunfengwang/laya-MNN-fp16"
|
|
30
|
+
Source = "https://huggingface.co/yunfengwang/laya-MNN-fp16"
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
laya-mnn = "laya_mnn.cli:main"
|
|
34
|
+
|
|
35
|
+
[tool.setuptools.packages.find]
|
|
36
|
+
where = ["src"]
|
laya_mnn-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Laya decision model on MNN: fast, non-autoregressive, calibrated decisions."""
|
|
2
|
+
from .download import DEFAULT_PRECISION, REPOS, cache_dir, ensure_model
|
|
3
|
+
from .runtime import LayaMNN
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
__all__ = ["LayaMNN", "ensure_model", "cache_dir", "DEFAULT_PRECISION", "REPOS", "__version__"]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""uvx-friendly CLI: download the converted weights, then answer typed questions."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .download import DEFAULT_PRECISION, REPOS, ensure_model
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _load_arg(value: str, what: str):
|
|
11
|
+
"""Accept inline JSON, a bare path, or @path."""
|
|
12
|
+
if value.startswith("@"):
|
|
13
|
+
value = value[1:]
|
|
14
|
+
if os.path.exists(value):
|
|
15
|
+
with open(value, encoding="utf-8") as f:
|
|
16
|
+
text = f.read().strip()
|
|
17
|
+
if what == "state":
|
|
18
|
+
try:
|
|
19
|
+
return json.loads(text)
|
|
20
|
+
except json.JSONDecodeError:
|
|
21
|
+
return text
|
|
22
|
+
return json.loads(text)
|
|
23
|
+
if what == "state":
|
|
24
|
+
try:
|
|
25
|
+
return json.loads(value)
|
|
26
|
+
except json.JSONDecodeError:
|
|
27
|
+
return value
|
|
28
|
+
return json.loads(value)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main(argv=None):
|
|
32
|
+
p = argparse.ArgumentParser(prog="laya-mnn",
|
|
33
|
+
description="Run the Laya System 1 decision model locally on MNN.")
|
|
34
|
+
sub = p.add_subparsers(dest="cmd")
|
|
35
|
+
|
|
36
|
+
d = sub.add_parser("decide", help="answer typed questions about a state")
|
|
37
|
+
d.add_argument("--state", required=True, help="email/ticket/JSON text, or @file, or inline JSON")
|
|
38
|
+
d.add_argument("--questions", required=True, help="questions JSON ({id: {type,instructions,criteria}}), or @file")
|
|
39
|
+
sub.add_parser("download", help="pre-fetch model weights").add_argument(
|
|
40
|
+
"--precision", default=DEFAULT_PRECISION, choices=sorted(REPOS))
|
|
41
|
+
sub.add_parser("info", help="show cache location and model manifest").add_argument(
|
|
42
|
+
"--precision", default=DEFAULT_PRECISION, choices=sorted(REPOS))
|
|
43
|
+
|
|
44
|
+
for sp in (d,):
|
|
45
|
+
sp.add_argument("--precision", default=DEFAULT_PRECISION, choices=sorted(REPOS))
|
|
46
|
+
sp.add_argument("--threads", type=int, default=0, help="CPU threads (default 4)")
|
|
47
|
+
sp.add_argument("--backend", default="cpu", choices=["cpu", "metal"],
|
|
48
|
+
help="metal is experimental and may return all-zero logits in some builds")
|
|
49
|
+
sp.add_argument("--quiet", action="store_true", help="suppress download progress")
|
|
50
|
+
|
|
51
|
+
args = p.parse_args(argv)
|
|
52
|
+
if not args.cmd:
|
|
53
|
+
p.print_help()
|
|
54
|
+
return 2
|
|
55
|
+
|
|
56
|
+
if args.cmd == "info":
|
|
57
|
+
d_ = ensure_model(args.precision, quiet=True)
|
|
58
|
+
print(json.dumps({"cache": d_, "manifest": json.load(open(os.path.join(d_, "manifest.json")))},
|
|
59
|
+
indent=2, ensure_ascii=False))
|
|
60
|
+
return 0
|
|
61
|
+
if args.cmd == "download":
|
|
62
|
+
print(ensure_model(args.precision))
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
state = _load_arg(args.state, "state")
|
|
66
|
+
questions = _load_arg(args.questions, "questions")
|
|
67
|
+
|
|
68
|
+
from .runtime import LayaMNN
|
|
69
|
+
model_dir = ensure_model(args.precision, quiet=args.quiet)
|
|
70
|
+
runtime = LayaMNN(model_dir, threads=args.threads, backend=args.backend)
|
|
71
|
+
result = runtime.system_one(state, questions)
|
|
72
|
+
json.dump(result, sys.stdout, indent=2, ensure_ascii=False)
|
|
73
|
+
sys.stdout.write("\n")
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
if __name__ == "__main__":
|
|
78
|
+
sys.exit(main())
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Fetch converted Laya weights from ModelScope (fast in CN) or Hugging Face."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.request
|
|
8
|
+
|
|
9
|
+
DEFAULT_PRECISION = "fp16"
|
|
10
|
+
|
|
11
|
+
# (registry, repo template) tried in order; ModelScope first because it is
|
|
12
|
+
# reliably fast from mainland China while huggingface.co is often throttled.
|
|
13
|
+
SOURCES = [
|
|
14
|
+
("modelscope", "https://modelscope.cn/models/{repo}/resolve/master/{file}"),
|
|
15
|
+
("hf", "{endpoint}/{repo}/resolve/main/{file}"),
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
REPOS = {
|
|
19
|
+
"fp16": {"hf": "yunfengwang/laya-MNN-fp16", "modelscope": "yunfeng/laya-MNN-fp16"},
|
|
20
|
+
"int8": {"hf": "yunfengwang/laya-MNN-int8", "modelscope": "yunfeng/laya-MNN-int8"},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cache_dir(precision: str = DEFAULT_PRECISION) -> str:
|
|
25
|
+
root = os.environ.get("LAYA_MNN_CACHE") or os.path.join(
|
|
26
|
+
os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache")), "laya-mnn")
|
|
27
|
+
return os.path.join(root, precision)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _url(source: str, repo: str, file: str) -> str:
|
|
31
|
+
endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
|
|
32
|
+
return SOURCES[[s[0] for s in SOURCES].index(source)][1].format(repo=repo, file=file, endpoint=endpoint)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _stream(url: str, dest: str):
|
|
36
|
+
"""Download with resume; returns without error if the server ignores Range."""
|
|
37
|
+
pos = os.path.getsize(dest) if os.path.exists(dest) else 0
|
|
38
|
+
req = urllib.request.Request(url, headers={"User-Agent": "laya-mnn"})
|
|
39
|
+
if pos:
|
|
40
|
+
req.add_header("Range", "bytes=%d-" % pos)
|
|
41
|
+
try:
|
|
42
|
+
with urllib.request.urlopen(req, timeout=60) as r:
|
|
43
|
+
total = int(r.headers.get("Content-Length", 0)) + (pos if r.status == 206 else 0)
|
|
44
|
+
if r.status != 206:
|
|
45
|
+
pos = 0
|
|
46
|
+
mode = "ab" if pos else "wb"
|
|
47
|
+
done = pos
|
|
48
|
+
with open(dest, mode) as f:
|
|
49
|
+
last = 0.0
|
|
50
|
+
while True:
|
|
51
|
+
chunk = r.read(1 << 20)
|
|
52
|
+
if not chunk:
|
|
53
|
+
break
|
|
54
|
+
f.write(chunk)
|
|
55
|
+
done += len(chunk)
|
|
56
|
+
if total and done - last > 32 << 20:
|
|
57
|
+
last = done
|
|
58
|
+
print(" %.0f/%.0f MB (%.0f%%)" % (done / 1e6, total / 1e6, 100.0 * done / total),
|
|
59
|
+
file=sys.stderr, flush=True)
|
|
60
|
+
except urllib.error.HTTPError as e:
|
|
61
|
+
if e.code == 416 and pos:
|
|
62
|
+
return
|
|
63
|
+
raise
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def fetch_file(precision: str, file: str, dest_dir: str, quiet: bool = False) -> str:
|
|
67
|
+
os.makedirs(dest_dir, exist_ok=True)
|
|
68
|
+
dest = os.path.join(dest_dir, file)
|
|
69
|
+
errors = []
|
|
70
|
+
for source, _ in SOURCES:
|
|
71
|
+
repo = REPOS[precision][source]
|
|
72
|
+
url = _url(source, repo, file)
|
|
73
|
+
try:
|
|
74
|
+
if not quiet:
|
|
75
|
+
print("[laya-mnn] %s <- %s" % (file, url), file=sys.stderr, flush=True)
|
|
76
|
+
_stream(url, dest)
|
|
77
|
+
return dest
|
|
78
|
+
except Exception as e:
|
|
79
|
+
errors.append("%s: %s" % (source, e))
|
|
80
|
+
raise RuntimeError("could not download %s\n %s" % (file, "\n ".join(errors)))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _sha256(path: str) -> str:
|
|
84
|
+
h = hashlib.sha256()
|
|
85
|
+
with open(path, "rb") as f:
|
|
86
|
+
for chunk in iter(lambda: f.read(1 << 22), b""):
|
|
87
|
+
h.update(chunk)
|
|
88
|
+
return h.hexdigest()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def ensure_model(precision: str = DEFAULT_PRECISION, quiet: bool = False) -> str:
|
|
92
|
+
"""Return a local dir containing manifest.json, tokenizer.json and the .mnn weights."""
|
|
93
|
+
if precision not in REPOS:
|
|
94
|
+
raise ValueError("unknown precision %r (expected one of %s)" % (precision, ", ".join(REPOS)))
|
|
95
|
+
d = cache_dir(precision)
|
|
96
|
+
manifest_path = os.path.join(d, "manifest.json")
|
|
97
|
+
if not os.path.exists(manifest_path):
|
|
98
|
+
fetch_file(precision, "manifest.json", d, quiet)
|
|
99
|
+
with open(manifest_path) as f:
|
|
100
|
+
manifest = json.load(f)
|
|
101
|
+
|
|
102
|
+
tok = os.path.join(d, "tokenizer.json")
|
|
103
|
+
if not os.path.exists(tok):
|
|
104
|
+
fetch_file(precision, "tokenizer.json", d, quiet)
|
|
105
|
+
|
|
106
|
+
weights = os.path.join(d, manifest["model_file"])
|
|
107
|
+
want = manifest.get("sha256")
|
|
108
|
+
if os.path.exists(weights) and want:
|
|
109
|
+
got = _sha256(weights)
|
|
110
|
+
if got != want:
|
|
111
|
+
if not quiet:
|
|
112
|
+
print("[laya-mnn] checksum mismatch, re-downloading", file=sys.stderr)
|
|
113
|
+
os.remove(weights)
|
|
114
|
+
if not os.path.exists(weights):
|
|
115
|
+
fetch_file(precision, manifest["model_file"], d, quiet)
|
|
116
|
+
if want and _sha256(weights) != want:
|
|
117
|
+
raise RuntimeError("checksum mismatch after download for %s" % weights)
|
|
118
|
+
return d
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Tokenizer, prompt construction and MNN inference for the Laya decision model.
|
|
2
|
+
|
|
3
|
+
The prompt format and confidence/temperature handling are ported from
|
|
4
|
+
NandhaKishorM/laya (Apache-2.0) so that this runtime matches the reference
|
|
5
|
+
implementation bit for bit; see NOTICE.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
from typing import Any, Dict, List, Optional, Union
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
QTYPES = {"choice": 0, "score": 1, "noul": 2}
|
|
14
|
+
QTYPE_NAMES = {v: k for k, v in QTYPES.items()}
|
|
15
|
+
|
|
16
|
+
CLS_ID, SEP_ID, PAD_ID, MASK_ID = 50281, 50282, 50283, 50284
|
|
17
|
+
|
|
18
|
+
TEMP_MIN, TEMP_MAX = 0.5, 5.0
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render_criterion(value: Any) -> str:
|
|
22
|
+
if isinstance(value, str):
|
|
23
|
+
return value
|
|
24
|
+
return json.dumps(value, ensure_ascii=False, separators=(", ", ": "), default=str)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def render_options(q: Dict) -> List[str]:
|
|
28
|
+
t, crit = q["t"], q.get("crit")
|
|
29
|
+
if t == "choice":
|
|
30
|
+
return [k if v is None or v == "" else "%s: %s" % (k, render_criterion(v)) for k, v in crit.items()]
|
|
31
|
+
if t == "score":
|
|
32
|
+
return ["level %d: %s" % (i, render_criterion(c)) for i, c in enumerate(crit)]
|
|
33
|
+
crit = crit or {}
|
|
34
|
+
false_crit, true_crit = crit.get("false"), crit.get("true")
|
|
35
|
+
return [
|
|
36
|
+
"false: " + (render_criterion(false_crit) if false_crit not in (None, "") else "no, the statement does not hold"),
|
|
37
|
+
"true: " + (render_criterion(true_crit) if true_crit not in (None, "") else "yes, the statement holds"),
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _encode(tok, text: str) -> List[int]:
|
|
42
|
+
return tok.encode(text, add_special_tokens=False).ids
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_sequence(tok, state, q, max_len=512, head_max_len=192):
|
|
46
|
+
"""[CLS] <type> question: <instructions> [SEP] [MASK] opt0 [MASK] opt1 ... [SEP] state [SEP]"""
|
|
47
|
+
opts = render_options(q)
|
|
48
|
+
order = list(range(len(opts)))
|
|
49
|
+
ins = str(q["ins"]).replace("[MASK]", " ")
|
|
50
|
+
head_ids = _encode(tok, "%s question: %s" % (q["t"], ins))
|
|
51
|
+
opt_ids = []
|
|
52
|
+
for i in order:
|
|
53
|
+
opt_ids.append([MASK_ID] + _encode(tok, " " + opts[i].replace("[MASK]", " "))[:48])
|
|
54
|
+
opt_budget = head_max_len - sum(len(o) for o in opt_ids)
|
|
55
|
+
if opt_budget < 16:
|
|
56
|
+
per = max(4, (head_max_len - 16) // max(1, len(opt_ids)))
|
|
57
|
+
opt_ids = [o[:per] for o in opt_ids]
|
|
58
|
+
opt_budget = head_max_len - sum(len(o) for o in opt_ids)
|
|
59
|
+
head_ids = head_ids[: max(8, opt_budget)]
|
|
60
|
+
ids = [CLS_ID] + head_ids + [SEP_ID]
|
|
61
|
+
markers = []
|
|
62
|
+
for o in opt_ids:
|
|
63
|
+
markers.append(len(ids))
|
|
64
|
+
ids.extend(o)
|
|
65
|
+
ids.append(SEP_ID)
|
|
66
|
+
room = max(0, max_len - len(ids) - 1)
|
|
67
|
+
st = _encode(tok, state.replace("[MASK]", " "))
|
|
68
|
+
st = st[:room]
|
|
69
|
+
ids = ids + st + [SEP_ID]
|
|
70
|
+
return ids[:max_len], [m for m in markers if m < max_len]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def confidence_from_probs(p: np.ndarray, k: int) -> float:
|
|
74
|
+
if k < 2:
|
|
75
|
+
return 1.0
|
|
76
|
+
p = p[:k]
|
|
77
|
+
ent = -(p * np.log(np.clip(p, 1e-12, 1.0))).sum()
|
|
78
|
+
return float(np.clip(1.0 - ent / math.log(k), 0.0, 1.0))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def temp_bucket(qtype: int, k: int) -> str:
|
|
82
|
+
size = "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11+"
|
|
83
|
+
return "%s:%s" % (QTYPE_NAMES[int(qtype)], size)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def clamp_temperature(t, lo: float = TEMP_MIN, hi: float = TEMP_MAX) -> float:
|
|
87
|
+
try:
|
|
88
|
+
t = float(t)
|
|
89
|
+
except (TypeError, ValueError):
|
|
90
|
+
return 1.0
|
|
91
|
+
if t != t or t in (float("inf"), float("-inf")):
|
|
92
|
+
return 1.0
|
|
93
|
+
return min(hi, max(lo, t))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _to_internal(qdef: Dict) -> Dict:
|
|
97
|
+
t = qdef["type"]
|
|
98
|
+
crit = qdef.get("criteria")
|
|
99
|
+
if t == "choice" and isinstance(crit, list):
|
|
100
|
+
crit = {c: None for c in crit}
|
|
101
|
+
ins = qdef["instructions"]
|
|
102
|
+
if not isinstance(ins, str):
|
|
103
|
+
ins = json.dumps(ins)
|
|
104
|
+
return {"t": t, "ins": ins, "crit": crit}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class LayaMNN:
|
|
108
|
+
"""Runs a converted Laya checkpoint on MNN."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, model_dir: str, threads: int = 0, backend: str = "cpu"):
|
|
111
|
+
import MNN
|
|
112
|
+
import MNN.expr as F
|
|
113
|
+
from tokenizers import Tokenizer
|
|
114
|
+
|
|
115
|
+
self._F = F
|
|
116
|
+
with open("%s/manifest.json" % model_dir) as f:
|
|
117
|
+
self.manifest = json.load(f)
|
|
118
|
+
self.cfg = self.manifest["config"]
|
|
119
|
+
self.tok = Tokenizer.from_file("%s/tokenizer.json" % model_dir)
|
|
120
|
+
self.max_len = self.cfg.get("max_len", 512)
|
|
121
|
+
self.head_max_len = self.cfg.get("head_max_len", 192)
|
|
122
|
+
self.max_options = self.manifest.get("max_options", 16)
|
|
123
|
+
self.temperature = [clamp_temperature(t) for t in self.cfg.get("temperature", [1.0, 1.0, 1.0])]
|
|
124
|
+
self.temperature_by_options = {k: clamp_temperature(v) for k, v in self.cfg.get("temperature_by_options", {}).items()}
|
|
125
|
+
|
|
126
|
+
kw = {"backend": F.Backend.METAL if backend == "metal" else F.Backend.CPU,
|
|
127
|
+
"thread_num": threads or 4}
|
|
128
|
+
if backend == "metal":
|
|
129
|
+
kw["precision_mode"] = F.PrecisionMode.Low
|
|
130
|
+
names = ["input_ids", "attention_mask", "marker_pos", "marker_mask", "qtype"]
|
|
131
|
+
self.model = MNN.nn.load_module_from_file(
|
|
132
|
+
"%s/%s" % (model_dir, self.manifest["model_file"]), names, ["logits", "act_logits"], **kw)
|
|
133
|
+
self._MNN = MNN
|
|
134
|
+
|
|
135
|
+
def _infer(self, items):
|
|
136
|
+
"""items: list of {ids, markers, qtype} -> list of (logits [k], act [2])
|
|
137
|
+
|
|
138
|
+
Questions run one at a time: the graph is exported for batch 1, and feeding
|
|
139
|
+
MNN a wider batch makes its shape inference mishandle the padding mask.
|
|
140
|
+
Marker tensors are padded to the graph's fixed width; the extra entries stay
|
|
141
|
+
masked and are dropped here.
|
|
142
|
+
"""
|
|
143
|
+
F = self._F
|
|
144
|
+
width = self.max_options
|
|
145
|
+
out_list = []
|
|
146
|
+
for it in items:
|
|
147
|
+
k = len(it["markers"])
|
|
148
|
+
if k > width:
|
|
149
|
+
raise ValueError("question has %d options but this model was converted for at most %d; "
|
|
150
|
+
"re-convert with a larger --max-options or split the option set"
|
|
151
|
+
% (k, width))
|
|
152
|
+
seq = it["ids"][: self.max_len]
|
|
153
|
+
pad = self.max_len - len(seq)
|
|
154
|
+
ids = np.array([list(seq) + [PAD_ID] * pad], dtype=np.int32)
|
|
155
|
+
att = np.array([[1] * len(seq) + [0] * pad], dtype=np.int32)
|
|
156
|
+
mpos = np.array([it["markers"][:k] + [0] * (width - k)], dtype=np.int32)
|
|
157
|
+
mmask = np.array([[1] * k + [0] * (width - k)], dtype=np.int32)
|
|
158
|
+
qtype = np.array([it["qtype"]], dtype=np.int32)
|
|
159
|
+
inps = [F.const(x, list(x.shape), F.NCHW, F.int) for x in (ids, att, mpos, mmask, qtype)]
|
|
160
|
+
out = self.model.forward(inps)
|
|
161
|
+
act = np.array(out[1].read(), dtype=np.float32).reshape(2)
|
|
162
|
+
act = np.exp(act - act.max())
|
|
163
|
+
out_list.append((np.array(out[0].read(), dtype=np.float32).reshape(width)[:k],
|
|
164
|
+
act / act.sum()))
|
|
165
|
+
return out_list
|
|
166
|
+
|
|
167
|
+
def system_one(self, state, questions: Dict[str, Dict[str, Any]]) -> Dict[str, Any]:
|
|
168
|
+
state = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
|
|
169
|
+
ids = list(questions.keys())
|
|
170
|
+
items = []
|
|
171
|
+
for qid in ids:
|
|
172
|
+
q = _to_internal(questions[qid])
|
|
173
|
+
seq, markers = build_sequence(self.tok, state, q, self.max_len, self.head_max_len)
|
|
174
|
+
if len(markers) != len(render_options(q)):
|
|
175
|
+
raise ValueError("question %r options exceed head_max_len=%d" % (qid, self.head_max_len))
|
|
176
|
+
items.append({"ids": seq, "markers": markers, "qtype": QTYPES[q["t"]]})
|
|
177
|
+
|
|
178
|
+
inferred = self._infer(items)
|
|
179
|
+
answers = {}
|
|
180
|
+
for r, qid in enumerate(ids):
|
|
181
|
+
q = _to_internal(questions[qid])
|
|
182
|
+
logit_row, act_row = inferred[r]
|
|
183
|
+
k = len(items[r]["markers"])
|
|
184
|
+
qt = QTYPES[q["t"]]
|
|
185
|
+
t_scale = self.temperature_by_options.get(temp_bucket(qt, k), self.temperature[qt])
|
|
186
|
+
z = logit_row / t_scale
|
|
187
|
+
p = np.exp(z - z.max())
|
|
188
|
+
p = p / p.sum()
|
|
189
|
+
conf = round(confidence_from_probs(p, k), 4)
|
|
190
|
+
ext = {"act_probability": round(float(act_row[0]), 4)}
|
|
191
|
+
if q["t"] == "choice":
|
|
192
|
+
keys = list(q["crit"].keys())
|
|
193
|
+
answers[qid] = {"type": "choice", "choice": keys[int(p.argmax())],
|
|
194
|
+
"probabilities": {kk: round(float(v), 4) for kk, v in zip(keys, p)},
|
|
195
|
+
"confidence": conf, "action": ext}
|
|
196
|
+
elif q["t"] == "score":
|
|
197
|
+
answers[qid] = {"type": "score", "score": round(float((np.arange(k) * p).sum()), 4),
|
|
198
|
+
"legend": {str(i): c for i, c in enumerate(q["crit"])},
|
|
199
|
+
"probabilities": {str(i): round(float(v), 4) for i, v in enumerate(p)},
|
|
200
|
+
"confidence": conf, "action": ext}
|
|
201
|
+
else:
|
|
202
|
+
answers[qid] = {"type": "noul", "noul": round(float(p[1]), 4),
|
|
203
|
+
"confidence": round(max(float(p[1]), 1.0 - float(p[1])), 4), "action": ext}
|
|
204
|
+
return {"model": "laya-mnn", "answers": answers}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: laya-mnn
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run the Laya System 1 decision model locally on MNN (CPU, no PyTorch, no API)
|
|
5
|
+
Author: yunfengwang
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://huggingface.co/yunfengwang/laya-MNN-fp16
|
|
8
|
+
Project-URL: Source, https://huggingface.co/yunfengwang/laya-MNN-fp16
|
|
9
|
+
Keywords: mnn,onnx,decision-model,system-one,laya,calibration,edge-inference
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Operating System :: MacOS
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
License-File: NOTICE
|
|
20
|
+
Requires-Dist: mnn>=3.6.1
|
|
21
|
+
Requires-Dist: tokenizers>=0.15
|
|
22
|
+
Requires-Dist: numpy>=1.21
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# laya-mnn
|
|
26
|
+
|
|
27
|
+
Run the [Laya](https://huggingface.co/convaiinnovations/laya) System 1 decision model **locally on MNN** — no PyTorch, no GPU, no API key.
|
|
28
|
+
|
|
29
|
+
Laya takes a **state** (email, ticket, JSON) plus **typed questions** and returns typed answers with calibrated probabilities in one forward pass. It never generates text, so there is nothing to parse and nothing to hallucinate. This package runs a converted Laya checkpoint on Alibaba's [MNN](https://github.com/alibaba/MNN) runtime.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
uvx laya-mnn decide \
|
|
33
|
+
--state "Hi, we were billed twice for March. Please refund the duplicate or we will cancel our plan." \
|
|
34
|
+
--questions '{"department":{"type":"choice","instructions":"Which department should handle this?","criteria":{"billing":"invoices, payments, refunds","technical":"bugs, outages","other":"everything else"}},
|
|
35
|
+
"churn_risk":{"type":"noul","instructions":"Does the user threaten to cancel?"}}'
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{
|
|
40
|
+
"model": "laya-mnn",
|
|
41
|
+
"answers": {
|
|
42
|
+
"department": {
|
|
43
|
+
"type": "choice", "choice": "billing",
|
|
44
|
+
"probabilities": { "billing": 0.9631, "technical": 0.0165, "other": 0.0204 },
|
|
45
|
+
"confidence": 0.8067, "action": { "act_probability": 0.9977 }
|
|
46
|
+
},
|
|
47
|
+
"churn_risk": { "type": "noul", "noul": 0.9476, "confidence": 0.9476, "action": { "act_probability": 0.9977 } }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Weights download automatically on first use (about 850 MB for `fp16`).
|
|
53
|
+
|
|
54
|
+
## Question types
|
|
55
|
+
|
|
56
|
+
| type | answer | use for |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `choice` | one of the `criteria` keys, plus a probability per option | routing, intent, classification |
|
|
59
|
+
| `score` | expected value over ordered `criteria` levels (0-based) | severity, urgency, sentiment strength |
|
|
60
|
+
| `noul` | `P(true)` | yes/no judgements |
|
|
61
|
+
|
|
62
|
+
`criteria` is defined **at request time** — new schemas do not need retraining. Up to 64 options per question with the shipped checkpoints.
|
|
63
|
+
|
|
64
|
+
## CLI
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
laya-mnn decide --state S --questions Q [--precision fp16|int8] [--threads N] [--quiet]
|
|
68
|
+
laya-mnn download [--precision ...] # pre-fetch weights
|
|
69
|
+
laya-mnn info [--precision ...] # cache dir + manifest
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`--state` accepts literal text, inline JSON, or `@path`. `--questions` accepts inline JSON or `@path`.
|
|
73
|
+
|
|
74
|
+
## Python
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from laya_mnn import LayaMNN, ensure_model
|
|
78
|
+
|
|
79
|
+
model = LayaMNN(ensure_model("fp16"), threads=4)
|
|
80
|
+
result = model.system_one(
|
|
81
|
+
{"subject": "Duplicate charge", "body": "We were billed twice..."},
|
|
82
|
+
{"department": {"type": "choice", "instructions": "Which department?", "criteria": ["billing", "technical", "other"]}},
|
|
83
|
+
)
|
|
84
|
+
print(result["answers"]["department"]["choice"], result["answers"]["department"]["probabilities"])
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Checkpoints
|
|
88
|
+
|
|
89
|
+
| precision | size | notes |
|
|
90
|
+
|---|---|---|
|
|
91
|
+
| `fp16` | 846 MB | weights stored in half precision; probability deltas vs. the original PyTorch model are below 1e-3 |
|
|
92
|
+
| `int8` | 581 MB | weight-only 8-bit quantization; larger deltas, check it against your own eval |
|
|
93
|
+
|
|
94
|
+
Both are conversions of `convaiinnovations/laya` (English, ModernBERT-large backbone, 421M parameters). The model was exported to ONNX (`opset 17`, eager attention, static 512-token sequence) and converted with the MNN converter 3.6.1.
|
|
95
|
+
|
|
96
|
+
Hosted on [Hugging Face](https://huggingface.co/yunfengwang/laya-MNN-fp16) and [ModelScope](https://modelscope.cn/models/yunfeng/laya-MNN-fp16); `modelscope` is tried first, then Hugging Face (override with `HF_ENDPOINT`).
|
|
97
|
+
Set `LAYA_MNN_CACHE` to change the cache directory (default `~/.cache/laya-mnn`).
|
|
98
|
+
|
|
99
|
+
## Notes and limits
|
|
100
|
+
|
|
101
|
+
- **CPU is the supported backend.** The MNN Metal backend was measured to return all-zero logits for this graph in some builds of the 3.6.1 wheel; `--backend metal` is exposed but not recommended.
|
|
102
|
+
- A 512-token forward pass costs roughly 1.3 s on an Apple Silicon CPU. Shorter states are cheaper — the graph is exported at a fixed 512 tokens, so the CLI pads and masks.
|
|
103
|
+
- Max 64 options per question, 512 tokens of context, English only. The multilingual checkpoint (`mmBERT-base`) is not converted here.
|
|
104
|
+
- Percentile-latency and calibration in the upstream model card are for the original PyTorch model; quantized results will differ slightly.
|
|
105
|
+
|
|
106
|
+
## License and attribution
|
|
107
|
+
|
|
108
|
+
Apache-2.0. The model, its prompt format and the calibration scheme come from [NandhaKishorM/laya](https://github.com/NandhaKishorM/laya) by Convai Innovations (Apache-2.0); this package is an independent MNN port and is not affiliated with or endorsed by them. See `NOTICE`.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
NOTICE
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
src/laya_mnn/__init__.py
|
|
6
|
+
src/laya_mnn/cli.py
|
|
7
|
+
src/laya_mnn/download.py
|
|
8
|
+
src/laya_mnn/runtime.py
|
|
9
|
+
src/laya_mnn.egg-info/PKG-INFO
|
|
10
|
+
src/laya_mnn.egg-info/SOURCES.txt
|
|
11
|
+
src/laya_mnn.egg-info/dependency_links.txt
|
|
12
|
+
src/laya_mnn.egg-info/entry_points.txt
|
|
13
|
+
src/laya_mnn.egg-info/requires.txt
|
|
14
|
+
src/laya_mnn.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
laya_mnn
|