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/loader.py ADDED
@@ -0,0 +1,571 @@
1
+ import contextlib
2
+ import ctypes
3
+ import queue
4
+ import sys
5
+ import threading
6
+ import zlib
7
+ from collections.abc import Callable, Iterator
8
+ from dataclasses import dataclass, field
9
+ from typing import Any, Literal, Protocol
10
+
11
+ import numpy as np
12
+
13
+ from tensorferry._pool import TICK, DaemonPool, check_cancel
14
+ from tensorferry.backend import Backend
15
+ from tensorferry.formats import FormatError
16
+ from tensorferry.plan import Fill, Plan
17
+ from tensorferry.progress import _download
18
+ from tensorferry.store import Blob
19
+
20
+ __all__ = ["Loader", "Sink", "StreamingLoader"]
21
+
22
+
23
+ def _load_malloc_trim() -> Callable[[int], int] | None:
24
+ if sys.platform != "linux":
25
+ return None
26
+ with contextlib.suppress(OSError, AttributeError):
27
+ fn = ctypes.CDLL("libc.so.6").malloc_trim
28
+ fn.argtypes = (ctypes.c_size_t,)
29
+ fn.restype = ctypes.c_int
30
+ return fn
31
+ return None
32
+
33
+
34
+ _MALLOC_TRIM = _load_malloc_trim()
35
+
36
+
37
+ # Takes each fill's finished host buffer, before the backend does.
38
+ type Sink = Callable[[Fill, np.ndarray], None]
39
+
40
+
41
+ class Loader(Protocol):
42
+ """Yield each fill once with its finished backend array, in any order."""
43
+
44
+ def __call__(
45
+ self, plan: Plan, backend: Backend, *, cancel: threading.Event | None = None
46
+ ) -> Iterator[tuple[Fill, Any]]: ...
47
+
48
+
49
+ @dataclass(frozen=True, slots=True)
50
+ class StreamingLoader:
51
+ """Coalesce file-ordered tensors into concurrent reads and overlap device transfers."""
52
+
53
+ workers: int = 16
54
+ chunk_bytes: int = 32 << 20
55
+ staging_bytes: int = 512 << 20
56
+ gap_bytes: int = 1 << 20
57
+ map_local: bool = True
58
+
59
+ def __call__(
60
+ self,
61
+ plan: Plan,
62
+ backend: Backend,
63
+ *,
64
+ cancel: threading.Event | None = None,
65
+ sink: Sink | None = None,
66
+ ) -> Iterator[tuple[Fill, Any]]:
67
+ return _Run(self, plan, backend, cancel, sink).results()
68
+
69
+
70
+ class _FillState:
71
+ __slots__ = ("batch", "buffer", "fill", "pending")
72
+
73
+ def __init__(self, fill: Fill) -> None:
74
+ self.fill = fill
75
+ self.pending = len(fill.parts)
76
+ self.buffer: np.ndarray | None = None
77
+ self.batch: _Batch | None = None
78
+
79
+
80
+ class _Batch:
81
+ __slots__ = ("fills", "pending")
82
+
83
+ def __init__(self, fills: list[_FillState]) -> None:
84
+ self.fills = fills
85
+ self.pending = len(fills)
86
+
87
+
88
+ class _PartState:
89
+ __slots__ = ("at", "direct", "landing", "needs_temporary", "owner", "pending", "tensor")
90
+
91
+ def __init__(self, owner: _FillState, index: int) -> None:
92
+ part = owner.fill.parts[index]
93
+ target = owner.fill.target
94
+ assert part.tensor is not None, "plans hold resolved parts"
95
+ self.owner = owner
96
+ self.tensor = part.tensor
97
+ self.at = (*part.at, Ellipsis)
98
+ self.pending = part.tensor.nbytes
99
+ # Bytes can land straight in the array's buffer when they need no
100
+ # conversion and their destination is one contiguous run of it.
101
+ self.direct = (
102
+ part.tensor.array is None
103
+ and not part.tensor.fortran
104
+ and part.tensor.dtype == target.dtype
105
+ and _contiguous(target.shape, part.at)
106
+ )
107
+ # Otherwise they land in a temporary and are converted from there.
108
+ self.needs_temporary = not self.direct and part.tensor.array is None
109
+ self.landing: np.ndarray | None = None # flat uint8: a view of the buffer, or a temporary
110
+
111
+
112
+ @dataclass(slots=True)
113
+ class _Task:
114
+ kind: Literal["read", "decode", "copy", "map"]
115
+ parts: list[_PartState]
116
+ blob: Blob | None = None
117
+ start: int = 0
118
+ stop: int = 0
119
+ # (part, offset in its landing, offset in the file, length)
120
+ pieces: list[tuple[_PartState, int, int, int]] = field(default_factory=list)
121
+
122
+
123
+ class _Run:
124
+ def __init__(
125
+ self,
126
+ cfg: StreamingLoader,
127
+ plan: Plan,
128
+ backend: Backend,
129
+ cancel: threading.Event | None,
130
+ sink: Sink | None = None,
131
+ ) -> None:
132
+ self.cfg = cfg
133
+ self.backend = backend
134
+ self.sink = sink
135
+ self.cancel = cancel or threading.Event()
136
+ self.fills = [_FillState(fill) for fill in plan.fills]
137
+ self.parts = [_PartState(fs, i) for fs in self.fills for i in range(len(fs.fill.parts))]
138
+ self.cond = threading.Condition()
139
+ self.allocated = 0
140
+ self.inflight = 0
141
+ self.error: BaseException | None = None
142
+ self.stopped = False
143
+ self.done: queue.SimpleQueue[tuple[Fill, Any] | None] = queue.SimpleQueue()
144
+ self._shared: set[tuple[int, str, int]] = set()
145
+
146
+ def results(self) -> Iterator[tuple[Fill, Any]]:
147
+ tasks = self._tasks()
148
+ if (download := _download.get()) is not None:
149
+ download.estimate(self._estimate_download_bytes(tasks))
150
+ remaining = len(self.fills)
151
+ pool = DaemonPool(self.cfg.workers)
152
+ completed = False
153
+ try:
154
+ for fs in self.fills:
155
+ if not fs.fill.parts: # nothing to read: a zero-size array
156
+ self.allocated += fs.fill.nbytes
157
+ fs.buffer = self._host_buffer(fs.fill)
158
+ self._place_all([fs])
159
+ for task in tasks:
160
+ self._check_cancel()
161
+ self._admit(task)
162
+ pool.submit(self._execute, task)
163
+ while (item := self._poll(block=False)) is not None:
164
+ remaining -= 1
165
+ yield item
166
+ while remaining:
167
+ item = self._poll(block=True)
168
+ assert item is not None
169
+ remaining -= 1
170
+ yield item
171
+ completed = True
172
+ finally:
173
+ self.stopped = True
174
+ # Queued reads never start. After a failure or cancellation, reads
175
+ # already running are left to finish on their own: waiting for one
176
+ # stuck on a stalled connection would hang the caller.
177
+ pool.shutdown(wait=completed, cancel_futures=True)
178
+ # After a failure or an early close, drop every staging buffer now,
179
+ # rather than whenever the last reference to this run goes away.
180
+ for fs in self.fills:
181
+ fs.buffer = None
182
+ for ps in self.parts:
183
+ ps.landing = None
184
+ if _MALLOC_TRIM is not None:
185
+ _MALLOC_TRIM(0)
186
+
187
+ # --- scheduling -----------------------------------------------------------
188
+
189
+ def _estimate_download_bytes(self, tasks: list[_Task]) -> int:
190
+ nbytes = 0
191
+ for task in tasks:
192
+ if task.kind == "read":
193
+ assert task.blob is not None
194
+ nbytes += task.blob._remote_bytes(task.start, task.stop)
195
+ elif task.kind == "decode":
196
+ tensor = task.parts[0].tensor
197
+ assert tensor.blob is not None
198
+ nbytes += tensor.blob._remote_bytes(tensor.start, tensor.stop)
199
+ return nbytes
200
+
201
+ def _tasks(self) -> list[_Task]:
202
+ """Every read, in file order; in-memory copies and deflated members first."""
203
+ copies: list[_Task] = []
204
+ decodes: list[_Task] = []
205
+ maps: dict[tuple[int, str], _Task] = {}
206
+ by_file: dict[tuple[int, str], list[_PartState]] = {}
207
+ # A stored tensor read by several parts must not be mapped: its views
208
+ # would share one writable mapping, so writing one array would change
209
+ # the others. Tied arrays are one request, hence one part.
210
+ readers: dict[tuple[int, str, int], int] = {}
211
+ for ps in self.parts:
212
+ if ps.tensor.blob is not None:
213
+ key = (id(ps.tensor.blob.store), ps.tensor.blob.name, ps.tensor.start)
214
+ readers[key] = readers.get(key, 0) + 1
215
+ self._shared = {key for key, count in readers.items() if count > 1}
216
+ for ps in self.parts:
217
+ t = ps.tensor
218
+ if self._mappable(ps):
219
+ assert t.blob is not None
220
+ key = (id(t.blob.store), t.blob.name)
221
+ maps.setdefault(key, _Task("map", [], t.blob)).parts.append(ps)
222
+ elif t.array is not None or t.nbytes == 0:
223
+ copies.append(_Task("copy", [ps]))
224
+ elif t.codec == "deflate":
225
+ decodes.append(_Task("decode", [ps]))
226
+ else:
227
+ assert t.blob is not None
228
+ by_file.setdefault((id(t.blob.store), t.blob.name), []).append(ps)
229
+ chunk, gap = self.cfg.chunk_bytes, self.cfg.gap_bytes
230
+ reads: list[_Task] = []
231
+ for group in by_file.values():
232
+ group.sort(key=lambda ps: ps.tensor.start)
233
+ current: _Task | None = None
234
+ for ps in group:
235
+ t, offset = ps.tensor, 0
236
+ while offset < t.nbytes:
237
+ start = t.start + offset
238
+ # A piece joins the open read only if it lies inside what that
239
+ # read fetches: a tensor loaded twice starts over at its own
240
+ # offset, before the read its first copy left open.
241
+ if (
242
+ current is not None
243
+ and current.start <= start < current.start + chunk
244
+ and start - current.stop <= gap
245
+ ):
246
+ n = min(t.nbytes - offset, current.start + chunk - start)
247
+ else:
248
+ current = _Task("read", [], t.blob, start, start)
249
+ reads.append(current)
250
+ n = min(t.nbytes - offset, chunk)
251
+ current.pieces.append((ps, offset, start, n))
252
+ if not current.parts or current.parts[-1] is not ps:
253
+ current.parts.append(ps)
254
+ current.stop = max(current.stop, start + n)
255
+ offset += n
256
+ self._batch(copies + decodes, reads)
257
+ return [*maps.values(), *copies, *decodes, *reads]
258
+
259
+ def _mappable(self, ps: _PartState) -> bool:
260
+ """Whether `ps` can be a view of the memory-mapped file instead of a copy."""
261
+ t, fill = ps.tensor, ps.owner.fill
262
+ accepts = getattr(self.backend, "accepts_mapped", None)
263
+ return (
264
+ self.cfg.map_local
265
+ and accepts is not None
266
+ and len(fill.parts) == 1
267
+ and ps.direct
268
+ and t.codec == "raw"
269
+ and t.crc32 is None
270
+ and 0 < t.nbytes == fill.nbytes
271
+ and t.start % t.dtype.alignment == 0
272
+ and t.blob is not None
273
+ and (id(t.blob.store), t.blob.name, t.start) not in self._shared
274
+ and t.blob.can("map")
275
+ and bool(accepts(fill.target))
276
+ )
277
+
278
+ def _batch(self, others: list[_Task], reads: list[_Task]) -> None:
279
+ home: dict[_FillState, _Task | None] = {}
280
+ for task in others:
281
+ for ps in task.parts:
282
+ home[ps.owner] = None
283
+ for task in reads:
284
+ for ps in task.parts:
285
+ home[ps.owner] = task if home.get(ps.owner, task) is task else None
286
+ for task in reads:
287
+ groups: dict[Any, list[_FillState]] = {}
288
+ for fs in dict.fromkeys(ps.owner for ps in task.parts):
289
+ if home[fs] is task:
290
+ try:
291
+ groups.setdefault(fs.fill.target.placement, []).append(fs)
292
+ except TypeError: # an unhashable placement finishes on its own
293
+ continue
294
+ for members in groups.values():
295
+ if len(members) > 1:
296
+ batch = _Batch(members)
297
+ for fs in members:
298
+ fs.batch = batch
299
+
300
+ def _admit(self, task: _Task) -> None:
301
+ """Wait for staging room, then allocate what `task` writes into."""
302
+ if task.kind == "map": # views of the file: nothing to allocate
303
+ with self.cond:
304
+ if self.error is not None:
305
+ raise self.error
306
+ self.inflight += 1
307
+ return
308
+ fills = dict.fromkeys(ps.owner for ps in task.parts if ps.owner.buffer is None)
309
+ # Nothing this adds up can change while it waits: only this thread allocates.
310
+ need = sum(fs.fill.nbytes for fs in fills) + sum(
311
+ ps.tensor.nbytes for ps in task.parts if ps.landing is None and ps.needs_temporary
312
+ )
313
+ with self.cond:
314
+ while True:
315
+ if self.error is not None:
316
+ raise self.error
317
+ if need == 0 or self.inflight == 0 or self.allocated + need <= self.cfg.staging_bytes:
318
+ break
319
+ self.cond.wait(TICK)
320
+ self._check_cancel()
321
+ self.allocated += need
322
+ self.inflight += 1
323
+ try:
324
+ for batch in dict.fromkeys(fs.batch for fs in fills if fs.batch is not None):
325
+ buffers = self._host_buffers([fs.fill for fs in batch.fills])
326
+ for fs, buffer in zip(batch.fills, buffers, strict=True):
327
+ fs.buffer = buffer
328
+ for fs in fills:
329
+ if fs.batch is None:
330
+ fs.buffer = self._host_buffer(fs.fill)
331
+ for ps in task.parts:
332
+ if ps.landing is not None:
333
+ continue
334
+ if ps.direct:
335
+ assert ps.owner.buffer is not None
336
+ view = ps.owner.buffer[ps.at]
337
+ assert view.flags.c_contiguous # what `direct` promises: reshaping copies nothing
338
+ ps.landing = view.reshape(-1).view(np.uint8)
339
+ elif ps.needs_temporary:
340
+ ps.landing = np.empty(ps.tensor.nbytes, np.uint8)
341
+ except BaseException:
342
+ with self.cond:
343
+ self.inflight -= 1
344
+ self.cond.notify_all()
345
+ raise
346
+
347
+ def _host_buffers(self, fills: list[Fill]) -> list[np.ndarray]:
348
+ method = getattr(self.backend, "host_buffers", None)
349
+ if method is None:
350
+ return [self._host_buffer(fill) for fill in fills]
351
+ buffers = list(method([fill.target for fill in fills]))
352
+ if len(buffers) != len(fills):
353
+ raise TypeError(f"host_buffers returned {len(buffers)} buffers for {len(fills)} arrays")
354
+ return [self._check(fill, buffer) for fill, buffer in zip(fills, buffers, strict=True)]
355
+
356
+ def _host_buffer(self, fill: Fill) -> np.ndarray:
357
+ return self._check(fill, self.backend.host_buffer(fill.target))
358
+
359
+ def _check(self, fill: Fill, buffer: Any) -> np.ndarray:
360
+ if (
361
+ not isinstance(buffer, np.ndarray)
362
+ or buffer.shape != fill.target.shape
363
+ or buffer.dtype != fill.target.dtype
364
+ or not buffer.flags.c_contiguous
365
+ or not buffer.flags.writeable
366
+ ):
367
+ raise TypeError(
368
+ f"{fill.name}: the backend's host buffer is not a writable C-contiguous "
369
+ f"{fill.target.shape} {fill.target.dtype} array"
370
+ )
371
+ return buffer
372
+
373
+ def _check_cancel(self) -> None:
374
+ check_cancel(self.cancel)
375
+
376
+ def _poll(self, *, block: bool) -> tuple[Fill, Any] | None:
377
+ while True:
378
+ try:
379
+ item = self.done.get(timeout=TICK) if block else self.done.get_nowait()
380
+ break
381
+ except queue.Empty:
382
+ if not block:
383
+ return None
384
+ self._check_cancel()
385
+ if item is None:
386
+ assert self.error is not None
387
+ raise self.error
388
+ return item
389
+
390
+ # --- work, on the pool's threads ------------------------------------------
391
+
392
+ def _execute(self, task: _Task) -> None:
393
+ try:
394
+ if self.stopped or self.error is not None or self.cancel.is_set():
395
+ return
396
+ if task.kind == "map":
397
+ self._map(task)
398
+ return
399
+ if task.kind == "read":
400
+ finished = self._read(task)
401
+ elif task.kind == "decode":
402
+ finished = task.parts if self._inflate(task.parts[0]) else []
403
+ else:
404
+ finished = task.parts
405
+ for ps in finished:
406
+ self._finish_part(ps)
407
+ except BaseException as exc:
408
+ with self.cond:
409
+ if self.error is None:
410
+ self.error = exc
411
+ self.done.put(None)
412
+ finally:
413
+ with self.cond:
414
+ self.inflight -= 1
415
+ self.cond.notify_all()
416
+
417
+ def _map(self, task: _Task) -> None:
418
+ """Hand each array over as a view of the memory-mapped file."""
419
+ assert task.blob is not None
420
+ store: Any = task.blob.store # `map` is an optional Store method
421
+ mapping = store.map(task.blob.name)
422
+ fills = [ps.owner.fill for ps in task.parts]
423
+ views = []
424
+ for ps in task.parts:
425
+ t, target = ps.tensor, ps.owner.fill.target
426
+ if t.stop > len(mapping): # never touch pages past the end: that is SIGBUS
427
+ raise EOFError(f"{task.blob}: {t.key} ends at {t.stop}, the file at {len(mapping)}")
428
+ count = t.nbytes // t.dtype.itemsize
429
+ views.append(np.frombuffer(mapping, t.dtype, count=count, offset=t.start).reshape(target.shape))
430
+ self._complete(fills, views) # views of the file: no staging to release
431
+
432
+ def _read(self, task: _Task) -> list[_PartState]:
433
+ # A run that has stopped (failed or cancelled) may already have dropped
434
+ # these buffers; a read still in flight then just ends quietly.
435
+ assert task.blob is not None
436
+ # One request for the whole range, unless the store reads straight into buffers.
437
+ data = None if task.blob.can("fetch_into") else task.blob.fetch_exact(task.start, task.stop)
438
+ for ps, offset, start, n in task.pieces:
439
+ landing = ps.landing
440
+ if landing is None or self.stopped:
441
+ return []
442
+ if data is None:
443
+ task.blob.read_into(start, landing[offset : offset + n])
444
+ else:
445
+ landing[offset : offset + n] = data[start - task.start : start - task.start + n]
446
+ finished = []
447
+ with self.cond:
448
+ for ps, _, _, n in task.pieces:
449
+ ps.pending -= n
450
+ if ps.pending == 0:
451
+ finished.append(ps)
452
+ return finished
453
+
454
+ def _inflate(self, ps: _PartState) -> bool:
455
+ t, out = ps.tensor, ps.landing
456
+ assert t.blob is not None
457
+ assert out is not None
458
+ decoder = zlib.decompressobj(-15)
459
+ skip, filled, overflow, crc = t.skip, 0, False, 0
460
+
461
+ def take(chunk: bytes) -> None:
462
+ nonlocal skip, filled, overflow, crc
463
+ crc = zlib.crc32(chunk, crc) # the zip CRC covers the .npy header too
464
+ view = memoryview(chunk)
465
+ if skip:
466
+ dropped = min(skip, len(view))
467
+ view, skip = view[dropped:], skip - dropped
468
+ n = min(len(view), out.size - filled)
469
+ overflow |= n < len(view)
470
+ out[filled : filled + n] = np.frombuffer(view[:n], np.uint8)
471
+ filled += n
472
+
473
+ step = self.cfg.chunk_bytes
474
+ try:
475
+ for start in range(t.start, t.stop, step):
476
+ # A long member is many reads: stop between them once the run is over.
477
+ self._check_cancel()
478
+ if self.stopped:
479
+ return False
480
+ take(decoder.decompress(t.blob.fetch_exact(start, min(start + step, t.stop))))
481
+ take(decoder.flush())
482
+ except zlib.error as exc:
483
+ raise FormatError(f"{t.blob}: {t.key}.npy is not a valid deflate stream") from exc
484
+ if filled != out.size or skip or overflow or not decoder.eof:
485
+ raise FormatError(f"{t.blob}: {t.key}.npy decodes to the wrong length")
486
+ if t.crc32 is not None and crc != t.crc32:
487
+ raise FormatError(f"{t.blob}: {t.key}.npy fails its CRC-32 check")
488
+ return True
489
+
490
+ def _finish_part(self, ps: _PartState) -> None:
491
+ """Copy (and convert) a part whose bytes are all in; finish its array if complete."""
492
+ t, fs = ps.tensor, ps.owner
493
+ buffer = fs.buffer
494
+ if buffer is None or self.stopped:
495
+ return
496
+ if t.codec == "raw" and t.crc32 is not None:
497
+ assert ps.landing is not None
498
+ if zlib.crc32(ps.landing, t.crc_seed) != t.crc32:
499
+ raise FormatError(f"{t.blob}: {t.key}.npy fails its CRC-32 check")
500
+ if not ps.direct:
501
+ if t.array is not None:
502
+ source = np.asarray(t.array)
503
+ else:
504
+ assert ps.landing is not None
505
+ flat = np.frombuffer(ps.landing, t.dtype)
506
+ source = flat.reshape(t.shape[::-1]).T if t.fortran else flat.reshape(t.shape)
507
+ dest = buffer[ps.at]
508
+ dest[...] = source.reshape(dest.shape)
509
+ freed = t.nbytes if ps.needs_temporary else 0
510
+ ps.landing = None
511
+ with self.cond:
512
+ self.allocated -= freed
513
+ fs.pending -= 1
514
+ complete = fs.pending == 0
515
+ batch = fs.batch
516
+ if complete and batch is not None:
517
+ batch.pending -= 1
518
+ complete = batch.pending == 0
519
+ self.cond.notify_all()
520
+ if complete:
521
+ self._place_all([fs] if batch is None else batch.fills)
522
+
523
+ def _place_all(self, states: list[_FillState]) -> None:
524
+ buffers = []
525
+ for fs in states:
526
+ assert fs.buffer is not None
527
+ buffers.append(fs.buffer)
528
+ fs.buffer = None
529
+ try:
530
+ self._complete([fs.fill for fs in states], buffers)
531
+ finally:
532
+ del buffers
533
+ with self.cond:
534
+ self.allocated -= sum(fs.fill.nbytes for fs in states)
535
+ self.cond.notify_all()
536
+
537
+ def _complete(self, fills: list[Fill], buffers: list[np.ndarray]) -> None:
538
+ if self.sink is not None:
539
+ for fill, buffer in zip(fills, buffers, strict=True):
540
+ self.sink(fill, buffer)
541
+ targets = [fill.target for fill in fills]
542
+ method = getattr(self.backend, "finish_many", None)
543
+ if len(fills) > 1 and method is not None:
544
+ results = list(method(targets, buffers))
545
+ if len(results) != len(targets):
546
+ raise TypeError(f"finish_many returned {len(results)} arrays for {len(targets)}")
547
+ else:
548
+ results = [self.backend.finish(t, b) for t, b in zip(targets, buffers, strict=True)]
549
+ for fill, result in zip(fills, results, strict=True):
550
+ self.done.put((fill, result))
551
+
552
+
553
+ def _contiguous(shape: tuple[int, ...], at: tuple[int | slice, ...]) -> bool:
554
+ """Whether `np.empty(shape)[at]` is one contiguous run of the C-ordered array."""
555
+ if not at:
556
+ return True
557
+ at = (*at, *(slice(None),) * (len(shape) - len(at)))
558
+ axis = 0
559
+ while axis < len(at) and isinstance(at[axis], (int, np.integer)):
560
+ axis += 1
561
+ if axis < len(at):
562
+ entry = at[axis]
563
+ if not isinstance(entry, slice) or entry.indices(shape[axis])[2] != 1:
564
+ return False
565
+ axis += 1
566
+ for entry, size in zip(at[axis:], shape[axis:], strict=True):
567
+ if size == 1:
568
+ continue
569
+ if not isinstance(entry, slice) or entry.indices(size) != (0, size, 1):
570
+ return False
571
+ return True