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/formats.py ADDED
@@ -0,0 +1,374 @@
1
+ import ast
2
+ import functools
3
+ import itertools
4
+ import json
5
+ import math
6
+ import struct
7
+ import threading
8
+ import zlib
9
+ from collections.abc import Iterator, Mapping, Sequence
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Literal
12
+
13
+ import ml_dtypes
14
+ import numpy as np
15
+
16
+ from tensorferry._pool import DaemonPool, check_cancel
17
+ from tensorferry.store import Blob
18
+
19
+ __all__ = ["FormatError", "Index", "Tensor", "read_index"]
20
+
21
+
22
+ class FormatError(ValueError):
23
+ pass
24
+
25
+
26
+ @dataclass(frozen=True, slots=True, eq=False)
27
+ class Tensor:
28
+ """One stored array: its key, shape and dtype, and how to get its bytes."""
29
+
30
+ key: str
31
+ shape: tuple[int, ...]
32
+ dtype: np.dtype
33
+ blob: Blob | None = None
34
+ start: int = 0
35
+ stop: int = 0
36
+ codec: Literal["raw", "deflate"] = "raw"
37
+ skip: int = 0
38
+ fortran: bool = False
39
+ array: np.ndarray | None = field(default=None, repr=False)
40
+ crc32: int | None = None
41
+ crc_seed: int = 0
42
+
43
+ @property
44
+ def nbytes(self) -> int:
45
+ return math.prod(self.shape) * self.dtype.itemsize
46
+
47
+ @property
48
+ def where(self) -> str:
49
+ return "<memory>" if self.blob is None else str(self.blob)
50
+
51
+
52
+ class Index(Mapping[str, Tensor]):
53
+ def __init__(self, tensors: dict[str, Tensor], metadata: dict[str, dict[str, Any]]) -> None:
54
+ self._tensors = tensors
55
+ self.metadata = metadata
56
+
57
+ def __getitem__(self, key: str) -> Tensor:
58
+ return self._tensors[key]
59
+
60
+ def __iter__(self) -> Iterator[str]:
61
+ return iter(self._tensors)
62
+
63
+ def __len__(self) -> int:
64
+ return len(self._tensors)
65
+
66
+ @property
67
+ def nbytes(self) -> int:
68
+ return sum(t.nbytes for t in self._tensors.values())
69
+
70
+
71
+ def read_index(sources: Sequence[Blob | Mapping[str, Any]], *, cancel: threading.Event | None = None) -> Index:
72
+ """Reads headers only. Duplicate tensor keys across files raise FormatError."""
73
+ with DaemonPool(min(8, len(sources))) as pool:
74
+ found = pool.map(functools.partial(_index_one, cancel=cancel), sources, cancel=cancel)
75
+ tensors: dict[str, Tensor] = {}
76
+ metadata: dict[str, dict[str, Any]] = {}
77
+ for part, meta in found:
78
+ for key, tensor in part.items():
79
+ if key in tensors:
80
+ raise FormatError(f"{key!r} is in both {tensors[key].where} and {tensor.where}")
81
+ tensors[key] = tensor
82
+ metadata |= meta
83
+ return Index(tensors, metadata)
84
+
85
+
86
+ type _Found = tuple[dict[str, Tensor], dict[str, dict[str, Any]]]
87
+
88
+
89
+ def _index_one(source: Blob | Mapping[str, Any], cancel: threading.Event | None) -> _Found:
90
+ if isinstance(source, Mapping):
91
+ arrays = {key: np.asarray(value) for key, value in source.items()}
92
+ return {k: Tensor(k, a.shape, a.dtype, array=a) for k, a in arrays.items()}, {}
93
+ name = source.name.lower()
94
+ if name.endswith(".safetensors.index.json"):
95
+ return _sharded(source, cancel)
96
+ if name.endswith(".safetensors"):
97
+ tensors, metadata = _safetensors(source)
98
+ return tensors, {source.name: metadata}
99
+ if name.endswith(".npz"):
100
+ return _npz(source, cancel), {source.name: {}}
101
+ raise FormatError(f"{source}: unknown format (expected .safetensors, .safetensors.index.json or .npz)")
102
+
103
+
104
+ # --- safetensors -------------------------------------------------------------
105
+
106
+ _SAFETENSORS_DTYPES = {
107
+ "BOOL": np.dtype(np.bool_),
108
+ "U8": np.dtype("<u1"),
109
+ "I8": np.dtype("<i1"),
110
+ "U16": np.dtype("<u2"),
111
+ "I16": np.dtype("<i2"),
112
+ "U32": np.dtype("<u4"),
113
+ "I32": np.dtype("<i4"),
114
+ "U64": np.dtype("<u8"),
115
+ "I64": np.dtype("<i8"),
116
+ "F16": np.dtype("<f2"),
117
+ "F32": np.dtype("<f4"),
118
+ "F64": np.dtype("<f8"),
119
+ "BF16": np.dtype(ml_dtypes.bfloat16),
120
+ "F8_E4M3": np.dtype(ml_dtypes.float8_e4m3fn),
121
+ "F8_E5M2": np.dtype(ml_dtypes.float8_e5m2),
122
+ }
123
+ # One request usually covers the whole header: 4482 tensors' worth is ~0.5 MB.
124
+ _SAFETENSORS_PREFETCH = 1 << 20
125
+ _SAFETENSORS_MAX_HEADER = 100 << 20
126
+
127
+
128
+ def _safetensors(blob: Blob) -> tuple[dict[str, Tensor], dict[str, Any]]:
129
+ head = blob.fetch(0, _SAFETENSORS_PREFETCH)
130
+ if head.size < 8:
131
+ raise FormatError(f"{blob}: too short to be a safetensors file")
132
+ n = int.from_bytes(head[:8].tobytes(), "little")
133
+ if n > _SAFETENSORS_MAX_HEADER:
134
+ raise FormatError(f"{blob}: implausible header length {n}")
135
+ if head.size < 8 + n:
136
+ head = np.concatenate([head, blob.fetch(head.size, 8 + n)])
137
+ if head.size < 8 + n:
138
+ raise FormatError(f"{blob}: the header runs past the end of the file")
139
+ try:
140
+ header = json.loads(head[8 : 8 + n].tobytes())
141
+ except ValueError as exc:
142
+ raise FormatError(f"{blob}: the header is not JSON") from exc
143
+ metadata = header.pop("__metadata__", None) or {}
144
+ base = 8 + n
145
+ tensors: dict[str, Tensor] = {}
146
+ for key, info in header.items():
147
+ try:
148
+ code, shape, (begin, end) = info["dtype"], info["shape"], info["data_offsets"]
149
+ shape = tuple(int(d) for d in shape)
150
+ except (KeyError, TypeError, ValueError) as exc:
151
+ raise FormatError(f"{blob}: malformed header entry for {key!r}") from exc
152
+ if code not in _SAFETENSORS_DTYPES:
153
+ raise FormatError(f"{blob}: {key!r} has unsupported dtype {code}")
154
+ dtype = _SAFETENSORS_DTYPES[code]
155
+ if begin < 0 or end - begin != math.prod(shape) * dtype.itemsize:
156
+ raise FormatError(f"{blob}: {key!r} spans {end - begin} bytes, not {shape} {dtype}")
157
+ tensors[key] = Tensor(key, shape, dtype, blob, base + begin, base + end)
158
+ # Tensors must not share bytes: arrays mapped from overlapping ranges would
159
+ # alias each other. (safetensors itself requires them to be packed.)
160
+ spans = sorted((t.start, t.stop, k) for k, t in tensors.items() if t.stop > t.start)
161
+ for (_, stop, a), (start, _, b) in itertools.pairwise(spans):
162
+ if start < stop:
163
+ raise FormatError(f"{blob}: the data of {a!r} and {b!r} overlap")
164
+ return tensors, metadata
165
+
166
+
167
+ def _sharded(blob: Blob, cancel: threading.Event | None) -> _Found:
168
+ text = blob.fetch(0, _SAFETENSORS_MAX_HEADER)
169
+ try:
170
+ weight_map: dict[str, str] = json.loads(text.tobytes())["weight_map"]
171
+ except (ValueError, KeyError, TypeError) as exc:
172
+ raise FormatError(f"{blob}: not a safetensors index (no weight_map)") from exc
173
+ shards = sorted(set(weight_map.values()))
174
+ files = [blob.sibling(s) for s in shards]
175
+ with DaemonPool(min(16, len(shards))) as pool:
176
+ found = pool.map(_safetensors, files, cancel=cancel)
177
+ tensors: dict[str, Tensor] = {}
178
+ metadata: dict[str, dict[str, Any]] = {}
179
+ for shard, file, (part, meta) in zip(shards, files, found, strict=True):
180
+ metadata[file.name] = meta
181
+ for key, tensor in part.items():
182
+ if weight_map.get(key) != shard:
183
+ raise FormatError(f"{blob}: {key!r} is in {shard}, the index says {weight_map.get(key)}")
184
+ tensors[key] = tensor
185
+ if missing := sorted(weight_map.keys() - tensors.keys()):
186
+ raise FormatError(f"{blob}: {len(missing)} indexed tensors are in no shard, e.g. {missing[0]!r}")
187
+ return tensors, metadata
188
+
189
+
190
+ # --- npz ---------------------------------------------------------------------
191
+
192
+ _EOCD, _EOCD64, _LOCATOR64 = b"PK\x05\x06", b"PK\x06\x06", b"PK\x06\x07"
193
+ _CENTRAL, _LOCAL = b"PK\x01\x02", b"PK\x03\x04"
194
+ # The end records plus, usually, the whole central directory -- and all of any
195
+ # file this small, which is then indexed from that one request.
196
+ _NPZ_TAIL = 1 << 20
197
+ _NPY_WINDOW = 1 << 13 # local header plus .npy header, read per member
198
+ _NPY_MAX_HEADER = 1 << 20
199
+
200
+
201
+ @dataclass(frozen=True, slots=True)
202
+ class _Member:
203
+ key: str
204
+ method: int
205
+ csize: int
206
+ usize: int
207
+ offset: int
208
+ crc: int
209
+
210
+
211
+ def _npz(blob: Blob, cancel: threading.Event | None) -> dict[str, Tensor]:
212
+ tail, size = blob.tail(_NPZ_TAIL)
213
+ base = size - tail.size
214
+ raw = tail.tobytes()
215
+ whole = raw if base == 0 else None
216
+ at = raw.rfind(_EOCD, max(0, len(raw) - 22 - 0xFFFF))
217
+ if at < 0 or len(raw) - at < 22:
218
+ raise FormatError(f"{blob}: not a zip archive (no end of central directory)")
219
+ count, cd_size, cd_offset = struct.unpack_from("<4s4H2LH", raw, at)[4:7]
220
+ if count == 0xFFFF or 0xFFFFFFFF in (cd_size, cd_offset):
221
+ if at < 20 or raw[at - 20 : at - 16] != _LOCATOR64:
222
+ raise FormatError(f"{blob}: zip64 archive without a zip64 locator")
223
+ offset64 = struct.unpack_from("<4sLQL", raw, at - 20)[2]
224
+ record = _span(blob, raw, base, offset64, 56)
225
+ if record[:4] != _EOCD64:
226
+ raise FormatError(f"{blob}: bad zip64 end of central directory")
227
+ count, cd_size, cd_offset = struct.unpack_from("<4sQ2H2L4Q", record)[7:10]
228
+ directory = _span(blob, raw, base, cd_offset, cd_size)
229
+ members = list(_central_directory(blob, directory, count))
230
+ if whole is not None:
231
+ found = [_member(blob, m, whole, cancel) for m in members]
232
+ else:
233
+ with DaemonPool(min(16, len(members))) as pool:
234
+ found = pool.map(lambda m: _member(blob, m, None, cancel), members, cancel=cancel)
235
+ return {t.key: t for t in found}
236
+
237
+
238
+ def _span(blob: Blob, raw: bytes, base: int, offset: int, length: int) -> bytes:
239
+ if offset >= base and offset + length <= base + len(raw):
240
+ return raw[offset - base : offset - base + length]
241
+ return blob.fetch_exact(offset, offset + length).tobytes()
242
+
243
+
244
+ def _central_directory(blob: Blob, data: bytes, count: int) -> Iterator[_Member]:
245
+ pos = 0
246
+ for _ in range(count):
247
+ if data[pos : pos + 4] != _CENTRAL:
248
+ raise FormatError(f"{blob}: corrupt zip central directory")
249
+ fields = struct.unpack_from("<4s6H3L5H2L", data, pos)
250
+ flags, method, crc, csize, usize = fields[3], fields[4], fields[7], fields[8], fields[9]
251
+ nlen, xlen, clen, offset = fields[10], fields[11], fields[12], fields[16]
252
+ name_bytes = data[pos + 46 : pos + 46 + nlen]
253
+ extra = data[pos + 46 + nlen : pos + 46 + nlen + xlen]
254
+ pos += 46 + nlen + xlen + clen
255
+ name = name_bytes.decode("utf-8" if flags & 0x800 else "cp437")
256
+ if not name.endswith(".npy"):
257
+ continue
258
+ if flags & 0x1:
259
+ raise FormatError(f"{blob}: {name} is encrypted")
260
+ if method not in (0, 8):
261
+ raise FormatError(f"{blob}: {name} uses zip compression method {method}")
262
+ usize, csize, offset = _zip64_sizes(blob, extra, usize, csize, offset)
263
+ yield _Member(name.removesuffix(".npy"), method, csize, usize, offset, crc)
264
+
265
+
266
+ def _zip64_sizes(blob: Blob, extra: bytes, usize: int, csize: int, offset: int) -> tuple[int, int, int]:
267
+ """Apply a zip64 extra field: it holds, in order, whichever values overflowed."""
268
+ pos = 0
269
+ while pos + 4 <= len(extra):
270
+ tag, n = struct.unpack_from("<2H", extra, pos)
271
+ body, pos = extra[pos + 4 : pos + 4 + n], pos + 4 + n
272
+ if tag != 0x0001:
273
+ continue
274
+ values = iter(struct.unpack_from(f"<{len(body) // 8}Q", body))
275
+ try:
276
+ if usize == 0xFFFFFFFF:
277
+ usize = next(values)
278
+ if csize == 0xFFFFFFFF:
279
+ csize = next(values)
280
+ if offset == 0xFFFFFFFF:
281
+ offset = next(values)
282
+ except StopIteration:
283
+ raise FormatError(f"{blob}: truncated zip64 extra field") from None
284
+ return usize, csize, offset
285
+
286
+
287
+ def _member(blob: Blob, m: _Member, whole: bytes | None, cancel: threading.Event | None) -> Tensor:
288
+ length = _NPY_WINDOW
289
+ while True:
290
+ check_cancel(cancel)
291
+ if whole is not None:
292
+ window = whole[m.offset : m.offset + length]
293
+ else:
294
+ window = blob.fetch(m.offset, m.offset + length).tobytes()
295
+ found = _member_tensor(blob, m, window)
296
+ if isinstance(found, Tensor):
297
+ return found
298
+ if len(window) < length or length > 4 * _NPY_MAX_HEADER:
299
+ raise FormatError(f"{blob}: {m.key}.npy is truncated")
300
+ length = max(found, 2 * length)
301
+
302
+
303
+ def _member_tensor(blob: Blob, m: _Member, window: bytes) -> Tensor | int:
304
+ if len(window) < 30:
305
+ return 30
306
+ if window[:4] != _LOCAL:
307
+ raise FormatError(f"{blob}: bad local header for {m.key}.npy")
308
+ nlen, xlen = struct.unpack_from("<2H", window, 26)
309
+ head = 30 + nlen + xlen
310
+ data_start = m.offset + head
311
+ where = f"{blob}: {m.key}.npy"
312
+ if m.method == 0:
313
+ npy = _parse_npy(window[head:], where)
314
+ if isinstance(npy, int):
315
+ return head + npy
316
+ skip, shape, fortran, dtype = npy
317
+ start = data_start + skip
318
+ stop = start + math.prod(shape) * dtype.itemsize
319
+ seed = zlib.crc32(window[head : head + skip])
320
+ tensor = Tensor(m.key, shape, dtype, blob, start, stop, fortran=fortran, crc32=m.crc, crc_seed=seed)
321
+ else:
322
+ try:
323
+ decoded = zlib.decompressobj(-15).decompress(window[head:], _NPY_MAX_HEADER + 16)
324
+ except zlib.error as exc:
325
+ raise FormatError(f"{where}: not a valid deflate stream") from exc
326
+ npy = _parse_npy(decoded, where)
327
+ if isinstance(npy, int):
328
+ return 2 * len(window)
329
+ skip, shape, fortran, dtype = npy
330
+ tensor = Tensor(
331
+ m.key,
332
+ shape,
333
+ dtype,
334
+ blob,
335
+ data_start,
336
+ data_start + m.csize,
337
+ "deflate",
338
+ skip,
339
+ fortran,
340
+ crc32=m.crc,
341
+ )
342
+ if m.usize != skip + tensor.nbytes:
343
+ raise FormatError(f"{where}: holds {m.usize} bytes, header says {skip + tensor.nbytes}")
344
+ return tensor
345
+
346
+
347
+ def _parse_npy(buf: bytes, where: str) -> tuple[int, tuple[int, ...], bool, np.dtype] | int:
348
+ """``(header length, shape, fortran order, dtype)``, or how many bytes it needs."""
349
+ if len(buf) < 12:
350
+ return 12
351
+ if buf[:6] != b"\x93NUMPY":
352
+ raise FormatError(f"{where}: not a .npy array")
353
+ major = buf[6]
354
+ if major == 1:
355
+ (length,), start = struct.unpack_from("<H", buf, 8), 10
356
+ elif major in (2, 3):
357
+ (length,), start = struct.unpack_from("<L", buf, 8), 12
358
+ else:
359
+ raise FormatError(f"{where}: unsupported .npy version {major}")
360
+ if length > _NPY_MAX_HEADER:
361
+ raise FormatError(f"{where}: implausible .npy header length {length}")
362
+ if len(buf) < start + length:
363
+ return start + length
364
+ try:
365
+ text = buf[start : start + length].decode("utf-8" if major == 3 else "latin1")
366
+ header = ast.literal_eval(text)
367
+ dtype = np.lib.format.descr_to_dtype(header["descr"])
368
+ shape = tuple(int(d) for d in header["shape"])
369
+ fortran = bool(header["fortran_order"]) and len(shape) > 1
370
+ except (ValueError, SyntaxError, KeyError, TypeError) as exc:
371
+ raise FormatError(f"{where}: malformed .npy header") from exc
372
+ if dtype.hasobject:
373
+ raise FormatError(f"{where}: object arrays need pickle, which this reader never runs")
374
+ return start + length, shape, fortran, dtype
tensorferry/jax.py ADDED
@@ -0,0 +1,297 @@
1
+ from collections.abc import Callable, Iterable, Sequence
2
+ from dataclasses import dataclass
3
+ from typing import Any, Literal
4
+
5
+ import jax
6
+ import jax.numpy as jnp
7
+ import numpy as np
8
+ from jax.sharding import Sharding, SingleDeviceSharding
9
+ from jax.tree_util import DictKey, FlattenedIndexKey, GetAttrKey, SequenceKey
10
+
11
+ from tensorferry.api import Pending, Source, _start_arrays, _start_load
12
+ from tensorferry.backend import Backend
13
+ from tensorferry.cache import CacheLike
14
+ from tensorferry.loader import Loader
15
+ from tensorferry.plan import Ignore, Request, Spec, Target, build_plan
16
+ from tensorferry.store import StoreLike
17
+
18
+ __all__ = [
19
+ "JaxBackend",
20
+ "KeysFn",
21
+ "Placement",
22
+ "Uncommitted",
23
+ "is_slot",
24
+ "load",
25
+ "load_arrays",
26
+ "state_dict_key",
27
+ ]
28
+
29
+ type KeyPath = tuple[Any, ...]
30
+ # None: a leaf's own committed sharding if it has one, else JAX's default
31
+ # device, uncommitted -- exactly where jnp.asarray would put it. A Device or
32
+ # Sharding commits every slot there. "host": numpy. A callable decides per
33
+ # leaf, returning a Device, a Sharding, or None for numpy.
34
+ type Placement = jax.Device | Sharding | Literal["host"] | Callable[[KeyPath, Any], jax.Device | Sharding | None] | None
35
+ # Maps a slot's key path and final shape to the stored tensors behind it.
36
+ type KeysFn = Callable[[KeyPath, jax.ShapeDtypeStruct], Spec]
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class Uncommitted:
41
+ device: jax.Device
42
+
43
+
44
+ def _sharding_of(target: Target) -> Sharding | None:
45
+ """The sharding a slot's `jax.ShapeDtypeStruct` states: None unless committed."""
46
+ placement = _normalize_placement(target.placement)
47
+ return None if isinstance(placement, Uncommitted) else placement
48
+
49
+
50
+ def _normalize_placement(placement: Any) -> Sharding | Uncommitted | None:
51
+ if isinstance(placement, Uncommitted):
52
+ return placement
53
+ return _as_sharding(placement)
54
+
55
+
56
+ class JaxBackend:
57
+ """A target without a placement stays in host memory as a NumPy array."""
58
+
59
+ def __init__(self, *, enable_x64: bool | None = None) -> None:
60
+ if enable_x64 is None:
61
+ enable_x64 = bool(getattr(jax.config, "jax_enable_x64", False)) # thread-local aware
62
+ self.enable_x64 = enable_x64
63
+
64
+ def accepts_mapped(self, target: Target) -> bool:
65
+ """Host (numpy) arrays may view a memory-mapped file; device arrays may not."""
66
+ return _normalize_placement(target.placement) is None
67
+
68
+ def host_buffer(self, target: Target) -> np.ndarray:
69
+ return np.empty(target.shape, target.dtype)
70
+
71
+ def finish(self, target: Target, buffer: np.ndarray) -> Any:
72
+ return self.finish_many([target], [buffer])[0]
73
+
74
+ def finish_many(self, targets: Sequence[Target], buffers: Sequence[np.ndarray]) -> list[Any]:
75
+ out: list[Any] = list(buffers)
76
+ placements = [_normalize_placement(t.placement) for t in targets]
77
+ committed = [i for i, p in enumerate(placements) if isinstance(p, Sharding)]
78
+ uncommitted: dict[jax.Device, list[int]] = {}
79
+ for i, p in enumerate(placements):
80
+ if isinstance(p, Uncommitted):
81
+ uncommitted.setdefault(p.device, []).append(i)
82
+ with jax.enable_x64(self.enable_x64):
83
+ if committed:
84
+ arrays = jax.device_put([buffers[i] for i in committed], [placements[i] for i in committed])
85
+ jax.block_until_ready(arrays)
86
+ for i, array in zip(committed, arrays, strict=True):
87
+ out[i] = array
88
+ for device, indices in uncommitted.items():
89
+ # No device named, so the result is uncommitted; the default
90
+ # device is this thread's, so set it to the caller's.
91
+ with jax.default_device(device):
92
+ arrays = jax.device_put([buffers[i] for i in indices])
93
+ jax.block_until_ready(arrays)
94
+ for i, array in zip(indices, arrays, strict=True):
95
+ out[i] = array
96
+ return out
97
+
98
+
99
+ def state_dict_key(path: KeyPath) -> str:
100
+ parts: list[str] = []
101
+ for entry in path:
102
+ match entry:
103
+ case GetAttrKey(name=name):
104
+ parts.append(name)
105
+ case SequenceKey(idx=idx) | FlattenedIndexKey(key=idx):
106
+ parts.append(str(idx))
107
+ case DictKey(key=key):
108
+ parts.append(str(key))
109
+ case _:
110
+ raise TypeError(f"unsupported key path entry {entry!r}")
111
+ return ".".join(parts)
112
+
113
+
114
+ def is_slot(leaf: Any) -> bool:
115
+ """The default test for a leaf to fill: any shape-only leaf, or a floating array."""
116
+ if isinstance(leaf, jax.ShapeDtypeStruct):
117
+ return True
118
+ return isinstance(leaf, (jax.Array, np.ndarray)) and jnp.issubdtype(leaf.dtype, jnp.inexact)
119
+
120
+
121
+ @dataclass(frozen=True, eq=False)
122
+ class _Layout:
123
+ """A tree's slots and the arrays they become; known without reading anything."""
124
+
125
+ treedef: Any
126
+ leaves: tuple[Any, ...]
127
+ paths: tuple[KeyPath, ...]
128
+ targets: dict[int, Target] # by leaf index, for the slots only
129
+
130
+ def shape_of(self, filled: Iterable[int]) -> Any:
131
+ leaves = list(self.leaves)
132
+ for i in filled:
133
+ t = self.targets[i]
134
+ leaves[i] = _struct(t)
135
+ return jax.tree_util.tree_unflatten(self.treedef, leaves)
136
+
137
+ def specs(self, keys: KeysFn) -> dict[int, Spec]:
138
+ """Each slot's spec, by leaf index; None marks a slot to leave alone."""
139
+ return {i: keys(self.paths[i], _struct(t)) for i, t in self.targets.items()}
140
+
141
+ def requests(self, specs: dict[int, Spec]) -> list[Request]:
142
+ """One request per slot; a shape-only slot must be loaded, an array may keep its value."""
143
+ return [
144
+ Request(
145
+ i,
146
+ jax.tree_util.keystr(self.paths[i]),
147
+ t,
148
+ specs[i],
149
+ required=isinstance(self.leaves[i], jax.ShapeDtypeStruct),
150
+ )
151
+ for i, t in self.targets.items()
152
+ ]
153
+
154
+ def assemble(self, arrays: dict[int, Any]) -> Any:
155
+ leaves = list(self.leaves)
156
+ for i, array in arrays.items():
157
+ leaves[i] = array
158
+ return jax.tree_util.tree_unflatten(self.treedef, leaves)
159
+
160
+
161
+ def _layout(
162
+ tree: Any,
163
+ *,
164
+ dtype: Any = None,
165
+ device: Placement = None,
166
+ is_slot: Callable[[Any], bool] = is_slot,
167
+ ) -> _Layout:
168
+ place = _placement(device)
169
+ flat, treedef = jax.tree_util.tree_flatten_with_path(tree)
170
+ targets: dict[int, Target] = {}
171
+ for i, (path, leaf) in enumerate(flat):
172
+ if not is_slot(leaf):
173
+ continue
174
+ leaf_dtype = np.dtype(leaf.dtype)
175
+ if dtype is not None and jnp.issubdtype(leaf_dtype, jnp.inexact):
176
+ leaf_dtype = np.dtype(dtype)
177
+ targets[i] = Target(tuple(leaf.shape), leaf_dtype, place(path, leaf))
178
+ return _Layout(treedef, tuple(leaf for _, leaf in flat), tuple(p for p, _ in flat), targets)
179
+
180
+
181
+ def load(
182
+ tree: Any,
183
+ source: Source | Sequence[Source],
184
+ *,
185
+ store: StoreLike | None = None,
186
+ keys: KeysFn | None = None,
187
+ prefix: str = "",
188
+ strict: bool = True,
189
+ ignore: Ignore = (),
190
+ dtype: Any = None,
191
+ device: Placement = None,
192
+ is_slot: Callable[[Any], bool] = is_slot,
193
+ loader: Loader | None = None,
194
+ backend: Backend | None = None,
195
+ cache: CacheLike = None,
196
+ ) -> Pending[Any]:
197
+ """Returns immediately. Compile against pending.shape while the weights load, then use pending.result() to get the
198
+ filled pytree.
199
+ """
200
+ lay = _layout(tree, dtype=dtype, device=device, is_slot=is_slot)
201
+ specs, scope = _specs(lay, keys, prefix)
202
+ loaded = [i for i, spec in specs.items() if spec is not None]
203
+ return _start_load(
204
+ source,
205
+ store,
206
+ cache,
207
+ lambda index: build_plan(lay.requests(specs), index, strict=strict, scope=scope, ignore=ignore),
208
+ lambda _, arrays: lay.assemble(arrays),
209
+ backend=backend or JaxBackend(),
210
+ loader=loader,
211
+ shape=lay.shape_of(loaded) if strict else None,
212
+ shape_of=None if strict else lambda planned: lay.shape_of(f.index for f in planned.fills),
213
+ )
214
+
215
+
216
+ def load_arrays(
217
+ source: Source | Sequence[Source],
218
+ *,
219
+ store: StoreLike | None = None,
220
+ names: Sequence[str] | None = None,
221
+ device: jax.Device | Sharding | Literal["host"] | None = "host",
222
+ loader: Loader | None = None,
223
+ cache: CacheLike = None,
224
+ ) -> Pending[dict[str, Any]]:
225
+ """Start loading every array in `source` (or just `names`), by key, in file order."""
226
+ return _start_arrays(
227
+ source,
228
+ store=store,
229
+ names=names,
230
+ backend=JaxBackend(),
231
+ placement=_placement(device)((), None),
232
+ loader=loader,
233
+ cache=cache,
234
+ native=True,
235
+ shape=_struct,
236
+ )
237
+
238
+
239
+ def _specs(lay: _Layout, keys: KeysFn | None, prefix: str) -> tuple[dict[int, Spec], str]:
240
+ if keys is None:
241
+ head = f"{prefix}." if prefix else ""
242
+
243
+ def keys(path: KeyPath, target: jax.ShapeDtypeStruct) -> Spec:
244
+ return head + state_dict_key(path)
245
+
246
+ return lay.specs(keys), head
247
+ return lay.specs(keys), prefix
248
+
249
+
250
+ def _struct(target: Target) -> jax.ShapeDtypeStruct:
251
+ """`target` as the shape-only array JAX compiles against."""
252
+ return jax.ShapeDtypeStruct(target.shape, target.dtype, sharding=_sharding_of(target))
253
+
254
+
255
+ def _placement(device: Placement) -> Callable[[KeyPath, Any], Sharding | Uncommitted | None]:
256
+ """`device` as a per-leaf function, with the default device fixed now."""
257
+ if isinstance(device, str):
258
+ if device != "host":
259
+ raise ValueError(f"device must be a Device, a Sharding, 'host' or a function, not {device!r}")
260
+ return lambda path, leaf: None
261
+ if callable(device) and not isinstance(device, (jax.Device, Sharding)):
262
+ chosen = device
263
+ return lambda path, leaf: _as_sharding(chosen(path, leaf))
264
+ if device is not None:
265
+ sharding = _as_sharding(device)
266
+ return lambda path, leaf: sharding
267
+ default = Uncommitted(_default_device())
268
+
269
+ def own_or_default(path: KeyPath, leaf: Any) -> Sharding | Uncommitted:
270
+ if isinstance(leaf, jax.Array):
271
+ if leaf.committed:
272
+ return leaf.sharding
273
+ (where,) = leaf.devices()
274
+ return Uncommitted(where)
275
+ return getattr(leaf, "sharding", None) or default # a stated sharding commits
276
+
277
+ return own_or_default
278
+
279
+
280
+ def _as_sharding(device: Any) -> Sharding | None:
281
+ if device is None or isinstance(device, Sharding):
282
+ return device
283
+ if isinstance(device, jax.Device):
284
+ return SingleDeviceSharding(device)
285
+ raise TypeError(
286
+ f"cannot place a JAX array on {device!r}: expected a jax.Device, a Sharding, "
287
+ "Uncommitted, or None for host memory"
288
+ )
289
+
290
+
291
+ def _default_device() -> jax.Device:
292
+ configured = getattr(jax.config, "jax_default_device", None) # thread-local aware
293
+ if isinstance(configured, jax.Device):
294
+ return configured
295
+ if isinstance(configured, str):
296
+ return jax.local_devices(backend=configured)[0]
297
+ return jax.local_devices()[0]