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.
@@ -0,0 +1,76 @@
1
+ from tensorferry.api import Pending, Source, StoreLike, index, load_arrays
2
+ from tensorferry.backend import Backend, NumpyBackend
3
+ from tensorferry.cache import Cache, CachedStore
4
+ from tensorferry.formats import FormatError, Index, Tensor, read_index
5
+ from tensorferry.loader import Loader, StreamingLoader
6
+ from tensorferry.plan import (
7
+ CheckpointMismatchError,
8
+ Concat,
9
+ Fill,
10
+ Ignore,
11
+ Part,
12
+ Plan,
13
+ Request,
14
+ Spec,
15
+ Stack,
16
+ Target,
17
+ build_plan,
18
+ )
19
+ from tensorferry.progress import DownloadProgress, track_downloads
20
+ from tensorferry.store import (
21
+ Blob,
22
+ FsspecStore,
23
+ LocalStore,
24
+ MemoryStore,
25
+ ObjectStore,
26
+ Store,
27
+ exists,
28
+ hub_token,
29
+ hub_url,
30
+ is_url,
31
+ join,
32
+ resolve,
33
+ )
34
+
35
+ __all__ = [
36
+ "Backend",
37
+ "Blob",
38
+ "Cache",
39
+ "CachedStore",
40
+ "CheckpointMismatchError",
41
+ "Concat",
42
+ "DownloadProgress",
43
+ "Fill",
44
+ "FormatError",
45
+ "FsspecStore",
46
+ "Ignore",
47
+ "Index",
48
+ "Loader",
49
+ "LocalStore",
50
+ "MemoryStore",
51
+ "NumpyBackend",
52
+ "ObjectStore",
53
+ "Part",
54
+ "Pending",
55
+ "Plan",
56
+ "Request",
57
+ "Source",
58
+ "Spec",
59
+ "Stack",
60
+ "Store",
61
+ "StoreLike",
62
+ "StreamingLoader",
63
+ "Target",
64
+ "Tensor",
65
+ "build_plan",
66
+ "exists",
67
+ "hub_token",
68
+ "hub_url",
69
+ "index",
70
+ "is_url",
71
+ "join",
72
+ "load_arrays",
73
+ "read_index",
74
+ "resolve",
75
+ "track_downloads",
76
+ ]
tensorferry/_pool.py ADDED
@@ -0,0 +1,114 @@
1
+ import queue
2
+ import threading
3
+ from collections.abc import Callable, Iterable, Sequence
4
+ from concurrent.futures import FIRST_EXCEPTION, CancelledError, Future, wait
5
+ from typing import Any
6
+
7
+ from tensorferry.progress import _download
8
+
9
+ __all__ = ["TICK", "DaemonPool", "check_cancel"]
10
+
11
+ # How often a blocked wait looks for cancellation, in seconds.
12
+ TICK = 0.05
13
+
14
+ _STOP = object()
15
+
16
+
17
+ def check_cancel(cancel: threading.Event | None) -> None:
18
+ """Raise `CancelledError` if `cancel` is set."""
19
+ if cancel is not None and cancel.is_set():
20
+ raise CancelledError()
21
+
22
+
23
+ def wait_all[T](futures: Sequence[Future[T]], cancel: threading.Event | None = None) -> list[T]:
24
+ """Every future's result, in their order, raising the first failure the moment it happens."""
25
+ pending: set[Future[T]] = set(futures)
26
+ while pending:
27
+ done, pending = wait(pending, timeout=TICK, return_when=FIRST_EXCEPTION)
28
+ for future in done:
29
+ error = future.exception() # a cancelled future raises CancelledError here
30
+ if error is not None:
31
+ raise error
32
+ check_cancel(cancel)
33
+ return [future.result() for future in futures]
34
+
35
+
36
+ class DaemonPool:
37
+ def __init__(self, workers: int) -> None:
38
+ self._workers = max(1, workers)
39
+ self._queue: queue.SimpleQueue[Any] = queue.SimpleQueue()
40
+ self._threads: list[threading.Thread] = []
41
+ self._idle = 0
42
+ self._lock = threading.Lock()
43
+ self._closed = False
44
+
45
+ def submit[T](self, fn: Callable[..., T], *args: Any) -> Future[T]:
46
+ future: Future[T] = Future()
47
+ if (download := _download.get()) is not None:
48
+ fn, args = download.run, (fn, *args)
49
+ with self._lock:
50
+ if self._closed:
51
+ raise RuntimeError("the pool is shut down")
52
+ self._queue.put((future, fn, args))
53
+ # `_idle` counts waiting workers minus unclaimed work: spawn only when
54
+ # no worker is free to take this item.
55
+ if self._idle <= 0 and len(self._threads) < self._workers:
56
+ thread = threading.Thread(target=self._work, name=f"tensorferry-{len(self._threads)}", daemon=True)
57
+ self._threads.append(thread)
58
+ thread.start()
59
+ else:
60
+ self._idle -= 1
61
+ return future
62
+
63
+ def map[T](self, fn: Callable[[Any], T], items: Iterable[Any], *, cancel: threading.Event | None = None) -> list[T]:
64
+ """`[fn(item) for item in items]`, concurrently."""
65
+ futures = [self.submit(fn, item) for item in items]
66
+ try:
67
+ return wait_all(futures, cancel)
68
+ except BaseException:
69
+ for future in futures:
70
+ future.cancel()
71
+ raise
72
+
73
+ def shutdown(self, *, wait: bool = True, cancel_futures: bool = False) -> None:
74
+ """Stop the workers once the queue is done; cancel what is still queued if asked."""
75
+ with self._lock:
76
+ self._closed = True
77
+ if cancel_futures:
78
+ while True:
79
+ try:
80
+ item = self._queue.get_nowait()
81
+ except queue.Empty:
82
+ break
83
+ if item is not _STOP:
84
+ item[0].cancel()
85
+ for _ in self._threads:
86
+ self._queue.put(_STOP)
87
+ threads = list(self._threads)
88
+ if wait:
89
+ for thread in threads:
90
+ if thread is not threading.current_thread():
91
+ thread.join()
92
+
93
+ def __enter__(self) -> "DaemonPool":
94
+ return self
95
+
96
+ def __exit__(self, kind: type[BaseException] | None, *_: Any) -> None:
97
+ # After an error or a cancellation, do not wait: a worker may be stuck
98
+ # in a read that will never return.
99
+ failed = kind is not None
100
+ self.shutdown(wait=not failed, cancel_futures=failed)
101
+
102
+ def _work(self) -> None:
103
+ while True:
104
+ item = self._queue.get()
105
+ if item is _STOP:
106
+ return
107
+ future, fn, args = item
108
+ if future.set_running_or_notify_cancel():
109
+ try:
110
+ future.set_result(fn(*args))
111
+ except BaseException as exc:
112
+ future.set_exception(exc)
113
+ with self._lock:
114
+ self._idle += 1
tensorferry/api.py ADDED
@@ -0,0 +1,271 @@
1
+ import inspect
2
+ import os
3
+ import threading
4
+ from collections.abc import Callable, Mapping, Sequence
5
+ from concurrent.futures import Future
6
+ from typing import Any
7
+
8
+ from tensorferry._pool import check_cancel
9
+ from tensorferry.backend import Backend, NumpyBackend
10
+ from tensorferry.cache import Cache, CacheLike, resolve_cache
11
+ from tensorferry.formats import Index, read_index
12
+ from tensorferry.loader import Loader, StreamingLoader
13
+ from tensorferry.plan import Plan, Request, Target, build_plan
14
+ from tensorferry.progress import _progress
15
+ from tensorferry.store import Blob, StoreLike, resolve
16
+
17
+ __all__ = [
18
+ "Pending",
19
+ "Source",
20
+ "StoreLike",
21
+ "index",
22
+ "load_arrays",
23
+ ]
24
+
25
+ # A path or URL, a file in a store, or arrays already in memory.
26
+ type Source = str | os.PathLike[str] | Blob | Mapping[str, Any]
27
+
28
+
29
+ class Pending[T]:
30
+ """The shape is available before the arrays. Use result() to wait for the load and propagate failures."""
31
+
32
+ def __init__(self, work: Callable[["Pending[T]"], T], shape: Any = None) -> None:
33
+ self._result: Future[T] = Future()
34
+ self._shape: Future[Any] = Future()
35
+ if shape is not None:
36
+ self._shape.set_result(shape)
37
+ self._cancelled = threading.Event()
38
+ self._upstream: Pending[Any] | None = None
39
+ self._done_bytes = 0
40
+ self._total_bytes: int | None = None
41
+ # A daemon, so an abandoned load never holds up interpreter exit.
42
+ self._thread = threading.Thread(target=self._main, args=(work,), name="tensorferry", daemon=True)
43
+ self._thread.start()
44
+
45
+ def _main(self, work: Callable[["Pending[T]"], T]) -> None:
46
+ try:
47
+ value = work(self)
48
+ except BaseException as exc:
49
+ if not self._shape.done():
50
+ self._shape.set_exception(exc)
51
+ self._result.set_exception(exc)
52
+ else:
53
+ self._result.set_result(value)
54
+
55
+ @property
56
+ def shape(self) -> Any:
57
+ """The result as shape-only placeholders (blocks at most until the index is read)."""
58
+ return self._shape.result()
59
+
60
+ def result(self, timeout: float | None = None) -> T:
61
+ return self._result.result(timeout)
62
+
63
+ def exception(self, timeout: float | None = None) -> BaseException | None:
64
+ return self._result.exception(timeout)
65
+
66
+ def done(self) -> bool:
67
+ return self._result.done()
68
+
69
+ def cancel(self) -> None:
70
+ """Stop loading; `result` then raises `concurrent.futures.CancelledError`."""
71
+ self._cancelled.set()
72
+ if self._upstream is not None:
73
+ self._upstream.cancel()
74
+
75
+ def then[U](self, fn: Callable[[T], U], shape: Any = None) -> "Pending[U]":
76
+ """Cancelling the derived result also cancels the original load."""
77
+
78
+ def work(derived: Pending[U]) -> U:
79
+ value = self.result()
80
+ check_cancel(derived._cancelled)
81
+ return fn(value)
82
+
83
+ derived = Pending(work, shape)
84
+ derived._upstream = self
85
+ return derived
86
+
87
+ def add_done_callback(self, fn: Callable[["Pending[T]"], None]) -> None:
88
+ self._result.add_done_callback(lambda _: fn(self))
89
+
90
+ @property
91
+ def progress(self) -> tuple[int, int | None]:
92
+ """Returns completed and total bytes. The total is unknown until the load plan is ready."""
93
+ return self._done_bytes, self._total_bytes
94
+
95
+
96
+ def _start[T](
97
+ make_plan: Callable[[threading.Event], Plan],
98
+ assemble: Callable[[Plan, dict[int, Any]], T],
99
+ *,
100
+ backend: Backend,
101
+ loader: Loader | None = None,
102
+ shape: Any = None,
103
+ shape_of: Callable[[Plan], Any] | None = None,
104
+ cache: Cache | None = None,
105
+ ) -> Pending[T]:
106
+ run = loader or StreamingLoader()
107
+ if shape is None and shape_of is None:
108
+
109
+ def shape_of(planned: Plan) -> dict[int, Target]:
110
+ return {f.index: f.target for f in planned.fills}
111
+
112
+ def work(pending: Pending[T]) -> T:
113
+ planned = make_plan(pending._cancelled)
114
+ if shape_of is not None:
115
+ pending._shape.set_result(shape_of(planned))
116
+ pending._total_bytes = planned.nbytes
117
+ check_cancel(pending._cancelled)
118
+ sink = None
119
+ if cache is not None:
120
+ planned, sink = cache.rewrite(planned, cancel=pending._cancelled)
121
+ extra = {"sink": sink} if sink is not None and _takes_sink(run) else {}
122
+ arrays: dict[int, Any] = {}
123
+ try:
124
+ results = run(planned, backend, cancel=pending._cancelled, **extra)
125
+ try:
126
+ for fill, array in results:
127
+ check_cancel(pending._cancelled)
128
+ if fill.index in arrays:
129
+ raise RuntimeError(f"the loader yielded {fill.name} twice")
130
+ arrays[fill.index] = array
131
+ pending._done_bytes += fill.nbytes
132
+ finally:
133
+ close = getattr(results, "close", None)
134
+ if close is not None:
135
+ close()
136
+ finally:
137
+ if sink is not None:
138
+ sink.close()
139
+ check_cancel(pending._cancelled)
140
+ if len(arrays) != len(planned.fills):
141
+ raise RuntimeError(f"the loader yielded {len(arrays)} of {len(planned.fills)} arrays")
142
+ return assemble(planned, arrays)
143
+
144
+ progress = _progress.get()
145
+ if progress is None:
146
+ return Pending(work, shape)
147
+
148
+ download = progress._start()
149
+
150
+ def tracked_work(pending: Pending[T]) -> T:
151
+ try:
152
+ return download.run(work, pending)
153
+ finally:
154
+ download.finish()
155
+
156
+ try:
157
+ return Pending(tracked_work, shape)
158
+ except BaseException:
159
+ download.finish()
160
+ raise
161
+
162
+
163
+ def _takes_sink(loader: Loader) -> bool:
164
+ try:
165
+ return "sink" in inspect.signature(loader).parameters
166
+ except (TypeError, ValueError):
167
+ return False
168
+
169
+
170
+ def load_arrays(
171
+ source: Source | Sequence[Source],
172
+ *,
173
+ store: StoreLike | None = None,
174
+ names: Sequence[str] | None = None,
175
+ backend: Backend | None = None,
176
+ placement: Any = None,
177
+ loader: Loader | None = None,
178
+ cache: CacheLike = None,
179
+ ) -> Pending[dict[str, Any]]:
180
+ """Start loading every array in `source` (or just `names`), by key, in file order."""
181
+ return _start_arrays(
182
+ source,
183
+ store=store,
184
+ names=names,
185
+ backend=backend or NumpyBackend(),
186
+ placement=placement,
187
+ loader=loader,
188
+ cache=cache,
189
+ )
190
+
191
+
192
+ def _start_load[T](
193
+ source: Source | Sequence[Source],
194
+ store: StoreLike | None,
195
+ cache: CacheLike,
196
+ make_plan: Callable[[Index], Plan],
197
+ assemble: Callable[[Plan, dict[int, Any]], T],
198
+ **start_kw: Any,
199
+ ) -> Pending[T]:
200
+ """Every front end's load: the cache and sources settled now, in the caller's thread, the index read and the plan
201
+ made on the load's own.
202
+ """
203
+ use = resolve_cache(cache)
204
+ found = _sources(source, store, use)
205
+ return _start(lambda cancel: make_plan(read_index(found, cancel=cancel)), assemble, cache=use, **start_kw)
206
+
207
+
208
+ def _start_arrays(
209
+ source: Source | Sequence[Source],
210
+ *,
211
+ store: StoreLike | None,
212
+ names: Sequence[str] | None,
213
+ backend: Backend,
214
+ placement: Any,
215
+ loader: Loader | None,
216
+ cache: CacheLike,
217
+ native: bool = False,
218
+ shape: Callable[[Target], Any] = lambda target: target,
219
+ ) -> Pending[dict[str, Any]]:
220
+ return _start_load(
221
+ source,
222
+ store,
223
+ cache,
224
+ lambda index: _plan_arrays(index, names, placement, native=native),
225
+ lambda planned, arrays: {f.name: arrays[f.index] for f in planned.fills},
226
+ backend=backend,
227
+ loader=loader,
228
+ shape_of=lambda planned: {f.name: shape(f.target) for f in planned.fills},
229
+ )
230
+
231
+
232
+ def _plan_arrays(
233
+ index: Index,
234
+ names: Sequence[str] | None = None,
235
+ placement: Any = None,
236
+ *,
237
+ native: bool = False,
238
+ ) -> Plan:
239
+ wanted = list(index) if names is None else list(names)
240
+ if absent := [n for n in wanted if n not in index]:
241
+ raise KeyError(f"not in the checkpoint: {absent}")
242
+ requests = []
243
+ for i, n in enumerate(wanted):
244
+ dtype = index[n].dtype.newbyteorder("=") if native else index[n].dtype
245
+ requests.append(Request(i, n, Target(index[n].shape, dtype, placement), n))
246
+ return build_plan(requests, index, strict=False)
247
+
248
+
249
+ def index(source: Source | Sequence[Source], *, store: StoreLike | None = None, cache: CacheLike = None) -> Index:
250
+ """Every tensor in `source` -- key, shape, dtype, location -- from the headers alone."""
251
+ return read_index(_sources(source, store, resolve_cache(cache)))
252
+
253
+
254
+ def _sources(
255
+ source: Source | Sequence[Source], store: StoreLike | None = None, cache: Cache | None = None
256
+ ) -> list[Blob | Mapping[str, Any]]:
257
+ single = isinstance(source, (str, os.PathLike, Blob, Mapping))
258
+ items: list[Any] = [source] if single else list(source)
259
+ if not items:
260
+ raise ValueError("no checkpoint sources given")
261
+ out: list[Blob | Mapping[str, Any]] = []
262
+ for item in items:
263
+ if isinstance(item, (Blob, Mapping)):
264
+ out.append(item)
265
+ elif isinstance(item, (str, os.PathLike)):
266
+ out.append(resolve(item, store))
267
+ else:
268
+ raise TypeError(f"not a checkpoint source: {item!r}")
269
+ if cache is not None:
270
+ out = [cache.wrap(item) if isinstance(item, Blob) else item for item in out]
271
+ return out
tensorferry/backend.py ADDED
@@ -0,0 +1,28 @@
1
+ from typing import Any, Protocol
2
+
3
+ import numpy as np
4
+
5
+ from tensorferry.plan import Target
6
+
7
+ __all__ = ["Backend", "NumpyBackend"]
8
+
9
+
10
+ class Backend(Protocol):
11
+ """Batched backends must return one buffer and one finished array per target, in request order."""
12
+
13
+ def host_buffer(self, target: Target) -> np.ndarray:
14
+ """A writable, C-contiguous array of `target`'s shape and dtype to assemble into."""
15
+ ...
16
+
17
+ def finish(self, target: Target, buffer: np.ndarray) -> Any: ...
18
+
19
+
20
+ class NumpyBackend:
21
+ def accepts_mapped(self, target: Target) -> bool:
22
+ return True
23
+
24
+ def host_buffer(self, target: Target) -> np.ndarray:
25
+ return np.empty(target.shape, target.dtype)
26
+
27
+ def finish(self, target: Target, buffer: np.ndarray) -> Any:
28
+ return buffer