embedflow 0.1.0__py3-none-any.whl

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 (64) hide show
  1. embedflow/__init__.py +25 -0
  2. embedflow/__main__.py +3 -0
  3. embedflow/analysis.py +192 -0
  4. embedflow/cache/__init__.py +4 -0
  5. embedflow/cache/base.py +28 -0
  6. embedflow/cache/persistent_cache.py +198 -0
  7. embedflow/cli.py +1200 -0
  8. embedflow/compatibility/__init__.py +28 -0
  9. embedflow/compatibility/candidate_gap.py +105 -0
  10. embedflow/compatibility/containment.py +17 -0
  11. embedflow/compatibility/evaluate.py +319 -0
  12. embedflow/compatibility/metrics.py +75 -0
  13. embedflow/compatibility/migration_depth.py +67 -0
  14. embedflow/compatibility/probe.py +34 -0
  15. embedflow/compatibility/report.py +102 -0
  16. embedflow/compatibility/t2.py +64 -0
  17. embedflow/config.py +455 -0
  18. embedflow/data/__init__.py +1 -0
  19. embedflow/data/registry/__init__.py +1 -0
  20. embedflow/data/registry/benchmark_profiles.jsonl +3 -0
  21. embedflow/data/registry/checksums.sha256 +4 -0
  22. embedflow/data/registry/migrations.jsonl +15 -0
  23. embedflow/data/registry/registry_manifest.json +16 -0
  24. embedflow/data/registry/research_summaries.json +55 -0
  25. embedflow/data/registry/schema_version.json +5 -0
  26. embedflow/frozen/T2_V1_FROZEN_SPEC.md +71 -0
  27. embedflow/frozen/T2_V1_FROZEN_SPEC.sha256 +1 -0
  28. embedflow/indexes/__init__.py +5 -0
  29. embedflow/indexes/base.py +60 -0
  30. embedflow/indexes/faiss_backend.py +240 -0
  31. embedflow/indexes/qdrant_backend.py +225 -0
  32. embedflow/metrics/__init__.py +3 -0
  33. embedflow/metrics/latency.py +50 -0
  34. embedflow/migration/__init__.py +3 -0
  35. embedflow/migration/compatibility.py +156 -0
  36. embedflow/migration/facade.py +312 -0
  37. embedflow/migration/materializer.py +190 -0
  38. embedflow/migration/planner.py +78 -0
  39. embedflow/migration/state.py +81 -0
  40. embedflow/models/__init__.py +4 -0
  41. embedflow/models/base.py +31 -0
  42. embedflow/models/huggingface.py +226 -0
  43. embedflow/registry/__init__.py +47 -0
  44. embedflow/registry/loader.py +785 -0
  45. embedflow/registry/matcher.py +197 -0
  46. embedflow/registry/schema.py +266 -0
  47. embedflow/runtime.py +115 -0
  48. embedflow/serving/__init__.py +3 -0
  49. embedflow/serving/api.py +161 -0
  50. embedflow/serving/engine.py +222 -0
  51. embedflow/serving/factory.py +3 -0
  52. embedflow/serving/schemas.py +39 -0
  53. embedflow-0.1.0.dist-info/METADATA +210 -0
  54. embedflow-0.1.0.dist-info/RECORD +64 -0
  55. embedflow-0.1.0.dist-info/WHEEL +5 -0
  56. embedflow-0.1.0.dist-info/entry_points.txt +2 -0
  57. embedflow-0.1.0.dist-info/licenses/LICENSE +178 -0
  58. embedflow-0.1.0.dist-info/top_level.txt +2 -0
  59. src/__init__.py +1 -0
  60. src/embed.py +123 -0
  61. src/probe_features.py +24 -0
  62. src/storage.py +51 -0
  63. src/t2_v1.py +21 -0
  64. src/utils.py +53 -0
@@ -0,0 +1,64 @@
1
+ embedflow/__init__.py,sha256=ttyYjZlh_OhOxQFjmW9VeCDP6Ob8rHtxbUXYHI1sXRY,866
2
+ embedflow/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ embedflow/analysis.py,sha256=O7HKJoYRTIQW_JO-dpaEsk0ALsM2EzDTUM3htz71CbM,8885
4
+ embedflow/cli.py,sha256=n162kBnLvcso-YAKpx7YtYSIsePkyPOaTtZj95rM72g,73249
5
+ embedflow/config.py,sha256=nRZBxAwUikcp47aA_hKn2kz1Z9pTpIcY8zHcshA6Elo,20970
6
+ embedflow/runtime.py,sha256=z9n8YVekEFt_d4b_v78X6aWh4mbhIqtaxz41gM5jQ3c,6515
7
+ embedflow/cache/__init__.py,sha256=tedr6nCGjocGGahMQDD1ZCk39npR35vvv6bO4EX5sj4,184
8
+ embedflow/cache/base.py,sha256=FZNXTmROQDsxtMjAPif8NFepwW3LT3Cwy3UTgIZSLTI,692
9
+ embedflow/cache/persistent_cache.py,sha256=oU_5zwscTjfVQQpubMCabZPJaiv5o0hl_i2ww9_YQ48,10390
10
+ embedflow/compatibility/__init__.py,sha256=AJGj9A_jJr7zb7xOk1NOm6Ic_1JYGs9k6Z1DV0Tg7o4,964
11
+ embedflow/compatibility/candidate_gap.py,sha256=8OBHqXywEozB8p1UA9pnkSGo7WT1ufbQrfWVUZQE-X8,4576
12
+ embedflow/compatibility/containment.py,sha256=oR8YXtQgO_Xm78WdNEsq2L9Tub0cQQhl_WroW0Wz_w8,772
13
+ embedflow/compatibility/evaluate.py,sha256=nqzNSQVo5jz1Ka36Xxgb98QNvhXL79NmRvSbfKJvAYg,14728
14
+ embedflow/compatibility/metrics.py,sha256=WKZ3HdVH_8I5pBDEYOLZFxhIXL_AuGIuUXuTCplRNL4,3652
15
+ embedflow/compatibility/migration_depth.py,sha256=XPs6QOtIosNnR30KRSqqubzatPlh8lQyC8j4874xtHo,3132
16
+ embedflow/compatibility/probe.py,sha256=DXkxX--RNz6R3YF2_0PTuKM92iW0EEQ6x37V4EtFZFE,818
17
+ embedflow/compatibility/report.py,sha256=WBHyxpqsP2FSciTzXxkZqy9fQPurKa621-G3Qh-0scU,5604
18
+ embedflow/compatibility/t2.py,sha256=EMWVyjmaS6qEhLfuA8DJDeKzd7CmMtVpCsI4hwfcfmE,2536
19
+ embedflow/data/__init__.py,sha256=sobXXMploY5aPtMW0CStpdqvJuINinVP7RzwoeF3kfs,49
20
+ embedflow/data/registry/__init__.py,sha256=I3VOImw5Im7Nhe9qbdfJdlBHOwIzY4YOoqezXf-r-oU,54
21
+ embedflow/data/registry/benchmark_profiles.jsonl,sha256=TvK9_J8YA-8QhACYa-agaRWHnTAuFKJ1f8CRwytbblQ,4388
22
+ embedflow/data/registry/checksums.sha256,sha256=QdcuqJTKlkT3aPxFmahsDPQoqy8rXpJRR4Ba4KI7LGs,350
23
+ embedflow/data/registry/migrations.jsonl,sha256=FHHnqTfYfuuljRmoAfuMFH9pgtLBUitdpD9phrkoANU,39100
24
+ embedflow/data/registry/registry_manifest.json,sha256=y_AX10bhUid0BfGvnMVK9NXpz0RYm3ymf5dXuEKJuF8,788
25
+ embedflow/data/registry/research_summaries.json,sha256=_L8voEVvw_wuMNG5RbBefX3PoRtxh5EM7Yo_oOafZyA,2494
26
+ embedflow/data/registry/schema_version.json,sha256=w9hRvP5m2cwaq8Tsi2FRIRDYgCrAvMevMjmprGzsFKk,120
27
+ embedflow/frozen/T2_V1_FROZEN_SPEC.md,sha256=bqNINz1f8lesD6TOCCB6hMZH-1ZwEvLWRZH7BXQo4Jo,2820
28
+ embedflow/frozen/T2_V1_FROZEN_SPEC.sha256,sha256=sDh5kHsCAnLo6mWzV87PO2uhPtJR0mswvvVz1v5Ku2A,65
29
+ embedflow/indexes/__init__.py,sha256=sGFYu1JJJnotXeJ9AcAueG8zyJ_dM5XthUiXtBCuz7c,252
30
+ embedflow/indexes/base.py,sha256=TUzQEQPwJBfocFIFfByEi4FtoSc70tGS5XcQRBjNZ8Q,1723
31
+ embedflow/indexes/faiss_backend.py,sha256=bf2betxhRFaaqgmCnhtlB8mT6iUnJN0PF2TumuBFVSI,13339
32
+ embedflow/indexes/qdrant_backend.py,sha256=r0RyEmm7Qc5eNSc6uS9B-8UG6aa2Zp26-HJ5y_GbFP0,11995
33
+ embedflow/metrics/__init__.py,sha256=quUSPg7lDGG9FTR1ViDUTiIic3DWFEqO50FhV3porL4,114
34
+ embedflow/metrics/latency.py,sha256=8BHrks-5znViJn1CMPynAeoERPESRNHbZMOXvu44N-Q,2508
35
+ embedflow/migration/__init__.py,sha256=wYgp_Gr8W3ZfPSMSJh4vGzRD2gsWQLXiyn1g2srhaPA,96
36
+ embedflow/migration/compatibility.py,sha256=LZADCO9o9vNUMNX-b6gnjDm5L8l84mZlEnZlPtH54dc,8813
37
+ embedflow/migration/facade.py,sha256=oeWrw4Bw7UfIw-9UW6mzyGsjtgieB9KSY1vix3m1GsU,13634
38
+ embedflow/migration/materializer.py,sha256=FmPoYaL4BoomTQ8sZBjUvOzz5t4EhbmV77MU1bND1D0,9343
39
+ embedflow/migration/planner.py,sha256=RMGTX-H0ceTHN-ZSZ4CZkRVHJA7H-X82iN4CloQZB3A,4048
40
+ embedflow/migration/state.py,sha256=aSSXNI_l6y4yryUcaOw2P2ASNadeNxBWIl-bweRcSTY,4280
41
+ embedflow/models/__init__.py,sha256=igk-3hE0CoBVO9TRlkzg1VLf6JB4BGGyBBhkOuBBIxU,231
42
+ embedflow/models/base.py,sha256=E8WmLKc9w5UQM1edb_y1RHvOUUQHaWS4gVzP_TWGtI4,830
43
+ embedflow/models/huggingface.py,sha256=Ns6KwQ16mda0H6b5nJ6UzYY4toqw9IOhVncMUYOIF3s,11950
44
+ embedflow/registry/__init__.py,sha256=Ioms1I8IpCU6qI8Sbo_-FVgkOfj8LwoKdgdLwmYwSOM,1063
45
+ embedflow/registry/loader.py,sha256=e-gSG3gXlCbJWK3ltAam1nS7QaOfx5FK7ZTMj-8UKqk,42104
46
+ embedflow/registry/matcher.py,sha256=xrjA8qcsRRKD1yECJa9MHp3fMQJ0RNioN57Iru4S0IQ,8741
47
+ embedflow/registry/schema.py,sha256=72OoY8WcfLusao69Xf9aQCq0r4x_SLNxkXLSjhND2Wo,13279
48
+ embedflow/serving/__init__.py,sha256=6fMxYNv0TcGO2Kk-f3pMKD9l-p-8GxtliFLlYmYj0s4,67
49
+ embedflow/serving/api.py,sha256=tvmuy3zdOP5QoNZ_1Pjc2GBMuv5ntkgCeMbfBW0mYK0,9718
50
+ embedflow/serving/engine.py,sha256=GLex8TW4gOf9RqyS4Ts-NrLS2vGwffY2O_2v1XIuWMU,13965
51
+ embedflow/serving/factory.py,sha256=81jp0PxbW3Nm0Sy96VsSSSw-yxkU7H2bOGfAKHxl380,61
52
+ embedflow/serving/schemas.py,sha256=cNyTBfGfIuFs5Iv4xCqvCeft6jk51rRucNCLO7P0IAU,1258
53
+ embedflow-0.1.0.dist-info/licenses/LICENSE,sha256=zNpul0odgfK2N1NDGJJObR26Wqk7rCgDEVJ5kRfV3a8,10205
54
+ src/__init__.py,sha256=ND_FEmf-MoSPOTTZF3LjNPf5vfu4MKF13BD-PF5cRu4,62
55
+ src/embed.py,sha256=9PHoyjUDaL1yk2k3nXOLgJsLoP-1_KnJGhr59TE4DrY,7767
56
+ src/probe_features.py,sha256=t5AKGmlE60eqyVF27-ajgFur-7iqxy9-e_PiHZmYKZg,1749
57
+ src/storage.py,sha256=L3uvThjIWY6gEO6bAX_Pn1tbsw6OipmKgPuImdlcNUQ,3166
58
+ src/t2_v1.py,sha256=AH8ILrah2tAlmj2lA7WHiEDnwrt1PPrjjA1kuU-GXHM,1299
59
+ src/utils.py,sha256=ul4w7p6CTUKO-FpQn6V4rXreEabMGIhwponbdNcUVMQ,2165
60
+ embedflow-0.1.0.dist-info/METADATA,sha256=XSkm76irfA9f3FVwIGyljpBHX5PPyPUYNbdsI3LxVtA,7387
61
+ embedflow-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
62
+ embedflow-0.1.0.dist-info/entry_points.txt,sha256=w7hwsj31zKortT7VcjPY7nUPQHGM2KEJzF80cxwcoUU,49
63
+ embedflow-0.1.0.dist-info/top_level.txt,sha256=DYwVeyaEuIxHJJGK9uJGqZUQvdiCuJQSuVzpHT-cXbI,14
64
+ embedflow-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ embedflow = embedflow.cli:main
@@ -0,0 +1,178 @@
1
+ Copyright 2026 Arnav Srivastav
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
@@ -0,0 +1,2 @@
1
+ embedflow
2
+ src
src/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """EmbedFlow million-document scale experiment components."""
src/embed.py ADDED
@@ -0,0 +1,123 @@
1
+ from __future__ import annotations
2
+ import gc, json, time
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from .storage import write_shard, valid_shard
6
+ from .utils import progress
7
+
8
+ class DummyEncoder:
9
+ def __init__(self, dimension:int, seed:int): self.dimension=dimension; self.seed=seed
10
+ def encode(self,texts,role='document'):
11
+ out=[]
12
+ for text in texts:
13
+ import hashlib
14
+ rng=np.random.default_rng(int(hashlib.sha256((str(self.seed)+role+'\0'+text).encode()).hexdigest()[:16],16))
15
+ v=rng.normal(size=self.dimension).astype('float32'); v/=max(np.linalg.norm(v),1e-12); out.append(v)
16
+ return np.asarray(out,dtype='float32'),sum(max(1,len(x.split())) for x in texts)
17
+ def close(self): pass
18
+
19
+ class TransformersEncoder:
20
+ """Qwen-style encoder following the frozen model contract.
21
+
22
+ The implementation deliberately supports CPU fallback for the tiny local
23
+ verification run. Remote jobs still select CUDA automatically and only
24
+ the batch size may be reduced after an OOM.
25
+ """
26
+ def __init__(self, config:dict, model_dir:Path, device='cuda'):
27
+ import torch
28
+ from transformers import AutoModel, AutoTokenizer
29
+ self.c=config; self.device=torch.device(device); self.tok=AutoTokenizer.from_pretrained(str(model_dir),revision=config['revision'],local_files_only=True,use_fast=True)
30
+ self.tok.padding_side=config.get('padding_side','left'); self.tok.truncation_side='right'; self.tok.pad_token=self.tok.pad_token or self.tok.eos_token
31
+ if self.device.type == 'cuda':
32
+ dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() and config.get('dtype_preference')=='bfloat16' else torch.float16
33
+ else:
34
+ dtype=torch.float32
35
+ self.net=AutoModel.from_pretrained(str(model_dir),revision=config['revision'],local_files_only=True,torch_dtype=dtype,low_cpu_mem_usage=True,attn_implementation='sdpa').eval().to(self.device)
36
+ def encode(self,texts,role='document'):
37
+ import torch
38
+ templ=self.c.get('query_instruction','') if role=='query' else self.c.get('document_instruction','')
39
+ texts=[templ.replace('{text}',x) if templ else x for x in texts]
40
+ e=self.tok(texts,padding=True,truncation=True,max_length=int(self.c.get('max_length',8192)),return_tensors='pt').to(self.device)
41
+ amp = self.device.type == 'cuda'
42
+ context = torch.autocast('cuda',dtype=next(self.net.parameters()).dtype) if amp else torch.autocast('cpu', enabled=False)
43
+ with torch.inference_mode(), context:
44
+ o=self.net(**e); h=o.last_hidden_state; pos=torch.full((h.shape[0],),h.shape[1]-1,dtype=torch.long,device=h.device); v=h[torch.arange(h.shape[0],device=h.device),pos]; v=torch.nn.functional.normalize(v.float(),p=2,dim=1)
45
+ return v.cpu().numpy().astype('float32'),int(e['attention_mask'].sum().item())
46
+ def close(self):
47
+ import torch
48
+ del self.net,self.tok; gc.collect()
49
+ if torch.cuda.is_available(): torch.cuda.empty_cache()
50
+
51
+ class SentenceEncoder:
52
+ def __init__(self, config:dict, model_dir:Path, device='cuda'):
53
+ from sentence_transformers import SentenceTransformer
54
+ kwargs={'device':device}
55
+ # Older sentence-transformers versions accept local_files_only only
56
+ # through the underlying HF loader; a local snapshot is always passed
57
+ # here, so avoiding the kwarg keeps this compatible across versions.
58
+ self.model=SentenceTransformer(str(model_dir),**kwargs)
59
+ self.model.max_seq_length=int(config.get('max_length',512))
60
+ def encode(self,texts,role='document'):
61
+ v=self.model.encode(texts,batch_size=32,convert_to_numpy=True,normalize_embeddings=True,show_progress_bar=False)
62
+ return np.asarray(v,dtype='float32'),sum(max(1,len(x.split())) for x in texts)
63
+ def close(self): del self.model; gc.collect()
64
+
65
+ def make_encoder(config, model_dir:Path, smoke=False, seed=20270823, device='cuda'):
66
+ if smoke: return DummyEncoder(int(config['dimension']),seed+hash(config['model_id'])%10000)
67
+ return SentenceEncoder(config,model_dir,device) if str(config['model_id']).startswith('sentence-transformers/') else TransformersEncoder(config,model_dir,device)
68
+
69
+ def is_oom(exc: Exception) -> bool:
70
+ return 'out of memory' in str(exc).lower() or 'cuda oom' in str(exc).lower()
71
+
72
+ def encode_resilient(encoder, texts:list[str], role:str, batch_size:int, desc: str = '') -> tuple[np.ndarray,int,int]:
73
+ values=[]; tokens=0; i=0; bs=max(1,int(batch_size)); min_bs=1
74
+ bar = None
75
+ if desc:
76
+ try:
77
+ from tqdm.auto import tqdm
78
+ import os
79
+ bar=tqdm(total=len(texts), desc=desc, unit='row', dynamic_ncols=True,
80
+ disable=os.environ.get('EMBEDFLOW_NO_PROGRESS','').lower() in {'1','true','yes'})
81
+ except Exception:
82
+ bar=None
83
+ try:
84
+ while i<len(texts):
85
+ take=min(bs,len(texts)-i)
86
+ try:
87
+ v,t=encoder.encode(texts[i:i+take],role); values.append(v);tokens+=t;i+=take
88
+ if bar is not None: bar.update(take)
89
+ except Exception as e:
90
+ if not is_oom(e) or bs<=min_bs: raise
91
+ try:
92
+ import torch; torch.cuda.empty_cache()
93
+ except Exception: pass
94
+ gc.collect(); bs=max(min_bs,bs//2)
95
+ finally:
96
+ if bar is not None: bar.close()
97
+ return (np.concatenate(values) if values else np.empty((0,getattr(encoder,'dimension',0)),dtype='float32')),tokens,bs
98
+
99
+ def encode_pool(encoder, ids:list[str], texts:list[str], out:Path, dimension:int, shard_rows:int, role:str, metadata:dict, resume=True, batch_size:int=32):
100
+ out.mkdir(parents=True,exist_ok=True); total=0; tokens=0
101
+ for start in progress(range(0,len(ids),shard_rows), desc=f'{metadata.get("model_key", "model")} {role}', unit='shard', total=(len(ids)+shard_rows-1)//shard_rows):
102
+ idx=start//shard_rows; end=min(len(ids),start+shard_rows)
103
+ if resume and valid_shard(out,idx,dimension): total+=end-start; continue
104
+ batch=ids[start:end]; vals,tok,used_bs=encode_resilient(encoder,texts[start:end],role,batch_size); tokens+=tok
105
+ write_shard(out,idx,batch,vals,dict(metadata,start=start,end=end,tokens=tok,role=role,batch_size=used_bs))
106
+ total+=len(batch)
107
+ return {'rows':total,'tokens':tokens,'shards':(len(ids)+shard_rows-1)//shard_rows}
108
+
109
+ def encode_pool_cached(encoder, ids:list[str], texts:list[str], out:Path, dimension:int, shard_rows:int, role:str, metadata:dict, cache:dict[str,np.ndarray], resume=True, batch_size:int=32):
110
+ """Encode a canonical row order while reusing already-produced vectors."""
111
+ out.mkdir(parents=True,exist_ok=True); total=0; tokens=0
112
+ for start in progress(range(0,len(ids),shard_rows), desc=f'{metadata.get("model_key", "model")} {role} (cached)', unit='shard', total=(len(ids)+shard_rows-1)//shard_rows):
113
+ idx=start//shard_rows; end=min(len(ids),start+shard_rows)
114
+ if resume and valid_shard(out,idx,dimension): total+=end-start; continue
115
+ chunk_ids=ids[start:end]; missing=[i for i,x in enumerate(chunk_ids) if x not in cache]
116
+ vals=np.empty((len(chunk_ids),dimension),dtype='float32')
117
+ for i,x in enumerate(chunk_ids):
118
+ if x in cache: vals[i]=cache[x]
119
+ if missing:
120
+ fresh,tok,used_bs=encode_resilient(encoder,[texts[start+i] for i in missing],role,batch_size); tokens+=tok
121
+ for j,i in enumerate(missing): vals[i]=fresh[j]
122
+ write_shard(out,idx,chunk_ids,vals,dict(metadata,start=start,end=end,tokens=tokens,role=role,batch_size=used_bs if missing else batch_size)); total+=len(chunk_ids)
123
+ return {'rows':total,'tokens':tokens,'shards':(len(ids)+shard_rows-1)//shard_rows}
src/probe_features.py ADDED
@@ -0,0 +1,24 @@
1
+ from __future__ import annotations
2
+ import numpy as np
3
+
4
+ def top10(records): return [x[0] for x in records[:10]]
5
+ def build_features(candidates:list[list[tuple[str,float,int]]], target_scores:dict[str,float], ks=(10,20,50,100,200,500)):
6
+ # candidates are source-ranked (id, source_score, source_rank); target_scores are finite-pool scores.
7
+ rerank={k:sorted(candidates[:k],key=lambda x:(-target_scores[x[0]],x[2])) for k in ks}; final=top10(rerank[max(ks)])
8
+ def stability(k): return len(set(top10(rerank[k]))&set(final))/10
9
+ def entrants(a,b): return len(set(top10(rerank[b]))-set(top10(rerank[a])))
10
+ e50=entrants(50,100); e100=entrants(100,200); e200=entrants(200,500)
11
+ margins=[]
12
+ for q in [candidates]:
13
+ t10=rerank[50][min(9,len(rerank[50])-1)][1] if not target_scores else target_scores[rerank[50][min(9,len(rerank[50])-1)][0]]
14
+ new=[target_scores[x[0]] for x in q[50:100]]; margins.append(t10-max(new) if new else 0.0)
15
+ deepest=max((x[2] for x in rerank[500][:10]),default=0)
16
+ vals={
17
+ 'probe_residual_tail_50_mean':1-stability(50),'stability_to_500_50_mean':stability(50),
18
+ 'deepest_p90':float(deepest),'late_tail_area':(e50/10+e100/10+e200/10)/3,
19
+ 'last_shell_any_rate':float(e200>0),'fraction_margin_nonpositive':float(np.mean(np.asarray(margins)<=0)),
20
+ 'p_any_entrant_50_100':float(e50>0),'p_any_entrant_100_200':float(e100>0),'p_any_entrant_200_500':float(e200>0),
21
+ 'mean_entrants_50_100':float(e50),'mean_entrants_100_200':float(e100),'mean_entrants_200_500':float(e200),
22
+ 'deepest_source_rank_top10':deepest,'stability_10_20':stability(10),'stability_20_50':stability(20),'stability_50_100':len(set(top10(rerank[50]))&set(top10(rerank[100])))/10,
23
+ }
24
+ return vals
src/storage.py ADDED
@@ -0,0 +1,51 @@
1
+ from __future__ import annotations
2
+ import json, hashlib
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from .utils import sha256_file, atomic_json
6
+
7
+ def write_shard(root: Path, index: int, ids: list[str], vectors: np.ndarray, metadata: dict) -> dict:
8
+ root.mkdir(parents=True,exist_ok=True); arr=np.asarray(vectors)
9
+ if arr.ndim!=2 or len(ids)!=arr.shape[0] or not np.isfinite(arr).all(): raise ValueError('invalid shard')
10
+ tmp=root/f'.shard-{index:06d}.npy.tmp'; p=root/f'shard-{index:06d}.npy';
11
+ with tmp.open('wb') as f: np.save(f,arr.astype(np.float16),allow_pickle=False)
12
+ tmp.replace(p)
13
+ ip=root/f'shard-{index:06d}.ids.json'; ip.write_text(json.dumps(ids,ensure_ascii=False));
14
+ meta=dict(metadata,shard=index,rows=len(ids),dimension=int(arr.shape[1]),dtype='float16',array_sha256=sha256_file(p),ids_sha256=sha256_file(ip))
15
+ atomic_json(root/f'shard-{index:06d}.json',meta); (root/f'shard-{index:06d}.done').write_text(meta['array_sha256']+'\n'); return meta
16
+
17
+ def valid_shard(root: Path,index:int,dimension:int|None=None)->bool:
18
+ p=root/f'shard-{index:06d}.npy'; m=root/f'shard-{index:06d}.json'; d=root/f'shard-{index:06d}.done'
19
+ if not (p.exists() and m.exists() and d.exists()): return False
20
+ try:
21
+ meta=json.loads(m.read_text()); a=np.load(p,mmap_mode='r')
22
+ return a.ndim==2 and (dimension is None or a.shape[1]==dimension) and meta.get('array_sha256')==sha256_file(p) and d.read_text().strip()==meta['array_sha256']
23
+ except Exception:return False
24
+
25
+ def load_shards(root: Path, dimension:int|None=None)->tuple[list[str],np.ndarray]:
26
+ arrays=[];ids=[]
27
+ for p in sorted(root.glob('shard-*.npy')):
28
+ i=int(p.stem.split('-')[1]);
29
+ if not valid_shard(root,i,dimension): raise ValueError(f'invalid shard {p}')
30
+ arrays.append(np.load(p)); ids.extend(json.loads((root/f'shard-{i:06d}.ids.json').read_text()))
31
+ if not arrays: raise ValueError(f'no shards in {root}')
32
+ return ids,np.concatenate(arrays).astype(np.float32)
33
+
34
+ def iter_shards(root: Path, dimension: int|None=None):
35
+ """Yield (ids, mmap vectors, metadata) without concatenating the corpus."""
36
+ for p in sorted(root.glob('shard-*.npy')):
37
+ i=int(p.stem.split('-')[1])
38
+ if not valid_shard(root,i,dimension): raise ValueError(f'invalid shard {p}')
39
+ ids=json.loads((root/f'shard-{i:06d}.ids.json').read_text())
40
+ yield ids,np.load(p,mmap_mode='r'),json.loads((root/f'shard-{i:06d}.json').read_text())
41
+
42
+ def vector_lookup(root: Path, ids: list[str], dimension: int|None=None) -> np.ndarray:
43
+ """Read only requested rows, grouped by shard; output follows ``ids``."""
44
+ wanted={str(x):i for i,x in enumerate(ids)}; out=None; found=set()
45
+ for shard_ids, arr, _ in iter_shards(root,dimension):
46
+ local=[(j,wanted[x]) for j,x in enumerate(shard_ids) if x in wanted]
47
+ if local:
48
+ if out is None: out=np.empty((len(ids),arr.shape[1]),dtype='float32')
49
+ for j,pos in local: out[pos]=np.asarray(arr[j],dtype='float32'); found.add(shard_ids[j])
50
+ if out is None or len(found)!=len(wanted): raise KeyError(f'missing {len(wanted)-len(found)} vector IDs')
51
+ return out
src/t2_v1.py ADDED
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ import hashlib, json
4
+
5
+ K_VALUES=(10,20,50,100,200,500)
6
+ def verify_t2_hash(root:Path)->None:
7
+ p=root/'frozen/T2_V1_FROZEN_SPEC.md'; expected=(root/'frozen/T2_V1_FROZEN_SPEC.sha256').read_text().strip(); actual=hashlib.sha256(p.read_bytes()).hexdigest()
8
+ if expected!=actual: raise RuntimeError(f'T2 frozen hash mismatch: {actual} != {expected}')
9
+
10
+ def decide(features:dict)->str:
11
+ safe=(features['probe_residual_tail_50_mean']<=.05 and features['deepest_p90']<=200 and features['late_tail_area']<=.20)
12
+ if safe:return 'SAFE'
13
+ guard=(features['probe_residual_tail_50_mean']>.10 or features['stability_to_500_50_mean']<.90 or features['last_shell_any_rate']>.25 or features['fraction_margin_nonpositive']>.50)
14
+ return 'UNSAFE_OR_UNCERTAIN' if guard else 'EXPAND'
15
+
16
+ def blind_predictions(rows:list[dict], out:Path)->None:
17
+ keys=['pair','dataset','probe_residual_tail_50_mean','stability_to_500_50_mean','deepest_p90','late_tail_area','last_shell_any_rate','fraction_margin_nonpositive']
18
+ out.parent.mkdir(parents=True,exist_ok=True)
19
+ with out.open('w') as f:
20
+ f.write(','.join(keys+['T2_v1_decision'])+'\n')
21
+ for r in rows:f.write(','.join(str(r.get(k,'')) for k in keys+[None])[:-1]+str(decide(r))+'\n')
src/utils.py ADDED
@@ -0,0 +1,53 @@
1
+ from __future__ import annotations
2
+ import hashlib, json, os, platform, subprocess, time
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ def progress(iterable, *, desc: str = '', total=None, unit: str = 'it', leave: bool = True):
7
+ """Return a tqdm iterator with optional nested-bar cleanup.
8
+
9
+ Set ``EMBEDFLOW_NO_PROGRESS=1`` for quiet runs. ``leave=False`` is useful
10
+ for fine-grained query bars nested inside a shard bar.
11
+ """
12
+ try:
13
+ from tqdm.auto import tqdm
14
+ disabled = os.environ.get('EMBEDFLOW_NO_PROGRESS', '').lower() in {'1', 'true', 'yes'}
15
+ return tqdm(iterable, desc=desc, total=total, unit=unit,
16
+ disable=disabled, dynamic_ncols=True, leave=leave)
17
+ except Exception:
18
+ return iterable
19
+
20
+ def sha256_file(path: Path, block: int = 1024 * 1024) -> str:
21
+ h = hashlib.sha256()
22
+ with path.open('rb') as f:
23
+ for b in iter(lambda: f.read(block), b''): h.update(b)
24
+ return h.hexdigest()
25
+
26
+ def stable_hash(value: str, seed: int = 0) -> str:
27
+ return hashlib.sha256(f'{seed}\0{value}'.encode()).hexdigest()
28
+
29
+ def atomic_json(path: Path, value: Any) -> None:
30
+ path.parent.mkdir(parents=True, exist_ok=True)
31
+ tmp = path.with_suffix(path.suffix + '.tmp')
32
+ tmp.write_text(json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False))
33
+ tmp.replace(path)
34
+
35
+ def load_yaml(path: Path) -> dict[str, Any]:
36
+ import yaml
37
+ return yaml.safe_load(path.read_text())
38
+
39
+ def command_output(args: list[str]) -> str:
40
+ try: return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT, timeout=30)
41
+ except Exception as e: return f'command failed: {e}'
42
+
43
+ def environment_snapshot() -> dict[str, Any]:
44
+ import sys
45
+ out = {'python': sys.version, 'platform': platform.platform(), 'hostname': platform.node(), 'cpu': platform.processor()}
46
+ try:
47
+ import torch
48
+ out.update({'torch': torch.__version__, 'cuda': torch.version.cuda, 'cuda_count': torch.cuda.device_count()})
49
+ except Exception as e: out['torch_error'] = repr(e)
50
+ out['nvidia_smi'] = command_output(['nvidia-smi'])
51
+ return out
52
+
53
+ def now() -> str: return time.strftime('%Y%m%d-%H%M%S')