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/plan.py ADDED
@@ -0,0 +1,289 @@
1
+ import math
2
+ from collections.abc import Callable, Collection, Sequence
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+
8
+ from tensorferry.formats import Index, Tensor
9
+
10
+ __all__ = [
11
+ "CheckpointMismatchError",
12
+ "Concat",
13
+ "Fill",
14
+ "Ignore",
15
+ "Part",
16
+ "Plan",
17
+ "Request",
18
+ "Spec",
19
+ "Stack",
20
+ "Target",
21
+ "build_plan",
22
+ ]
23
+
24
+
25
+ class CheckpointMismatchError(Exception):
26
+ pass
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Target:
31
+ shape: tuple[int, ...]
32
+ dtype: np.dtype
33
+ placement: Any = None
34
+
35
+ @property
36
+ def nbytes(self) -> int:
37
+ return math.prod(self.shape) * self.dtype.itemsize
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class Part:
42
+ """Stored tensor `key` lands in `target[at]`; `at=()` is the whole array."""
43
+
44
+ key: str
45
+ at: tuple[int | slice, ...] = ()
46
+ tensor: Tensor | None = field(default=None, compare=False)
47
+
48
+
49
+ @dataclass(frozen=True, slots=True, init=False)
50
+ class _Keys:
51
+ keys: tuple[str, ...]
52
+ axis: int
53
+
54
+ def __init__(self, keys: Sequence[str], axis: int = 0) -> None:
55
+ object.__setattr__(self, "keys", tuple(keys))
56
+ object.__setattr__(self, "axis", axis)
57
+
58
+
59
+ @dataclass(frozen=True, slots=True, init=False)
60
+ class Stack(_Keys):
61
+ """Tensors stacked along a new `axis`: ``keys[i]`` lands at index ``i``."""
62
+
63
+
64
+ @dataclass(frozen=True, slots=True, init=False)
65
+ class Concat(_Keys):
66
+ """Tensors concatenated, in order, along an existing `axis`."""
67
+
68
+
69
+ # The stored tensors behind one array: a key, a composite, explicit parts, or
70
+ # None to leave the array alone.
71
+ type Spec = str | Part | Stack | Concat | Sequence[Part] | None
72
+ # Checkpoint keys that may go unused: a collection of keys, or a predicate.
73
+ type Ignore = Collection[str] | Callable[[str], bool]
74
+
75
+
76
+ @dataclass(frozen=True, slots=True)
77
+ class Request:
78
+ index: int
79
+ name: str
80
+ target: Target
81
+ spec: Spec
82
+ required: bool = True
83
+
84
+
85
+ @dataclass(frozen=True, slots=True, eq=False)
86
+ class Fill:
87
+ index: int
88
+ name: str
89
+ target: Target
90
+ parts: tuple[Part, ...]
91
+
92
+ @property
93
+ def nbytes(self) -> int:
94
+ return self.target.nbytes
95
+
96
+
97
+ @dataclass(frozen=True, eq=False)
98
+ class Plan:
99
+ fills: tuple[Fill, ...]
100
+ index: Index
101
+
102
+ @property
103
+ def nbytes(self) -> int:
104
+ return sum(f.nbytes for f in self.fills)
105
+
106
+
107
+ def build_plan(
108
+ requests: Sequence[Request],
109
+ index: Index,
110
+ *,
111
+ strict: bool = True,
112
+ scope: str = "",
113
+ ignore: Ignore = (),
114
+ ) -> Plan:
115
+ """Strict loading requires all requested and stored keys to match before any tensor data moves."""
116
+ fills: list[Fill] = []
117
+ used: set[str] = set()
118
+ missing: list[str] = []
119
+ mismatched: list[str] = []
120
+ for request in requests:
121
+ target, name = request.target, request.name
122
+ if request.spec is None:
123
+ if strict and request.required:
124
+ missing.append(f"{name} (no source)")
125
+ continue
126
+ parts, absent = _expand(request.spec, target, index, name, mismatched)
127
+ if absent:
128
+ if strict:
129
+ missing.extend(absent)
130
+ continue
131
+ resolved = []
132
+ covered = 0
133
+ for part in parts:
134
+ tensor = index[part.key]
135
+ used.add(part.key)
136
+ dest = target.shape if not part.at else _dest_shape(target.shape, part.at)
137
+ if dest is None:
138
+ mismatched.append(f"{name}: index {part.at} is outside {target.shape}")
139
+ continue
140
+ if not _reshapable(tensor.shape, dest):
141
+ at = f"[{', '.join(map(_index_str, part.at))}]" if part.at else ""
142
+ mismatched.append(f"{name}{at}: {part.key} {tensor.shape} != {dest}")
143
+ continue
144
+ covered += math.prod(dest)
145
+ resolved.append(Part(part.key, part.at, tensor))
146
+ # One part for the whole array -- nearly every array -- covers it by construction.
147
+ whole = len(resolved) == 1 and not resolved[0].at
148
+ if (
149
+ not whole
150
+ and len(resolved) == len(parts)
151
+ and (problem := _cover_problem(target.shape, [p.at for p in resolved], covered))
152
+ ):
153
+ mismatched.append(f"{name}: {problem}")
154
+ fills.append(Fill(request.index, name, target, tuple(resolved)))
155
+ ignored = ignore if callable(ignore) else frozenset(ignore).__contains__
156
+ # Only strict plans collect what is missing; so, too, what is unexpected.
157
+ unexpected = sorted(k for k in index if k.startswith(scope) and k not in used and not ignored(k)) if strict else []
158
+ if missing or unexpected or mismatched:
159
+ raise CheckpointMismatchError(_describe(missing, unexpected, mismatched))
160
+ return Plan(tuple(fills), index)
161
+
162
+
163
+ def _expand(spec: Spec, target: Target, index: Index, name: str, mismatched: list[str]) -> tuple[list[Part], list[str]]:
164
+ match spec:
165
+ case str():
166
+ parts = [Part(spec)]
167
+ case Part():
168
+ parts = [spec]
169
+ case Stack(keys=keys, axis=axis):
170
+ axis = _axis(axis, len(target.shape), name, mismatched)
171
+ if axis is None:
172
+ return [], []
173
+ if len(keys) != target.shape[axis]:
174
+ mismatched.append(f"{name}: stacks {len(keys)} tensors on an axis of {target.shape[axis]}")
175
+ return [], []
176
+ parts = [Part(key, (slice(None),) * axis + (i,)) for i, key in enumerate(keys)]
177
+ case Concat(keys=keys, axis=axis):
178
+ absent = [k for k in keys if k not in index]
179
+ axis = _axis(axis, len(target.shape), name, mismatched)
180
+ if absent or axis is None:
181
+ return [], absent
182
+ parts, offset = [], 0
183
+ for key in keys:
184
+ shape = index[key].shape
185
+ if len(shape) != len(target.shape):
186
+ mismatched.append(f"{name}: concatenates {key} {shape} into {target.shape}")
187
+ return [], []
188
+ size = shape[axis]
189
+ parts.append(Part(key, (slice(None),) * axis + (slice(offset, offset + size),)))
190
+ offset += size
191
+ case Sequence() if all(isinstance(p, Part) for p in spec):
192
+ parts = list(spec)
193
+ case _:
194
+ raise TypeError(f"{name}: unsupported spec {spec!r}")
195
+ return parts, [p.key for p in parts if p.key not in index]
196
+
197
+
198
+ def _axis(axis: int, ndim: int, name: str, mismatched: list[str]) -> int | None:
199
+ if not -ndim <= axis < ndim:
200
+ mismatched.append(f"{name}: axis {axis} is out of range for rank {ndim}")
201
+ return None
202
+ return axis % ndim
203
+
204
+
205
+ def _dest_shape(shape: tuple[int, ...], at: tuple[int | slice, ...]) -> tuple[int, ...] | None:
206
+ """The shape of ``np.empty(shape)[at]``, computed without allocating."""
207
+ try:
208
+ return np.broadcast_to(np.empty((), np.uint8), shape)[(*at, Ellipsis)].shape
209
+ except IndexError:
210
+ return None
211
+
212
+
213
+ _MASK_LIMIT = 1 << 24 # elements; strided parts are checked with a mask up to this size
214
+
215
+
216
+ def _cover_problem(shape: tuple[int, ...], ats: list[tuple[int | slice, ...]], covered: int) -> str | None:
217
+ """Why `ats` do not write every element of an array of `shape` exactly once, if they don't."""
218
+ total = math.prod(shape)
219
+ boxes = [_box(shape, at) for at in ats]
220
+ if all(box is not None for box in boxes):
221
+ # Empty parts write nothing; the rest are swept in order of their first axis.
222
+ live = [box for box in boxes if box is not None and all(lo < hi for lo, hi in box)]
223
+ live.sort(key=lambda box: box[0][0] if box else 0)
224
+ for i, a in enumerate(live):
225
+ for b in live[i + 1 :]:
226
+ if a and b[0][0] >= a[0][1]:
227
+ break # sorted: no later box reaches back into `a` on axis 0
228
+ if all(lo1 < hi2 and lo2 < hi1 for (lo1, hi1), (lo2, hi2) in zip(a, b, strict=True)):
229
+ return "parts overlap"
230
+ elif total <= _MASK_LIMIT:
231
+ occupied = np.zeros(shape, np.bool_)
232
+ for at in ats:
233
+ region = occupied[(*at, Ellipsis)] # basic indexing: a view, no repeats
234
+ if region.any():
235
+ return "parts overlap"
236
+ region[...] = True
237
+ else:
238
+ return f"strided parts of a {total}-element array cannot be checked for overlap"
239
+ if covered != total:
240
+ return f"parts cover {covered} of {total} elements"
241
+ return None
242
+
243
+
244
+ def _box(shape: tuple[int, ...], at: tuple[int | slice, ...]) -> tuple[tuple[int, int], ...] | None:
245
+ at = (*at, *(slice(None),) * (len(shape) - len(at)))
246
+ box = []
247
+ for entry, size in zip(at, shape, strict=True):
248
+ if isinstance(entry, slice):
249
+ start, stop, step = entry.indices(size)
250
+ if step != 1:
251
+ return None
252
+ box.append((start, max(start, stop)))
253
+ else:
254
+ index = int(entry) + (size if int(entry) < 0 else 0)
255
+ box.append((index, index + 1))
256
+ return tuple(box)
257
+
258
+
259
+ def _reshapable(source: tuple[int, ...], target: tuple[int, ...]) -> bool:
260
+ """Whether shapes agree up to singleton axes."""
261
+
262
+ def squeezed(shape: tuple[int, ...]) -> tuple[int, ...]:
263
+ return tuple(d for d in shape if d != 1)
264
+
265
+ return squeezed(tuple(source)) == squeezed(tuple(target))
266
+
267
+
268
+ def _index_str(entry: int | slice) -> str:
269
+ if isinstance(entry, slice):
270
+ start = "" if entry.start is None else entry.start
271
+ stop = "" if entry.stop is None else entry.stop
272
+ return f"{start}:{stop}"
273
+ return str(entry)
274
+
275
+
276
+ def _describe(missing: list[str], unexpected: list[str], mismatched: list[str]) -> str:
277
+ def section(title: str, names: list[str], limit: int = 20) -> str:
278
+ if not names:
279
+ return ""
280
+ shown = "\n ".join(names[:limit])
281
+ more = f"\n ... and {len(names) - limit} more" if len(names) > limit else ""
282
+ return f"\n{title} ({len(names)}):\n {shown}{more}"
283
+
284
+ body = (
285
+ section("missing from checkpoint", missing)
286
+ + section("unexpected in checkpoint", unexpected)
287
+ + section("shape mismatch", mismatched)
288
+ )
289
+ return f"checkpoint does not match the model:{body}"
@@ -0,0 +1,90 @@
1
+ """Progress shared by the tensorferry loads started in a Python context."""
2
+
3
+ from collections.abc import Buffer, Callable, Generator
4
+ from contextlib import contextmanager
5
+ from contextvars import ContextVar
6
+ from threading import Lock
7
+
8
+ __all__ = ["DownloadProgress", "track_downloads"]
9
+
10
+
11
+ class DownloadProgress:
12
+ """A thread-safe snapshot of remote payload bytes received by a group of loads."""
13
+
14
+ def __init__(self) -> None:
15
+ self._lock = Lock()
16
+ self._received = 0
17
+ self._remaining: dict[_Download, int | None] = {}
18
+
19
+ def snapshot(self) -> tuple[int, int | None]:
20
+ """Return ``(received_bytes, estimated_total_bytes)``.
21
+
22
+ The total is None while any active load has yet to estimate its reads.
23
+ The estimate can change as loads start or finish. With no active loads,
24
+ the total equals bytes received so far. Reads already in flight may
25
+ still finish after cancellation.
26
+ """
27
+ with self._lock:
28
+ total = self._received
29
+ for n in self._remaining.values():
30
+ if n is None:
31
+ return self._received, None
32
+ total += n
33
+ return self._received, total
34
+
35
+ def _start(self) -> "_Download":
36
+ load = _Download(self)
37
+ with self._lock:
38
+ self._remaining[load] = None
39
+ return load
40
+
41
+
42
+ class _Download:
43
+ def __init__(self, progress: DownloadProgress) -> None:
44
+ self.progress = progress
45
+
46
+ def run[T, **P](self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:
47
+ token = _download.set(self)
48
+ try:
49
+ return fn(*args, **kwargs)
50
+ finally:
51
+ _download.reset(token)
52
+
53
+ def estimate(self, remaining: int) -> None:
54
+ with self.progress._lock:
55
+ self.progress._remaining[self] = remaining
56
+
57
+ def received(self, nbytes: int) -> None:
58
+ with self.progress._lock:
59
+ self.progress._received += nbytes
60
+ loads = self.progress._remaining
61
+ if (remaining := loads.get(self)) is not None:
62
+ loads[self] = max(0, remaining - nbytes)
63
+
64
+ def finish(self) -> None:
65
+ with self.progress._lock:
66
+ self.progress._remaining.pop(self, None)
67
+
68
+
69
+ _progress: ContextVar[DownloadProgress | None] = ContextVar("tensorferry_progress", default=None)
70
+ _download: ContextVar[_Download | None] = ContextVar("tensorferry_download", default=None)
71
+
72
+
73
+ @contextmanager
74
+ def track_downloads() -> Generator[DownloadProgress]:
75
+ """Track remote payloads for loads started inside this scope.
76
+
77
+ The built-in remote stores count successful reads, including headers and
78
+ indexes. The default loader estimates its remaining fetches after discovery.
79
+ """
80
+ progress = DownloadProgress()
81
+ token = _progress.set(progress)
82
+ try:
83
+ yield progress
84
+ finally:
85
+ _progress.reset(token)
86
+
87
+
88
+ def _record_read(data: Buffer) -> None:
89
+ if (download := _download.get()) is not None:
90
+ download.received(memoryview(data).nbytes)