shared-tensor 0.2.10__tar.gz → 0.2.12__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Athena Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: shared-tensor
3
- Version: 0.2.10
3
+ Version: 0.2.12
4
4
  Summary: Native PyTorch CUDA IPC over Unix Domain Socket for same-host process separation
5
5
  Author-email: Athena Team <contact@world-sim-dev.org>
6
6
  Maintainer-email: Athena Team <contact@world-sim-dev.org>
7
- License-Expression: Apache-2.0
7
+ License-Expression: MIT
8
8
  Project-URL: Homepage, https://github.com/world-sim-dev/shared-tensor
9
9
  Project-URL: Repository, https://github.com/world-sim-dev/shared-tensor
10
10
  Project-URL: Documentation, https://github.com/world-sim-dev/shared-tensor/tree/main/docs
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "shared-tensor"
7
- version = "0.2.10"
7
+ version = "0.2.12"
8
8
  description = "Native PyTorch CUDA IPC over Unix Domain Socket for same-host process separation"
9
9
  readme = "README.md"
10
- license = "Apache-2.0"
10
+ license = "MIT"
11
11
  authors = [
12
12
  {name = "Athena Team", email = "contact@world-sim-dev.org"}
13
13
  ]
@@ -19,4 +19,4 @@ __all__ = [
19
19
  "TaskStatus",
20
20
  ]
21
21
 
22
- __version__ = "0.2.10"
22
+ __version__ = "0.2.12"
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import hashlib
6
+ import importlib
6
7
  import inspect
7
8
  import io
8
9
  import multiprocessing.reduction as mp_reduction
@@ -23,12 +24,19 @@ try:
23
24
  except ImportError: # pragma: no cover - exercised only without torch installed.
24
25
  _torch = cast(Any, None)
25
26
 
27
+ try:
28
+ from transformers import PreTrainedModel as _transformers_pretrained_model
29
+ except ImportError: # pragma: no cover - exercised when transformers is not installed.
30
+ _transformers_pretrained_model = cast(Any, None)
31
+
26
32
 
27
33
  TORCH_MODULE: Any | None = _torch
34
+ TRANSFORMERS_PRETRAINED_MODEL: Any | None = _transformers_pretrained_model
28
35
 
29
36
 
30
37
  CONTROL_ENCODING = "control_pickle"
31
38
  TORCH_ENCODING = "torch_cuda_ipc"
39
+ TRANSFORMERS_MODEL_ENCODING = "torch_transformers_pretrained_model"
32
40
  SHARED_TENSOR_BASE_PATH_ENV = "SHARED_TENSOR_BASE_PATH"
33
41
  DEFAULT_SOCKET_BASE_PATH = "/tmp/shared-tensor"
34
42
  _EMPTY_TUPLE = ()
@@ -162,17 +170,41 @@ def _torch_serialize(obj: Any) -> bytes:
162
170
  return buffer.getvalue()
163
171
 
164
172
 
165
- def _serialize_ipc_payload(obj: Any) -> bytes:
173
+ def _serialize_transformers_model(module: Any) -> bytes:
174
+ config = getattr(module, "config", None)
175
+ if config is None:
176
+ raise SharedTensorSerializationError("transformers model is missing a config")
177
+ if not hasattr(config, "to_dict"):
178
+ raise SharedTensorSerializationError("transformers model config must provide to_dict()")
179
+ payload = {
180
+ "model_module": type(module).__module__,
181
+ "model_name": type(module).__name__,
182
+ "config_module": type(config).__module__,
183
+ "config_name": type(config).__name__,
184
+ "config_dict": config.to_dict(),
185
+ "training": bool(module.training),
186
+ "state_bytes": _torch_serialize(module.state_dict()),
187
+ }
188
+ return pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)
189
+
190
+
191
+ def _serialize_ipc_payload(obj: Any) -> tuple[str, bytes]:
192
+ if (
193
+ TORCH_MODULE is not None
194
+ and TRANSFORMERS_PRETRAINED_MODEL is not None
195
+ and isinstance(obj, TRANSFORMERS_PRETRAINED_MODEL)
196
+ ):
197
+ return TRANSFORMERS_MODEL_ENCODING, _serialize_transformers_model(obj)
166
198
  if TORCH_MODULE is not None and isinstance(obj, (TORCH_MODULE.Tensor, TORCH_MODULE.nn.Module)):
167
- return _torch_serialize(obj)
168
- return pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
199
+ return TORCH_ENCODING, _torch_serialize(obj)
200
+ return CONTROL_ENCODING, pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
169
201
 
170
202
 
171
203
  def serialize_payload(obj: Any) -> tuple[str, bytes]:
172
204
  """Serialize a CUDA torch payload using PyTorch's IPC-aware pickler."""
173
205
  try:
174
206
  _validate_torch_payload(obj, allow_dict_keys=isinstance(obj, dict))
175
- return TORCH_ENCODING, _serialize_ipc_payload(obj)
207
+ return _serialize_ipc_payload(obj)
176
208
  except SharedTensorCapabilityError:
177
209
  raise
178
210
  except Exception as exc: # pragma: no cover - defensive
@@ -208,6 +240,41 @@ def serialize_call_payloads(
208
240
  raise SharedTensorSerializationError(f"Failed to serialize call payloads: {exc}") from exc
209
241
 
210
242
 
243
+ def _load_module_state_dict(module: Any, state_dict: dict[str, Any]) -> None:
244
+ load_state_dict = module.load_state_dict
245
+ if "assign" in inspect.signature(load_state_dict).parameters:
246
+ incompatible = load_state_dict(state_dict, strict=False, assign=True)
247
+ else: # pragma: no cover - compatibility fallback
248
+ incompatible = load_state_dict(state_dict, strict=False)
249
+ missing = list(getattr(incompatible, "missing_keys", []))
250
+ unexpected = list(getattr(incompatible, "unexpected_keys", []))
251
+ if missing or unexpected:
252
+ raise SharedTensorSerializationError(
253
+ f"Failed to reconstruct module state: missing={missing[:10]} unexpected={unexpected[:10]}"
254
+ )
255
+
256
+
257
+ def _deserialize_transformers_model(payload: bytes) -> Any:
258
+ encoded = pickle.loads(payload)
259
+ model_module = importlib.import_module(encoded["model_module"])
260
+ model_cls = getattr(model_module, encoded["model_name"])
261
+ config_module = importlib.import_module(encoded["config_module"])
262
+ config_cls = getattr(config_module, encoded["config_name"])
263
+ if hasattr(config_cls, "from_dict"):
264
+ config = config_cls.from_dict(encoded["config_dict"])
265
+ else: # pragma: no cover - defensive
266
+ config = config_cls(**encoded["config_dict"])
267
+ state_dict = pickle.loads(encoded["state_bytes"])
268
+ model = model_cls(config)
269
+ first_tensor = next(iter(state_dict.values()), None)
270
+ if TORCH_MODULE is not None and isinstance(first_tensor, TORCH_MODULE.Tensor):
271
+ model = model.to(first_tensor.device)
272
+ _load_module_state_dict(model, state_dict)
273
+ model.train(bool(encoded["training"]))
274
+ _validate_module_device(model)
275
+ return model
276
+
277
+
211
278
  def deserialize_payload(encoding: str, data: bytes | str) -> Any:
212
279
  """Deserialize a payload produced by :func:`serialize_payload`."""
213
280
  payload = bytes.fromhex(data) if isinstance(data, str) else data
@@ -216,6 +283,8 @@ def deserialize_payload(encoding: str, data: bytes | str) -> Any:
216
283
  return pickle.loads(payload)
217
284
  if encoding == TORCH_ENCODING:
218
285
  return pickle.loads(payload)
286
+ if encoding == TRANSFORMERS_MODEL_ENCODING:
287
+ return _deserialize_transformers_model(payload)
219
288
  raise SharedTensorSerializationError(f"Unsupported payload encoding: {encoding}")
220
289
  except SharedTensorCapabilityError:
221
290
  raise
@@ -1,181 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity granting the License.
13
-
14
- "Legal Entity" shall mean the union of the acting entity and all
15
- other entities that control, are controlled by, or are under common
16
- control with that entity. For the purposes of this definition,
17
- "control" means (i) the power, direct or indirect, to cause the
18
- direction or management of such entity, whether by contract or
19
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
- outstanding shares, or (iii) beneficial ownership of such entity.
21
-
22
- "You" (or "Your") shall mean an individual or Legal Entity
23
- exercising permissions granted by this License.
24
-
25
- "Source" form shall mean the preferred form for making modifications,
26
- including but not limited to software source code, documentation
27
- source, and configuration files.
28
-
29
- "Object" form shall mean any form resulting from mechanical
30
- transformation or translation of a Source form, including but
31
- not limited to compiled object code, generated documentation,
32
- and conversions to other media types.
33
-
34
- "Work" shall mean the work of authorship, whether in Source or
35
- Object form, made available under the License, as indicated by a
36
- copyright notice that is included in or attached to the work
37
- (which shall not include communications that are clearly marked or
38
- otherwise designated in writing by the copyright owner as "Not a Contribution").
39
-
40
- "Contribution" shall mean any work of authorship, including
41
- the original version of the Work and any modifications or additions
42
- to that Work or Derivative Works thereof, that is intentionally
43
- submitted to Licensor for inclusion in the Work by the copyright owner
44
- or by an individual or Legal Entity authorized to submit on behalf of
45
- the copyright owner. For the purposes of this definition, "submitted"
46
- means any form of electronic, verbal, or written communication sent
47
- to the Licensor or its representatives, including but not limited to
48
- communication on electronic mailing lists, source code control
49
- systems, and issue tracking systems that are managed by, or on behalf of,
50
- the Licensor for the purpose of discussing and improving the Work, but
51
- excluding communication that is conspicuously marked or otherwise
52
- designated in writing by the copyright owner as "Not a Contribution."
53
-
54
- 2. Grant of Copyright License. Subject to the terms and conditions of
55
- this License, each Contributor hereby grants to You a perpetual,
56
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
- copyright license to use, reproduce, modify, merge, publish,
58
- distribute, sublicense, and/or sell copies of the Work, and to
59
- permit persons to whom the Work is furnished to do so, subject to
60
- the following conditions:
61
-
62
- The above copyright notice and this permission notice shall be
63
- included in all copies or substantial portions of the Work.
64
-
65
- 3. Grant of Patent License. Subject to the terms and conditions of
66
- this License, each Contributor hereby grants to You a perpetual,
67
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
- (except as stated in this section) patent license to make, have made,
69
- use, offer to sell, sell, import, and otherwise transfer the Work,
70
- where such license applies only to those patent claims licensable
71
- by such Contributor that are necessarily infringed by their
72
- Contribution(s) alone or by combination of their Contribution(s)
73
- with the Work to which such Contribution(s) was submitted. If You
74
- institute patent litigation against any entity (including a
75
- cross-claim or counterclaim in a lawsuit) alleging that the Work
76
- or a Contribution incorporated within the Work constitutes direct
77
- or contributory patent infringement, then any patent licenses
78
- granted to You under this License for that Work shall terminate
79
- as of the date such litigation is filed.
80
-
81
- 4. Redistribution. You may reproduce and distribute copies of the
82
- Work or Derivative Works thereof in any medium, with or without
83
- modifications, and in Source or Object form, provided that You
84
- meet the following conditions:
85
-
86
- (a) You must give any other recipients of the Work or
87
- Derivative Works a copy of this License; and
88
-
89
- (b) You must cause any modified files to carry prominent notices
90
- stating that You changed the files; and
91
-
92
- (c) You must retain, in the Source form of any Derivative Works
93
- that You distribute, all copyright, trademark, patent, and
94
- attribution notices from the Source form of the Work,
95
- excluding those notices that do not pertain to any part of
96
- the Derivative Works; and
97
-
98
- (d) If the Work includes a "NOTICE" text file as part of its
99
- distribution, then any Derivative Works that You distribute must
100
- include a readable copy of the attribution notices contained
101
- within such NOTICE file, excluding those notices that do not
102
- pertain to any part of the Derivative Works, in at least one
103
- of the following places: within a NOTICE text file distributed
104
- as part of the Derivative Works; within the Source form or
105
- documentation, if provided along with the Derivative Works; or,
106
- within a display generated by the Derivative Works, if and
107
- wherever such third-party notices normally appear. The contents
108
- of the NOTICE file are for informational purposes only and
109
- do not modify the License. You may add Your own attribution
110
- notices within Derivative Works that You distribute, alongside
111
- or as an addendum to the NOTICE text from the Work, provided
112
- that such additional attribution notices cannot be construed
113
- as modifying the License.
114
-
115
- You may add Your own copyright notice to Your modifications and
116
- may provide additional or different license terms and conditions
117
- for use, reproduction, or distribution of Your modifications, or
118
- for any such Derivative Works as a whole, provided Your use,
119
- reproduction, and distribution of the Work otherwise complies with
120
- the conditions stated in this License.
121
-
122
- 5. Submission of Contributions. Unless You explicitly state otherwise,
123
- any Contribution intentionally submitted for inclusion in the Work
124
- by You to the Licensor shall be under the terms and conditions of
125
- this License, without any additional terms or conditions.
126
- Notwithstanding the above, nothing herein shall supersede or modify
127
- the terms of any separate license agreement you may have executed
128
- with Licensor regarding such Contributions.
129
-
130
- 6. Trademarks. This License does not grant permission to use the trade
131
- names, trademarks, service marks, or product names of the Licensor,
132
- except as required for reasonable and customary use in describing the
133
- origin of the Work and reproducing the content of the NOTICE file.
134
-
135
- 7. Disclaimer of Warranty. Unless required by applicable law or
136
- agreed to in writing, Licensor provides the Work (and each
137
- Contributor provides its Contributions) on an "AS IS" BASIS,
138
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
139
- implied, including, without limitation, any warranties or conditions
140
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
141
- PARTICULAR PURPOSE. You are solely responsible for determining the
142
- appropriateness of using or redistributing the Work and assume any
143
- risks associated with Your exercise of permissions under this License.
144
-
145
- 8. Limitation of Liability. In no event and under no legal theory,
146
- whether in tort (including negligence), contract, or otherwise,
147
- unless required by applicable law (such as deliberate and grossly
148
- negligent acts) or agreed to in writing, shall any Contributor be
149
- liable to You for damages, including any direct, indirect, special,
150
- incidental, or consequential damages of any character arising as a
151
- result of this License or out of the use or inability to use the
152
- Work (including but not limited to damages for loss of goodwill,
153
- work stoppage, computer failure or malfunction, or any and all
154
- other commercial damages or losses), even if such Contributor
155
- has been advised of the possibility of such damages.
156
-
157
- 9. Accepting Warranty or Support. You may choose to offer,
158
- and charge a fee for, warranty, support, indemnity or other
159
- liability obligations and/or rights consistent with this License.
160
- However, in accepting such obligations, You may act only on Your
161
- own behalf and on Your sole responsibility, not on behalf of any
162
- other Contributor, and only if You agree to indemnify, defend,
163
- and hold each Contributor harmless for any liability incurred by,
164
- or claims asserted against, such Contributor by reason of your
165
- accepting any such warranty or support.
166
-
167
- END OF TERMS AND CONDITIONS
168
-
169
- Copyright 2024 Athena Team
170
-
171
- Licensed under the Apache License, Version 2.0 (the "License");
172
- you may not use this file except in compliance with the License.
173
- You may obtain a copy of the License at
174
-
175
- http://www.apache.org/licenses/LICENSE-2.0
176
-
177
- Unless required by applicable law or agreed to in writing, software
178
- distributed under the License is distributed on an "AS IS" BASIS,
179
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
- See the License for the specific language governing permissions and
181
- limitations under the License.
File without changes
File without changes