omnicache 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 (47) hide show
  1. omnicache-0.1.0/LICENSE +202 -0
  2. omnicache-0.1.0/MANIFEST.in +6 -0
  3. omnicache-0.1.0/PKG-INFO +102 -0
  4. omnicache-0.1.0/README.md +74 -0
  5. omnicache-0.1.0/omnicache/__init__.py +27 -0
  6. omnicache-0.1.0/omnicache/client/__init__.py +0 -0
  7. omnicache-0.1.0/omnicache/client/agent.py +179 -0
  8. omnicache-0.1.0/omnicache/client/grid.py +80 -0
  9. omnicache-0.1.0/omnicache/client/http.py +251 -0
  10. omnicache-0.1.0/omnicache/config.py +225 -0
  11. omnicache-0.1.0/omnicache/configs/connector_receiver.json +28 -0
  12. omnicache-0.1.0/omnicache/configs/connector_sender.json +22 -0
  13. omnicache-0.1.0/omnicache/configs/profile_parity.json +14 -0
  14. omnicache-0.1.0/omnicache/configs/profile_production.json +9 -0
  15. omnicache-0.1.0/omnicache/connector.py +222 -0
  16. omnicache-0.1.0/omnicache/core/__init__.py +6 -0
  17. omnicache-0.1.0/omnicache/core/codec_bridge.py +103 -0
  18. omnicache-0.1.0/omnicache/core/codec_loader.py +267 -0
  19. omnicache-0.1.0/omnicache/core/codec_modules.py +122 -0
  20. omnicache-0.1.0/omnicache/core/contract.py +135 -0
  21. omnicache-0.1.0/omnicache/core/features.py +52 -0
  22. omnicache-0.1.0/omnicache/core/finalizer.py +146 -0
  23. omnicache-0.1.0/omnicache/core/hf_reference.py +208 -0
  24. omnicache-0.1.0/omnicache/core/paged.py +205 -0
  25. omnicache-0.1.0/omnicache/core/pipeline.py +211 -0
  26. omnicache-0.1.0/omnicache/core/reference.py +55 -0
  27. omnicache-0.1.0/omnicache/core/rope.py +178 -0
  28. omnicache-0.1.0/omnicache/core/sched_logic.py +530 -0
  29. omnicache-0.1.0/omnicache/core/store.py +514 -0
  30. omnicache-0.1.0/omnicache/core/streams.py +69 -0
  31. omnicache-0.1.0/omnicache/plugin.py +21 -0
  32. omnicache-0.1.0/omnicache/scheduler_side.py +57 -0
  33. omnicache-0.1.0/omnicache/tools/__init__.py +0 -0
  34. omnicache-0.1.0/omnicache/tools/build_rope_bank.py +63 -0
  35. omnicache-0.1.0/omnicache/tools/export_codec_bundle.py +77 -0
  36. omnicache-0.1.0/omnicache/tools/produce_u_hf.py +68 -0
  37. omnicache-0.1.0/omnicache/tools/store_gc.py +50 -0
  38. omnicache-0.1.0/omnicache/vllm_facts.py +158 -0
  39. omnicache-0.1.0/omnicache/worker_side.py +494 -0
  40. omnicache-0.1.0/omnicache.egg-info/PKG-INFO +102 -0
  41. omnicache-0.1.0/omnicache.egg-info/SOURCES.txt +45 -0
  42. omnicache-0.1.0/omnicache.egg-info/dependency_links.txt +1 -0
  43. omnicache-0.1.0/omnicache.egg-info/entry_points.txt +2 -0
  44. omnicache-0.1.0/omnicache.egg-info/requires.txt +13 -0
  45. omnicache-0.1.0/omnicache.egg-info/top_level.txt +1 -0
  46. omnicache-0.1.0/pyproject.toml +50 -0
  47. omnicache-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ include README.md LICENSE pyproject.toml
2
+ recursive-include omnicache/configs *.json
3
+ prune omnicache/server
4
+ prune omnicache/tests
5
+ prune omnicache/server_tests
6
+ global-exclude __pycache__ *.pyc *.sh *.proto.* .venv
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.4
2
+ Name: omnicache
3
+ Version: 0.1.0
4
+ Summary: A unified-representation KV cache for vLLM: one model's KV cache becomes reusable by another model
5
+ Author: omnicache contributors
6
+ License: Apache-2.0
7
+ Project-URL: Codec weights, https://www.modelscope.ai/models/Zachary777/omnicache-qwen3-codec
8
+ Keywords: vllm,kv-cache,kv-connector,llm,inference
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: vllm==0.15.1
17
+ Requires-Dist: torch>=2.4
18
+ Requires-Dist: numpy
19
+ Requires-Dist: safetensors>=0.4
20
+ Requires-Dist: transformers>=4.51
21
+ Requires-Dist: huggingface_hub
22
+ Requires-Dist: modelscope
23
+ Provides-Extra: redis
24
+ Requires-Dist: redis>=5; extra == "redis"
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest>=8; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # omnicache
30
+
31
+ A unified-representation KV cache for vLLM. One model reads a passage; another model answers questions about it
32
+ without reading it again.
33
+
34
+ The sender's vLLM instance encodes the KV cache of the passage into a shared representation `U` (1,024 dims per
35
+ token, 2 KB/token in bf16) and writes it to a store. The receiver's vLLM instance, running a different model, decodes
36
+ `U` into its own KV cache, writes it into its paged KV memory and prefills only the question.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install omnicache # pulls vllm==0.15.1
42
+ ```
43
+
44
+ The base models are the official Qwen3 checkpoints. The codec weights (one encoder/decoder pair per model) are
45
+ downloaded on first start from ModelScope
46
+ ([Zachary777/omnicache-qwen3-codec](https://www.modelscope.ai/models/Zachary777/omnicache-qwen3-codec)); each server
47
+ fetches only its own model's part.
48
+
49
+ ## Start two models
50
+
51
+ ```bash
52
+ KTC='{"kv_connector":"OmniCacheConnector","kv_role":"kv_both",
53
+ "kv_connector_extra_config":{"store":"/shared/omnicache_store"}}'
54
+ ARGS="--attention-backend FLASH_ATTN --max-model-len 4096 --enforce-eager --no-async-scheduling"
55
+
56
+ CUDA_VISIBLE_DEVICES=0 vllm serve Qwen/Qwen3-8B --port 8001 $ARGS --kv-transfer-config "$KTC"
57
+ CUDA_VISIBLE_DEVICES=1 vllm serve Qwen/Qwen3-14B --port 8002 $ARGS --kv-transfer-config "$KTC"
58
+ ```
59
+
60
+ Both servers must point at the same `store`, a directory both can reach. `kv_both` lets each server send and
61
+ receive. Optional keys: `"codec"` (a local bundle directory, a Hugging Face repo `owner/name`, or
62
+ `modelscope://owner/name` / `modelscope.ai://owner/name`).
63
+
64
+ ## Talk
65
+
66
+ ```python
67
+ from omnicache import Agent
68
+
69
+ a = Agent("http://127.0.0.1:8001") # Qwen3-8B
70
+ b = Agent("http://127.0.0.1:8002") # Qwen3-14B
71
+
72
+ msg = a.send(open("contract.txt").read()) # A prefills the passage and publishes U
73
+ reply = b.ask(msg, "Who is liable if delivery is late?") # B decodes U, prefills only the question
74
+ print(reply.text)
75
+
76
+ back = b.send(long_report) # the other direction works the same way
77
+ print(a.ask(back, "Summarise the report.").text)
78
+ ```
79
+
80
+ `msg` holds only a key and the passage token ids (JSON-serialisable with `msg.to_json()`); `U` goes from server to
81
+ server through the store and never passes through the client. `ask()` raises `OmniCacheMiss` when the receiver did
82
+ not load `U`, so an answer from a native re-read is never reported as a hand-off.
83
+
84
+ ## How a message is matched
85
+
86
+ The store key is `sha256` of the passage token ids, their count and the codec version. The sender computes it when it
87
+ encodes; the receiver recomputes it from the first `T` tokens of its prompt and loads `U` only if the two agree. The
88
+ same passage published twice is encoded once. Each sender's `U` is kept separately, and a receiver reuses the KV it
89
+ decoded from a given sender's `U` for repeated questions on the same passage (vLLM prefix cache, isolated per
90
+ passage and sender with `cache_salt`).
91
+
92
+ ## Scope of this release
93
+
94
+ - Models: Qwen3-4B-Instruct-2507, Qwen3-8B, Qwen3-14B, any direction (they share one tokenizer).
95
+ - Passage at the very start of the receiver prompt, bare text, at most 2,048 tokens together with the question.
96
+ - Question format `"\n\nQuestion: ...\nAnswer:"`, completions API, non-streaming.
97
+ - Single GPU per model (no tensor parallelism), FlashAttention backend, bf16 KV cache.
98
+ - Store: a shared directory (a Redis backend is experimental).
99
+
100
+ ## License
101
+
102
+ Apache-2.0
@@ -0,0 +1,74 @@
1
+ # omnicache
2
+
3
+ A unified-representation KV cache for vLLM. One model reads a passage; another model answers questions about it
4
+ without reading it again.
5
+
6
+ The sender's vLLM instance encodes the KV cache of the passage into a shared representation `U` (1,024 dims per
7
+ token, 2 KB/token in bf16) and writes it to a store. The receiver's vLLM instance, running a different model, decodes
8
+ `U` into its own KV cache, writes it into its paged KV memory and prefills only the question.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install omnicache # pulls vllm==0.15.1
14
+ ```
15
+
16
+ The base models are the official Qwen3 checkpoints. The codec weights (one encoder/decoder pair per model) are
17
+ downloaded on first start from ModelScope
18
+ ([Zachary777/omnicache-qwen3-codec](https://www.modelscope.ai/models/Zachary777/omnicache-qwen3-codec)); each server
19
+ fetches only its own model's part.
20
+
21
+ ## Start two models
22
+
23
+ ```bash
24
+ KTC='{"kv_connector":"OmniCacheConnector","kv_role":"kv_both",
25
+ "kv_connector_extra_config":{"store":"/shared/omnicache_store"}}'
26
+ ARGS="--attention-backend FLASH_ATTN --max-model-len 4096 --enforce-eager --no-async-scheduling"
27
+
28
+ CUDA_VISIBLE_DEVICES=0 vllm serve Qwen/Qwen3-8B --port 8001 $ARGS --kv-transfer-config "$KTC"
29
+ CUDA_VISIBLE_DEVICES=1 vllm serve Qwen/Qwen3-14B --port 8002 $ARGS --kv-transfer-config "$KTC"
30
+ ```
31
+
32
+ Both servers must point at the same `store`, a directory both can reach. `kv_both` lets each server send and
33
+ receive. Optional keys: `"codec"` (a local bundle directory, a Hugging Face repo `owner/name`, or
34
+ `modelscope://owner/name` / `modelscope.ai://owner/name`).
35
+
36
+ ## Talk
37
+
38
+ ```python
39
+ from omnicache import Agent
40
+
41
+ a = Agent("http://127.0.0.1:8001") # Qwen3-8B
42
+ b = Agent("http://127.0.0.1:8002") # Qwen3-14B
43
+
44
+ msg = a.send(open("contract.txt").read()) # A prefills the passage and publishes U
45
+ reply = b.ask(msg, "Who is liable if delivery is late?") # B decodes U, prefills only the question
46
+ print(reply.text)
47
+
48
+ back = b.send(long_report) # the other direction works the same way
49
+ print(a.ask(back, "Summarise the report.").text)
50
+ ```
51
+
52
+ `msg` holds only a key and the passage token ids (JSON-serialisable with `msg.to_json()`); `U` goes from server to
53
+ server through the store and never passes through the client. `ask()` raises `OmniCacheMiss` when the receiver did
54
+ not load `U`, so an answer from a native re-read is never reported as a hand-off.
55
+
56
+ ## How a message is matched
57
+
58
+ The store key is `sha256` of the passage token ids, their count and the codec version. The sender computes it when it
59
+ encodes; the receiver recomputes it from the first `T` tokens of its prompt and loads `U` only if the two agree. The
60
+ same passage published twice is encoded once. Each sender's `U` is kept separately, and a receiver reuses the KV it
61
+ decoded from a given sender's `U` for repeated questions on the same passage (vLLM prefix cache, isolated per
62
+ passage and sender with `cache_salt`).
63
+
64
+ ## Scope of this release
65
+
66
+ - Models: Qwen3-4B-Instruct-2507, Qwen3-8B, Qwen3-14B, any direction (they share one tokenizer).
67
+ - Passage at the very start of the receiver prompt, bare text, at most 2,048 tokens together with the question.
68
+ - Question format `"\n\nQuestion: ...\nAnswer:"`, completions API, non-streaming.
69
+ - Single GPU per model (no tensor parallelism), FlashAttention backend, bf16 KV cache.
70
+ - Store: a shared directory (a Redis backend is experimental).
71
+
72
+ ## License
73
+
74
+ Apache-2.0
@@ -0,0 +1,27 @@
1
+ """OmniCache: cross-model latent hand-off for vLLM.
2
+
3
+ A sender vLLM instance encodes the KV of a passage into the shared latent U (1,024 dims per token); a receiver
4
+ instance of a different model decodes U into its own KV and skips the passage prefill.
5
+
6
+ from omnicache import Agent
7
+ a, b = Agent("http://127.0.0.1:8001"), Agent("http://127.0.0.1:8002")
8
+ msg = a.send(doc)
9
+ reply = b.ask(msg, "Who is the supplier?")
10
+
11
+ The connector itself (omnicache.connector.OmniCacheConnector) is registered with vLLM by the
12
+ `vllm.general_plugins` entry point (omnicache.plugin:register).
13
+ """
14
+ __version__ = "0.1.0"
15
+
16
+ _CLIENT = ("Agent", "Member", "Message", "Reply", "OmniCacheMiss")
17
+
18
+
19
+ def __getattr__(name): # lazy: vLLM imports this package in every process via the plugin entry point
20
+ if name in _CLIENT:
21
+ from .client import agent
22
+
23
+ return agent.Member if name == "Agent" else getattr(agent, name)
24
+ raise AttributeError(name)
25
+
26
+
27
+ __all__ = list(_CLIENT)
File without changes
@@ -0,0 +1,179 @@
1
+ """Application-level API: one `Member` per vLLM endpoint, messages flow between any two members.
2
+
3
+ a = Member("http://host:8001", "qwen3_8b", ...)
4
+ b = Member("http://host:8002", "qwen3_14b", ...)
5
+ a.chat("hello") # ordinary generation, OmniCache not involved
6
+ msg = a.send(doc) # A prefills doc, encodes U, stores it; returns a small handle
7
+ reply = b.ask(msg, "Who is the supplier?") # B decodes U into its own KV, reads only the question
8
+ back = b.send(long_report); a.ask(back, "...") # reverse direction, same two calls
9
+
10
+ Constraints (the codec's training distribution, enforced here):
11
+ * the passage is the very beginning of the receiver prompt, as bare text (no chat template before it);
12
+ * all members share the public token grid (Qwen3 tokenizer); cross-tokenizer members are out of MVP scope;
13
+ * ask() fails loudly (OmniCacheMiss) unless the receiver echoes load == "loaded", so a silent native read is never
14
+ reported as a latent hand-off.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import time
21
+ from dataclasses import asdict, dataclass, field
22
+ from typing import Any, Dict, List, Optional
23
+
24
+ from .grid import Grid, cache_salt_for, key_for, question_suffix
25
+ from .http import _completion, _post
26
+
27
+
28
+ class OmniCacheMiss(RuntimeError):
29
+ """The receiver did not load the U (miss, bad salt, wrong T, store not visible, ...)."""
30
+
31
+
32
+ @dataclass
33
+ class Message:
34
+ """What travels between applications: a key into the U store plus the passage token ids (the receiver prompt
35
+ must start with exactly these ids). Small: ~4 bytes per token plus a header."""
36
+ id: str
37
+ sender: str
38
+ T: int
39
+ passage_ids: List[int]
40
+ codec_sha256: str
41
+ publish_s: float = 0.0
42
+ echo: Dict[str, Any] = field(default_factory=dict)
43
+
44
+ def to_json(self) -> str:
45
+ return json.dumps(asdict(self))
46
+
47
+ @classmethod
48
+ def from_json(cls, s: str) -> "Message":
49
+ return cls(**json.loads(s))
50
+
51
+
52
+ @dataclass
53
+ class Reply:
54
+ text: str
55
+ loaded: bool # the passage KV came from the sender's U (fresh decode or reuse of an earlier decode)
56
+ latency_s: float
57
+ echo: Dict[str, Any]
58
+ raw: Dict[str, Any] = field(repr=False, default_factory=dict)
59
+
60
+
61
+ DEFAULT_GRID_TOKENIZER = "Qwen/Qwen3-8B" # public grid; all Qwen3 members tokenise identically
62
+
63
+
64
+ def _served_model(url: str, api_key: Optional[str], timeout: float) -> Dict[str, Any]:
65
+ import urllib.request
66
+
67
+ req = urllib.request.Request(url + "/v1/models", headers={"Authorization": f"Bearer {api_key}"} if api_key else {})
68
+ with urllib.request.urlopen(req, timeout=timeout) as r:
69
+ data = json.loads(r.read().decode("utf-8"))["data"]
70
+ return data[0]
71
+
72
+
73
+ class Member:
74
+ """One vLLM endpoint running the OmniCache connector.
75
+
76
+ Only `url` is required: the served model id (and its local path, used as tokenizer when it exists) is read from
77
+ /v1/models; the member name and codec version of a sender come back in its publish echo.
78
+ """
79
+
80
+ def __init__(self, url: str, name: Optional[str] = None, tokenizer_path: Optional[str] = None,
81
+ codec_sha256: Optional[str] = None, store=None, api_key: Optional[str] = None,
82
+ timeout: float = 600.0, model_id: Optional[str] = None):
83
+ self.url = url.rstrip("/")
84
+ self.api_key = api_key
85
+ self.timeout = timeout
86
+ info: Dict[str, Any] = {}
87
+ if model_id is None or tokenizer_path is None:
88
+ info = _served_model(self.url, api_key, timeout)
89
+ self.model = model_id or info.get("id")
90
+ if tokenizer_path is None:
91
+ root = info.get("root")
92
+ tokenizer_path = root if root and os.path.isdir(root) else DEFAULT_GRID_TOKENIZER
93
+ self.grid = Grid(tokenizer_path)
94
+ self.name = name # member name; learnt from the first publish echo when None
95
+ self.codec_sha256 = codec_sha256 # learnt from the first echo when None
96
+ self.store = store # optional FileUStore: enables sha-pinned salts + visibility wait
97
+
98
+ # ---- ① ordinary chat, untouched by the connector -------------------------------------------------------
99
+ def chat(self, text: str, max_tokens: int = 256, **kw) -> str:
100
+ payload = {"model": self.model, "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens,
101
+ "temperature": kw.pop("temperature", 0.0), **kw}
102
+ r = _post(self.url + "/v1/chat/completions", payload, self.timeout, self.api_key)
103
+ return r["choices"][0]["message"]["content"]
104
+
105
+ # ---- ② publish a passage as U ---------------------------------------------------------------------------
106
+ def send(self, doc: str, wait_s: float = 10.0) -> Message:
107
+ ids = self.grid.passage_ids(doc)
108
+ T = len(ids)
109
+ payload = {"model": self.model, "prompt": ids, "max_tokens": 1, "temperature": 0.0,
110
+ "kv_transfer_params": {"omnicache": {"op": "send", "T": T}}}
111
+ t0 = time.perf_counter()
112
+ r = _post(self.url + "/v1/completions", payload, self.timeout, self.api_key)
113
+ echo = (r.get("kv_transfer_params") or {}).get("omnicache", {})
114
+ if echo.get("store") not in ("written", "queued", "exists"):
115
+ raise RuntimeError(f"{self.name or self.url} did not publish U: {echo}")
116
+ self.name = self.name or echo.get("member")
117
+ self.codec_sha256 = self.codec_sha256 or echo.get("codec_sha256")
118
+ key = key_for(ids, T, self.codec_sha256)
119
+ if echo.get("u_key") and echo["u_key"] != key:
120
+ raise RuntimeError(f"server key {echo['u_key']} != client key {key} (tokenizer grid or codec mismatch)")
121
+ if self.store is not None: # make sure the U is visible before handing out the id
122
+ deadline = time.monotonic() + wait_s
123
+ while self.store.stat(key, self.name) is None:
124
+ if time.monotonic() > deadline:
125
+ raise RuntimeError(f"U {key} from {self.name} not visible in the store after {wait_s}s")
126
+ time.sleep(0.05)
127
+ return Message(id=key, sender=self.name, T=T, passage_ids=ids, codec_sha256=self.codec_sha256,
128
+ publish_s=time.perf_counter() - t0, echo=echo)
129
+
130
+ # ---- ③ answer a question about a received message ---------------------------------------------------------
131
+ def _salt(self, msg: Message) -> str:
132
+ u_sha = None
133
+ if self.store is not None:
134
+ ent = self.store.stat(msg.id, msg.sender)
135
+ u_sha = ent.u_sha256 if ent is not None else None
136
+ return cache_salt_for(msg.id, msg.sender, u_sha)
137
+
138
+ def ask(self, msg: Message, question: str, max_tokens: int = 64, first_line: bool = True, strict: bool = True,
139
+ lang: str = "en") -> Reply:
140
+ if self.codec_sha256 and msg.codec_sha256 != self.codec_sha256:
141
+ raise ValueError(f"message encoded with codec {msg.codec_sha256[:12]}, this member uses {self.codec_sha256[:12]}")
142
+ q_ids = self.grid.question_suffix_ids(question, lang)
143
+ payload: Dict[str, Any] = {"model": self.model, "prompt": list(msg.passage_ids) + q_ids, "max_tokens": max_tokens,
144
+ "temperature": 0.0,
145
+ "kv_transfer_params": {"omnicache": {"op": "recv", "T": msg.T, "sender": msg.sender, "u_key": msg.id}},
146
+ "cache_salt": self._salt(msg)}
147
+ if first_line:
148
+ payload["stop_token_ids"] = self.grid.newline_token_ids()
149
+ t0 = time.perf_counter()
150
+ r = _completion(self.url + "/v1/completions", payload, self.timeout, self.api_key, False)
151
+ dt = time.perf_counter() - t0
152
+ echo = (r.get("kv_transfer_params") or {}).get("omnicache", {})
153
+ # "loaded": U decoded into fresh blocks this request. "local_hit": the blocks were decoded from the same U by an
154
+ # earlier ask and reused through the prefix cache; they sit under the sender-qualified cache_salt, which only
155
+ # connector loads use, so they are U-derived, never a native read of the passage.
156
+ loaded = echo.get("load") in ("loaded", "local_hit") and int(echo.get("T") or 0) == msg.T
157
+ if strict and not loaded:
158
+ raise OmniCacheMiss(f"{self.name} did not load U {msg.id[:16]} from {msg.sender}: {echo}")
159
+ text = r["text"].split("\n", 1)[0].strip() if first_line else r["text"]
160
+ return Reply(text=text, loaded=loaded, latency_s=dt, echo=echo, raw=r)
161
+
162
+ # ---- references for evaluation ---------------------------------------------------------------------------
163
+ def read_and_ask(self, doc: str, question: str, max_tokens: int = 64, lang: str = "en") -> Reply:
164
+ """Receiver reads the passage itself (native upper bound)."""
165
+ p, q = self.grid.build(doc, question, lang)
166
+ payload = {"model": self.model, "prompt": p + q, "max_tokens": max_tokens, "temperature": 0.0,
167
+ "stop_token_ids": self.grid.newline_token_ids()}
168
+ t0 = time.perf_counter()
169
+ r = _completion(self.url + "/v1/completions", payload, self.timeout, self.api_key, False)
170
+ return Reply(text=r["text"].split("\n", 1)[0].strip(), loaded=False, latency_s=time.perf_counter() - t0, echo={}, raw=r)
171
+
172
+ def ask_blind(self, question: str, max_tokens: int = 64, lang: str = "en") -> Reply:
173
+ """No context at all (floor)."""
174
+ q = self.grid.question_suffix_ids(question, lang)
175
+ payload = {"model": self.model, "prompt": q, "max_tokens": max_tokens, "temperature": 0.0,
176
+ "stop_token_ids": self.grid.newline_token_ids()}
177
+ t0 = time.perf_counter()
178
+ r = _completion(self.url + "/v1/completions", payload, self.timeout, self.api_key, False)
179
+ return Reply(text=r["text"].split("\n", 1)[0].strip(), loaded=False, latency_s=time.perf_counter() - t0, echo={}, raw=r)