tensorferry 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.
- tensorferry-0.1.0/LICENSE +202 -0
- tensorferry-0.1.0/MANIFEST.in +2 -0
- tensorferry-0.1.0/PKG-INFO +154 -0
- tensorferry-0.1.0/README.md +139 -0
- tensorferry-0.1.0/pyproject.toml +60 -0
- tensorferry-0.1.0/scripts/bench_remote.py +62 -0
- tensorferry-0.1.0/setup.cfg +4 -0
- tensorferry-0.1.0/src/tensorferry/__init__.py +76 -0
- tensorferry-0.1.0/src/tensorferry/_pool.py +114 -0
- tensorferry-0.1.0/src/tensorferry/api.py +271 -0
- tensorferry-0.1.0/src/tensorferry/backend.py +28 -0
- tensorferry-0.1.0/src/tensorferry/cache.py +1099 -0
- tensorferry-0.1.0/src/tensorferry/formats.py +374 -0
- tensorferry-0.1.0/src/tensorferry/jax.py +297 -0
- tensorferry-0.1.0/src/tensorferry/loader.py +571 -0
- tensorferry-0.1.0/src/tensorferry/plan.py +289 -0
- tensorferry-0.1.0/src/tensorferry/progress.py +90 -0
- tensorferry-0.1.0/src/tensorferry/store.py +361 -0
- tensorferry-0.1.0/src/tensorferry/torch.py +497 -0
- tensorferry-0.1.0/src/tensorferry.egg-info/PKG-INFO +154 -0
- tensorferry-0.1.0/src/tensorferry.egg-info/SOURCES.txt +33 -0
- tensorferry-0.1.0/src/tensorferry.egg-info/dependency_links.txt +1 -0
- tensorferry-0.1.0/src/tensorferry.egg-info/requires.txt +3 -0
- tensorferry-0.1.0/src/tensorferry.egg-info/top_level.txt +1 -0
- tensorferry-0.1.0/tests/__init__.py +0 -0
- tensorferry-0.1.0/tests/_files.py +61 -0
- tensorferry-0.1.0/tests/conftest.py +18 -0
- tensorferry-0.1.0/tests/test_cache.py +627 -0
- tensorferry-0.1.0/tests/test_formats.py +163 -0
- tensorferry-0.1.0/tests/test_jax.py +246 -0
- tensorferry-0.1.0/tests/test_loader.py +502 -0
- tensorferry-0.1.0/tests/test_progress.py +142 -0
- tensorferry-0.1.0/tests/test_remote.py +126 -0
- tensorferry-0.1.0/tests/test_store.py +122 -0
- tensorferry-0.1.0/tests/test_torch.py +311 -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 2026 Revanta Inc
|
|
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,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tensorferry
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Streaming checkpoint loading for NumPy, JAX, and PyTorch
|
|
5
|
+
Author: Revanta
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/Revanta-Inc/tensorferry
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: numpy>=2
|
|
12
|
+
Requires-Dist: ml-dtypes>=0.5
|
|
13
|
+
Requires-Dist: obstore>=0.11.1
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# tensorferry
|
|
17
|
+
|
|
18
|
+
tensorferry streams weights from disk, Hugging Face, or object storage so large GPU models can start sooner and use less host RAM. In an ESM-C 6B (fp32, 24GiB) benchmark on a Google Cloud G4 GPU VM, streaming from GCS cut time to first prediction from **70 seconds to 34–36 seconds** and peak host RAM from **25.5 GiB to 2.8 GiB**.
|
|
19
|
+
|
|
20
|
+
To load a full model, give tensorferry a PyTorch module or a JAX pytree. It assembles the weights in the layout and dtype your model expects. Device transfers can begin as soon as the first weights are ready, while the rest are still loading.
|
|
21
|
+
|
|
22
|
+
## Features
|
|
23
|
+
|
|
24
|
+
- **Fetch tensors by name** from single-file or sharded checkpoints on disk, cloud storage, or Hugging Face.
|
|
25
|
+
- **Assemble model weights** by stacking, concatenating, or casting tensors as they load.
|
|
26
|
+
- **Load in the background** so device transfers and compilation can overlap checkpoint reads.
|
|
27
|
+
- **Reduce peak host memory** by releasing staging buffers as finished weights move onto the GPU.
|
|
28
|
+
- **Cache weights across runs** to reuse downloaded byte ranges and skip repeated casts or decompression.
|
|
29
|
+
|
|
30
|
+
## From checkpoint to first JAX prediction
|
|
31
|
+
|
|
32
|
+

|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
tensorferry requires Python 3.12 or newer. Once the first release is on PyPI, add it to your project with uv.
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
uv add tensorferry
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## First-class support for safetensors
|
|
43
|
+
|
|
44
|
+
The 8M-parameter ESM-2 model stores its token embeddings in a 29.9 MiB checkpoint on Hugging Face and you are only interested in its embedding table. Simply pass its key to `load_arrays`.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import tensorferry as tf
|
|
48
|
+
|
|
49
|
+
source = "hf://facebook/esm2_t6_8M_UR50D@c731040fcd8d73dceaa04b0a8e6329b345b0f5df/model.safetensors"
|
|
50
|
+
key = "esm.embeddings.word_embeddings.weight"
|
|
51
|
+
|
|
52
|
+
with tf.track_downloads() as transfer:
|
|
53
|
+
embeddings = tf.load_arrays(source, names=[key], cache=False).result()[key]
|
|
54
|
+
|
|
55
|
+
print(embeddings.shape) # (33, 320)
|
|
56
|
+
print(transfer.snapshot()[0]) # 1090816 bytes received
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
tensorferry first fetches 1 MiB from the start of the file to read its header. The header locates the embedding table, so the next read covers just its 41.25 KiB. Together those two reads bring the total transfer to **1.04 MiB**.
|
|
60
|
+
|
|
61
|
+
If you don't know the key, `tf.index(source)` lists each tensor's name, shape, dtype, and byte range without building any arrays. Both `index` and `load_arrays` accept local paths, cloud storage, and HTTP(S) URLs that support range requests. For a sharded checkpoint, give either function the `.safetensors.index.json` file and tensorferry will follow it to each shard's header.
|
|
62
|
+
|
|
63
|
+
You can also combine files and in-memory arrays in one load, use your own storage client, or load named tensors directly onto a PyTorch or JAX device. [Loading options](docs/loading.md)
|
|
64
|
+
|
|
65
|
+
## Cache weights across runs
|
|
66
|
+
|
|
67
|
+
tensorferry caches weights on disk by default on supported POSIX systems. The ESM-2 example turns caching off to measure the download. Omit `cache=False` and try the same `source` and `key` twice.
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
for _ in range(2):
|
|
71
|
+
with tf.track_downloads() as transfer:
|
|
72
|
+
embeddings = tf.load_arrays(source, names=[key]).result()[key]
|
|
73
|
+
print(transfer.snapshot()[0])
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
With an empty cache, the first load fetches the byte ranges it needs. The second reads them from disk and prints **0**. If you ask for another tensor from the same file, tensorferry fetches any missing ranges. Processes can share the same cache directory on POSIX systems with `preadv`.
|
|
77
|
+
|
|
78
|
+
The cache also saves work after download. If your model uses bfloat16 weights from a float32 checkpoint, tensorferry can keep the converted arrays at their final size. It can do the same for decompressed `.npz` members. To cap disk usage, set a budget such as `TENSORFERRY_CACHE_MAX_BYTES=20G`. Source ranges and converted arrays share that budget, and tensorferry evicts the least recently used entries it can release.
|
|
79
|
+
|
|
80
|
+
Set `TENSORFERRY_CACHE` to a directory to move the cache or to `off` to disable it across an application. To bypass it for one load, pass `cache=False`. By default, tensorferry trusts the cached copy, which suits a pinned revision like the one above. If the contents can change at the same URL, use `tf.Cache(revalidate=True)` to check the source version on first access. [Cache configuration](docs/loading.md#configure-the-disk-cache)
|
|
81
|
+
|
|
82
|
+
## Load the same weights into different model layouts
|
|
83
|
+
|
|
84
|
+
The ESM-2 embedding table was ready to use as stored. When a model needs a different layout, you can tell tensorferry how the stored tensors fit together. Consider an attention checkpoint with three 4 × 4 matrices, one each for the query, key, and value projections.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import numpy as np
|
|
88
|
+
|
|
89
|
+
eye = np.eye(4, dtype=np.float32)
|
|
90
|
+
np.savez("attention.npz", q=eye, k=2 * eye, v=3 * eye)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Fill a fused PyTorch projection
|
|
94
|
+
|
|
95
|
+
One PyTorch linear layer can compute all three projections at once. Its `weight` parameter needs 12 rows, so `Concat` joins `q`, `k`, and `v` along their rows in that order. Creating the layer on the `meta` device avoids allocating weights that the load would immediately replace.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import torch
|
|
99
|
+
from tensorferry import Concat
|
|
100
|
+
from tensorferry.torch import load
|
|
101
|
+
|
|
102
|
+
qkv = torch.nn.Linear(4, 12, bias=False, device="meta")
|
|
103
|
+
weight = Concat(["q", "k", "v"], axis=0)
|
|
104
|
+
load(qkv, "attention.npz", keys=lambda name, tensor: weight, device="cpu").result()
|
|
105
|
+
print(qkv(torch.ones(4)).reshape(3, 4)[:, 0].tolist()) # [1.0, 2.0, 3.0]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Once `.result()` returns, you can call the layer directly. tensorferry updates the module in place, replacing its parameters and persistent buffers while keeping tied weights shared. If the checkpoint names already match the module's `state_dict()`, you can omit `keys`. To load floating-point weights as bfloat16 on a CUDA GPU, pass `dtype=torch.bfloat16, device="cuda"`.
|
|
109
|
+
|
|
110
|
+
If you need the populated state dictionary itself, `tensorferry.torch.load_state_dict(module, source).result()` gives you the tensors while preserving the original module.
|
|
111
|
+
|
|
112
|
+
### Compile in JAX while weights load
|
|
113
|
+
|
|
114
|
+
In JAX, the same three matrices can form a batch. `Stack` adds a leading axis so `matmul` can apply all three projections to one vector. To compile that operation, JAX needs to know the shape and dtype of the weights. Both are available in `pending.shape` as soon as this load starts.
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
import jax
|
|
118
|
+
import jax.numpy as jnp
|
|
119
|
+
from tensorferry import Stack
|
|
120
|
+
from tensorferry.jax import load
|
|
121
|
+
|
|
122
|
+
template = jax.ShapeDtypeStruct((3, 4, 4), jnp.float32)
|
|
123
|
+
weights = Stack(["q", "k", "v"], axis=0)
|
|
124
|
+
pending = load(template, "attention.npz", keys=lambda path, target: weights)
|
|
125
|
+
x = jnp.ones(4, dtype=jnp.float32)
|
|
126
|
+
project = jax.jit(jnp.matmul).lower(pending.shape, x).compile()
|
|
127
|
+
print(project(pending.result(), x)[:, 0].tolist()) # [1.0, 2.0, 3.0]
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The compiled function gets the actual weights from `pending.result()`, which waits for the load to finish. When you load a nested pytree, `.result()` returns the filled tree. By default, tensorferry matches its leaves to checkpoint keys using dotted paths such as `blocks.0.weight`. To distribute the arrays across devices, pass a JAX `Sharding` as the `device` argument.
|
|
131
|
+
|
|
132
|
+
## How tensorferry plans a load
|
|
133
|
+
|
|
134
|
+
Before assembling weights for PyTorch or JAX, tensorferry checks how the checkpoint maps to the model. With the default `strict=True`, `.result()` reports missing keys, unexpected keys, and incompatible shapes together in a `CheckpointMismatchError`. To load one subtree or allow known extra keys, use `prefix` or `ignore`. A `keys` callback can also map individual tensors to slices of a destination array. [Model mapping and placement](docs/loading.md#map-checkpoint-keys-to-a-model)
|
|
135
|
+
|
|
136
|
+
Once it has a plan, tensorferry groups nearby weights into byte ranges it can read concurrently. Reading across a small gap between weights can save a network round trip. For `.npz` files, tensorferry indexes the archive's member headers so it can find individual arrays and decompress those stored with deflate.
|
|
137
|
+
|
|
138
|
+
A local safetensors file can back compatible NumPy arrays and CPU PyTorch tensors directly through a copy-on-write memory map. For GPU loads, tensorferry releases host staging buffers as transfers finish. The `staging_bytes` setting on `tf.StreamingLoader` controls the budget for those buffers. A read that needs more room can run on its own.
|
|
139
|
+
|
|
140
|
+
In an archived ESM-C 6B benchmark, the download-first workflow fetched six float32 shards from GCS and loaded them with `EsmcModel.from_pretrained`. tensorferry streamed the same weights to CUDA. Both used bfloat16 on the GPU and ran in fresh JAX processes on a G4 VM in the bucket's region. Through the first prediction, the model process's peak resident set size was **25.5 GiB** with the download-first loader and **2.8 GiB** with tensorferry.
|
|
141
|
+
|
|
142
|
+
While a load runs, `pending.progress` counts completed output bytes. The download counter in the ESM-2 example measures bytes received over the network, which can be much smaller on a cache hit. [Progress and cancellation](docs/loading.md#monitor-a-background-load)
|
|
143
|
+
|
|
144
|
+
## Measure throughput on your storage
|
|
145
|
+
|
|
146
|
+
Run both benchmark modes on the same checkpoint. `ceiling` measures how fast your storage serves raw byte ranges. `sweep` bypasses tensorferry's cache and measures the full load, including the work of building the NumPy arrays. [Benchmark script](scripts/bench_remote.py)
|
|
147
|
+
|
|
148
|
+
```sh
|
|
149
|
+
url=gs://your-bucket/model.safetensors
|
|
150
|
+
python scripts/bench_remote.py ceiling "$url" --workers 4,16 --chunk-mib 8,32
|
|
151
|
+
python scripts/bench_remote.py sweep "$url" --workers 4,16 --chunk-mib 8,32
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Licensed under [Apache 2.0](LICENSE).
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# tensorferry
|
|
2
|
+
|
|
3
|
+
tensorferry streams weights from disk, Hugging Face, or object storage so large GPU models can start sooner and use less host RAM. In an ESM-C 6B (fp32, 24GiB) benchmark on a Google Cloud G4 GPU VM, streaming from GCS cut time to first prediction from **70 seconds to 34–36 seconds** and peak host RAM from **25.5 GiB to 2.8 GiB**.
|
|
4
|
+
|
|
5
|
+
To load a full model, give tensorferry a PyTorch module or a JAX pytree. It assembles the weights in the layout and dtype your model expects. Device transfers can begin as soon as the first weights are ready, while the rest are still loading.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Fetch tensors by name** from single-file or sharded checkpoints on disk, cloud storage, or Hugging Face.
|
|
10
|
+
- **Assemble model weights** by stacking, concatenating, or casting tensors as they load.
|
|
11
|
+
- **Load in the background** so device transfers and compilation can overlap checkpoint reads.
|
|
12
|
+
- **Reduce peak host memory** by releasing staging buffers as finished weights move onto the GPU.
|
|
13
|
+
- **Cache weights across runs** to reuse downloaded byte ranges and skip repeated casts or decompression.
|
|
14
|
+
|
|
15
|
+
## From checkpoint to first JAX prediction
|
|
16
|
+
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
tensorferry requires Python 3.12 or newer. Once the first release is on PyPI, add it to your project with uv.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
uv add tensorferry
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## First-class support for safetensors
|
|
28
|
+
|
|
29
|
+
The 8M-parameter ESM-2 model stores its token embeddings in a 29.9 MiB checkpoint on Hugging Face and you are only interested in its embedding table. Simply pass its key to `load_arrays`.
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
import tensorferry as tf
|
|
33
|
+
|
|
34
|
+
source = "hf://facebook/esm2_t6_8M_UR50D@c731040fcd8d73dceaa04b0a8e6329b345b0f5df/model.safetensors"
|
|
35
|
+
key = "esm.embeddings.word_embeddings.weight"
|
|
36
|
+
|
|
37
|
+
with tf.track_downloads() as transfer:
|
|
38
|
+
embeddings = tf.load_arrays(source, names=[key], cache=False).result()[key]
|
|
39
|
+
|
|
40
|
+
print(embeddings.shape) # (33, 320)
|
|
41
|
+
print(transfer.snapshot()[0]) # 1090816 bytes received
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
tensorferry first fetches 1 MiB from the start of the file to read its header. The header locates the embedding table, so the next read covers just its 41.25 KiB. Together those two reads bring the total transfer to **1.04 MiB**.
|
|
45
|
+
|
|
46
|
+
If you don't know the key, `tf.index(source)` lists each tensor's name, shape, dtype, and byte range without building any arrays. Both `index` and `load_arrays` accept local paths, cloud storage, and HTTP(S) URLs that support range requests. For a sharded checkpoint, give either function the `.safetensors.index.json` file and tensorferry will follow it to each shard's header.
|
|
47
|
+
|
|
48
|
+
You can also combine files and in-memory arrays in one load, use your own storage client, or load named tensors directly onto a PyTorch or JAX device. [Loading options](docs/loading.md)
|
|
49
|
+
|
|
50
|
+
## Cache weights across runs
|
|
51
|
+
|
|
52
|
+
tensorferry caches weights on disk by default on supported POSIX systems. The ESM-2 example turns caching off to measure the download. Omit `cache=False` and try the same `source` and `key` twice.
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
for _ in range(2):
|
|
56
|
+
with tf.track_downloads() as transfer:
|
|
57
|
+
embeddings = tf.load_arrays(source, names=[key]).result()[key]
|
|
58
|
+
print(transfer.snapshot()[0])
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
With an empty cache, the first load fetches the byte ranges it needs. The second reads them from disk and prints **0**. If you ask for another tensor from the same file, tensorferry fetches any missing ranges. Processes can share the same cache directory on POSIX systems with `preadv`.
|
|
62
|
+
|
|
63
|
+
The cache also saves work after download. If your model uses bfloat16 weights from a float32 checkpoint, tensorferry can keep the converted arrays at their final size. It can do the same for decompressed `.npz` members. To cap disk usage, set a budget such as `TENSORFERRY_CACHE_MAX_BYTES=20G`. Source ranges and converted arrays share that budget, and tensorferry evicts the least recently used entries it can release.
|
|
64
|
+
|
|
65
|
+
Set `TENSORFERRY_CACHE` to a directory to move the cache or to `off` to disable it across an application. To bypass it for one load, pass `cache=False`. By default, tensorferry trusts the cached copy, which suits a pinned revision like the one above. If the contents can change at the same URL, use `tf.Cache(revalidate=True)` to check the source version on first access. [Cache configuration](docs/loading.md#configure-the-disk-cache)
|
|
66
|
+
|
|
67
|
+
## Load the same weights into different model layouts
|
|
68
|
+
|
|
69
|
+
The ESM-2 embedding table was ready to use as stored. When a model needs a different layout, you can tell tensorferry how the stored tensors fit together. Consider an attention checkpoint with three 4 × 4 matrices, one each for the query, key, and value projections.
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import numpy as np
|
|
73
|
+
|
|
74
|
+
eye = np.eye(4, dtype=np.float32)
|
|
75
|
+
np.savez("attention.npz", q=eye, k=2 * eye, v=3 * eye)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Fill a fused PyTorch projection
|
|
79
|
+
|
|
80
|
+
One PyTorch linear layer can compute all three projections at once. Its `weight` parameter needs 12 rows, so `Concat` joins `q`, `k`, and `v` along their rows in that order. Creating the layer on the `meta` device avoids allocating weights that the load would immediately replace.
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
import torch
|
|
84
|
+
from tensorferry import Concat
|
|
85
|
+
from tensorferry.torch import load
|
|
86
|
+
|
|
87
|
+
qkv = torch.nn.Linear(4, 12, bias=False, device="meta")
|
|
88
|
+
weight = Concat(["q", "k", "v"], axis=0)
|
|
89
|
+
load(qkv, "attention.npz", keys=lambda name, tensor: weight, device="cpu").result()
|
|
90
|
+
print(qkv(torch.ones(4)).reshape(3, 4)[:, 0].tolist()) # [1.0, 2.0, 3.0]
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Once `.result()` returns, you can call the layer directly. tensorferry updates the module in place, replacing its parameters and persistent buffers while keeping tied weights shared. If the checkpoint names already match the module's `state_dict()`, you can omit `keys`. To load floating-point weights as bfloat16 on a CUDA GPU, pass `dtype=torch.bfloat16, device="cuda"`.
|
|
94
|
+
|
|
95
|
+
If you need the populated state dictionary itself, `tensorferry.torch.load_state_dict(module, source).result()` gives you the tensors while preserving the original module.
|
|
96
|
+
|
|
97
|
+
### Compile in JAX while weights load
|
|
98
|
+
|
|
99
|
+
In JAX, the same three matrices can form a batch. `Stack` adds a leading axis so `matmul` can apply all three projections to one vector. To compile that operation, JAX needs to know the shape and dtype of the weights. Both are available in `pending.shape` as soon as this load starts.
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import jax
|
|
103
|
+
import jax.numpy as jnp
|
|
104
|
+
from tensorferry import Stack
|
|
105
|
+
from tensorferry.jax import load
|
|
106
|
+
|
|
107
|
+
template = jax.ShapeDtypeStruct((3, 4, 4), jnp.float32)
|
|
108
|
+
weights = Stack(["q", "k", "v"], axis=0)
|
|
109
|
+
pending = load(template, "attention.npz", keys=lambda path, target: weights)
|
|
110
|
+
x = jnp.ones(4, dtype=jnp.float32)
|
|
111
|
+
project = jax.jit(jnp.matmul).lower(pending.shape, x).compile()
|
|
112
|
+
print(project(pending.result(), x)[:, 0].tolist()) # [1.0, 2.0, 3.0]
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
The compiled function gets the actual weights from `pending.result()`, which waits for the load to finish. When you load a nested pytree, `.result()` returns the filled tree. By default, tensorferry matches its leaves to checkpoint keys using dotted paths such as `blocks.0.weight`. To distribute the arrays across devices, pass a JAX `Sharding` as the `device` argument.
|
|
116
|
+
|
|
117
|
+
## How tensorferry plans a load
|
|
118
|
+
|
|
119
|
+
Before assembling weights for PyTorch or JAX, tensorferry checks how the checkpoint maps to the model. With the default `strict=True`, `.result()` reports missing keys, unexpected keys, and incompatible shapes together in a `CheckpointMismatchError`. To load one subtree or allow known extra keys, use `prefix` or `ignore`. A `keys` callback can also map individual tensors to slices of a destination array. [Model mapping and placement](docs/loading.md#map-checkpoint-keys-to-a-model)
|
|
120
|
+
|
|
121
|
+
Once it has a plan, tensorferry groups nearby weights into byte ranges it can read concurrently. Reading across a small gap between weights can save a network round trip. For `.npz` files, tensorferry indexes the archive's member headers so it can find individual arrays and decompress those stored with deflate.
|
|
122
|
+
|
|
123
|
+
A local safetensors file can back compatible NumPy arrays and CPU PyTorch tensors directly through a copy-on-write memory map. For GPU loads, tensorferry releases host staging buffers as transfers finish. The `staging_bytes` setting on `tf.StreamingLoader` controls the budget for those buffers. A read that needs more room can run on its own.
|
|
124
|
+
|
|
125
|
+
In an archived ESM-C 6B benchmark, the download-first workflow fetched six float32 shards from GCS and loaded them with `EsmcModel.from_pretrained`. tensorferry streamed the same weights to CUDA. Both used bfloat16 on the GPU and ran in fresh JAX processes on a G4 VM in the bucket's region. Through the first prediction, the model process's peak resident set size was **25.5 GiB** with the download-first loader and **2.8 GiB** with tensorferry.
|
|
126
|
+
|
|
127
|
+
While a load runs, `pending.progress` counts completed output bytes. The download counter in the ESM-2 example measures bytes received over the network, which can be much smaller on a cache hit. [Progress and cancellation](docs/loading.md#monitor-a-background-load)
|
|
128
|
+
|
|
129
|
+
## Measure throughput on your storage
|
|
130
|
+
|
|
131
|
+
Run both benchmark modes on the same checkpoint. `ceiling` measures how fast your storage serves raw byte ranges. `sweep` bypasses tensorferry's cache and measures the full load, including the work of building the NumPy arrays. [Benchmark script](scripts/bench_remote.py)
|
|
132
|
+
|
|
133
|
+
```sh
|
|
134
|
+
url=gs://your-bucket/model.safetensors
|
|
135
|
+
python scripts/bench_remote.py ceiling "$url" --workers 4,16 --chunk-mib 8,32
|
|
136
|
+
python scripts/bench_remote.py sweep "$url" --workers 4,16 --chunk-mib 8,32
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Licensed under [Apache 2.0](LICENSE).
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tensorferry"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
description = "Streaming checkpoint loading for NumPy, JAX, and PyTorch"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Revanta" }]
|
|
14
|
+
dependencies = ["numpy>=2", "ml-dtypes>=0.5", "obstore>=0.11.1"]
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.packages.find]
|
|
17
|
+
where = ["src"]
|
|
18
|
+
include = ["tensorferry", "tensorferry.*"]
|
|
19
|
+
namespaces = false
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Repository = "https://github.com/Revanta-Inc/tensorferry"
|
|
23
|
+
|
|
24
|
+
[dependency-groups]
|
|
25
|
+
dev = ["pytest>=8", "safetensors>=0.4.5", "fsspec", "ruff>=0.9", "ty>=1.0.0"]
|
|
26
|
+
|
|
27
|
+
[tool.pytest.ini_options]
|
|
28
|
+
testpaths = ["tests"]
|
|
29
|
+
markers = ["remote: reads or writes a real object store"]
|
|
30
|
+
|
|
31
|
+
[tool.ruff]
|
|
32
|
+
line-length = 120
|
|
33
|
+
target-version = "py312"
|
|
34
|
+
src = ["src", "tests"]
|
|
35
|
+
|
|
36
|
+
[tool.ruff.lint]
|
|
37
|
+
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF", "N", "C4", "PIE", "PT", "PTH", "ANN"]
|
|
38
|
+
ignore = [
|
|
39
|
+
"F722", # jaxtyping shape specs (`Float[Array, "n c"]`) are not forward refs
|
|
40
|
+
"UP037", # ...and their quotes are necessary
|
|
41
|
+
"E741", # l/I/O are conventional tensor-axis names here
|
|
42
|
+
"N803", # argument names mirror the paper and checkpoint (Q, K, V, N_step)
|
|
43
|
+
"N806", # ditto for locals
|
|
44
|
+
"ANN401", # Any is legitimate in the pytree/feature-dict plumbing
|
|
45
|
+
"SIM108",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[tool.ruff.lint.per-file-ignores]
|
|
49
|
+
"tests/*" = ["ANN", "B018"]
|
|
50
|
+
"scripts/*" = ["ANN", "E501", "B023", "T201", "N812", "C408", "E402", "PTH111", "PT018"]
|
|
51
|
+
|
|
52
|
+
[tool.ty.environment]
|
|
53
|
+
root = ["./src", "."]
|
|
54
|
+
python-version = "3.12"
|
|
55
|
+
|
|
56
|
+
[tool.ty.analysis]
|
|
57
|
+
allowed-unresolved-imports = ["jax", "jax.**", "torch", "torch.**", "equinox"]
|
|
58
|
+
|
|
59
|
+
[tool.ty.rules]
|
|
60
|
+
unused-ignore-comment = "ignore"
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import concurrent.futures as cf
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import obstore
|
|
6
|
+
from obstore.store import from_url
|
|
7
|
+
|
|
8
|
+
import tensorferry as tf
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def ceiling(url, workers, chunk):
|
|
12
|
+
parent, _, name = url.rpartition("/")
|
|
13
|
+
store = from_url(parent)
|
|
14
|
+
size = obstore.head(store, name)["size"]
|
|
15
|
+
|
|
16
|
+
def get(start):
|
|
17
|
+
return len(obstore.get_range(store, name, start=start, end=min(start + chunk, size)))
|
|
18
|
+
|
|
19
|
+
start = time.perf_counter()
|
|
20
|
+
with cf.ThreadPoolExecutor(workers) as pool:
|
|
21
|
+
got = sum(pool.map(get, range(0, size, chunk)))
|
|
22
|
+
assert got == size
|
|
23
|
+
return size, time.perf_counter() - start
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def sweep(url, workers, chunks):
|
|
27
|
+
size = tf.index(url, cache=False).nbytes
|
|
28
|
+
for w in workers:
|
|
29
|
+
for c in chunks:
|
|
30
|
+
loader = tf.StreamingLoader(workers=w, chunk_bytes=c << 20)
|
|
31
|
+
start = time.perf_counter()
|
|
32
|
+
tf.load_arrays(url, loader=loader, cache=False).result()
|
|
33
|
+
dt = time.perf_counter() - start
|
|
34
|
+
print(
|
|
35
|
+
f"SWEEP workers={w:3d} chunk={c:3d}MiB {dt:6.2f} s {size / dt / 1e9:5.2f} GB/s",
|
|
36
|
+
flush=True,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def main():
|
|
41
|
+
parser = argparse.ArgumentParser()
|
|
42
|
+
parser.add_argument("what", choices=["ceiling", "sweep"])
|
|
43
|
+
parser.add_argument("url")
|
|
44
|
+
parser.add_argument("--workers", default="16")
|
|
45
|
+
parser.add_argument("--chunk-mib", default="32")
|
|
46
|
+
args = parser.parse_args()
|
|
47
|
+
workers = [int(w) for w in args.workers.split(",")]
|
|
48
|
+
chunks = [int(c) for c in args.chunk_mib.split(",")]
|
|
49
|
+
if args.what == "ceiling":
|
|
50
|
+
for w in workers:
|
|
51
|
+
for c in chunks:
|
|
52
|
+
size, dt = ceiling(args.url, w, c << 20)
|
|
53
|
+
print(
|
|
54
|
+
f"CEILING workers={w:3d} chunk={c:3d}MiB {dt:6.2f} s {size / dt / 1e9:5.2f} GB/s",
|
|
55
|
+
flush=True,
|
|
56
|
+
)
|
|
57
|
+
else:
|
|
58
|
+
sweep(args.url, workers, chunks)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
if __name__ == "__main__":
|
|
62
|
+
main()
|