fast-universal-sentence-encoder 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.
Files changed (28) hide show
  1. fast_universal_sentence_encoder-0.1.0/.gitattributes +3 -0
  2. fast_universal_sentence_encoder-0.1.0/.github/workflows/publish.yml +70 -0
  3. fast_universal_sentence_encoder-0.1.0/.gitignore +6 -0
  4. fast_universal_sentence_encoder-0.1.0/LICENSE +217 -0
  5. fast_universal_sentence_encoder-0.1.0/PKG-INFO +98 -0
  6. fast_universal_sentence_encoder-0.1.0/README.md +79 -0
  7. fast_universal_sentence_encoder-0.1.0/examples/bench_numbers.py +96 -0
  8. fast_universal_sentence_encoder-0.1.0/examples/quickstart.py +28 -0
  9. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/PKG-INFO +98 -0
  10. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/SOURCES.txt +26 -0
  11. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/dependency_links.txt +1 -0
  12. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/requires.txt +4 -0
  13. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/scm_file_list.json +23 -0
  14. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/scm_version.json +8 -0
  15. fast_universal_sentence_encoder-0.1.0/fast_universal_sentence_encoder.egg-info/top_level.txt +1 -0
  16. fast_universal_sentence_encoder-0.1.0/pyproject.toml +37 -0
  17. fast_universal_sentence_encoder-0.1.0/scripts/build_weights.py +76 -0
  18. fast_universal_sentence_encoder-0.1.0/setup.cfg +4 -0
  19. fast_universal_sentence_encoder-0.1.0/tests/test_embedder.py +82 -0
  20. fast_universal_sentence_encoder-0.1.0/usem3/__init__.py +12 -0
  21. fast_universal_sentence_encoder-0.1.0/usem3/backends/__init__.py +3 -0
  22. fast_universal_sentence_encoder-0.1.0/usem3/backends/numpy.py +99 -0
  23. fast_universal_sentence_encoder-0.1.0/usem3/embedder.py +89 -0
  24. fast_universal_sentence_encoder-0.1.0/usem3/preprocess.py +43 -0
  25. fast_universal_sentence_encoder-0.1.0/usem3/pure_tokenizer.py +350 -0
  26. fast_universal_sentence_encoder-0.1.0/usem3/resources/sp.model +0 -0
  27. fast_universal_sentence_encoder-0.1.0/usem3/resources/weights.npz +0 -0
  28. fast_universal_sentence_encoder-0.1.0/usem3/tokenizer.py +12 -0
@@ -0,0 +1,3 @@
1
+ # Large model files are stored with Git LFS
2
+ usem3/resources/*.npz filter=lfs diff=lfs merge=lfs -text
3
+ usem3/resources/*.model filter=lfs diff=lfs merge=lfs -text
@@ -0,0 +1,70 @@
1
+ name: build-and-publish
2
+
3
+ "on":
4
+ push:
5
+ tags:
6
+ - "v*"
7
+ workflow_dispatch:
8
+
9
+ jobs:
10
+ test:
11
+ name: test (${{ matrix.os }})
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ # amd64, arm64, Windows x64, macOS Apple Silicon
16
+ os:
17
+ - ubuntu-latest # linux amd64
18
+ - ubuntu-24.04-arm # linux arm64
19
+ - windows-latest # windows amd64
20
+ - macos-latest # macOS arm64 (Apple Silicon)
21
+ runs-on: ${{ matrix.os }}
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+ with:
25
+ fetch-depth: 0
26
+ lfs: true
27
+ - uses: actions/setup-python@v5
28
+ with:
29
+ python-version: "3.12"
30
+ - name: Install package
31
+ run: pip install .
32
+ - name: Run tests
33
+ run: python tests/test_embedder.py
34
+
35
+ build:
36
+ name: build sdist + wheel
37
+ needs: test
38
+ runs-on: ubuntu-latest
39
+ steps:
40
+ - uses: actions/checkout@v4
41
+ with:
42
+ fetch-depth: 0
43
+ lfs: true
44
+ - uses: actions/setup-python@v5
45
+ with:
46
+ python-version: "3.12"
47
+ - name: Install build tooling
48
+ run: pip install build
49
+ - name: Build distributions
50
+ run: python -m build
51
+ - uses: actions/upload-artifact@v4
52
+ with:
53
+ name: dist
54
+ path: dist/
55
+
56
+ publish:
57
+ name: publish to PyPI
58
+ needs: build
59
+ runs-on: ubuntu-latest
60
+ environment: pypi
61
+ steps:
62
+ - uses: actions/download-artifact@v4
63
+ with:
64
+ name: dist
65
+ path: dist/
66
+ - name: Publish to PyPI
67
+ uses: pypa/gh-action-pypi-publish@release/v1
68
+ with:
69
+ password: ${{ secrets.PYPI_TOKEN }}
70
+ packages-dir: dist/
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
@@ -0,0 +1,217 @@
1
+ # Apache License, Version 2.0
2
+ #
3
+ # Copyright 2026 cnmoro
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
193
+
194
+ APPENDIX: How to apply the Apache License to your work.
195
+
196
+ To apply the Apache License to your work, attach the following
197
+ boilerplate notice, with the fields enclosed by brackets "[]"
198
+ replaced with your own identifying information. (Don't include
199
+ the brackets!) The text should be enclosed in the appropriate
200
+ comment syntax for the file format. We also recommend that a
201
+ file or class name and description of purpose be included on the
202
+ same "printed page" as the copyright notice for easier
203
+ identification within third-party archives.
204
+
205
+ Copyright [yyyy] [name of copyright owner]
206
+
207
+ Licensed under the Apache License, Version 2.0 (the "License");
208
+ you may not use this file except in compliance with the License.
209
+ You may obtain a copy of the License at
210
+
211
+ http://www.apache.org/licenses/LICENSE-2.0
212
+
213
+ Unless required by applicable law or agreed to in writing, software
214
+ distributed under the License is distributed on an "AS IS" BASIS,
215
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
216
+ See the License for the specific language governing permissions and
217
+ limitations under the License.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: fast-universal-sentence-encoder
3
+ Version: 0.1.0
4
+ Summary: Fast, dependency-light Google USE multilingual v3 sentence embeddings (pure numpy, no C++ deps)
5
+ Author: cnmoro
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/cnmoro/fast-universal-sentence-encoder-3
8
+ Keywords: embeddings,sentence-transformers,universal-sentence-encoder,pt-br,multilingual
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.22
16
+ Provides-Extra: fast
17
+ Requires-Dist: threadpoolctl>=3.1; extra == "fast"
18
+ Dynamic: license-file
19
+
20
+ # fast-universal-sentence-encoder
21
+
22
+ Fast, dependency-light implementation of **Google's universal-sentence-encoder-multilingual v3**.
23
+ Same SentencePiece (128k) vocabulary, same DAN + CNN n-gram encoder, same 512-dim L2-normalized output —
24
+ reproducing the original quantized ONNX at **cosine ≥ 0.99** — with **no C++ dependencies**:
25
+ a pure-Python port of the normalizer + unigram Viterbi and a pure numpy forward pass.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install fast-universal-sentence-encoder
31
+ ```
32
+
33
+ Only needs `numpy`. (Optionally `threadpoolctl` via `pip install "fast-universal-sentence-encoder[fast]"`
34
+ for faster small-batch matmuls.)
35
+
36
+ ## Quickstart
37
+
38
+ ```python
39
+ from usem3 import USE
40
+
41
+ use = USE()
42
+ vec = use.encode("o gato preto correu pelo jardim") # (512,) L2-normalized
43
+ vecs = use.encode(["a menina lê um livro", "investir em renda fixa é seguro"]) # (2, 512)
44
+
45
+ use.similarity("gato preto correu", "o gato preto correu pelo jardim")
46
+ # 0.53
47
+ ```
48
+
49
+ > The package is distributed as `fast-universal-sentence-encoder`; the import
50
+ > name is `usem3`.
51
+
52
+ ### Number denoising
53
+
54
+ USE embeddings are sensitive to number tokens: two sentences that differ only in
55
+ their quantities get cosine ~0.6-0.8 instead of ~1.0, which can hurt semantic
56
+ search when the same content appears with different numbers. Normalizing numbers
57
+ to a placeholder fixes this and is a no-op on clean text:
58
+
59
+ ```python
60
+ use = USE(denoise=True)
61
+ use.similarity("O projeto custou 1 milhão", "O projeto custou 5 milhões")
62
+ # 0.97 (vs 0.80 without denoise)
63
+ ```
64
+
65
+ `denoise=True` replaces number tokens (digits, separators, `%`) with a fixed
66
+ placeholder before embedding. It is OFF by default because it slightly changes
67
+ the embeddings; enable it when your corpus mixes quantities. See
68
+ `examples/bench_numbers.py` for the evaluation.
69
+
70
+ ## Model
71
+
72
+ - **Architecture**: deep averaging network (DAN) with CNN n-gram features (orders 2/3/5)
73
+ followed by a residual DNN, trained multi-task across 16 languages.
74
+ - **Output**: 512-dim, L2-normalized sentence embeddings.
75
+ - **Languages**: ar, de, en, es, fr, it, ja, ko, nl, pl, pt, ru, th, tr, zh, zh-TW.
76
+ - **Size**: the package is ~33 MB (the embedding table is stored 6-bit-quantized
77
+ per chunk, which halves it with no measurable quality loss).
78
+
79
+ ## Files
80
+
81
+ ```
82
+ usem3/
83
+ ├── resources/
84
+ │ ├── sp.model # sentencepiece model (128k vocab)
85
+ │ └── weights.npz # compact 6-bit-quantized weights
86
+ ├── backends/numpy.py # pure numpy forward pass
87
+ ├── pure_tokenizer.py # pure-Python sentencepiece port (normalizer + unigram)
88
+ ├── preprocess.py # optional number denoising
89
+ ├── embedder.py # USE front-end
90
+ └── tokenizer.py # tokenizer front-end (wraps pure_tokenizer)
91
+ scripts/build_weights.py # regenerate weights.npz from float32 weights
92
+ ```
93
+
94
+ ## License
95
+
96
+ Apache-2.0. The underlying model is Google's
97
+ [universal-sentence-encoder-multilingual-3](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3)
98
+ (Apache-2.0).
@@ -0,0 +1,79 @@
1
+ # fast-universal-sentence-encoder
2
+
3
+ Fast, dependency-light implementation of **Google's universal-sentence-encoder-multilingual v3**.
4
+ Same SentencePiece (128k) vocabulary, same DAN + CNN n-gram encoder, same 512-dim L2-normalized output —
5
+ reproducing the original quantized ONNX at **cosine ≥ 0.99** — with **no C++ dependencies**:
6
+ a pure-Python port of the normalizer + unigram Viterbi and a pure numpy forward pass.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install fast-universal-sentence-encoder
12
+ ```
13
+
14
+ Only needs `numpy`. (Optionally `threadpoolctl` via `pip install "fast-universal-sentence-encoder[fast]"`
15
+ for faster small-batch matmuls.)
16
+
17
+ ## Quickstart
18
+
19
+ ```python
20
+ from usem3 import USE
21
+
22
+ use = USE()
23
+ vec = use.encode("o gato preto correu pelo jardim") # (512,) L2-normalized
24
+ vecs = use.encode(["a menina lê um livro", "investir em renda fixa é seguro"]) # (2, 512)
25
+
26
+ use.similarity("gato preto correu", "o gato preto correu pelo jardim")
27
+ # 0.53
28
+ ```
29
+
30
+ > The package is distributed as `fast-universal-sentence-encoder`; the import
31
+ > name is `usem3`.
32
+
33
+ ### Number denoising
34
+
35
+ USE embeddings are sensitive to number tokens: two sentences that differ only in
36
+ their quantities get cosine ~0.6-0.8 instead of ~1.0, which can hurt semantic
37
+ search when the same content appears with different numbers. Normalizing numbers
38
+ to a placeholder fixes this and is a no-op on clean text:
39
+
40
+ ```python
41
+ use = USE(denoise=True)
42
+ use.similarity("O projeto custou 1 milhão", "O projeto custou 5 milhões")
43
+ # 0.97 (vs 0.80 without denoise)
44
+ ```
45
+
46
+ `denoise=True` replaces number tokens (digits, separators, `%`) with a fixed
47
+ placeholder before embedding. It is OFF by default because it slightly changes
48
+ the embeddings; enable it when your corpus mixes quantities. See
49
+ `examples/bench_numbers.py` for the evaluation.
50
+
51
+ ## Model
52
+
53
+ - **Architecture**: deep averaging network (DAN) with CNN n-gram features (orders 2/3/5)
54
+ followed by a residual DNN, trained multi-task across 16 languages.
55
+ - **Output**: 512-dim, L2-normalized sentence embeddings.
56
+ - **Languages**: ar, de, en, es, fr, it, ja, ko, nl, pl, pt, ru, th, tr, zh, zh-TW.
57
+ - **Size**: the package is ~33 MB (the embedding table is stored 6-bit-quantized
58
+ per chunk, which halves it with no measurable quality loss).
59
+
60
+ ## Files
61
+
62
+ ```
63
+ usem3/
64
+ ├── resources/
65
+ │ ├── sp.model # sentencepiece model (128k vocab)
66
+ │ └── weights.npz # compact 6-bit-quantized weights
67
+ ├── backends/numpy.py # pure numpy forward pass
68
+ ├── pure_tokenizer.py # pure-Python sentencepiece port (normalizer + unigram)
69
+ ├── preprocess.py # optional number denoising
70
+ ├── embedder.py # USE front-end
71
+ └── tokenizer.py # tokenizer front-end (wraps pure_tokenizer)
72
+ scripts/build_weights.py # regenerate weights.npz from float32 weights
73
+ ```
74
+
75
+ ## License
76
+
77
+ Apache-2.0. The underlying model is Google's
78
+ [universal-sentence-encoder-multilingual-3](https://tfhub.dev/google/universal-sentence-encoder-multilingual/3)
79
+ (Apache-2.0).
@@ -0,0 +1,96 @@
1
+ """Evaluate whether number/noise tokens corrupt USE embeddings, and show the
2
+ value of the denoise preprocessing step.
3
+
4
+ Findings:
5
+ * USE multilingual v3 is sensitive to number tokens. Two sentences that differ
6
+ only in their numbers get cosine ~0.6-0.8 instead of ~1.0 (harms semantic
7
+ search / similarity for the same content with different quantities).
8
+ * Injecting a number clause into 800/2448 ASSIN2 pairs drops STS spearman
9
+ 0.688 -> 0.640 and entailment AUC 0.752 -> 0.735.
10
+ * Normalizing numbers to a placeholder restores cosine 0.72 -> ~0.99 for
11
+ number-differing paraphrases, and is a no-op on clean text.
12
+
13
+ Run: python bench_numbers.py
14
+ """
15
+
16
+ import sys
17
+ import os
18
+ import re
19
+
20
+ import numpy as np
21
+
22
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
23
+ from usem3 import USE
24
+
25
+ DENOISE = USE(denoise=True)
26
+ RAW = USE()
27
+
28
+
29
+ def cos(a, b):
30
+ return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))
31
+
32
+
33
+ def main():
34
+ print("=== 1. Same meaning, numbers swapped -> raw cosine is low ===")
35
+ pairs = [
36
+ ("O projeto custou 1 milhão de reais.", "O projeto custou 5 milhões de reais."),
37
+ ("Em 2010 foram criados 100 novos empregos.", "Em 2020 foram criados 300 novos empregos."),
38
+ ("A empresa tem 50 funcionários.", "A empresa tem 200 funcionários."),
39
+ ("O preço subiu 10% este ano.", "O preço subiu 25% este ano."),
40
+ ("Foram vendidas 1000 unidades.", "Foram vendidas 2500 unidades."),
41
+ ("A reunião às 10h foi adiada.", "A reunião às 15h foi adiada."),
42
+ ]
43
+ raw_c = []
44
+ den_c = []
45
+ for a, b in pairs:
46
+ r = cos(*RAW.encode([a, b]))
47
+ d = cos(*DENOISE.encode([a, b]))
48
+ raw_c.append(r)
49
+ den_c.append(d)
50
+ print(f" {a[:32]:<34} raw={r:.3f} denoised={d:.3f}")
51
+ print(f" MEAN raw={np.mean(raw_c):.3f} denoised={np.mean(den_c):.3f}")
52
+
53
+ print("\n=== 2. Effect of number-noise at scale (ASSIN2 pt-br) ===")
54
+ try:
55
+ from datasets import load_dataset
56
+ from scipy.stats import spearmanr
57
+ from sklearn.metrics import roc_auc_score
58
+
59
+ ds = load_dataset("nilc-nlp/assin2", split="test")
60
+ s1, s2 = list(ds["premise"]), list(ds["hypothesis"])
61
+ y = np.array(ds["entailment_judgment"])
62
+ g = np.array(ds["relatedness_score"], dtype=float)
63
+ rng = np.random.default_rng(0)
64
+ idx = set(rng.choice(len(s1), 800, replace=False))
65
+
66
+ def inject(t):
67
+ return t + " em 2020 foram 12345 unidades no total"
68
+
69
+ s1n = [inject(t) if i in idx else t for i, t in enumerate(s1)]
70
+ s2n = [inject(t) if i in idx else t for i, t in enumerate(s2)]
71
+
72
+ def score(e1, e2):
73
+ pred = np.array([cos(a, b) for a, b in zip(e1, e2)])
74
+ return spearmanr(pred, g)[0], roc_auc_score(y, pred)
75
+
76
+ e1 = RAW.encode(s1)
77
+ e2 = RAW.encode(s2)
78
+ rho0, auc0 = score(e1, e2)
79
+ e1n = RAW.encode(s1n)
80
+ e2n = RAW.encode(s2n)
81
+ rho1, auc1 = score(e1n, e2n)
82
+ print(f" clean spearman={rho0:.4f} auc={auc0:.4f}")
83
+ print(f" +number clause spearman={rho1:.4f} auc={auc1:.4f}")
84
+ print(f" delta spearman={rho1-rho0:+.4f} auc={auc1-auc0:+.4f}")
85
+ except ImportError as e:
86
+ print(" (skip: need datasets/scipy/scikit-learn:", e, ")")
87
+
88
+ print("\n=== 3. Denoise is a no-op on clean text ===")
89
+ clean = "o gato preto correu pelo jardim e a menina lê um livro na sala."
90
+ r = cos(*RAW.encode([clean, clean]))
91
+ d = cos(*DENOISE.encode([clean, clean]))
92
+ print(f" clean vs clean: raw={r:.4f} denoised={d:.4f}")
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
@@ -0,0 +1,28 @@
1
+ """Quickstart for usem3."""
2
+
3
+ import os
4
+ import sys
5
+
6
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
7
+
8
+ from usem3 import USE
9
+
10
+ use = USE()
11
+
12
+ texts = [
13
+ "o gato preto correu pelo jardim",
14
+ "a menina lê um livro",
15
+ "investir em renda fixa é seguro",
16
+ "O desmatamento da Amazônia contribui para o aumento das emissões de carbono.",
17
+ ]
18
+
19
+ vecs = use.encode(texts)
20
+ print("shape:", vecs.shape) # (4, 512)
21
+
22
+ sim = use.similarity(texts, texts)
23
+ print("similarity matrix (4x4):")
24
+ for row in sim:
25
+ print(" " + " ".join(f"{v:.2f}" for v in row))
26
+
27
+ # single string -> 1-d vector
28
+ print("single:", use.encode("só uma frase").shape)