nbxgrammar 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.
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to nbxgrammar are documented in this file. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [0.1.0] - unreleased
8
+
9
+ ### Added
10
+ - **The grammar engine**: a JSON Schema subset and grammar descriptions (literals, schemas, sequences, choices,
11
+ repetitions, free text up to a terminator or a special token, token ids) compiled into a matcher; per-step token
12
+ masks over a tokenizer's byte vocabulary, string-safe and free-text tokens cached once per vocabulary; any constraint
13
+ it cannot enforce refused by name.
14
+ - **The Python package**: `Grammar.json_schema`, `Grammar.description`, `Vocab`, `Matcher.mask / advance / accepting`,
15
+ through the library's C ABI with `ctypes`; one wheel per platform (`py3-none-<platform>`) for Linux x86_64 and
16
+ aarch64, macOS arm64 and x86_64, Windows x86_64.
@@ -0,0 +1,7 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "nbxgrammar"
7
+ version = "0.1.0"
@@ -0,0 +1,20 @@
1
+ [package]
2
+ name = "nbxgrammar"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "NeuroBrix's grammar engine for constrained decoding: JSON Schema and tool-call envelopes to per-step token masks (std only)"
6
+ license = "Apache-2.0"
7
+ publish = false
8
+ repository = "https://github.com/NeuroBrix/nbxgrammar"
9
+ homepage = "https://neurobrix.org"
10
+
11
+ [lib]
12
+ crate-type = ["cdylib", "rlib"]
13
+
14
+ [dependencies]
15
+
16
+ [profile.release]
17
+ opt-level = 3
18
+ lto = true
19
+ codegen-units = 1
20
+ panic = "abort"
@@ -0,0 +1,189 @@
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
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to the Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by the Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding any notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2025 Neural Networks Holding LTD
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188
+ See the License for the specific language governing permissions and
189
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ include Cargo.toml Cargo.lock rust-toolchain.toml LICENSE NOTICE README.md CHANGELOG.md
2
+ recursive-include src *.rs
3
+ recursive-include tests *.rs
4
+ recursive-include examples *.rs
5
+ recursive-include tests_py *.py
6
+ prune target
@@ -0,0 +1,8 @@
1
+ nbxgrammar
2
+ Copyright 2025–2026 Hocine Benkelaya
3
+ Owner of the NeuroBrix project (the Owner under the Contributor Assignment Agreement): Hocine Benkelaya
4
+
5
+ Supported and funded by Neural Network Holding Ltd (https://neuralnetworkholding.com).
6
+ Commercial distribution by WizWorks OÜ (https://wizworks.io).
7
+
8
+ This product is released under the Apache License 2.0 (LICENSE). It carries no third-party code: the crate uses the Rust standard library only.
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.4
2
+ Name: nbxgrammar
3
+ Version: 0.1.0
4
+ Summary: NeuroBrix's grammar engine for constrained decoding: JSON Schema and tool-call envelopes to per-step token masks
5
+ Author-email: The NeuroBrix project <contact@neurobrix.org>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://neurobrix.org
8
+ Project-URL: Source, https://github.com/NeuroBrix/nbxgrammar
9
+ Project-URL: Documentation, https://docs.neurobrix.org
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Rust
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ License-File: NOTICE
20
+ Requires-Dist: numpy>=1.22
21
+ Dynamic: license-file
22
+
23
+ # nbxgrammar
24
+
25
+ NeuroBrix's grammar engine for constrained decoding. It compiles a JSON Schema, or a description of a tool-call
26
+ format, into a matcher that gives at every decoding step the mask of the tokens a model may write next — so the output
27
+ can only be what the schema or the format allows. It is the engine behind `response_format: json_schema` and forced
28
+ `tool_choice` in [NeuroBrix](https://github.com/NeuroBrix/neurobrix)'s OpenAI-compatible server.
29
+
30
+ Written in Rust with the standard library only, loaded from Python with `ctypes` (no binding library). One wheel per
31
+ platform serves every Python 3.
32
+
33
+ ```bash
34
+ pip install nbxgrammar
35
+ ```
36
+
37
+ ```python
38
+ import json, numpy as np, nbxgrammar as G
39
+
40
+ grammar = G.Grammar.json_schema(json.dumps({"type": "object", "properties": {"city": {"type": "string"}},
41
+ "required": ["city"]}))
42
+ vocab = G.Vocab(token_bytes, eos_ids) # each token id's bytes (None for a special token), the end-of-sequence ids
43
+ matcher = G.Matcher(grammar)
44
+ mask = matcher.mask(vocab) # int32 words, ceil(vocab / 32): bit v % 32 of word v // 32 = token v allowed
45
+ matcher.advance(vocab, token_id) # the token the sampler chose
46
+ ```
47
+
48
+ ## What it enforces
49
+
50
+ - **JSON Schema, a subset**: objects (`properties`, `required`; no other property is generated), arrays (`items`,
51
+ `minItems`, `maxItems`), strings, numbers, integers, booleans, null, `enum`, `const`, `anyOf` whose alternatives start
52
+ differently, `$ref` into `$defs`. Any other constraining keyword is refused by name (a `ValueError`), never ignored;
53
+ annotations (`title`, `description`, `default`, `examples`, ...) are read as annotations.
54
+ - **Descriptions**: literals, schemas, sequences, choices by a literal prefix, repetitions with a separator, free text up
55
+ to a terminator (`until`, optionally ended by a special token), and exact token ids — what a chat template's tool-call
56
+ format is made of.
57
+ - **Whitespace**: at most one space where JSON allows whitespace inside a value, never a newline, and none around a
58
+ JSON root.
59
+
60
+ Measured on Qwen3's vocabulary (151 936 tokens, Apple M4 Pro): a mask in about 15 µs median inside JSON, 73 µs in free
61
+ text.
62
+
63
+ ## Building from source
64
+
65
+ The crate pins its toolchain (`rust-toolchain.toml`). `pip install .` builds the library with `cargo` and places it in
66
+ the package; `cargo test --release` runs the oracle tests (every mask against a brute force over the vocabulary, every
67
+ completed output against an independent validator).
68
+
69
+ ## License
70
+
71
+ Apache License 2.0 ([LICENSE](LICENSE)); see [NOTICE](NOTICE). Contributions are made under the
72
+ [NeuroBrix Contributor Assignment Agreement](https://github.com/NeuroBrix/neurobrix/blob/main/docs/legal/contributor-assignment-agreement.md)
73
+ ([CONTRIBUTING.md](CONTRIBUTING.md)).
74
+
75
+ Project: [neurobrix.org](https://neurobrix.org) · documentation: [docs.neurobrix.org](https://docs.neurobrix.org) ·
76
+ contact@neurobrix.org
@@ -0,0 +1,54 @@
1
+ # nbxgrammar
2
+
3
+ NeuroBrix's grammar engine for constrained decoding. It compiles a JSON Schema, or a description of a tool-call
4
+ format, into a matcher that gives at every decoding step the mask of the tokens a model may write next — so the output
5
+ can only be what the schema or the format allows. It is the engine behind `response_format: json_schema` and forced
6
+ `tool_choice` in [NeuroBrix](https://github.com/NeuroBrix/neurobrix)'s OpenAI-compatible server.
7
+
8
+ Written in Rust with the standard library only, loaded from Python with `ctypes` (no binding library). One wheel per
9
+ platform serves every Python 3.
10
+
11
+ ```bash
12
+ pip install nbxgrammar
13
+ ```
14
+
15
+ ```python
16
+ import json, numpy as np, nbxgrammar as G
17
+
18
+ grammar = G.Grammar.json_schema(json.dumps({"type": "object", "properties": {"city": {"type": "string"}},
19
+ "required": ["city"]}))
20
+ vocab = G.Vocab(token_bytes, eos_ids) # each token id's bytes (None for a special token), the end-of-sequence ids
21
+ matcher = G.Matcher(grammar)
22
+ mask = matcher.mask(vocab) # int32 words, ceil(vocab / 32): bit v % 32 of word v // 32 = token v allowed
23
+ matcher.advance(vocab, token_id) # the token the sampler chose
24
+ ```
25
+
26
+ ## What it enforces
27
+
28
+ - **JSON Schema, a subset**: objects (`properties`, `required`; no other property is generated), arrays (`items`,
29
+ `minItems`, `maxItems`), strings, numbers, integers, booleans, null, `enum`, `const`, `anyOf` whose alternatives start
30
+ differently, `$ref` into `$defs`. Any other constraining keyword is refused by name (a `ValueError`), never ignored;
31
+ annotations (`title`, `description`, `default`, `examples`, ...) are read as annotations.
32
+ - **Descriptions**: literals, schemas, sequences, choices by a literal prefix, repetitions with a separator, free text up
33
+ to a terminator (`until`, optionally ended by a special token), and exact token ids — what a chat template's tool-call
34
+ format is made of.
35
+ - **Whitespace**: at most one space where JSON allows whitespace inside a value, never a newline, and none around a
36
+ JSON root.
37
+
38
+ Measured on Qwen3's vocabulary (151 936 tokens, Apple M4 Pro): a mask in about 15 µs median inside JSON, 73 µs in free
39
+ text.
40
+
41
+ ## Building from source
42
+
43
+ The crate pins its toolchain (`rust-toolchain.toml`). `pip install .` builds the library with `cargo` and places it in
44
+ the package; `cargo test --release` runs the oracle tests (every mask against a brute force over the vocabulary, every
45
+ completed output against an independent validator).
46
+
47
+ ## License
48
+
49
+ Apache License 2.0 ([LICENSE](LICENSE)); see [NOTICE](NOTICE). Contributions are made under the
50
+ [NeuroBrix Contributor Assignment Agreement](https://github.com/NeuroBrix/neurobrix/blob/main/docs/legal/contributor-assignment-agreement.md)
51
+ ([CONTRIBUTING.md](CONTRIBUTING.md)).
52
+
53
+ Project: [neurobrix.org](https://neurobrix.org) · documentation: [docs.neurobrix.org](https://docs.neurobrix.org) ·
54
+ contact@neurobrix.org
@@ -0,0 +1,60 @@
1
+ //! Mask cost per step on a real vocabulary (the owner's gate: < 1 ms CPU on ~150 k tokens): random walks over the
2
+ //! oracle's schemas; median / p99 / max per step, and the schema compile time. Usage: bench <vocab file>
3
+ use nbxgrammar::{json::parse, matcher::Matcher, schema::compile, vocab::Vocab};
4
+ use std::time::Instant;
5
+
6
+ fn read_vocab(p: &str) -> Vocab {
7
+ let b = std::fs::read(p).unwrap();
8
+ let u = |i: &mut usize| { let v = u32::from_le_bytes(b[*i..*i + 4].try_into().unwrap()); *i += 4; v };
9
+ let mut i = 0;
10
+ let n = u(&mut i) as usize;
11
+ let mut toks = Vec::with_capacity(n);
12
+ for _ in 0..n {
13
+ let l = u(&mut i);
14
+ if l == u32::MAX { toks.push(None) } else { toks.push(Some(b[i..i + l as usize].to_vec())); i += l as usize; }
15
+ }
16
+ let ne = u(&mut i) as usize;
17
+ let eos = (0..ne).map(|_| u(&mut i)).collect();
18
+ Vocab::new(toks, eos)
19
+ }
20
+
21
+ const SCHEMAS: &[&str] = &[
22
+ r#"{"type":"object","properties":{"name":{"type":"string"},"n":{"type":"integer"},"ok":{"type":"boolean"}},"required":["name","n"]}"#,
23
+ r#"{"type":"array","items":{"enum":["alpha","beta",12,1,null]},"minItems":1,"maxItems":8}"#,
24
+ r#"{"type":"object","properties":{"tags":{"type":"array","items":{"type":"string"}},"x":{"type":["number","null"]},"o":{"type":"object","properties":{"a":{"const":true}},"required":["a"]}},"required":["tags"]}"#,
25
+ r#"{"type":"object","properties":{"location":{"type":"string"},"unit":{"enum":["celsius","fahrenheit"]},"days":{"type":"integer"}},"required":["location","unit"],"additionalProperties":false}"#,
26
+ ];
27
+
28
+ fn main() {
29
+ let path = std::env::args().nth(1).expect("vocab file");
30
+ let t0 = Instant::now();
31
+ let v = read_vocab(&path);
32
+ println!("vocabulary {} tokens, built (trie + string cache) in {:.0} ms", v.tokens.len(), t0.elapsed().as_secs_f64() * 1e3);
33
+ let mut rng = 0x2545F4914F6CDD1Du64;
34
+ let mut next = || { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; rng };
35
+ let mut times: Vec<f64> = Vec::new();
36
+ let mut compiles: Vec<f64> = Vec::new();
37
+ for src in SCHEMAS {
38
+ let t = Instant::now();
39
+ let schema = compile(&parse(src).unwrap()).unwrap();
40
+ compiles.push(t.elapsed().as_secs_f64() * 1e6);
41
+ for _ in 0..30 {
42
+ let mut m = Matcher::new(&schema);
43
+ let mut mask = vec![0u32; v.words()];
44
+ for _ in 0..80 {
45
+ let t = Instant::now();
46
+ v.mask(&m, &mut mask);
47
+ times.push(t.elapsed().as_secs_f64() * 1e6);
48
+ let allowed: Vec<u32> = (0..v.tokens.len() as u32).filter(|&t| mask[(t >> 5) as usize] >> (t & 31) & 1 == 1).collect();
49
+ let pick = allowed[(next() % allowed.len() as u64) as usize];
50
+ if v.eos.contains(&pick) { break; }
51
+ v.advance(&mut m, pick).unwrap();
52
+ }
53
+ }
54
+ }
55
+ times.sort_by(|a, b| a.partial_cmp(b).unwrap());
56
+ let q = |p: f64| times[((times.len() as f64 - 1.0) * p) as usize];
57
+ println!("mask per step over {} steps: median {:.1} us, p99 {:.1} us, max {:.1} us", times.len(), q(0.5), q(0.99), times[times.len() - 1]);
58
+ compiles.sort_by(|a, b| a.partial_cmp(b).unwrap());
59
+ println!("schema compile: median {:.1} us, max {:.1} us", compiles[compiles.len() / 2], compiles[compiles.len() - 1]);
60
+ }
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=69", "wheel>=0.42"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nbxgrammar"
7
+ version = "0.1.0"
8
+ description = "NeuroBrix's grammar engine for constrained decoding: JSON Schema and tool-call envelopes to per-step token masks"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = ["numpy>=1.22"]
14
+ authors = [{ name = "The NeuroBrix project", email = "contact@neurobrix.org" }]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Rust",
18
+ "Operating System :: MacOS",
19
+ "Operating System :: POSIX :: Linux",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://neurobrix.org"
26
+ Source = "https://github.com/NeuroBrix/nbxgrammar"
27
+ Documentation = "https://docs.neurobrix.org"
28
+
29
+ [tool.setuptools]
30
+ package-dir = { "" = "python" }
31
+ packages = ["nbxgrammar"]
@@ -0,0 +1,112 @@
1
+ """nbxgrammar: NeuroBrix's grammar engine (this repository's Rust crate, std only) through its C ABI, loaded with ctypes - no
2
+ binding library. The shared library lives beside this file (built by the package's build from the crate and placed
3
+ here). Masks are int32 words, ceil(vocab / 32), bit v % 32 of word v // 32 = token v allowed."""
4
+ from __future__ import annotations
5
+
6
+ import ctypes
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import Optional, Sequence
10
+
11
+ import numpy as np
12
+
13
+ _NAME = {"darwin": "libnbxgrammar.dylib", "win32": "nbxgrammar.dll"}.get(sys.platform, "libnbxgrammar.so")
14
+ _PATH = Path(__file__).with_name(_NAME)
15
+ if not _PATH.is_file():
16
+ raise ImportError(f"nbxgrammar: its library {_PATH} is not in the package (install a wheel: pip install nbxgrammar; from a checkout: pip install .)")
17
+ _lib = ctypes.CDLL(str(_PATH))
18
+ _P, _U32, _SZ = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_size_t
19
+ _lib.ng_vocab_new.restype = _P
20
+ _lib.ng_vocab_new.argtypes = [ctypes.c_char_p, ctypes.POINTER(_U32), _U32, ctypes.POINTER(_U32), _U32]
21
+ _lib.ng_vocab_free.argtypes = [_P]
22
+ _lib.ng_grammar_json_schema.restype = _P
23
+ _lib.ng_grammar_json_schema.argtypes = [ctypes.c_char_p, _SZ, ctypes.c_char_p, _SZ]
24
+ _lib.ng_grammar_description.restype = _P
25
+ _lib.ng_grammar_description.argtypes = [ctypes.c_char_p, _SZ, ctypes.c_char_p, _SZ]
26
+ _lib.ng_grammar_free.argtypes = [_P]
27
+ _lib.ng_matcher_new.restype = _P
28
+ _lib.ng_matcher_new.argtypes = [_P]
29
+ _lib.ng_matcher_free.argtypes = [_P]
30
+ _lib.ng_mask.restype = ctypes.c_int32
31
+ _lib.ng_mask.argtypes = [_P, _P, ctypes.POINTER(_U32), _SZ]
32
+ _lib.ng_advance.restype = ctypes.c_int32
33
+ _lib.ng_advance.argtypes = [_P, _P, _U32]
34
+ _lib.ng_accepting.restype = ctypes.c_int32
35
+ _lib.ng_accepting.argtypes = [_P]
36
+
37
+
38
+ class Vocab:
39
+ """A tokenizer's tokens as bytes (None: a token no grammar emits) and its end-of-sequence ids; built once."""
40
+
41
+ def __init__(self, token_bytes: Sequence[Optional[bytes]], eos: Sequence[int]):
42
+ lens = np.array([0xFFFFFFFF if b is None else len(b) for b in token_bytes], dtype=np.uint32)
43
+ data = b"".join(b for b in token_bytes if b is not None)
44
+ e = np.array(list(eos), dtype=np.uint32)
45
+ self.size = len(lens)
46
+ self.words = (self.size + 31) // 32
47
+ self._h = _lib.ng_vocab_new(data, lens.ctypes.data_as(ctypes.POINTER(_U32)), self.size,
48
+ e.ctypes.data_as(ctypes.POINTER(_U32)), len(e))
49
+ if not self._h:
50
+ raise ValueError(f"nbxgrammar: an end-of-sequence id of {list(eos)} lies past the {self.size} tokens")
51
+
52
+ def __del__(self):
53
+ if getattr(self, "_h", None):
54
+ _lib.ng_vocab_free(self._h)
55
+ self._h = None
56
+
57
+
58
+ class Grammar:
59
+ def __init__(self, handle):
60
+ self._h = handle
61
+
62
+ @classmethod
63
+ def json_schema(cls, text: str) -> "Grammar":
64
+ """A JSON schema compiled; ValueError naming the construct when it cannot be enforced."""
65
+ raw = text.encode("utf-8")
66
+ err = ctypes.create_string_buffer(512)
67
+ h = _lib.ng_grammar_json_schema(raw, len(raw), err, len(err))
68
+ if not h:
69
+ raise ValueError(err.value.decode("utf-8", "replace"))
70
+ return cls(h)
71
+
72
+ @classmethod
73
+ def description(cls, text: str) -> "Grammar":
74
+ """A grammar description (JSON: lit / schema / seq / choice / repeat / until / token) compiled; ValueError
75
+ naming what cannot be enforced."""
76
+ raw = text.encode("utf-8")
77
+ err = ctypes.create_string_buffer(512)
78
+ h = _lib.ng_grammar_description(raw, len(raw), err, len(err))
79
+ if not h:
80
+ raise ValueError(err.value.decode("utf-8", "replace"))
81
+ return cls(h)
82
+
83
+ def __del__(self):
84
+ if getattr(self, "_h", None):
85
+ _lib.ng_grammar_free(self._h)
86
+ self._h = None
87
+
88
+
89
+ class Matcher:
90
+ """One request's position in its grammar (keeps its grammar alive)."""
91
+
92
+ def __init__(self, grammar: Grammar):
93
+ self._grammar = grammar
94
+ self._h = _lib.ng_matcher_new(grammar._h)
95
+
96
+ def mask(self, vocab: Vocab) -> np.ndarray:
97
+ out = np.zeros(vocab.words, dtype=np.uint32)
98
+ if _lib.ng_mask(vocab._h, self._h, out.ctypes.data_as(ctypes.POINTER(_U32)), vocab.words) != 0:
99
+ raise ValueError("nbxgrammar: a mask of the wrong size")
100
+ return out.view(np.int32)
101
+
102
+ def advance(self, vocab: Vocab, token: int) -> None:
103
+ if _lib.ng_advance(vocab._h, self._h, int(token)) != 0:
104
+ raise ValueError(f"nbxgrammar: token {token} is not allowed here")
105
+
106
+ def accepting(self) -> bool:
107
+ return bool(_lib.ng_accepting(self._h))
108
+
109
+ def __del__(self):
110
+ if getattr(self, "_h", None):
111
+ _lib.ng_matcher_free(self._h)
112
+ self._h = None