afterthoughts 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.
- afterthoughts-0.1.0/LICENSE +203 -0
- afterthoughts-0.1.0/NOTICE +4 -0
- afterthoughts-0.1.0/PKG-INFO +421 -0
- afterthoughts-0.1.0/README.md +380 -0
- afterthoughts-0.1.0/afterthoughts/__init__.py +65 -0
- afterthoughts-0.1.0/afterthoughts/avail.py +182 -0
- afterthoughts-0.1.0/afterthoughts/chunk.py +1361 -0
- afterthoughts-0.1.0/afterthoughts/encode.py +1347 -0
- afterthoughts-0.1.0/afterthoughts/tokenize.py +733 -0
- afterthoughts-0.1.0/afterthoughts/utils.py +620 -0
- afterthoughts-0.1.0/afterthoughts/validation.py +137 -0
- afterthoughts-0.1.0/afterthoughts.egg-info/PKG-INFO +421 -0
- afterthoughts-0.1.0/afterthoughts.egg-info/SOURCES.txt +22 -0
- afterthoughts-0.1.0/afterthoughts.egg-info/dependency_links.txt +1 -0
- afterthoughts-0.1.0/afterthoughts.egg-info/requires.txt +17 -0
- afterthoughts-0.1.0/afterthoughts.egg-info/top_level.txt +1 -0
- afterthoughts-0.1.0/pyproject.toml +114 -0
- afterthoughts-0.1.0/setup.cfg +4 -0
- afterthoughts-0.1.0/tests/test_alignment.py +890 -0
- afterthoughts-0.1.0/tests/test_chunk.py +288 -0
- afterthoughts-0.1.0/tests/test_encode.py +999 -0
- afterthoughts-0.1.0/tests/test_tokenize.py +318 -0
- afterthoughts-0.1.0/tests/test_utils.py +202 -0
- afterthoughts-0.1.0/tests/test_validation.py +198 -0
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Copyright 2024-2026 Nicholas Gigliotti
|
|
2
|
+
|
|
3
|
+
Apache License
|
|
4
|
+
Version 2.0, January 2004
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
|
179
|
+
|
|
180
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
181
|
+
|
|
182
|
+
To apply the Apache License to your work, attach the following
|
|
183
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
184
|
+
replaced with your own identifying information. (Don't include
|
|
185
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
186
|
+
comment syntax for the file format. We also recommend that a
|
|
187
|
+
file or class name and description of purpose be included on the
|
|
188
|
+
same "printed page" as the copyright notice for easier
|
|
189
|
+
identification within third-party archives.
|
|
190
|
+
|
|
191
|
+
Copyright [yyyy] [name of copyright owner]
|
|
192
|
+
|
|
193
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
194
|
+
you may not use this file except in compliance with the License.
|
|
195
|
+
You may obtain a copy of the License at
|
|
196
|
+
|
|
197
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
198
|
+
|
|
199
|
+
Unless required by applicable law or agreed to in writing, software
|
|
200
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
201
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
202
|
+
See the License for the specific language governing permissions and
|
|
203
|
+
limitations under the License.
|
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: afterthoughts
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sentence-aware embeddings using late chunking with transformers.
|
|
5
|
+
Author-email: Nicholas Gigliotti <ndgigliotti@gmail.com>
|
|
6
|
+
Maintainer-email: Nicholas Gigliotti <ndgigliotti@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: bugs, https://github.com/ndgigliotti/afterthoughts/issues
|
|
9
|
+
Project-URL: changelog, https://github.com/ndgigliotti/afterthoughts/blob/main/CHANGELOG.md
|
|
10
|
+
Project-URL: homepage, https://github.com/ndgigliotti/afterthoughts
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Topic :: Text Processing :: Linguistic
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
License-File: NOTICE
|
|
25
|
+
Requires-Dist: blingfire
|
|
26
|
+
Requires-Dist: joblib
|
|
27
|
+
Requires-Dist: numpy
|
|
28
|
+
Requires-Dist: polars
|
|
29
|
+
Requires-Dist: torch
|
|
30
|
+
Requires-Dist: tqdm
|
|
31
|
+
Requires-Dist: transformers
|
|
32
|
+
Provides-Extra: pandas
|
|
33
|
+
Requires-Dist: pandas; extra == "pandas"
|
|
34
|
+
Provides-Extra: dev
|
|
35
|
+
Requires-Dist: coverage; extra == "dev"
|
|
36
|
+
Requires-Dist: pre-commit; extra == "dev"
|
|
37
|
+
Requires-Dist: pyright; extra == "dev"
|
|
38
|
+
Requires-Dist: pytest; extra == "dev"
|
|
39
|
+
Requires-Dist: ruff; extra == "dev"
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
# Afterthoughts
|
|
43
|
+
|
|
44
|
+
A Python library for late chunking ([Günther et al., 2024](https://arxiv.org/abs/2409.04701)) that preserves context across chunks for improved RAG retrieval, semantic search, clustering, and exploratory data analysis.
|
|
45
|
+
|
|
46
|
+
## Quick Start
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install afterthoughts
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from afterthoughts import Encoder
|
|
54
|
+
|
|
55
|
+
model = Encoder("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
|
|
56
|
+
|
|
57
|
+
docs = [
|
|
58
|
+
"The Amazon rainforest produces 20% of Earth's oxygen. "
|
|
59
|
+
"Deforestation threatens its biodiversity. "
|
|
60
|
+
"Scientists warn of a tipping point.", # 1 document, 3 sentences
|
|
61
|
+
]
|
|
62
|
+
df, X = model.encode(docs, num_sents=1) # 1 sentence per chunk
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
>>> df
|
|
67
|
+
shape: (3, 4)
|
|
68
|
+
┌──────────────┬───────────┬───────────┬─────────────────────────────────┐
|
|
69
|
+
│ document_idx ┆ chunk_idx ┆ num_sents ┆ chunk │
|
|
70
|
+
│ --- ┆ --- ┆ --- ┆ --- │
|
|
71
|
+
│ i64 ┆ i64 ┆ i64 ┆ str │
|
|
72
|
+
╞══════════════╪═══════════╪═══════════╪═════════════════════════════════╡
|
|
73
|
+
│ 0 ┆ 0 ┆ 1 ┆ The Amazon rainforest produces… │
|
|
74
|
+
│ 0 ┆ 1 ┆ 1 ┆ Deforestation threatens its bi… │
|
|
75
|
+
│ 0 ┆ 2 ┆ 1 ┆ Scientists warn of a tipping p… │
|
|
76
|
+
└──────────────┴───────────┴───────────┴─────────────────────────────────┘
|
|
77
|
+
|
|
78
|
+
>>> X.shape
|
|
79
|
+
(3, 384) # 3 sentence embeddings, each with full document context
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## What is Late Chunking?
|
|
83
|
+
|
|
84
|
+
Traditional RAG pipelines split documents into chunks *before* embedding, which loses contextual information. Consider a technical report that opens with "The new lithium-sulfur battery achieved 400 Wh/kg energy density" and later states "The technology could double EV range" or "Its cycle life remains a challenge." When these sentences are embedded separately, the later chunks lose their connection to lithium-sulfur batteries—a search for "lithium battery limitations" might miss the cycle life sentence entirely.
|
|
85
|
+
|
|
86
|
+
**Late chunking inverts this process:**
|
|
87
|
+
|
|
88
|
+
1. **Embed first**: Pass the entire document through the transformer model to get contextually-enriched token embeddings
|
|
89
|
+
2. **Chunk second**: Pool token embeddings into chunks *after* the model has established cross-chunk context
|
|
90
|
+
|
|
91
|
+
This approach ensures that pronouns, references, and contextual cues in each chunk are informed by the full document context.
|
|
92
|
+
|
|
93
|
+
## Why Late Chunking?
|
|
94
|
+
|
|
95
|
+
**The problem:** Document-level embeddings are too coarse for long documents. Traditional chunking loses context—pronouns like "it" or "the technology" become meaningless when separated from their referents.
|
|
96
|
+
|
|
97
|
+
**The solution:** Late chunking embeds the full document first, then pools token embeddings into chunks. Each chunk retains full document context.
|
|
98
|
+
|
|
99
|
+
**Performance:** One forward pass for the entire document, regardless of chunk count.
|
|
100
|
+
|
|
101
|
+
## Features
|
|
102
|
+
|
|
103
|
+
* **Late chunking implementation**: Embed documents first, then pool into chunks for context-aware embeddings
|
|
104
|
+
* **Flexible chunk configuration**: Customize sentences per chunk and overlap between chunks
|
|
105
|
+
* **Sentence boundary detection**: Choice of BlingFire (default), NLTK, pysbd, or syntok for accurate sentence segmentation
|
|
106
|
+
* **Query embedding**: Embed queries in the same space as chunks for semantic search
|
|
107
|
+
* **HuggingFace integration**: Works with any transformer model from the HuggingFace Hub
|
|
108
|
+
* **Automatic mixed precision (AMP)**: Faster inference with reduced memory footprint
|
|
109
|
+
* **Dynamic batching**: Batches by total token count (not sequence count) for optimal GPU utilization
|
|
110
|
+
* **Structured output**: Returns chunks and metadata as Polars/pandas DataFrame for easy manipulation
|
|
111
|
+
* **Memory optimizations**: Optional float16 embedding conversion and dimension truncation for reduced memory
|
|
112
|
+
|
|
113
|
+
## Usage Guide
|
|
114
|
+
|
|
115
|
+
### Basic Usage
|
|
116
|
+
|
|
117
|
+
1. Install the package using pip:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
pip install afterthoughts
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
2. Create an `Encoder` object and load a transformer model.
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from afterthoughts import Encoder
|
|
127
|
+
|
|
128
|
+
# Choose a model which works well with mean-tokens pooling
|
|
129
|
+
model = Encoder("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
3. Prepare a list of documents `docs` (strings) from which to extract chunk embeddings.
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
docs = [
|
|
136
|
+
"I am a document. It has multiple sentences.",
|
|
137
|
+
"I am another document. This one also has sentences.",
|
|
138
|
+
"I am yet another document. Sentences are great.",
|
|
139
|
+
"I'm not like the others. I'm special.",
|
|
140
|
+
]
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
4. Encode and extract chunk embeddings:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
df, X = model.encode(
|
|
147
|
+
docs,
|
|
148
|
+
num_sents=[1, 2], # Extract 1-sentence and 2-sentence chunks
|
|
149
|
+
chunk_overlap=0.5, # Overlap between chunks (in sentences)
|
|
150
|
+
)
|
|
151
|
+
```
|
|
152
|
+
The `encode` method returns a tuple containing a Polars DataFrame and a NumPy array of chunk embeddings. Pass `return_frame="pandas"` for a pandas DataFrame instead.
|
|
153
|
+
|
|
154
|
+
To use a different sentence tokenizer, pass the `sent_tokenizer` parameter:
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
df, X = model.encode(
|
|
158
|
+
docs,
|
|
159
|
+
num_sents=2,
|
|
160
|
+
sent_tokenizer="pysbd", # Options: "blingfire" (default), "nltk", "pysbd", "syntok"
|
|
161
|
+
)
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The DataFrame contains the following columns:
|
|
165
|
+
* `document_idx`: The index of the document from which the chunk was extracted
|
|
166
|
+
* `chunk_idx`: The chunk index within each document
|
|
167
|
+
* `num_sents`: The number of sentences in the chunk
|
|
168
|
+
* `chunk`: The chunk text
|
|
169
|
+
|
|
170
|
+
Additional columns are available when `debug=True`:
|
|
171
|
+
* `embed_idx`: The original embedding index before re-sorting
|
|
172
|
+
* `sequence_idx`: The index of the tokenized sequence (differs from `document_idx` when long documents are split)
|
|
173
|
+
* `batch_idx`: The index of the batch in which the chunk was processed
|
|
174
|
+
|
|
175
|
+
To access the chunk embeddings from the `i`-th document:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
i = 10
|
|
179
|
+
doc_chunks = X[df["document_idx"] == i]
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
This works identically for both Polars and pandas DataFrames.
|
|
183
|
+
|
|
184
|
+
### Using Pandas Instead of Polars
|
|
185
|
+
|
|
186
|
+
Afterthoughts uses Polars by default for its speed and memory efficiency, but pandas is fully supported for users who prefer it or need compatibility with existing code. Simply set `return_frame="pandas"`:
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
df, X = model.encode(
|
|
190
|
+
docs,
|
|
191
|
+
num_sents=2,
|
|
192
|
+
return_frame="pandas", # Return a pandas DataFrame
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# Use familiar pandas operations
|
|
196
|
+
df.groupby("document_idx").size()
|
|
197
|
+
df[df["num_sents"] == 2]
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The pandas integration requires pandas to be installed (`pip install pandas`). The DataFrame schema and all functionality remain identical—only the return type changes.
|
|
201
|
+
|
|
202
|
+
### Memory Optimizations
|
|
203
|
+
|
|
204
|
+
The `Encoder` class supports two memory optimization parameters:
|
|
205
|
+
|
|
206
|
+
#### Dimension Truncation (`truncate_dims`)
|
|
207
|
+
|
|
208
|
+
For models trained with Matryoshka Representation Learning (MRL), you can truncate embeddings to smaller dimensions with minimal quality loss. No retraining required—just slice the first N dimensions.
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from afterthoughts import Encoder
|
|
212
|
+
|
|
213
|
+
# This model was trained with MRL at dimensions [768, 512, 256, 128, 64]
|
|
214
|
+
model = Encoder(
|
|
215
|
+
"tomaarsen/mpnet-base-nli-matryoshka",
|
|
216
|
+
truncate_dims=256, # Truncate to 256 dimensions
|
|
217
|
+
)
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Truncation is applied to token embeddings *before* pooling, which saves both memory and compute during inference.
|
|
221
|
+
|
|
222
|
+
Note: Truncation also works on non-MRL models, but may degrade embedding quality since they weren't trained to preserve information in leading dimensions.
|
|
223
|
+
|
|
224
|
+
#### Float16 Embeddings (`half_embeds`)
|
|
225
|
+
|
|
226
|
+
Convert chunk embeddings to float16 for 2x memory reduction:
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
from afterthoughts import Encoder
|
|
230
|
+
|
|
231
|
+
model = Encoder(
|
|
232
|
+
"sentence-transformers/multi-qa-MiniLM-L6-cos-v1",
|
|
233
|
+
half_embeds=True, # Convert embeddings to float16
|
|
234
|
+
)
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
These options can be combined for additional savings.
|
|
238
|
+
|
|
239
|
+
### Performance Optimizations
|
|
240
|
+
|
|
241
|
+
#### Using Automatic Mixed Precision (AMP)
|
|
242
|
+
|
|
243
|
+
To enable automatic mixed precision, set the `amp` parameter to `True` during initialization. This will automatically lower the numerical precision of the most numerically stable layers, reducing the memory footprint of the model and increasing inference speed. Using AMP generally lets you increase the batch size.
|
|
244
|
+
|
|
245
|
+
```python
|
|
246
|
+
import torch
|
|
247
|
+
from afterthoughts import Encoder
|
|
248
|
+
|
|
249
|
+
model = Encoder(
|
|
250
|
+
"sentence-transformers/multi-qa-MiniLM-L6-cos-v1",
|
|
251
|
+
amp=True,
|
|
252
|
+
amp_dtype=torch.float16, # Choose the lower-precision data type
|
|
253
|
+
)
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
#### Running the Model in 16-Bit Precision
|
|
257
|
+
|
|
258
|
+
To run the model in 16-bit precision, set the `torch_dtype` parameter to `torch.float16` or `torch.bfloat16` during initialization. This will reduce the memory footprint of the model and increase inference speed. Using 16-bit precision also generally lets you increase the batch size. This is similar to using AMP, but it is a cruder and more aggressive approach.
|
|
259
|
+
|
|
260
|
+
```python
|
|
261
|
+
import torch
|
|
262
|
+
from afterthoughts import Encoder
|
|
263
|
+
model = Encoder(
|
|
264
|
+
"sentence-transformers/multi-qa-MiniLM-L6-cos-v1",
|
|
265
|
+
torch_dtype=torch.float16, # Run the model in 16-bit precision
|
|
266
|
+
)
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Alternatively, you can convert the model to 16-bit precision after it has been loaded:
|
|
270
|
+
|
|
271
|
+
```python
|
|
272
|
+
from afterthoughts import Encoder
|
|
273
|
+
|
|
274
|
+
model = Encoder("sentence-transformers/multi-qa-MiniLM-L6-cos-v1")
|
|
275
|
+
model.half() # Convert the model to 16-bit precision
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
### Logging
|
|
279
|
+
|
|
280
|
+
Afterthoughts uses Python's standard logging module for diagnostic output. By default, logging is silent. To enable logging:
|
|
281
|
+
|
|
282
|
+
```python
|
|
283
|
+
import afterthoughts
|
|
284
|
+
|
|
285
|
+
# Quick setup with configure_logging
|
|
286
|
+
afterthoughts.configure_logging(level="INFO") # INFO, DEBUG, WARNING, etc.
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Or use Python's logging module directly for more control:
|
|
290
|
+
|
|
291
|
+
```python
|
|
292
|
+
import logging
|
|
293
|
+
|
|
294
|
+
# Enable debug output from Afterthoughts
|
|
295
|
+
logging.getLogger("afterthoughts").setLevel(logging.DEBUG)
|
|
296
|
+
logging.basicConfig()
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
**Log levels:**
|
|
300
|
+
- `INFO`: Model loading, compilation, preprocessing time
|
|
301
|
+
- `DEBUG`: Batch sizes, token counts, and other diagnostic details
|
|
302
|
+
|
|
303
|
+
### Instruct-Style Embedding Models
|
|
304
|
+
|
|
305
|
+
Many modern embedding models require instruction prefixes to achieve optimal performance. Afterthoughts supports these models through `query_prompt` and `document_prompt` parameters.
|
|
306
|
+
|
|
307
|
+
#### E5-Instruct Models
|
|
308
|
+
|
|
309
|
+
E5-instruct models (e5-mistral-7b-instruct, multilingual-e5-large-instruct) require a task instruction for queries but not for documents:
|
|
310
|
+
|
|
311
|
+
```python
|
|
312
|
+
from afterthoughts import Encoder
|
|
313
|
+
|
|
314
|
+
model = Encoder(
|
|
315
|
+
"intfloat/multilingual-e5-large-instruct",
|
|
316
|
+
query_prompt="Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: ",
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
# Queries use the prompt automatically
|
|
320
|
+
query_embeds = model.encode_queries(["how much protein should a female eat"])
|
|
321
|
+
|
|
322
|
+
# Documents are encoded without any prompt
|
|
323
|
+
df, X = model.encode(docs, num_sents=2)
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
#### BGE Models
|
|
327
|
+
|
|
328
|
+
BGE models use a simpler prefix for queries:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
model = Encoder(
|
|
332
|
+
"BAAI/bge-large-en-v1.5",
|
|
333
|
+
query_prompt="Represent this sentence for searching relevant passages: ",
|
|
334
|
+
)
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
#### Nomic Embed
|
|
338
|
+
|
|
339
|
+
Nomic requires task prefixes for both queries and documents:
|
|
340
|
+
|
|
341
|
+
```python
|
|
342
|
+
model = Encoder(
|
|
343
|
+
"nomic-ai/nomic-embed-text-v1.5",
|
|
344
|
+
query_prompt="search_query: ",
|
|
345
|
+
document_prompt="search_document: ",
|
|
346
|
+
)
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
#### Instructor Models
|
|
350
|
+
|
|
351
|
+
Instructor models use domain-specific instructions for both queries and documents:
|
|
352
|
+
|
|
353
|
+
```python
|
|
354
|
+
model = Encoder(
|
|
355
|
+
"hkunlp/instructor-large",
|
|
356
|
+
query_prompt="Represent the Wikipedia question for retrieving supporting documents: ",
|
|
357
|
+
document_prompt="Represent the Wikipedia document for retrieval: ",
|
|
358
|
+
)
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
#### Per-Call Prompt Override
|
|
362
|
+
|
|
363
|
+
You can override the default prompt for specific calls:
|
|
364
|
+
|
|
365
|
+
```python
|
|
366
|
+
# Use a different task for this specific query
|
|
367
|
+
query_embeds = model.encode_queries(
|
|
368
|
+
queries,
|
|
369
|
+
prompt="Represent the sentence for clustering: ",
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
# Override document prompt for a specific encoding
|
|
373
|
+
df, X = model.encode(
|
|
374
|
+
docs,
|
|
375
|
+
prompt="Represent the scientific abstract: ",
|
|
376
|
+
)
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
#### How Prompts Work with Late Chunking
|
|
380
|
+
|
|
381
|
+
When a document prompt is provided:
|
|
382
|
+
1. The prompt is prepended to each document before tokenization
|
|
383
|
+
2. Sentence boundaries are detected on the original text (without prompt)
|
|
384
|
+
3. Prompt tokens are included in the model input for attention context
|
|
385
|
+
4. Prompt tokens are excluded from chunk mean-pooling (they get `sentence_id=-1`)
|
|
386
|
+
|
|
387
|
+
This ensures that document token embeddings benefit from attending to the prompt during the forward pass, while the final chunk embeddings represent only the actual document content.
|
|
388
|
+
|
|
389
|
+
## Differences from the Late Chunking Paper
|
|
390
|
+
|
|
391
|
+
Afterthoughts implements the core late chunking approach from [Günther et al., 2024](https://arxiv.org/abs/2409.04701) with some implementation choices that differ from the paper's recommendations. For details on special token handling, deduplication strategy, and chunk definitions, see [docs/gunther-et-al-2024-differences.md](docs/gunther-et-al-2024-differences.md).
|
|
392
|
+
|
|
393
|
+
## Known Limitations
|
|
394
|
+
|
|
395
|
+
#### Memory Requirements
|
|
396
|
+
|
|
397
|
+
Since each document can contain many chunks, the memory requirements for this approach can be quite high. Use `half_embeds=True` and `truncate_dims` for reduced memory footprint.
|
|
398
|
+
|
|
399
|
+
#### Sequence Length
|
|
400
|
+
|
|
401
|
+
Late chunking's contextual benefits are bounded by the model's maximum sequence length. Documents exceeding this limit are split into overlapping sequences at sentence boundaries, which can reduce cross-chunk context at the boundaries. For best results, use long-context embedding models (e.g., models supporting 8K+ tokens) with documents that fit within the context window.
|
|
402
|
+
|
|
403
|
+
## Future Work
|
|
404
|
+
|
|
405
|
+
* Add paragraph segmentation
|
|
406
|
+
* Support for additional chunking strategies (e.g., semantic chunking)
|
|
407
|
+
* Support task-specific LoRA adapters (e.g., jina-embeddings-v3)
|
|
408
|
+
|
|
409
|
+
## References
|
|
410
|
+
|
|
411
|
+
Late chunking technique:
|
|
412
|
+
|
|
413
|
+
> Günther, M., Milliken, I., Geuter, J., Mastrapas, G., Wang, B., & Xiao, H. (2024). *Late Chunking: Contextual Chunk Embeddings Using Long-Context Embedding Models*. arXiv:2409.04701. https://arxiv.org/abs/2409.04701
|
|
414
|
+
|
|
415
|
+
## License
|
|
416
|
+
|
|
417
|
+
This project is licensed under the Apache License 2.0.
|
|
418
|
+
|
|
419
|
+
Copyright 2024-2026 Nicholas Gigliotti.
|
|
420
|
+
|
|
421
|
+
You may use, distribute, and modify this project under the terms of the Apache License 2.0. For detailed information, see the [LICENSE](LICENSE) file included in this repository or visit the official [Apache License website](http://www.apache.org/licenses/LICENSE-2.0).
|