tensorferry 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tensorferry/torch.py ADDED
@@ -0,0 +1,497 @@
1
+ import mmap
2
+ import threading
3
+ import weakref
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import ml_dtypes
9
+ import numpy as np
10
+ import torch
11
+
12
+ from tensorferry.api import Pending, Source, _start_arrays, _start_load
13
+ from tensorferry.backend import Backend
14
+ from tensorferry.cache import CacheLike
15
+ from tensorferry.formats import Index
16
+ from tensorferry.loader import Loader
17
+ from tensorferry.plan import Ignore, Plan, Request, Spec, Target, build_plan
18
+ from tensorferry.store import StoreLike
19
+
20
+ __all__ = [
21
+ "KeysFn",
22
+ "Placement",
23
+ "TorchBackend",
24
+ "load",
25
+ "load_arrays",
26
+ "load_state_dict",
27
+ "numpy_dtype",
28
+ "torch_dtype",
29
+ ]
30
+
31
+ # None: each tensor keeps its device, meta tensors go to torch's default device.
32
+ # A callable decides per tensor, from its state_dict name and current tensor.
33
+ type Placement = torch.device | str | Callable[[str, torch.Tensor], torch.device | str | None] | None
34
+ # Maps a state_dict name and its current tensor to the stored tensors behind it.
35
+ type KeysFn = Callable[[str, torch.Tensor], Spec]
36
+ type Model = torch.nn.Module | Mapping[str, torch.Tensor]
37
+
38
+ _TORCH_TO_NUMPY: dict[torch.dtype, np.dtype] = {
39
+ torch.float64: np.dtype(np.float64),
40
+ torch.float32: np.dtype(np.float32),
41
+ torch.float16: np.dtype(np.float16),
42
+ torch.bfloat16: np.dtype(ml_dtypes.bfloat16),
43
+ torch.float8_e4m3fn: np.dtype(ml_dtypes.float8_e4m3fn),
44
+ torch.float8_e5m2: np.dtype(ml_dtypes.float8_e5m2),
45
+ torch.complex64: np.dtype(np.complex64),
46
+ torch.complex128: np.dtype(np.complex128),
47
+ torch.int64: np.dtype(np.int64),
48
+ torch.int32: np.dtype(np.int32),
49
+ torch.int16: np.dtype(np.int16),
50
+ torch.int8: np.dtype(np.int8),
51
+ torch.uint64: np.dtype(np.uint64),
52
+ torch.uint32: np.dtype(np.uint32),
53
+ torch.uint16: np.dtype(np.uint16),
54
+ torch.uint8: np.dtype(np.uint8),
55
+ torch.bool: np.dtype(np.bool_),
56
+ }
57
+ _NUMPY_TO_TORCH = {v: k for k, v in _TORCH_TO_NUMPY.items()}
58
+
59
+
60
+ def numpy_dtype(dtype: torch.dtype) -> np.dtype:
61
+ if dtype not in _TORCH_TO_NUMPY:
62
+ raise TypeError(f"no numpy dtype for {dtype}")
63
+ return _TORCH_TO_NUMPY[dtype]
64
+
65
+
66
+ def torch_dtype(dtype: np.dtype) -> torch.dtype:
67
+ key = np.dtype(dtype).newbyteorder("=")
68
+ if key not in _NUMPY_TO_TORCH:
69
+ raise TypeError(f"no torch dtype for {dtype}")
70
+ return _NUMPY_TO_TORCH[key]
71
+
72
+
73
+ # What torch.from_numpy takes directly. Everything else -- bf16 and every fp8
74
+ # (ml_dtypes, whose numpy kind varies: e5m2 reports "f") and the wider
75
+ # unsigned integers on older torch -- goes through a uint8 view instead.
76
+ _FROM_NUMPY = frozenset(
77
+ np.dtype(t)
78
+ for t in (
79
+ np.float16, np.float32, np.float64, np.complex64, np.complex128,
80
+ np.int8, np.int16, np.int32, np.int64, np.uint8, np.bool_,
81
+ )
82
+ ) # fmt: skip
83
+
84
+
85
+ def _as_tensor(buffer: np.ndarray) -> torch.Tensor:
86
+ if not buffer.dtype.isnative:
87
+ buffer = buffer.astype(buffer.dtype.newbyteorder("="))
88
+ if buffer.dtype in _FROM_NUMPY:
89
+ return torch.from_numpy(buffer)
90
+ raw = torch.from_numpy(buffer.reshape(-1).view(np.uint8))
91
+ return raw.view(torch_dtype(buffer.dtype)).reshape(buffer.shape)
92
+
93
+
94
+ class TorchBackend:
95
+ """CUDA transfers use pinned host buffers by default."""
96
+
97
+ _ALIGN = 64
98
+ _MAPPED_BATCH_BYTES = 32 << 20
99
+
100
+ def __init__(self, *, pin_memory: bool | None = None) -> None:
101
+ self.pin_memory = pin_memory
102
+ # Arenas by the id of their host array, which every buffer of the batch
103
+ # views. An entry goes when that array dies, so a batch abandoned by a
104
+ # failed or cancelled load cannot keep its arena (or pinned pages) alive,
105
+ # and an id is never reused while its entry exists.
106
+ self._arenas: dict[int, tuple[weakref.ref[np.ndarray], torch.Tensor, list[int]]] = {}
107
+ self._lock = threading.Lock()
108
+
109
+ def accepts_mapped(self, target: Target) -> bool:
110
+ """CPU tensors retain file views; CUDA copies file ranges without staging."""
111
+ device = _device_of(target).type
112
+ return device == "cpu" or (device == "cuda" and self.pin_memory is not True)
113
+
114
+ def host_buffer(self, target: Target) -> np.ndarray:
115
+ raw = self._raw(target.nbytes, _device_of(target))
116
+ if raw is None:
117
+ return np.empty(target.shape, target.dtype)
118
+ return raw.numpy().view(target.dtype).reshape(target.shape)
119
+
120
+ def finish(self, target: Target, buffer: np.ndarray) -> Any:
121
+ return self._move(_as_tensor(buffer), _device_of(target))
122
+
123
+ def host_buffers(self, targets: Sequence[Target]) -> list[np.ndarray]:
124
+ device = _device_of(targets[0])
125
+ if (
126
+ device.type == "cpu"
127
+ or any(_device_of(t) != device for t in targets)
128
+ # A big-endian array must be converted, which a raw arena copy cannot do.
129
+ or any(not t.dtype.isnative for t in targets)
130
+ ):
131
+ return [self.host_buffer(t) for t in targets]
132
+ offsets, size = [], 0
133
+ for t in targets:
134
+ size = -(-size // self._ALIGN) * self._ALIGN
135
+ offsets.append(size)
136
+ size += t.nbytes
137
+ raw = self._raw(size, device)
138
+ arena = raw if raw is not None else torch.from_numpy(np.empty(size, np.uint8))
139
+ flat = arena.numpy()
140
+ buffers = [flat[o : o + t.nbytes].view(t.dtype).reshape(t.shape) for t, o in zip(targets, offsets, strict=True)]
141
+ with self._lock:
142
+ self._arenas[id(flat)] = (weakref.ref(flat), arena, offsets)
143
+ weakref.finalize(flat, self._forget, id(flat))
144
+ return buffers
145
+
146
+ def finish_many(self, targets: Sequence[Target], buffers: Sequence[np.ndarray]) -> list[Any]:
147
+ entry = self._take(buffers[0])
148
+ if entry is None:
149
+ mapped = self._finish_mapped_many(targets, buffers)
150
+ if mapped is not None:
151
+ return mapped
152
+ return [self.finish(t, b) for t, b in zip(targets, buffers, strict=True)]
153
+ arena, offsets = entry
154
+ placed = self._move(arena, _device_of(targets[0]))
155
+ return [
156
+ placed[o : o + t.nbytes].view(torch_dtype(t.dtype)).reshape(t.shape)
157
+ for t, o in zip(targets, offsets, strict=True)
158
+ ]
159
+
160
+ def _finish_mapped_many(self, targets: Sequence[Target], buffers: Sequence[np.ndarray]) -> list[Any] | None:
161
+ """Copy adjacent mapped tensors with one transfer per bounded file range."""
162
+ device = _device_of(targets[0])
163
+ if device.type != "cuda" or any(_device_of(t) != device for t in targets):
164
+ return None
165
+
166
+ def mapping_of(buffer: np.ndarray) -> mmap.mmap | None:
167
+ root: Any = buffer
168
+ while isinstance(root, np.ndarray) and root.base is not None:
169
+ root = root.base
170
+ if isinstance(root, memoryview):
171
+ root = root.obj
172
+ return root if isinstance(root, mmap.mmap) else None
173
+
174
+ mapping = mapping_of(buffers[0])
175
+ if mapping is None or any(mapping_of(b) is not mapping for b in buffers[1:]):
176
+ return None
177
+ source = np.frombuffer(mapping, np.uint8)
178
+ origin = source.ctypes.data
179
+ spans = sorted((b.ctypes.data - origin, i, b.nbytes) for i, b in enumerate(buffers))
180
+ out: list[Any] = [None] * len(targets)
181
+ batch: list[tuple[int, int, int]] = []
182
+ lo = hi = 0
183
+
184
+ def finish() -> None:
185
+ placed = self._move(torch.from_numpy(source[lo:hi]), device)
186
+ for start, i, size in batch:
187
+ out[i] = (
188
+ placed[start - lo : start - lo + size].view(torch_dtype(targets[i].dtype)).reshape(targets[i].shape)
189
+ )
190
+
191
+ for start, i, size in spans:
192
+ if batch and (
193
+ start < hi
194
+ or start - hi > self._ALIGN
195
+ or start + size - lo > self._MAPPED_BATCH_BYTES
196
+ # Match the alignment of staged CUDA tensors: kernels can
197
+ # choose different arithmetic for an unaligned weight pointer.
198
+ or (start - lo) % self._ALIGN
199
+ or (start - lo) % targets[i].dtype.itemsize
200
+ ):
201
+ finish()
202
+ batch = []
203
+ if not batch:
204
+ lo = start
205
+ hi = start + size
206
+ batch.append((start, i, size))
207
+ if batch:
208
+ finish()
209
+ return out
210
+
211
+ def _take(self, buffer: np.ndarray) -> tuple[torch.Tensor, list[int]] | None:
212
+ node: Any = buffer
213
+ with self._lock:
214
+ while isinstance(node, np.ndarray):
215
+ entry = self._arenas.get(id(node))
216
+ if entry is not None and entry[0]() is node:
217
+ del self._arenas[id(node)]
218
+ return entry[1], entry[2]
219
+ node = node.base
220
+ return None
221
+
222
+ def _forget(self, key: int) -> None:
223
+ with self._lock:
224
+ self._arenas.pop(key, None)
225
+
226
+ def _raw(self, nbytes: int, device: torch.device) -> torch.Tensor | None:
227
+ """Pinned host bytes for a CUDA target, or None for ordinary memory."""
228
+ pin = self.pin_memory if self.pin_memory is not None else device.type == "cuda"
229
+ if pin and torch.cuda.is_available():
230
+ return torch.empty(nbytes, dtype=torch.uint8, pin_memory=True)
231
+ return None
232
+
233
+ def _move(self, host: torch.Tensor, device: torch.device) -> torch.Tensor:
234
+ if device.type == "cpu":
235
+ return host
236
+ if device.type == "cuda":
237
+ pinned = host.is_pinned()
238
+ out = host.to(device, non_blocking=pinned)
239
+ if pinned:
240
+ torch.cuda.current_stream(device).synchronize()
241
+ return out
242
+ return host.to(device)
243
+
244
+
245
+ def _device_of(target: Target) -> torch.device:
246
+ return target.placement if target.placement is not None else torch.device("cpu")
247
+
248
+
249
+ @dataclass(frozen=True, eq=False)
250
+ class _Layout:
251
+ groups: tuple[tuple[str, ...], ...] # names sharing one tensor, in state_dict order
252
+ templates: tuple[torch.Tensor, ...] # each group's current tensor
253
+ targets: tuple[Target, ...]
254
+
255
+ def shape_of(self, filled: Iterable[int]) -> dict[str, torch.Tensor]:
256
+ loaded = set(filled)
257
+ out: dict[str, torch.Tensor] = {}
258
+ for i, (names, template, target) in enumerate(zip(self.groups, self.templates, self.targets, strict=True)):
259
+ dtype = torch_dtype(target.dtype) if i in loaded else template.dtype
260
+ out |= dict.fromkeys(names, torch.empty(target.shape, dtype=dtype, device="meta"))
261
+ return out
262
+
263
+
264
+ def _layout(model: Model, dtype: torch.dtype | None, device: Placement) -> _Layout:
265
+ state = model.state_dict(keep_vars=True) if isinstance(model, torch.nn.Module) else model
266
+ place = _placement(device)
267
+ by_tensor: dict[int, list[str]] = {}
268
+ tensors: dict[int, torch.Tensor] = {}
269
+ for name, tensor in state.items():
270
+ by_tensor.setdefault(id(tensor), []).append(name)
271
+ tensors[id(tensor)] = tensor
272
+ groups, templates, targets = [], [], []
273
+ for key, names in by_tensor.items():
274
+ tensor = tensors[key]
275
+ final = dtype if dtype is not None and tensor.is_floating_point() else tensor.dtype
276
+ groups.append(tuple(names))
277
+ templates.append(tensor)
278
+ targets.append(Target(tuple(tensor.shape), numpy_dtype(final), place(names[0], tensor)))
279
+ return _Layout(tuple(groups), tuple(templates), tuple(targets))
280
+
281
+
282
+ def _specs(lay: _Layout, keys: KeysFn | None, prefix: str) -> tuple[list[list[Spec]], str]:
283
+ if keys is None:
284
+ head = f"{prefix}." if prefix else ""
285
+
286
+ def keys(name: str, tensor: torch.Tensor) -> Spec:
287
+ return head + name
288
+
289
+ scope = head
290
+ else:
291
+ scope = prefix
292
+ specs = [
293
+ [keys(name, template) for name in names] for names, template in zip(lay.groups, lay.templates, strict=True)
294
+ ]
295
+ return specs, scope
296
+
297
+
298
+ def _skipped(group_specs: list[Spec]) -> bool:
299
+ return all(spec is None for spec in group_specs)
300
+
301
+
302
+ def _plan(
303
+ lay: _Layout,
304
+ index: Index,
305
+ specs: list[list[Spec]],
306
+ scope: str,
307
+ strict: bool,
308
+ ignore: Ignore = (),
309
+ ) -> Plan:
310
+ requests, tied_copies = [], set()
311
+ for i, (names, template, target, group) in enumerate(
312
+ zip(lay.groups, lay.templates, lay.targets, specs, strict=True)
313
+ ):
314
+ # A tied tensor loads from whichever of its names the checkpoint holds.
315
+ present = [j for j, s in enumerate(group) if isinstance(s, str) and s in index]
316
+ named = [j for j, s in enumerate(group) if s is not None]
317
+ chosen = present[0] if present else (named[0] if named else 0)
318
+ tied_copies |= {group[j] for j in present[1:]}
319
+ requests.append(Request(i, names[chosen], target, group[chosen], required=template.is_meta))
320
+ user = ignore if callable(ignore) else frozenset(ignore).__contains__
321
+
322
+ def ignored(key: str) -> bool:
323
+ return key in tied_copies or bool(user(key))
324
+
325
+ return build_plan(requests, index, strict=strict, scope=scope, ignore=ignored)
326
+
327
+
328
+ def _shapes(
329
+ lay: _Layout, specs: list[list[Spec]], strict: bool
330
+ ) -> tuple[dict[str, torch.Tensor] | None, Callable[[Plan], dict[str, torch.Tensor]] | None]:
331
+ """`start`'s `shape` / `shape_of`: known at once when strict, else once the plan is."""
332
+ if strict:
333
+ return lay.shape_of(i for i, group in enumerate(specs) if not _skipped(group)), None
334
+ return None, lambda planned: lay.shape_of(f.index for f in planned.fills)
335
+
336
+
337
+ def _state_dict(lay: _Layout, arrays: dict[int, Any]) -> dict[str, torch.Tensor]:
338
+ out: dict[str, torch.Tensor] = {}
339
+ for i, (names, template) in enumerate(zip(lay.groups, lay.templates, strict=True)):
340
+ out |= dict.fromkeys(names, arrays.get(i, template))
341
+ return out
342
+
343
+
344
+ def _assign(module: torch.nn.Module, lay: _Layout, arrays: dict[int, Any]) -> torch.nn.Module:
345
+ for i, (names, template) in enumerate(zip(lay.groups, lay.templates, strict=True)):
346
+ if i not in arrays:
347
+ continue
348
+ tensor = arrays[i]
349
+ if isinstance(template, torch.nn.Parameter):
350
+ tensor = torch.nn.Parameter(tensor, requires_grad=template.requires_grad)
351
+ for name in names:
352
+ owner_name, _, attr = name.rpartition(".")
353
+ owner = module.get_submodule(owner_name)
354
+ if attr in owner._parameters:
355
+ owner._parameters[attr] = tensor
356
+ else:
357
+ owner._buffers[attr] = tensor
358
+ return module
359
+
360
+
361
+ def load(
362
+ module: torch.nn.Module,
363
+ source: Source | Sequence[Source],
364
+ *,
365
+ store: StoreLike | None = None,
366
+ keys: KeysFn | None = None,
367
+ prefix: str = "",
368
+ strict: bool = True,
369
+ ignore: Ignore = (),
370
+ dtype: torch.dtype | None = None,
371
+ device: Placement = None,
372
+ loader: Loader | None = None,
373
+ backend: Backend | None = None,
374
+ cache: CacheLike = None,
375
+ ) -> Pending[torch.nn.Module]:
376
+ """Replaces parameters and persistent buffers in place, preserving requires_grad. Wait for pending.result() before
377
+ using the module.
378
+ """
379
+ return _start_model(
380
+ module,
381
+ source,
382
+ (lambda lay, arrays: _assign(module, lay, arrays)),
383
+ store=store,
384
+ keys=keys,
385
+ prefix=prefix,
386
+ strict=strict,
387
+ ignore=ignore,
388
+ dtype=dtype,
389
+ device=device,
390
+ loader=loader,
391
+ backend=backend,
392
+ cache=cache,
393
+ )
394
+
395
+
396
+ def load_state_dict(
397
+ model: Model,
398
+ source: Source | Sequence[Source],
399
+ *,
400
+ store: StoreLike | None = None,
401
+ keys: KeysFn | None = None,
402
+ prefix: str = "",
403
+ strict: bool = True,
404
+ ignore: Ignore = (),
405
+ dtype: torch.dtype | None = None,
406
+ device: Placement = None,
407
+ loader: Loader | None = None,
408
+ backend: Backend | None = None,
409
+ cache: CacheLike = None,
410
+ ) -> Pending[dict[str, torch.Tensor]]:
411
+ return _start_model(
412
+ model,
413
+ source,
414
+ _state_dict,
415
+ store=store,
416
+ keys=keys,
417
+ prefix=prefix,
418
+ strict=strict,
419
+ ignore=ignore,
420
+ dtype=dtype,
421
+ device=device,
422
+ loader=loader,
423
+ backend=backend,
424
+ cache=cache,
425
+ )
426
+
427
+
428
+ def load_arrays(
429
+ source: Source | Sequence[Source],
430
+ *,
431
+ store: StoreLike | None = None,
432
+ names: Sequence[str] | None = None,
433
+ device: torch.device | str = "cpu",
434
+ loader: Loader | None = None,
435
+ cache: CacheLike = None,
436
+ ) -> Pending[dict[str, torch.Tensor]]:
437
+ return _start_arrays(
438
+ source,
439
+ store=store,
440
+ names=names,
441
+ backend=TorchBackend(),
442
+ placement=torch.device(device),
443
+ loader=loader,
444
+ cache=cache,
445
+ native=True,
446
+ shape=lambda t: torch.empty(t.shape, dtype=torch_dtype(t.dtype), device="meta"),
447
+ )
448
+
449
+
450
+ def _start_model[T](
451
+ model: Model,
452
+ source: Source | Sequence[Source],
453
+ assemble: Callable[["_Layout", dict[int, Any]], T],
454
+ *,
455
+ store: StoreLike | None,
456
+ keys: KeysFn | None,
457
+ prefix: str,
458
+ strict: bool,
459
+ ignore: Ignore,
460
+ dtype: torch.dtype | None,
461
+ device: Placement,
462
+ loader: Loader | None,
463
+ backend: Backend | None,
464
+ cache: CacheLike,
465
+ ) -> Pending[T]:
466
+ lay = _layout(model, dtype, device)
467
+ specs, scope = _specs(lay, keys, prefix)
468
+ shape, shape_of = _shapes(lay, specs, strict)
469
+ return _start_load(
470
+ source,
471
+ store,
472
+ cache,
473
+ lambda index: _plan(lay, index, specs, scope, strict, ignore),
474
+ lambda _, arrays: assemble(lay, arrays),
475
+ backend=backend or TorchBackend(),
476
+ loader=loader,
477
+ shape=shape,
478
+ shape_of=shape_of,
479
+ )
480
+
481
+
482
+ def _placement(device: Placement) -> Callable[[str, torch.Tensor], torch.device]:
483
+ """`device` as a per-tensor function, with the default device fixed now."""
484
+ if device is None:
485
+ default = _default_device()
486
+ return lambda name, tensor: default if tensor.is_meta else tensor.device
487
+ if callable(device) and not isinstance(device, (str, torch.device)):
488
+ chosen = device
489
+ return lambda name, tensor: torch.device(chosen(name, tensor) or "cpu")
490
+ fixed = torch.device(device)
491
+ return lambda name, tensor: fixed
492
+
493
+
494
+ def _default_device() -> torch.device:
495
+ """torch's default device for new tensors, or the CPU when that is ``meta``."""
496
+ device = torch.get_default_device()
497
+ return torch.device("cpu") if device.type == "meta" else device
@@ -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
+ ![Two JAX workflows from checkpoint to first prediction. tensorferry overlaps selected reads, remapping, device transfers, and compilation. In a separate ESM-C 6B GPU benchmark, the model process peaked at 2.8 GiB of host RAM with tensorferry versus 25.5 GiB with the download-first loader.](https://raw.githubusercontent.com/Revanta-Inc/tensorferry/main/docs/checkpoint-to-prediction.svg)
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,17 @@
1
+ tensorferry/__init__.py,sha256=lrmdiAMLU7v-wJBfGaZZ8ZakIVpE4D2R_Pl0-so5YC4,1408
2
+ tensorferry/_pool.py,sha256=S0yR07HyuYGEhKrv-5nlUHPRF1ak-8-bgmoesRu0PNI,4337
3
+ tensorferry/api.py,sha256=ALvYQ82K2VgbOmRxpYkHVn3l2xxt8ABDVFAfGrnfjx8,9359
4
+ tensorferry/backend.py,sha256=2qBJ2jgc57RoP23dcEYFxzQQ_lQ5YiXoLh2B-4D5UJU,786
5
+ tensorferry/cache.py,sha256=kjwVI-HJWKOmHefcbDbxQtXSu4nxE9Ktl-JvW7vI0ZI,42511
6
+ tensorferry/formats.py,sha256=mhuydB67O4-_8F55TI0z2AjyKIzl1r8L0BFtogI4LHk,15008
7
+ tensorferry/jax.py,sha256=fmhIZW7ijxcUYDaeBXIcCu4rONxpgwaS8EEhvIrI9UQ,11070
8
+ tensorferry/loader.py,sha256=o03qPy4FyCNeHriiyttoue0Il0yvHxBAUgRH3TOF2TI,23387
9
+ tensorferry/plan.py,sha256=sMoiy-BuG1P0eJmzkW7UpKlcstVj1wys7qurkOuqKqc,10118
10
+ tensorferry/progress.py,sha256=5taG43nI7OKxIF7GFr5_MR_VCWmCv-IRSm6j9vymzVg,3022
11
+ tensorferry/store.py,sha256=9VZ4hWhgMeT3LIMdpL4f7wmxHKM4dZ-QkgBA3zSFIA4,12847
12
+ tensorferry/torch.py,sha256=l-UfsPN6S8sja54UGMipfk9WeAo-RQiiIleTM_wqk5Y,18356
13
+ tensorferry-0.1.0.dist-info/licenses/LICENSE,sha256=fE-s5Yysu_1hZmpbZIBj5SHplYK1HmfFPBI9045BvMM,11341
14
+ tensorferry-0.1.0.dist-info/METADATA,sha256=HuKNbJTeUwphsG3dAKxFL44DsnjUP1zWe8gHZ4YQahk,10382
15
+ tensorferry-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
16
+ tensorferry-0.1.0.dist-info/top_level.txt,sha256=tEyZXhcwDrb31nxogwm0EtXCHDdl_TOZp0CC6wqsaJA,12
17
+ tensorferry-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+