ctxprune 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.
- ctxprune-0.1.0/.gitignore +6 -0
- ctxprune-0.1.0/LICENSE +202 -0
- ctxprune-0.1.0/PKG-INFO +143 -0
- ctxprune-0.1.0/README.md +98 -0
- ctxprune-0.1.0/ctxprune/__init__.py +6 -0
- ctxprune-0.1.0/ctxprune/align.py +93 -0
- ctxprune-0.1.0/ctxprune/atoms.py +106 -0
- ctxprune-0.1.0/ctxprune/chunking.py +104 -0
- ctxprune-0.1.0/ctxprune/cli.py +40 -0
- ctxprune-0.1.0/ctxprune/compress.py +182 -0
- ctxprune-0.1.0/ctxprune/idcheck.py +59 -0
- ctxprune-0.1.0/ctxprune/integrations.py +90 -0
- ctxprune-0.1.0/ctxprune/sources.py +256 -0
- ctxprune-0.1.0/ctxprune/teacher.py +241 -0
- ctxprune-0.1.0/ctxprune/tokenlabels.py +71 -0
- ctxprune-0.1.0/pyproject.toml +65 -0
- ctxprune-0.1.0/space/static/README.md +17 -0
- ctxprune-0.1.0/tests/test_core.py +143 -0
- ctxprune-0.1.0/tests/test_integrations.py +31 -0
ctxprune-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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
|
|
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 [yyyy] [name of copyright owner]
|
|
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.
|
|
202
|
+
|
ctxprune-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ctxprune
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Context compression for AI agents: an LLMLingua-2 successor that keeps identifiers intact
|
|
5
|
+
Project-URL: Homepage, https://github.com/riceharvest/ctxprune
|
|
6
|
+
Project-URL: Model, https://huggingface.co/darioooooo0o/ctxprune-small
|
|
7
|
+
Project-URL: Demo, https://huggingface.co/spaces/darioooooo0o/ctxprune
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,context-compression,llm,llmlingua,prompt-compression,rag,token-classification
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Classifier: Topic :: Text Processing
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Requires-Dist: huggingface-hub>=0.25
|
|
19
|
+
Requires-Dist: numpy
|
|
20
|
+
Requires-Dist: onnxruntime>=1.18
|
|
21
|
+
Requires-Dist: transformers>=4.45
|
|
22
|
+
Provides-Extra: baseline
|
|
23
|
+
Requires-Dist: llmlingua; extra == 'baseline'
|
|
24
|
+
Requires-Dist: torch; extra == 'baseline'
|
|
25
|
+
Provides-Extra: data
|
|
26
|
+
Requires-Dist: httpx; extra == 'data'
|
|
27
|
+
Requires-Dist: pyarrow; extra == 'data'
|
|
28
|
+
Requires-Dist: tokenizers; extra == 'data'
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: httpx; extra == 'dev'
|
|
31
|
+
Requires-Dist: pyarrow; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
33
|
+
Provides-Extra: export
|
|
34
|
+
Requires-Dist: onnx; extra == 'export'
|
|
35
|
+
Requires-Dist: onnxruntime>=1.18; extra == 'export'
|
|
36
|
+
Requires-Dist: torch; extra == 'export'
|
|
37
|
+
Provides-Extra: langchain
|
|
38
|
+
Requires-Dist: langchain-core>=0.3; extra == 'langchain'
|
|
39
|
+
Provides-Extra: llamaindex
|
|
40
|
+
Requires-Dist: llama-index-core>=0.12; extra == 'llamaindex'
|
|
41
|
+
Provides-Extra: onnx
|
|
42
|
+
Provides-Extra: torch
|
|
43
|
+
Requires-Dist: torch; extra == 'torch'
|
|
44
|
+
Description-Content-Type: text/markdown
|
|
45
|
+
|
|
46
|
+
# ctxprune
|
|
47
|
+
|
|
48
|
+
Context compression for AI agents. A small token classifier deletes the least useful words from
|
|
49
|
+
tool outputs, code, documents and chat before they reach an LLM. It is a successor to Microsoft's
|
|
50
|
+
LLMLingua-2, built for agent text, and it never splits or re-spaces identifiers.
|
|
51
|
+
|
|
52
|
+
Model: [darioooooo0o/ctxprune-small](https://huggingface.co/darioooooo0o/ctxprune-small) (Apache-2.0).
|
|
53
|
+
Results and limitations are on the model card. **Try it next to LLMLingua-2 on your own text:
|
|
54
|
+
[live demo](https://huggingface.co/spaces/darioooooo0o/ctxprune).**
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install "ctxprune @ git+https://github.com/riceharvest/ctxprune" # CPU, ONNX; no torch needed
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from ctxprune import Compressor
|
|
62
|
+
|
|
63
|
+
c = Compressor("darioooooo0o/ctxprune-small", backend="onnx")
|
|
64
|
+
c.compress(tool_output, rate=0.5)["text"] # keep ~50%
|
|
65
|
+
c.compress(tool_output, rate=0.33, force_protected=True)["text"] # never drop IDs/numbers/paths
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
ctxprune order.json --rate 0.5 # CLI, same thing
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
LangChain and LlamaIndex:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from ctxprune.integrations import CtxpruneDocumentCompressor # LangChain
|
|
77
|
+
retriever = ContextualCompressionRetriever(base_compressor=CtxpruneDocumentCompressor(rate=0.5),
|
|
78
|
+
base_retriever=base_retriever)
|
|
79
|
+
|
|
80
|
+
from ctxprune.integrations import CtxpruneNodePostprocessor # LlamaIndex
|
|
81
|
+
engine = index.as_query_engine(node_postprocessors=[CtxpruneNodePostprocessor(rate=0.5)])
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Works inside LLMLingua too, once its tokenizer-detection fix is merged:
|
|
85
|
+
[microsoft/LLMLingua#261](https://github.com/microsoft/LLMLingua/pull/261) (`upstream/llmlingua-subword-style.patch`).
|
|
86
|
+
|
|
87
|
+
At 50% of tokens kept, an independent LLM answers 68.8% of held-out questions correctly from ctxprune's
|
|
88
|
+
output vs 53.4% from LLMLingua-2-large's (91.8% uncompressed); at 33%, 53.4% vs 32.5%. Details, per-source
|
|
89
|
+
results and limitations: [model card](https://huggingface.co/darioooooo0o/ctxprune-small).
|
|
90
|
+
|
|
91
|
+
By [@imdariotoo](https://x.com/imdariotoo).
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Reproducing the model
|
|
96
|
+
|
|
97
|
+
Why: LLMLingua-2 (Microsoft, Mar 2024) was trained only on meeting transcripts
|
|
98
|
+
under CC BY-NC-SA labels. On agent tool outputs it loses or mangles about half
|
|
99
|
+
of all identifiers (UUIDs, IPs, paths, versions) and breaks JSON.
|
|
100
|
+
|
|
101
|
+
## Pipeline
|
|
102
|
+
|
|
103
|
+
| step | script | where | notes |
|
|
104
|
+
|---|---|---|---|
|
|
105
|
+
| corpus | `scripts/build_corpus.py` | CPU, ~2 min | ranged parquet reads from 8 permissive sources; split per repo/server/site |
|
|
106
|
+
| labels | `scripts/label.py` | teacher LLM (`scripts/teacher_up.sh`) | deletion-only compression, LCS-aligned to atoms; cached |
|
|
107
|
+
| train | `scripts/train.py` | any torch device (we used an Intel Arc Pro B70) or CPU | token classifier, label 1 = keep (LLMLingua-2 convention) |
|
|
108
|
+
| quick eval | `scripts/eval_quick.py` | CPU | identifiers lost, JSON validity, char ratio vs LLMLingua-2 |
|
|
109
|
+
| QA eval | `scripts/eval_qa.py questions/answer` | teacher LLM | can a reader still answer from the compressed text |
|
|
110
|
+
|
|
111
|
+
`scripts/run_v1.sh` runs corpus and labels; `scripts/after_label.sh` runs everything after them.
|
|
112
|
+
|
|
113
|
+
## Data sources (all permissive)
|
|
114
|
+
|
|
115
|
+
SWE-smith trajectories (MIT), SWE-rebench OpenHands trajectories (CC BY 4.0),
|
|
116
|
+
Toucan-1.5M MCP tool calls (Apache-2.0), github-code-clean filtered to
|
|
117
|
+
MIT/Apache/BSD/ISC files, FineWeb-Edu and FineWeb-2 (ODC-BY), oasst2
|
|
118
|
+
(Apache-2.0). Every chunk records its dataset, license and source reference.
|
|
119
|
+
Teacher: Qwen3.8-27B GPTQ (Apache-2.0 outputs).
|
|
120
|
+
|
|
121
|
+
## Training more after an eval
|
|
122
|
+
|
|
123
|
+
Nothing has to be redone:
|
|
124
|
+
|
|
125
|
+
1. **More data, same mix.** Rerun `build_corpus.py` into the same directory
|
|
126
|
+
with a larger `--total`. Sampling is deterministic, and dataset revisions
|
|
127
|
+
are pinned in `chunks/revisions.json`, so every source file becomes a
|
|
128
|
+
superset of the old one. To weight a domain up, add `--mix toucan_mcp=0.3`.
|
|
129
|
+
2. **Label only the new chunks.** Rerun `label.py`. The teacher cache is keyed
|
|
130
|
+
by (prompt version, model, text), so old chunks come back from disk.
|
|
131
|
+
3. **Continue training** from the previous model:
|
|
132
|
+
`train.py --data <dir> --init-from runs/v1-mmbert-small/final --out runs/v2-...`
|
|
133
|
+
(or `--resume` to continue an interrupted run from its checkpoint).
|
|
134
|
+
`--data` accepts several directories, to mix label sets.
|
|
135
|
+
4. **Re-run evals.** Question and answer caches mean only new contexts cost LLM calls.
|
|
136
|
+
|
|
137
|
+
Changing the teacher prompt bumps `PROMPT_VERSION` in `ctxprune/teacher.py`, which
|
|
138
|
+
invalidates the cache on purpose.
|
|
139
|
+
|
|
140
|
+
## Tests
|
|
141
|
+
|
|
142
|
+
`uv run pytest`: atom round-trips, identifier atoms, CJK handling, LCS
|
|
143
|
+
alignment, chunk budgets, split stability and cache resume.
|
ctxprune-0.1.0/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# ctxprune
|
|
2
|
+
|
|
3
|
+
Context compression for AI agents. A small token classifier deletes the least useful words from
|
|
4
|
+
tool outputs, code, documents and chat before they reach an LLM. It is a successor to Microsoft's
|
|
5
|
+
LLMLingua-2, built for agent text, and it never splits or re-spaces identifiers.
|
|
6
|
+
|
|
7
|
+
Model: [darioooooo0o/ctxprune-small](https://huggingface.co/darioooooo0o/ctxprune-small) (Apache-2.0).
|
|
8
|
+
Results and limitations are on the model card. **Try it next to LLMLingua-2 on your own text:
|
|
9
|
+
[live demo](https://huggingface.co/spaces/darioooooo0o/ctxprune).**
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install "ctxprune @ git+https://github.com/riceharvest/ctxprune" # CPU, ONNX; no torch needed
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from ctxprune import Compressor
|
|
17
|
+
|
|
18
|
+
c = Compressor("darioooooo0o/ctxprune-small", backend="onnx")
|
|
19
|
+
c.compress(tool_output, rate=0.5)["text"] # keep ~50%
|
|
20
|
+
c.compress(tool_output, rate=0.33, force_protected=True)["text"] # never drop IDs/numbers/paths
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
ctxprune order.json --rate 0.5 # CLI, same thing
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
LangChain and LlamaIndex:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from ctxprune.integrations import CtxpruneDocumentCompressor # LangChain
|
|
32
|
+
retriever = ContextualCompressionRetriever(base_compressor=CtxpruneDocumentCompressor(rate=0.5),
|
|
33
|
+
base_retriever=base_retriever)
|
|
34
|
+
|
|
35
|
+
from ctxprune.integrations import CtxpruneNodePostprocessor # LlamaIndex
|
|
36
|
+
engine = index.as_query_engine(node_postprocessors=[CtxpruneNodePostprocessor(rate=0.5)])
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Works inside LLMLingua too, once its tokenizer-detection fix is merged:
|
|
40
|
+
[microsoft/LLMLingua#261](https://github.com/microsoft/LLMLingua/pull/261) (`upstream/llmlingua-subword-style.patch`).
|
|
41
|
+
|
|
42
|
+
At 50% of tokens kept, an independent LLM answers 68.8% of held-out questions correctly from ctxprune's
|
|
43
|
+
output vs 53.4% from LLMLingua-2-large's (91.8% uncompressed); at 33%, 53.4% vs 32.5%. Details, per-source
|
|
44
|
+
results and limitations: [model card](https://huggingface.co/darioooooo0o/ctxprune-small).
|
|
45
|
+
|
|
46
|
+
By [@imdariotoo](https://x.com/imdariotoo).
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## Reproducing the model
|
|
51
|
+
|
|
52
|
+
Why: LLMLingua-2 (Microsoft, Mar 2024) was trained only on meeting transcripts
|
|
53
|
+
under CC BY-NC-SA labels. On agent tool outputs it loses or mangles about half
|
|
54
|
+
of all identifiers (UUIDs, IPs, paths, versions) and breaks JSON.
|
|
55
|
+
|
|
56
|
+
## Pipeline
|
|
57
|
+
|
|
58
|
+
| step | script | where | notes |
|
|
59
|
+
|---|---|---|---|
|
|
60
|
+
| corpus | `scripts/build_corpus.py` | CPU, ~2 min | ranged parquet reads from 8 permissive sources; split per repo/server/site |
|
|
61
|
+
| labels | `scripts/label.py` | teacher LLM (`scripts/teacher_up.sh`) | deletion-only compression, LCS-aligned to atoms; cached |
|
|
62
|
+
| train | `scripts/train.py` | any torch device (we used an Intel Arc Pro B70) or CPU | token classifier, label 1 = keep (LLMLingua-2 convention) |
|
|
63
|
+
| quick eval | `scripts/eval_quick.py` | CPU | identifiers lost, JSON validity, char ratio vs LLMLingua-2 |
|
|
64
|
+
| QA eval | `scripts/eval_qa.py questions/answer` | teacher LLM | can a reader still answer from the compressed text |
|
|
65
|
+
|
|
66
|
+
`scripts/run_v1.sh` runs corpus and labels; `scripts/after_label.sh` runs everything after them.
|
|
67
|
+
|
|
68
|
+
## Data sources (all permissive)
|
|
69
|
+
|
|
70
|
+
SWE-smith trajectories (MIT), SWE-rebench OpenHands trajectories (CC BY 4.0),
|
|
71
|
+
Toucan-1.5M MCP tool calls (Apache-2.0), github-code-clean filtered to
|
|
72
|
+
MIT/Apache/BSD/ISC files, FineWeb-Edu and FineWeb-2 (ODC-BY), oasst2
|
|
73
|
+
(Apache-2.0). Every chunk records its dataset, license and source reference.
|
|
74
|
+
Teacher: Qwen3.8-27B GPTQ (Apache-2.0 outputs).
|
|
75
|
+
|
|
76
|
+
## Training more after an eval
|
|
77
|
+
|
|
78
|
+
Nothing has to be redone:
|
|
79
|
+
|
|
80
|
+
1. **More data, same mix.** Rerun `build_corpus.py` into the same directory
|
|
81
|
+
with a larger `--total`. Sampling is deterministic, and dataset revisions
|
|
82
|
+
are pinned in `chunks/revisions.json`, so every source file becomes a
|
|
83
|
+
superset of the old one. To weight a domain up, add `--mix toucan_mcp=0.3`.
|
|
84
|
+
2. **Label only the new chunks.** Rerun `label.py`. The teacher cache is keyed
|
|
85
|
+
by (prompt version, model, text), so old chunks come back from disk.
|
|
86
|
+
3. **Continue training** from the previous model:
|
|
87
|
+
`train.py --data <dir> --init-from runs/v1-mmbert-small/final --out runs/v2-...`
|
|
88
|
+
(or `--resume` to continue an interrupted run from its checkpoint).
|
|
89
|
+
`--data` accepts several directories, to mix label sets.
|
|
90
|
+
4. **Re-run evals.** Question and answer caches mean only new contexts cost LLM calls.
|
|
91
|
+
|
|
92
|
+
Changing the teacher prompt bumps `PROMPT_VERSION` in `ctxprune/teacher.py`, which
|
|
93
|
+
invalidates the cache on purpose.
|
|
94
|
+
|
|
95
|
+
## Tests
|
|
96
|
+
|
|
97
|
+
`uv run pytest`: atom round-trips, identifier atoms, CJK handling, LCS
|
|
98
|
+
alignment, chunk budgets, split stability and cache resume.
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Turn a teacher's deletion-only compression into per-atom keep labels.
|
|
2
|
+
|
|
3
|
+
The teacher is asked to only delete atoms, so its output should be an
|
|
4
|
+
ordered subsequence of the source atoms. We find the longest common
|
|
5
|
+
subsequence (exact match first, casefold second) and label matched source
|
|
6
|
+
atoms as kept. Teacher atoms that match nothing are "variations" (the
|
|
7
|
+
teacher rewrote or invented text); a high variation rate means the sample
|
|
8
|
+
is untrustworthy and gets filtered.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from .atoms import Atom, atomize, is_protected, norm
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Alignment:
|
|
20
|
+
keep: list[bool]
|
|
21
|
+
n_src: int
|
|
22
|
+
n_comp: int
|
|
23
|
+
n_matched: int
|
|
24
|
+
variation_rate: float # teacher atoms with no source match
|
|
25
|
+
comp_rate: float # kept / source, in atoms
|
|
26
|
+
protected_total: int
|
|
27
|
+
protected_kept: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _lcs_pairs(a: list[str], b: list[str]) -> list[tuple[int, int]]:
|
|
31
|
+
n, m = len(a), len(b)
|
|
32
|
+
if n == 0 or m == 0:
|
|
33
|
+
return []
|
|
34
|
+
# dp[i][j] = LCS length of a[i:], b[j:]; rows built bottom-up.
|
|
35
|
+
dp = [[0] * (m + 1) for _ in range(n + 1)]
|
|
36
|
+
for i in range(n - 1, -1, -1):
|
|
37
|
+
ai, row, nxt = a[i], dp[i], dp[i + 1]
|
|
38
|
+
for j in range(m - 1, -1, -1):
|
|
39
|
+
if ai == b[j]:
|
|
40
|
+
row[j] = nxt[j + 1] + 1
|
|
41
|
+
else:
|
|
42
|
+
x, y = nxt[j], row[j + 1]
|
|
43
|
+
row[j] = x if x >= y else y
|
|
44
|
+
pairs, i, j = [], 0, 0
|
|
45
|
+
while i < n and j < m:
|
|
46
|
+
if a[i] == b[j]:
|
|
47
|
+
pairs.append((i, j))
|
|
48
|
+
i += 1
|
|
49
|
+
j += 1
|
|
50
|
+
elif dp[i + 1][j] >= dp[i][j + 1]:
|
|
51
|
+
i += 1
|
|
52
|
+
else:
|
|
53
|
+
j += 1
|
|
54
|
+
return pairs
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def align(src_atoms: list[Atom], comp_text: str) -> Alignment:
|
|
58
|
+
src = [a.text for a in src_atoms]
|
|
59
|
+
comp = [a.text for a in atomize(comp_text) if a.text]
|
|
60
|
+
keep = [False] * len(src)
|
|
61
|
+
matched_comp = [False] * len(comp)
|
|
62
|
+
|
|
63
|
+
# Pass 1: exact. Pass 2: casefold over what is left, in the gaps between
|
|
64
|
+
# pass-1 anchors so order is preserved.
|
|
65
|
+
pairs = _lcs_pairs(src, comp)
|
|
66
|
+
for i, j in pairs:
|
|
67
|
+
keep[i] = True
|
|
68
|
+
matched_comp[j] = True
|
|
69
|
+
anchors = [(-1, -1)] + pairs + [(len(src), len(comp))]
|
|
70
|
+
for (i0, j0), (i1, j1) in zip(anchors, anchors[1:]):
|
|
71
|
+
si = [i for i in range(i0 + 1, i1) if not keep[i]]
|
|
72
|
+
cj = [j for j in range(j0 + 1, j1) if not matched_comp[j]]
|
|
73
|
+
if not si or not cj:
|
|
74
|
+
continue
|
|
75
|
+
sub = _lcs_pairs([norm(src[i]) for i in si], [norm(comp[j]) for j in cj])
|
|
76
|
+
for a, b in sub:
|
|
77
|
+
keep[si[a]] = True
|
|
78
|
+
matched_comp[cj[b]] = True
|
|
79
|
+
|
|
80
|
+
real = [i for i, t in enumerate(src) if t]
|
|
81
|
+
n_src = len(real)
|
|
82
|
+
n_matched = sum(matched_comp)
|
|
83
|
+
prot = [i for i in real if is_protected(src[i])]
|
|
84
|
+
return Alignment(
|
|
85
|
+
keep=keep,
|
|
86
|
+
n_src=n_src,
|
|
87
|
+
n_comp=len(comp),
|
|
88
|
+
n_matched=n_matched,
|
|
89
|
+
variation_rate=(1 - n_matched / len(comp)) if comp else 0.0,
|
|
90
|
+
comp_rate=(sum(keep[i] for i in real) / n_src) if n_src else 0.0,
|
|
91
|
+
protected_total=len(prot),
|
|
92
|
+
protected_kept=sum(keep[i] for i in prot),
|
|
93
|
+
)
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Atom segmentation: the unit the compressor keeps or drops.
|
|
2
|
+
|
|
3
|
+
An atom is either a "word" that glues identifier-ish characters together
|
|
4
|
+
(paths, URLs, versions, IPs, snake_case, UUIDs) or a single punctuation
|
|
5
|
+
character. Each atom remembers the whitespace that preceded it, so
|
|
6
|
+
``detok(atoms, keep)`` rebuilds kept text exactly as it appeared in the
|
|
7
|
+
source, without the "0. 21" / "ord _ 8f3a" artifacts LLMLingua-2 produces.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
# Scripts written without spaces (Han, kana) get one atom per character, so
|
|
16
|
+
# a deletion inside a sentence is still a deletion and not a "rewrite".
|
|
17
|
+
_CJK = "\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff"
|
|
18
|
+
_W = rf"[^\W{_CJK}]" # word char that is not CJK
|
|
19
|
+
# A word may start with one path/flag sigil, then word chars, with
|
|
20
|
+
# identifier punctuation allowed only *between* word chars.
|
|
21
|
+
_WORD = rf"(?:--?|[/~.$@#])?{_W}(?:(?:{_W}|[.:/@%+#~=?&'\-])*{_W})?"
|
|
22
|
+
_ATOM_RE = re.compile(rf"(\s*)({_WORD}|[{_CJK}]|[^\s])", re.UNICODE)
|
|
23
|
+
|
|
24
|
+
# All-caps English that is prose, not an identifier (license headers, shouting).
|
|
25
|
+
_CAPS_WORDS = set(
|
|
26
|
+
"THE AND FOR ANY NOT BUT ARE WAS YOU ALL WITH FROM THIS THAT WITHOUT WARRANTIES WARRANTY SOFTWARE KIND "
|
|
27
|
+
"IMPLIED INCLUDING LIMITED COPYRIGHT OTHER LIABILITY USE BASIS CONDITIONS SUCH EVENT SHALL HOLDERS "
|
|
28
|
+
"CONTRIBUTORS DAMAGES PURPOSE PARTICULAR FITNESS MERCHANTABILITY EXPRESS OUT CONNECTION ARISING "
|
|
29
|
+
"WHETHER CONTRACT TORT OTHERWISE PROVIDED LICENSE NOTICE NOTE IMPORTANT".split()
|
|
30
|
+
)
|
|
31
|
+
_HEX_RE = re.compile(r"^[0-9a-fA-F]{7,}$")
|
|
32
|
+
_CAMEL_RE = re.compile(r"[a-z][A-Z]|[A-Z]{2}[a-z]")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Atom:
|
|
37
|
+
ws: str # whitespace preceding the atom in the source
|
|
38
|
+
text: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def atomize(text: str) -> list[Atom]:
|
|
42
|
+
atoms: list[Atom] = []
|
|
43
|
+
pos = 0
|
|
44
|
+
for m in _ATOM_RE.finditer(text):
|
|
45
|
+
if m.start() != pos: # unreachable by construction; guard anyway
|
|
46
|
+
raise ValueError(f"atomizer skipped {text[pos:m.start()]!r}")
|
|
47
|
+
atoms.append(Atom(m.group(1), m.group(2)))
|
|
48
|
+
pos = m.end()
|
|
49
|
+
tail = text[pos:]
|
|
50
|
+
if tail.strip():
|
|
51
|
+
raise ValueError(f"atomizer left non-space tail {tail!r}")
|
|
52
|
+
if tail: # trailing whitespace rides on a sentinel-free empty atom
|
|
53
|
+
atoms.append(Atom(tail, ""))
|
|
54
|
+
return atoms
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def detok(atoms: list[Atom], keep: list[bool], collapse_ws: bool = True) -> str:
|
|
58
|
+
"""Rebuild text from kept atoms.
|
|
59
|
+
|
|
60
|
+
Kept atoms keep their own leading whitespace. When an atom's predecessor
|
|
61
|
+
was dropped, the dropped run's whitespace is collapsed to the "largest"
|
|
62
|
+
whitespace seen in that run (a newline wins over a space), so line
|
|
63
|
+
structure survives deletions.
|
|
64
|
+
"""
|
|
65
|
+
out: list[str] = []
|
|
66
|
+
pending = ""
|
|
67
|
+
for a, k in zip(atoms, keep):
|
|
68
|
+
if k:
|
|
69
|
+
ws = a.ws
|
|
70
|
+
if pending and collapse_ws:
|
|
71
|
+
ws = _merge_ws(pending, a.ws)
|
|
72
|
+
if not out:
|
|
73
|
+
ws = ws if not collapse_ws else ""
|
|
74
|
+
out.append(ws + a.text)
|
|
75
|
+
pending = ""
|
|
76
|
+
else:
|
|
77
|
+
pending = _merge_ws(pending, a.ws) if pending else (a.ws or " ")
|
|
78
|
+
return "".join(out)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _merge_ws(a: str, b: str) -> str:
|
|
82
|
+
if "\n" in a or "\n" in b:
|
|
83
|
+
return "\n"
|
|
84
|
+
return " " if (a or b) else ""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def is_protected(atom: str) -> bool:
|
|
88
|
+
"""Atoms an agent is likely to need verbatim later (IDs, numbers, paths)."""
|
|
89
|
+
if not atom or not any(c.isalnum() for c in atom):
|
|
90
|
+
return False
|
|
91
|
+
if any(c.isdigit() for c in atom):
|
|
92
|
+
return True
|
|
93
|
+
core = atom.lstrip("-/~.$@#")
|
|
94
|
+
if any(c in core for c in "_/.:@="):
|
|
95
|
+
return True
|
|
96
|
+
if _HEX_RE.match(core):
|
|
97
|
+
return True
|
|
98
|
+
if len(core) >= 3 and core.isupper() and core not in _CAPS_WORDS:
|
|
99
|
+
return True
|
|
100
|
+
if _CAMEL_RE.search(core):
|
|
101
|
+
return True
|
|
102
|
+
return atom != core # flags like --format, paths like /tmp
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def norm(atom: str) -> str:
|
|
106
|
+
return atom.casefold()
|