typeseg 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.
- typeseg-0.1.0/LICENSE +201 -0
- typeseg-0.1.0/PKG-INFO +250 -0
- typeseg-0.1.0/README.md +226 -0
- typeseg-0.1.0/pyproject.toml +44 -0
- typeseg-0.1.0/setup.cfg +4 -0
- typeseg-0.1.0/tests/test_cupy_parity.py +53 -0
- typeseg-0.1.0/tests/test_distribution.py +71 -0
- typeseg-0.1.0/tests/test_postprocess_perf.py +66 -0
- typeseg-0.1.0/typeseg/__init__.py +30 -0
- typeseg-0.1.0/typeseg/__main__.py +4 -0
- typeseg-0.1.0/typeseg/_cli.py +130 -0
- typeseg-0.1.0/typeseg/_color.py +70 -0
- typeseg-0.1.0/typeseg/_cupy_backend.py +196 -0
- typeseg-0.1.0/typeseg/_mamba_kernel.py +208 -0
- typeseg-0.1.0/typeseg/_numpy_backend.py +193 -0
- typeseg-0.1.0/typeseg/_onnx_backend.py +158 -0
- typeseg-0.1.0/typeseg/_options.py +35 -0
- typeseg-0.1.0/typeseg/_postprocess.py +472 -0
- typeseg-0.1.0/typeseg/_runtime.py +209 -0
- typeseg-0.1.0/typeseg/_segmentation.py +78 -0
- typeseg-0.1.0/typeseg/_tokenize.py +56 -0
- typeseg-0.1.0/typeseg/data/mamba_al.npz +0 -0
- typeseg-0.1.0/typeseg/data/mamba_al.onnx +0 -0
- typeseg-0.1.0/typeseg/data/manifest.json +69 -0
- typeseg-0.1.0/typeseg/data/unet_al.npz +0 -0
- typeseg-0.1.0/typeseg/data/unet_al.onnx +0 -0
- typeseg-0.1.0/typeseg.egg-info/PKG-INFO +250 -0
- typeseg-0.1.0/typeseg.egg-info/SOURCES.txt +30 -0
- typeseg-0.1.0/typeseg.egg-info/dependency_links.txt +1 -0
- typeseg-0.1.0/typeseg.egg-info/entry_points.txt +3 -0
- typeseg-0.1.0/typeseg.egg-info/requires.txt +8 -0
- typeseg-0.1.0/typeseg.egg-info/top_level.txt +1 -0
typeseg-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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 Derivative
|
|
95
|
+
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, excluding
|
|
103
|
+
those notices that do not pertain to any part of the Derivative
|
|
104
|
+
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
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Martin Dallinger
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
typeseg-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: typeseg
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fine-grained, character-level content-type segmentation for textual inputs (U-Net + Mamba).
|
|
5
|
+
Author: Martin Dallinger
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/s0urc10ud/semantic-text-segmentation
|
|
8
|
+
Project-URL: Demo, https://typeseg.martin-dallinger.me
|
|
9
|
+
Keywords: segmentation,content-type,security,mamba,u-net,tokenization
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
13
|
+
Classifier: Topic :: Security
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: numpy>=1.21
|
|
18
|
+
Provides-Extra: onnx
|
|
19
|
+
Requires-Dist: onnxruntime>=1.17; extra == "onnx"
|
|
20
|
+
Provides-Extra: gpu
|
|
21
|
+
Requires-Dist: onnxruntime-gpu>=1.17; extra == "gpu"
|
|
22
|
+
Requires-Dist: cupy-cuda12x>=13; extra == "gpu"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# TypeSeg
|
|
26
|
+
|
|
27
|
+
**Fine-grained, character-level content-type segmentation for textual inputs.**
|
|
28
|
+
|
|
29
|
+
[](https://github.com/S0urC10ud/semantic-text-segmentation/blob/main/LICENSE)
|
|
30
|
+
[](https://pypi.org/project/typeseg/)
|
|
31
|
+
[](https://www.python.org/)
|
|
32
|
+
[](https://typeseg.martin-dallinger.me)
|
|
33
|
+
|
|
34
|
+
`typeseg` labels every character position of a text with one of 35 content types
|
|
35
|
+
(`html`, `css`, `javascript_typescript`, `python`, `powershell`, `encoding_base64`, …),
|
|
36
|
+
recovering the internal structure of mixed, malformed, or convention-breaking inputs.
|
|
37
|
+
The only runtime dependency is `numpy`.
|
|
38
|
+
|
|
39
|
+
<p align="center">
|
|
40
|
+
<img src="https://typeseg.martin-dallinger.me/images/llm_segmentation.png" alt="Correct model output on a heavily mangled HTML input with a hidden shell payload" width="460">
|
|
41
|
+
</p>
|
|
42
|
+
<p align="center">
|
|
43
|
+
<em>Model output on a heavily mangled input (stress-test): the script/style tags are missing and a
|
|
44
|
+
reverse shell targeting an LLM is hidden inside an HTML comment, yet the embedded <code>shell</code>
|
|
45
|
+
region is recovered correctly. Color saturation reflects per-character confidence.</em>
|
|
46
|
+
</p>
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install typeseg # CPU, numpy only
|
|
50
|
+
pip install "typeseg[onnx]" # + ONNX Runtime (faster CPU)
|
|
51
|
+
pip install "typeseg[gpu]" # + CUDA: onnxruntime-gpu (U-Net) and cupy (Mamba scan)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
import typeseg
|
|
56
|
+
|
|
57
|
+
text = "<html><body>IgnoreAbovecG93ZXJzaGVsbA==</body></html>"
|
|
58
|
+
|
|
59
|
+
result = typeseg.precise(text) # Mamba: highest quality, long-context (recommended)
|
|
60
|
+
result = typeseg.fast(text) # U-Net: faster, when throughput matters more than quality
|
|
61
|
+
|
|
62
|
+
for seg in result.segments:
|
|
63
|
+
print(f"{seg.start:>4}-{seg.end:<4} {seg.label:<22} {seg.confidence:.2f}")
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Installing the package also gives you a `typeseg` command (alias `segcat`) that
|
|
67
|
+
renders a file — tinted by content type, with a legend and a per-segment
|
|
68
|
+
confidence table — straight in the terminal, no Python REPL needed:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
typeseg file.html # segment a file with Mamba (precise)
|
|
72
|
+
typeseg --model fast file.html # use the faster U-Net instead
|
|
73
|
+
cat foo.txt | typeseg # read from stdin
|
|
74
|
+
typeseg --demo # built-in mixed / prompt-injection sample
|
|
75
|
+
python -m typeseg --demo # equivalent module form
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
<p align="center">
|
|
79
|
+
<img src="https://typeseg.martin-dallinger.me/images/typeseg-example.png" alt="typeseg segmenting a mixed CSS/JS/HTML/SQL/shell input in the terminal" width="760">
|
|
80
|
+
</p>
|
|
81
|
+
|
|
82
|
+
A `Segmentation` exposes:
|
|
83
|
+
|
|
84
|
+
- `segments` — merged runs as `Segment(start, end, label, confidence, text)`,
|
|
85
|
+
- `char_labels` — per-character label (length `len(text)`),
|
|
86
|
+
- `char_confidence` — per-character confidence in `[0, 1]`,
|
|
87
|
+
- `char_probs` — the full per-character probability distribution, a float32 array of
|
|
88
|
+
shape `(len(text), len(labels))` whose rows sum to ~1. This is the **raw model
|
|
89
|
+
output** (before post-processing relabelling); columns follow `labels`. The open-set
|
|
90
|
+
`other` class is *not* a column — it is derived by confidence gating, so a character
|
|
91
|
+
routed to `other` still keeps its distribution over the known classes here.
|
|
92
|
+
- `labels` — the class names, in `char_probs` column order.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
r = typeseg.precise("SELECT 1")
|
|
96
|
+
r.char_probs.shape # (8, 35)
|
|
97
|
+
r.char_distribution(0) # {'sql': 0.99, 'text': 0.001, ...} for char 0
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
When printed to a terminal, a `Segment` renders as a colour-tinted chip of its text
|
|
101
|
+
(matching the interactive viewer). Colour is auto-detected: it is emitted only to a TTY
|
|
102
|
+
and honours `NO_COLOR`; force it with `TYPESEG_COLOR=always` or disable with
|
|
103
|
+
`TYPESEG_COLOR=never`.
|
|
104
|
+
|
|
105
|
+
## Use cases
|
|
106
|
+
|
|
107
|
+
<p align="center">
|
|
108
|
+
<img src="https://typeseg.martin-dallinger.me/images/use_cases.png" alt="Representative use cases for granular content-type segmentation" width="820">
|
|
109
|
+
</p>
|
|
110
|
+
|
|
111
|
+
Content-aware routing and LLM-agent guardrails, span-level scanning of mixed/encoded payloads,
|
|
112
|
+
structure recovery in malformed or convention-breaking inputs, and dataset triage — moving the
|
|
113
|
+
decision from the whole file down to individual character spans. See the
|
|
114
|
+
[project README](https://github.com/S0urC10ud/semantic-text-segmentation#use-cases) for details.
|
|
115
|
+
|
|
116
|
+
### Backends
|
|
117
|
+
|
|
118
|
+
The only required dependency is `numpy`; both models run at **arbitrary input
|
|
119
|
+
length** on it. The `onnx`/`gpu` extras transparently swap in faster backends — the
|
|
120
|
+
API and output are identical (verified bit-close). Inspect the active backend:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
import typeseg
|
|
124
|
+
typeseg.backend_info()
|
|
125
|
+
# {'backend': 'onnx', 'gpu': True, 'precise_gpu': True,
|
|
126
|
+
# 'fast_providers': ['CUDAExecutionProvider', 'CPUExecutionProvider'],
|
|
127
|
+
# 'precise_providers': ['CuPyCUDA:NVIDIA GeForce RTX 5070 Laptop GPU']}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Providers report what each model **actually loaded** — if the CUDA provider fails to
|
|
131
|
+
initialise (missing CUDA/cuDNN libraries) it falls back to CPU and is reported as CPU
|
|
132
|
+
honestly.
|
|
133
|
+
|
|
134
|
+
**Per-model device (auto).** The two models reach the GPU by different routes:
|
|
135
|
+
|
|
136
|
+
- `fast()` (U-Net) runs on **onnxruntime-gpu** — ~3–4× faster on GPU; ~140k chars/s.
|
|
137
|
+
- `precise()` (Mamba) runs its selective-scan through a **custom CUDA scan kernel**
|
|
138
|
+
(a CuPy `RawKernel`, `cupy-cuda12x`), reaching ~58k tokens/s for the raw forward —
|
|
139
|
+
edging out the research model's JAX `associative_scan` (54.9k tok/s). The selective-scan
|
|
140
|
+
is a first-order linear (associative) recurrence; the stock ONNX `Scan` op evaluates it
|
|
141
|
+
one timestep per kernel launch and is actually ~4× *slower* on CUDA than CPU. Our kernel
|
|
142
|
+
instead gives **one GPU thread per inner channel** — each thread holds its own state
|
|
143
|
+
vector in registers and sweeps the whole sequence in a single launch — so the ONNX Mamba
|
|
144
|
+
path always stays on CPU and CuPy carries the GPU acceleration instead (~100× over the
|
|
145
|
+
ONNX `Scan` path). When CuPy/GPU is absent, `precise()` falls back to ONNX (or numpy) on CPU.
|
|
146
|
+
|
|
147
|
+
Select the backend with the `TYPESEG_BACKEND` environment variable:
|
|
148
|
+
|
|
149
|
+
| `TYPESEG_BACKEND` | behaviour |
|
|
150
|
+
|---|---|
|
|
151
|
+
| *(unset)* / `onnx` / `cpu` | auto: U-Net on CUDA (onnxruntime) when it loads, Mamba on CuPy CUDA when present; otherwise CPU/numpy |
|
|
152
|
+
| `numpy` | force the pure-numpy backend |
|
|
153
|
+
| `gpu` / `cuda` | **require** CUDA for *both* models — no CPU fallback; raise immediately if it cannot initialise |
|
|
154
|
+
|
|
155
|
+
`gpu`/`cuda` is the "fail fast" mode: rather than silently running on CPU it errors if
|
|
156
|
+
the GPU backends are missing, the CUDA provider is absent, or CUDA fails to load. GPU
|
|
157
|
+
needs `pip install "typeseg[gpu]"` (onnxruntime-gpu for the U-Net, CuPy for the Mamba
|
|
158
|
+
scan) plus CUDA 12.x + cuDNN 9.x on the library path.
|
|
159
|
+
|
|
160
|
+
#### Running on GPU
|
|
161
|
+
|
|
162
|
+
Requires an NVIDIA GPU with the CUDA 12.x runtime and cuDNN 9.x. The simplest setup
|
|
163
|
+
pulls the CUDA libraries as pip wheels so nothing has to be installed system-wide:
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
# 1. The GPU extra: onnxruntime-gpu (U-Net) + cupy-cuda12x (Mamba scan)
|
|
167
|
+
pip install "typeseg[gpu]"
|
|
168
|
+
|
|
169
|
+
# 2. CUDA 12 + cuDNN 9 libraries that onnxruntime-gpu needs (CuPy bundles its own).
|
|
170
|
+
# Skip any you already have system-wide.
|
|
171
|
+
pip install nvidia-cudnn-cu12 nvidia-cublas-cu12 nvidia-cuda-runtime-cu12 \
|
|
172
|
+
nvidia-cufft-cu12 nvidia-curand-cu12
|
|
173
|
+
|
|
174
|
+
# 3. Put those wheels' libs on the loader path (one-off per shell; not needed if
|
|
175
|
+
# CUDA/cuDNN are already installed system-wide):
|
|
176
|
+
export LD_LIBRARY_PATH="$(python - <<'PY'
|
|
177
|
+
import os, nvidia, glob
|
|
178
|
+
root = os.path.dirname(nvidia.__file__)
|
|
179
|
+
print(":".join(glob.glob(os.path.join(root, "*", "lib"))))
|
|
180
|
+
PY
|
|
181
|
+
):$LD_LIBRARY_PATH"
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Verify both models are on the GPU:
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
import typeseg
|
|
188
|
+
typeseg.backend_info()
|
|
189
|
+
# {'backend': 'onnx', 'gpu': True, 'precise_gpu': True,
|
|
190
|
+
# 'fast_providers': ['CUDAExecutionProvider', 'CPUExecutionProvider'],
|
|
191
|
+
# 'precise_providers': ['CuPyCUDA:NVIDIA GeForce RTX 5070 Laptop GPU']}
|
|
192
|
+
|
|
193
|
+
typeseg.fast(text) # U-Net on onnxruntime-gpu (~140k chars/s)
|
|
194
|
+
typeseg.precise(text) # Mamba on the CuPy scan (~58k tokens/s raw forward)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
To make GPU mandatory (raise instead of silently using CPU), set
|
|
198
|
+
`TYPESEG_BACKEND=gpu`. Notes:
|
|
199
|
+
|
|
200
|
+
- The **first** CUDA call compiles kernels — a one-time warmup of seconds (longer on
|
|
201
|
+
brand-new GPU architectures, e.g. Blackwell `sm_120`). Keep the process warm.
|
|
202
|
+
- `backend_info()` reflects what each model **actually** loaded; if it shows
|
|
203
|
+
`CPUExecutionProvider` for `fast_providers`, a CUDA/cuDNN library failed to load —
|
|
204
|
+
re-check step 2/3 (a common miss is `libcurand.so.10` → `nvidia-curand-cu12`).
|
|
205
|
+
- On Windows use WSL2 for CUDA.
|
|
206
|
+
|
|
207
|
+
Post-processing mirrors the interactive viewer via an `Options` object; every step
|
|
208
|
+
can be tuned or disabled:
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from typeseg import precise, Options
|
|
212
|
+
|
|
213
|
+
result = precise(text, Options(other_threshold=0.30, min_run_chars=3))
|
|
214
|
+
result = precise(text, Options(paired_delimiter_fill=False)) # disable one step
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Building from source
|
|
218
|
+
|
|
219
|
+
The model weights (`typeseg/data/*.npz`, `*.onnx`) are generated from the released
|
|
220
|
+
checkpoints and are not checked in. From the repository root:
|
|
221
|
+
|
|
222
|
+
```bash
|
|
223
|
+
python scripts/export_typeseg_weights.py # checkpoints -> data/*.npz + manifest.json
|
|
224
|
+
python scripts/export_typeseg_onnx.py # data/*.npz -> data/*.onnx
|
|
225
|
+
python -m build packages/typeseg # or: uv build packages/typeseg
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
See the project repository and the accompanying MSc thesis for methodology, models,
|
|
229
|
+
and benchmarks. Licensed under Apache-2.0.
|
|
230
|
+
|
|
231
|
+
## Post-processing methods
|
|
232
|
+
|
|
233
|
+
The raw model gives a probability vector per character. Post-processing applies a few
|
|
234
|
+
cheap local passes (each `O(n)`, no parsing) before segments are exposed. They run in
|
|
235
|
+
the order below; toggle each via `Options`. Implementation: `typeseg/_postprocess.py`
|
|
236
|
+
(the interactive viewer in `viewers/core.py` has a few additional heuristics).
|
|
237
|
+
|
|
238
|
+
| step | `Options` flag | what it does |
|
|
239
|
+
|---|---|---|
|
|
240
|
+
| 1. Whitespace relabeling | `whitespace_relabel` | Whitespace carries no real prediction, so each space/tab/newline copies the label of its nearest non-whitespace neighbour (ties go left). Keeps segments from fragmenting on indentation. *(Thesis step 1.)* |
|
|
241
|
+
| 2. Confidence gating | `confidence_gating`, `other_threshold` | A character whose top class probability is below `other_threshold` (default `0.30`) is routed to a virtual open-set `other` label. *(Thesis step 2.)* |
|
|
242
|
+
| 3. Boundary snapping | `boundary_snap`, `boundary_snap_max_shift` | A boundary between two runs may shift by ≤ `boundary_snap_max_shift` (default `2`) onto a nearby delimiter symbol (`< > " ' \` ( ) [ ] { } / \ , ; : =`) or whitespace, so cuts land on natural seams. A shift is rejected if a moved non-delimiter position's destination-label probability is materially lower than the model's. *(Thesis step 3.)* |
|
|
243
|
+
| 4. Minimum-run normalization | `min_run_normalize`, `min_run_chars` | Interior runs shorter than `min_run_chars` (default `3`) are absorbed into the better-supported neighbour (`AABBAA → AAAAAA`); short *edge* runs are kept. Removes single-character noise. *(Thesis step 4.)* |
|
|
244
|
+
| 5. Paired-delimiter fill | `paired_delimiter_fill`, `paired_delimiter_max_shift` | For a run wrapped by the same host on both sides (`A B A`), nudge both edges (≤ shift, default `2`) so the inner run sits **inside a matching delimiter pair** — `" "`, `' '`, `` ` ` ``, `( )`, `[ ]`, `{ }` — pushing the delimiters out to the host. Example: in `onclick="alert(…)"` the `="` is ejected to `html` and only `alert(…)` stays `javascript`. **Not part of the thesis four steps; matches the deployment viewer.** |
|
|
245
|
+
|
|
246
|
+
Steps 1–4 are the four steps documented in the thesis (off by default for the thesis
|
|
247
|
+
benchmark numbers; on by default here for deployment-style output). Step 5 is an extra
|
|
248
|
+
the interactive viewer also applies. The viewer has further heuristics
|
|
249
|
+
(`markdown_structure_fill`, `local_host_fill`, `newline_snap`) not ported here — see
|
|
250
|
+
`viewers/core.py` for those.
|