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/cache.py ADDED
@@ -0,0 +1,1099 @@
1
+ import atexit
2
+ import bisect
3
+ import contextlib
4
+ import copy
5
+ import dataclasses
6
+ import functools
7
+ import hashlib
8
+ import json
9
+ import mmap
10
+ import os
11
+ import shutil
12
+ import threading
13
+ import time
14
+ import uuid
15
+ import warnings
16
+ import weakref
17
+ from collections.abc import Buffer, Callable, Iterable
18
+ from pathlib import Path
19
+ from typing import Any, TypeGuard
20
+
21
+ import numpy as np
22
+
23
+ from tensorferry._pool import TICK, DaemonPool, check_cancel
24
+ from tensorferry.formats import _SAFETENSORS_DTYPES, Tensor
25
+ from tensorferry.plan import Fill, Part, Plan
26
+ from tensorferry.store import Blob, LocalStore, ObjectStore, Store, StoreLike, as_store
27
+
28
+ __all__ = ["Cache", "CacheLike", "CachedStore", "default_cache_dir", "parse_bytes", "resolve_cache"]
29
+
30
+ # What a load's ``cache=`` accepts.
31
+ type CacheLike = Cache | str | os.PathLike[str] | bool | None
32
+
33
+ # How long written ranges wait before they are flushed and published, in seconds.
34
+ _SYNC_INTERVAL = 0.25
35
+ # How long a process keeps the right to fill a file once it has no read in flight.
36
+ _FILL_LINGER = 0.5
37
+ _STATE = "state.json"
38
+
39
+ # Bump the layout version when the on-disk format changes so processes can still open older entries.
40
+ _LAYOUT = "v1"
41
+ _ARRAYS = "arrays" # names entries in state.json
42
+ _ARRAYS_PREFIX = "arrays-" # names the folders of kept arrays
43
+ # What an entry's folder holds; a source segment spelled like these is renamed.
44
+ _ENTRY_FILES = frozenset({"data", "data.safetensors", _STATE, "lock", "fill.lock"})
45
+ # Bump when what goes into a cached array changes, e.g. how casts round.
46
+ _FORMAT = "tensorferry-arrays/1"
47
+ # Where arrays start in a cached file: 64 bytes, as XLA wants to alias host memory.
48
+ _ALIGN = 64
49
+ _CODES = {dtype: code for code, dtype in _SAFETENSORS_DTYPES.items()}
50
+ _UNITS = {"": 1, "K": 1 << 10, "M": 1 << 20, "G": 1 << 30, "T": 1 << 40}
51
+
52
+
53
+ def default_cache_dir() -> Path:
54
+ """Where a cache goes unless told: `$XDG_CACHE_HOME/tensorferry`, else `~/.cache/tensorferry`."""
55
+ base = os.environ.get("XDG_CACHE_HOME", "")
56
+ root = Path(base) if base and Path(base).is_absolute() else Path.home() / ".cache"
57
+ return root / "tensorferry"
58
+
59
+
60
+ def _data(folder: Path) -> Path:
61
+ """A cached file's data: kept arrays are a safetensors file, and named so."""
62
+ return folder / ("data.safetensors" if folder.name.startswith(_ARRAYS_PREFIX) else "data")
63
+
64
+
65
+ def _place(url: str, name: str = "") -> Path:
66
+ """A source's folder, relative to the layout folder: its URL, one folder per segment."""
67
+ scheme, sep, rest = url.partition("://")
68
+ segments = [scheme, *rest.split("/")] if sep else url.split("/")
69
+ segments += name.split("/")
70
+ return Path(*(_segment(s) for s in segments if s not in ("", ".")))
71
+
72
+
73
+ def _segment(part: str) -> str:
74
+ if part == ".." or len(part.encode()) > 200 or part in _ENTRY_FILES or part.startswith(_ARRAYS_PREFIX):
75
+ return f"{part[:64].replace('.', '_')}-{hashlib.sha256(part.encode()).hexdigest()[:16]}"
76
+ return part
77
+
78
+
79
+ def parse_bytes(text: str | int | None) -> int | None:
80
+ """``"50G"`` -> 53687091200: a byte count, with an optional binary unit (K, M, G, T)."""
81
+ if text is None or isinstance(text, int):
82
+ return text
83
+ value = text.strip().upper().removesuffix("B").removesuffix("I")
84
+ unit = value[-1:] if value[-1:] in _UNITS else ""
85
+ return int(float(value.removesuffix(unit)) * _UNITS[unit])
86
+
87
+
88
+ class Cache:
89
+ """Processes can share a cache directory. Remote byte ranges and converted arrays share one LRU byte budget."""
90
+
91
+ def __init__(
92
+ self,
93
+ root: str | os.PathLike[str] | None = None,
94
+ *,
95
+ max_bytes: int | str | None = None,
96
+ arrays: bool = True,
97
+ sources: bool = True,
98
+ revalidate: bool = False,
99
+ patience: float = 30.0,
100
+ ) -> None:
101
+ if os.name != "posix" or not hasattr(os, "preadv"):
102
+ raise OSError("tensorferry's cache needs a POSIX system (file locks, positioned reads)")
103
+ self.root = Path(default_cache_dir() if root is None else root).expanduser().resolve()
104
+ (self.root / _LAYOUT).mkdir(parents=True, exist_ok=True)
105
+ self.max_bytes = parse_bytes(max_bytes)
106
+ self.arrays = arrays
107
+ self.sources = sources
108
+ self.revalidate = revalidate
109
+ self.patience = patience
110
+ self._stores: dict[Any, tuple[Any, CachedStore]] = {}
111
+ self._lock = threading.Lock()
112
+
113
+ def __repr__(self) -> str:
114
+ return f"Cache({str(self.root)!r})"
115
+
116
+ def store(self, store: Store) -> "CachedStore":
117
+ """`store` behind this cache: one :class:`CachedStore` per store, kept for reuse."""
118
+ with self._lock:
119
+ if id(store) not in self._stores: # holding `store` keeps its id unique
120
+ self._stores[id(store)] = (store, CachedStore(store, self))
121
+ return self._stores[id(store)][1]
122
+
123
+ def wrap(self, blob: Blob) -> Blob:
124
+ """`blob`, read through this cache if sources are kept and its store is remote."""
125
+ store = blob.store
126
+ url = getattr(store, "url", None)
127
+ if not self.sources or not url or url.startswith("file:") or isinstance(store, CachedStore):
128
+ return blob
129
+ return Blob(self.store(store), blob.name)
130
+
131
+ def rewrite(self, plan: Plan, *, cancel: threading.Event | None = None) -> "tuple[Plan, _Sink | None]":
132
+ """`plan`, reading the arrays this cache holds from it; and a sink for the rest."""
133
+ if not self.arrays:
134
+ return plan, None
135
+ return _derive(self, plan, cancel)
136
+
137
+ def adopt(self, url: str | os.PathLike[str] | Blob, path: str | os.PathLike[str], *, link: bool = True) -> Path:
138
+ """The caller guarantees that the bytes match the remote file. With link=True, replace the source file
139
+ atomically if it needs updating. In-place writes also change the cached copy.
140
+ """
141
+ from tensorferry.store import resolve
142
+
143
+ blob = url if isinstance(url, Blob) else resolve(url)
144
+ return self.store(blob.store)._adopt(blob.name, Path(path), link=link)
145
+
146
+ def flush(self) -> None:
147
+ for entry in list(_LIVE):
148
+ if entry.cache.root == self.root:
149
+ entry.flush()
150
+
151
+ def clear(self) -> None:
152
+ """Evicts cached files except those in use. Other processes can share the directory."""
153
+ self.flush()
154
+ with self._lock:
155
+ stores = [cached for _, cached in self._stores.values()]
156
+ for cached in stores:
157
+ cached._forget()
158
+ for folder in self._folders():
159
+ _evict(folder)
160
+
161
+ def _folders(self) -> list[Path]:
162
+ """Every entry's folder: wherever a state file is, in this layout."""
163
+ return [p.parent for p in (self.root / _LAYOUT).rglob(_STATE)]
164
+
165
+ def _make_room(self, need: int, keep: Path) -> None:
166
+ if self.max_bytes is None:
167
+ return
168
+ found = []
169
+ for folder in self._folders():
170
+ if folder == keep:
171
+ continue
172
+ try:
173
+ used = _data(folder).stat().st_blocks * 512 # sparse: what is actually there
174
+ last = (folder / _STATE).stat().st_mtime
175
+ except FileNotFoundError:
176
+ continue
177
+ found.append((last, used, folder))
178
+ total = sum(used for _, used, _ in found)
179
+ for _, used, folder in sorted(found):
180
+ if total + need <= self.max_bytes:
181
+ break
182
+ if _evict(folder):
183
+ total -= used
184
+
185
+
186
+ def resolve_cache(cache: CacheLike) -> Cache | None:
187
+ """Use the default disk cache unless TENSORFERRY_CACHE or an explicit choice overrides it."""
188
+ if cache is None:
189
+ setting = os.environ.get("TENSORFERRY_CACHE")
190
+ root = "1" if setting is None else setting.strip()
191
+ if not root or root.lower() in ("0", "false", "no", "off"):
192
+ return None
193
+ try:
194
+ if root.lower() in ("1", "true", "yes", "on"):
195
+ root = str(default_cache_dir())
196
+ return _cache_at(_absolute(root), os.environ.get("TENSORFERRY_CACHE_MAX_BYTES"))
197
+ except (OSError, RuntimeError):
198
+ if setting is not None:
199
+ raise
200
+ # Ordinary reads still work without disk-cache support or a writable default directory.
201
+ return None
202
+ if cache is False:
203
+ return None
204
+ if cache is True:
205
+ return _cache_at(_absolute(default_cache_dir()))
206
+ if isinstance(cache, Cache):
207
+ return cache
208
+ if isinstance(cache, (str, os.PathLike)):
209
+ return _cache_at(_absolute(cache))
210
+ raise TypeError(f"cache= takes a Cache, a directory, a bool or None, not {cache!r}")
211
+
212
+
213
+ def _absolute(path: str | os.PathLike[str]) -> str:
214
+ return str(Path(path).expanduser().resolve())
215
+
216
+
217
+ @functools.cache
218
+ def _cache_at(root: str, limit: str | None = None) -> Cache:
219
+ return Cache(root, max_bytes=limit)
220
+
221
+
222
+ class CachedStore:
223
+ def __init__(
224
+ self,
225
+ store: StoreLike | str | os.PathLike[str],
226
+ cache: Cache | str | os.PathLike[str],
227
+ *,
228
+ namespace: str | None = None,
229
+ ) -> None:
230
+ if isinstance(store, (str, os.PathLike)):
231
+ text = os.fspath(store)
232
+ remote = "://" in text and not text.startswith("file://")
233
+ store = ObjectStore(text) if remote else LocalStore(text.removeprefix("file://"))
234
+ self.store = as_store(store)
235
+ self.cache = cache if isinstance(cache, Cache) else Cache(cache)
236
+ namespace = namespace or getattr(self.store, "url", None)
237
+ if not namespace:
238
+ raise TypeError(f"{self.store!r} has no url to key the cache on; pass namespace=")
239
+ self.namespace: str = namespace
240
+ self._entries: dict[str, _Entry | None] = {}
241
+ self._opening: dict[str, threading.Lock] = {}
242
+ self._lock = threading.Lock()
243
+ self._warned = False
244
+ self._write = True # False in the read-only view
245
+
246
+ def __repr__(self) -> str:
247
+ return f"CachedStore({self.store!r}, {self.cache!r}{'' if self._write else ', read-only'})"
248
+
249
+ @property
250
+ def url(self) -> str:
251
+ return self.namespace
252
+
253
+ @functools.cached_property
254
+ def readonly(self) -> "CachedStore":
255
+ """This store, reading what is cached but adding nothing to it."""
256
+ view = copy.copy(self)
257
+ view._write = False
258
+ return view
259
+
260
+ # --- the Store protocol ---------------------------------------------------
261
+
262
+ def size(self, name: str) -> int:
263
+ return self.stat(name)[0]
264
+
265
+ def stat(self, name: str) -> tuple[int, str | None]:
266
+ entry = self._entry(name)
267
+ return _stat(self.store, name) if entry is None else (entry.size, entry.version)
268
+
269
+ def offers(self, name: str, method: str) -> bool:
270
+ entry = self._entry(name)
271
+ if entry is None:
272
+ return Blob(self.store, name).can(method)
273
+ if method in ("map", "fetch_into"):
274
+ return entry.complete
275
+ return method == "fetch_tail"
276
+
277
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
278
+ entry = self._entry(name)
279
+ if entry is None:
280
+ return self.store.fetch(name, start, stop)
281
+ stop = min(stop, entry.size)
282
+ if stop <= start:
283
+ return b""
284
+ if entry.covers(start, stop):
285
+ return entry.read(start, stop)
286
+ return entry.fill(start, stop, lambda a, b: self.store.fetch(name, a, b), write=self._write)
287
+
288
+ def fetch_into(self, name: str, start: int, out: memoryview) -> None:
289
+ entry = self._entry(name)
290
+ if entry is not None and entry.covers(start, start + out.nbytes):
291
+ entry.read_into(start, out)
292
+ elif entry is None and Blob(self.store, name).can("fetch_into"):
293
+ getattr(self.store, "fetch_into")(name, start, out) # noqa: B009
294
+ else:
295
+ data = np.frombuffer(self.fetch(name, start, start + out.nbytes), np.uint8)
296
+ if data.size != out.nbytes:
297
+ raise EOFError(f"{name}: wanted {out.nbytes} bytes at {start}, got {data.size}")
298
+ np.frombuffer(out.cast("B"), np.uint8)[...] = data
299
+
300
+ def fetch_tail(self, name: str, length: int) -> tuple[Buffer, int]:
301
+ entry = self._entry(name)
302
+ if entry is None:
303
+ return Blob(self.store, name).tail(length)
304
+ return self.fetch(name, max(0, entry.size - length), entry.size), entry.size
305
+
306
+ def _remote_bytes(self, name: str, start: int, stop: int) -> int:
307
+ inner = getattr(self.store, "_remote_bytes", None)
308
+ if inner is None:
309
+ return 0
310
+ # Use the ranges we already know about, with no I/O to make an estimate.
311
+ with self._lock:
312
+ entry = self._entries.get(name)
313
+ if entry is not None:
314
+ with entry.lock:
315
+ if not entry.replaced:
316
+ return sum(inner(name, a, b) for a, b in entry.readable.gaps(start, min(stop, entry.size)))
317
+ return inner(name, start, stop)
318
+
319
+ def map(self, name: str) -> mmap.mmap:
320
+ entry = self._entry(name)
321
+ if entry is None:
322
+ return getattr(self.store, "map")(name) # noqa: B009
323
+ if not entry.complete:
324
+ raise ValueError(f"{name} is not cached in full (did it change while loading?)")
325
+ return mmap.mmap(entry.fd, 0, access=mmap.ACCESS_COPY)
326
+
327
+ def flush(self) -> None:
328
+ with self._lock:
329
+ entries = [e for e in self._entries.values() if e is not None]
330
+ for entry in entries:
331
+ entry.flush()
332
+
333
+ # --- entries --------------------------------------------------------------
334
+
335
+ def _entry(self, name: str) -> "_Entry | None":
336
+ """The file's local copy, opened (and with `revalidate`, checked) on first access."""
337
+ with self._lock:
338
+ if self._known(name):
339
+ return self._entries[name]
340
+ opening = self._opening.setdefault(name, threading.Lock())
341
+ with opening: # one check per file at a time, not one per reading thread
342
+ with self._lock:
343
+ if self._known(name):
344
+ return self._entries[name]
345
+ entry = self._open(name)
346
+ with self._lock:
347
+ self._entries[name] = entry
348
+ return entry
349
+
350
+ def _known(self, name: str) -> bool:
351
+ """Whether `name` was opened already, and its copy still stands (not evicted or replaced elsewhere)."""
352
+ if name not in self._entries:
353
+ return False
354
+ entry = self._entries[name]
355
+ return entry is None or not entry.replaced
356
+
357
+ def _forget(self, name: str | None = None) -> None:
358
+ with self._lock:
359
+ if name is None:
360
+ self._entries.clear()
361
+ else:
362
+ self._entries.pop(name, None)
363
+
364
+ def _adopt(self, name: str, path: Path, *, link: bool) -> Path:
365
+ size, version = _stat(self.store, name)
366
+ if version is None and self.cache.revalidate:
367
+ raise ValueError(f"{self.store!r} reports no version for {name}, so a revalidating Cache cannot keep it")
368
+ if path.stat().st_size != size:
369
+ raise ValueError(f"{path} is {path.stat().st_size} bytes, but {self.namespace}/{name} is {size}")
370
+ folder = self.cache.root / _LAYOUT / _place(self.namespace, name)
371
+ _Entry.adopt(self.cache, self.namespace, name, folder, size, version, path, link=link)
372
+ self._forget(name) # opened afresh next time
373
+ return folder
374
+
375
+ def _open(self, name: str) -> "_Entry | None":
376
+ cache = self.cache
377
+ folder = cache.root / _LAYOUT / _place(self.namespace, name)
378
+ if not cache.revalidate:
379
+ trusted = _Entry.existing(cache, self.namespace, name, folder)
380
+ if trusted is not None:
381
+ return trusted
382
+ try:
383
+ size, version = _stat(self.store, name)
384
+ except Exception:
385
+ # A URL may allow range reads but deny the metadata request needed to cache them.
386
+ return None
387
+ if version is None and cache.revalidate:
388
+ if not self._warned:
389
+ self._warned = True
390
+ warnings.warn(
391
+ f"tensorferry: {self.store!r} reports no file versions, so its files are "
392
+ "not cached by a revalidating Cache",
393
+ RuntimeWarning,
394
+ stacklevel=4,
395
+ )
396
+ return None
397
+ if size == 0 or (cache.max_bytes is not None and size > cache.max_bytes):
398
+ return None
399
+ try:
400
+ return _Entry.create(cache, self.namespace, name, folder, size, version)
401
+ except OSError as exc:
402
+ warnings.warn(f"tensorferry: not caching {name}: {exc}", RuntimeWarning, stacklevel=4)
403
+ return None
404
+
405
+
406
+ class _Pinned:
407
+ """A cached file read through its entry's descriptor, so evicting it mid-load is harmless."""
408
+
409
+ def __init__(self, entry: "_Entry") -> None:
410
+ self.entry = entry
411
+
412
+ def __repr__(self) -> str:
413
+ return f"cached arrays {self.entry.folder.name}"
414
+
415
+ def size(self, name: str) -> int:
416
+ return self.entry.size
417
+
418
+ def fetch(self, name: str, start: int, stop: int) -> Buffer:
419
+ return self.entry.read(start, min(stop, self.entry.size))
420
+
421
+ def fetch_into(self, name: str, start: int, out: memoryview) -> None:
422
+ self.entry.read_into(start, out)
423
+
424
+ def map(self, name: str) -> mmap.mmap:
425
+ return mmap.mmap(self.entry.fd, 0, access=mmap.ACCESS_COPY)
426
+
427
+
428
+ # --- the array layer -----------------------------------------------------------
429
+
430
+
431
+ class _Sink:
432
+ """Writes each array a plan's cached file is missing, as the loader finishes it."""
433
+
434
+ def __init__(self, entry: "_Entry", starts: dict[int, int], claimed: bool) -> None:
435
+ self.entry = entry
436
+ self.starts = starts # id(fill) -> where its bytes go
437
+ self.claimed = claimed
438
+
439
+ def __call__(self, fill: Fill, buffer: np.ndarray) -> None:
440
+ start = self.starts.get(id(fill))
441
+ if start is not None:
442
+ self.entry.write(start, buffer.reshape(-1).view(np.uint8))
443
+
444
+ def close(self) -> None:
445
+ if self.claimed:
446
+ self.claimed = False
447
+ self.entry._release()
448
+
449
+
450
+ def _derive(cache: Cache, plan: Plan, cancel: threading.Event | None) -> tuple[Plan, _Sink | None]:
451
+ candidates = [fill for fill in plan.fills if _derivable(fill)]
452
+ if not candidates:
453
+ return plan, None
454
+ blobs: dict[tuple[int, str], Blob] = {}
455
+ for fill in candidates:
456
+ for part in fill.parts:
457
+ blob = _blob(part)
458
+ blobs.setdefault((id(blob.store), blob.name), blob)
459
+ with DaemonPool(min(8, len(blobs))) as pool:
460
+ found = pool.map(functools.partial(_identify, cache), list(blobs.values()), cancel=cancel)
461
+ ids = dict(zip(blobs, found, strict=True))
462
+ fills = [f for f in candidates if all(ids[_blob_key(p)] is not None for p in f.parts)]
463
+ names = [f.name for f in fills]
464
+ if not fills or len(set(names)) < len(names) or any(_reserved(n) for n in names):
465
+ return plan, None
466
+ described = [_describe(fill, ids) for fill in fills]
467
+ key = hashlib.sha256(json.dumps([_FORMAT, described]).encode()).hexdigest()
468
+ head, spans, size = _layout(fills, key)
469
+ # Beside the sources: in the deepest folder that holds all of them.
470
+ files = [_place(url, name).parent for url, name, _ in (i for i in ids.values() if i is not None)]
471
+ folder = cache.root / _LAYOUT / os.path.commonpath(files) / f"{_ARRAYS_PREFIX}{key[:16]}"
472
+ if cache.max_bytes is not None and size > cache.max_bytes:
473
+ return plan, None
474
+ try:
475
+ entry = _Entry.create(cache, _ARRAYS, key, folder, size, key)
476
+ except OSError as exc:
477
+ warnings.warn(f"tensorferry: not caching arrays: {exc}", RuntimeWarning, stacklevel=3)
478
+ return plan, None
479
+ if not entry.covers(0, len(head)):
480
+ entry.write(0, head)
481
+ # Another process making these arrays: wait for them, rather than read their sources too.
482
+ claimed = entry._await(0, size, cancel=cancel)
483
+ span_of = {id(fill): span for fill, span in zip(fills, spans, strict=True)}
484
+ pinned = Blob(_Pinned(entry), _data(folder).name)
485
+ out: list[Fill] = []
486
+ starts: dict[int, int] = {}
487
+ for fill in plan.fills:
488
+ span = span_of.get(id(fill))
489
+ if span is None:
490
+ out.append(fill)
491
+ elif entry.covers(*span):
492
+ target = fill.target
493
+ tensor = Tensor(fill.name, target.shape, target.dtype, pinned, *span)
494
+ out.append(dataclasses.replace(fill, parts=(Part(fill.name, (), tensor),)))
495
+ else:
496
+ parts = tuple(dataclasses.replace(p, tensor=_past_cache(p.tensor)) for p in fill.parts)
497
+ missing = dataclasses.replace(fill, parts=parts)
498
+ starts[id(missing)] = span[0]
499
+ out.append(missing)
500
+ rewritten = Plan(tuple(out), plan.index)
501
+ if not starts:
502
+ if claimed:
503
+ entry._release()
504
+ return rewritten, None
505
+ return rewritten, _Sink(entry, starts, claimed)
506
+
507
+
508
+ def _derivable(fill: Fill) -> bool:
509
+ if not fill.parts or fill.target.dtype not in _CODES:
510
+ return False
511
+ changed = False
512
+ for part in fill.parts:
513
+ t = part.tensor
514
+ if t is None or t.blob is None: # in memory already
515
+ return False
516
+ changed |= t.dtype != fill.target.dtype or t.codec != "raw" or t.fortran
517
+ return changed
518
+
519
+
520
+ def _blob(part: Part) -> Blob:
521
+ assert part.tensor is not None
522
+ assert part.tensor.blob is not None
523
+ return part.tensor.blob
524
+
525
+
526
+ def _blob_key(part: Part) -> tuple[int, str]:
527
+ blob = _blob(part)
528
+ return id(blob.store), blob.name
529
+
530
+
531
+ def _identify(cache: Cache, blob: Blob) -> list[Any] | None:
532
+ url = getattr(blob.store, "url", None)
533
+ if not url:
534
+ return None
535
+ try:
536
+ version = _stat(blob.store, blob.name)[1]
537
+ except Exception: # the store cannot be reached: the arrays are just not cached
538
+ return None
539
+ if version is None and cache.revalidate:
540
+ return None
541
+ return [url, blob.name, version]
542
+
543
+
544
+ def _describe(fill: Fill, ids: dict[tuple[int, str], list[Any] | None]) -> list[Any]:
545
+ target = fill.target
546
+ parts = []
547
+ for part in fill.parts:
548
+ t = part.tensor
549
+ assert t is not None
550
+ parts.append(
551
+ [
552
+ ids[_blob_key(part)],
553
+ t.key,
554
+ list(t.shape),
555
+ _dtype_id(t.dtype),
556
+ t.start,
557
+ t.stop,
558
+ t.codec,
559
+ t.skip,
560
+ t.fortran,
561
+ t.crc32,
562
+ repr(part.at),
563
+ ]
564
+ )
565
+ return [fill.name, list(target.shape), _dtype_id(target.dtype), parts]
566
+
567
+
568
+ def _dtype_id(dtype: np.dtype) -> str:
569
+ # ml_dtypes' types share `str`s ("<V2" is bfloat16 and more), so the name too.
570
+ return f"{dtype.name}{dtype.str}"
571
+
572
+
573
+ def _reserved(name: str) -> bool:
574
+ return name == "__metadata__" or name.startswith("__pad.")
575
+
576
+
577
+ def _layout(fills: list[Fill], key: str) -> tuple[bytes, list[tuple[int, int]], int]:
578
+ """A safetensors file holding `fills`, each 64-byte aligned: its header, spans and size."""
579
+ header: dict[str, Any] = {"__metadata__": {"format": _FORMAT, "key": key}}
580
+ offsets, at = [], 0
581
+ for fill in fills:
582
+ if pad := -at % _ALIGN:
583
+ header[f"__pad.{len(header)}"] = {
584
+ "dtype": "U8",
585
+ "shape": [pad],
586
+ "data_offsets": [at, at + pad],
587
+ }
588
+ at += pad
589
+ header[fill.name] = {
590
+ "dtype": _CODES[fill.target.dtype],
591
+ "shape": list(fill.target.shape),
592
+ "data_offsets": [at, at + fill.nbytes],
593
+ }
594
+ offsets.append(at)
595
+ at += fill.nbytes
596
+ text = json.dumps(header).encode()
597
+ text += b" " * (-(8 + len(text)) % _ALIGN)
598
+ head = len(text).to_bytes(8, "little") + text
599
+ base = len(head)
600
+ spans = [(base + o, base + o + f.nbytes) for o, f in zip(offsets, fills, strict=True)]
601
+ return head, spans, base + at
602
+
603
+
604
+ def _past_cache(tensor: Tensor | None) -> Tensor | None:
605
+ """`tensor`, read without adding its bytes to the source layer."""
606
+ if tensor is None or tensor.blob is None or not isinstance(tensor.blob.store, CachedStore):
607
+ return tensor
608
+ return dataclasses.replace(tensor, blob=Blob(tensor.blob.store.readonly, tensor.blob.name))
609
+
610
+
611
+ class _Entry:
612
+ """One file's local copy: its data, which of its ranges are there, and who is filling it."""
613
+
614
+ def __init__(
615
+ self,
616
+ cache: Cache,
617
+ namespace: str,
618
+ name: str,
619
+ folder: Path,
620
+ size: int,
621
+ version: str | None,
622
+ fd: int,
623
+ generation: str,
624
+ ranges: Iterable[Iterable[int]],
625
+ ) -> None:
626
+ self.cache = cache
627
+ self.namespace = namespace
628
+ self.name = name
629
+ self.folder = folder
630
+ self.size = size
631
+ self.version = version
632
+ self.fd = fd
633
+ self.generation = generation
634
+ self.readable = _Ranges(ranges)
635
+ self.lock = threading.Lock()
636
+ self.fill_fd = os.open(folder / "fill.lock", os.O_RDWR | os.O_CREAT, 0o644)
637
+ # Closed once nothing uses the entry, since a read or a mapping may outlive its
638
+ # replacement -- but left open at exit, for the final flush to use.
639
+ weakref.finalize(self, _close, fd, self.fill_fd).atexit = False
640
+ self.filling = 0
641
+ self.fill_held = False
642
+ self.last_fill = 0.0
643
+ self.dirty = False
644
+ self.syncing = False
645
+ self.flushing = threading.Lock()
646
+ self.broken = False # nothing more is written to this copy
647
+ self.replaced = False # ...because another process evicted or replaced it
648
+ self.impatient = False
649
+ self.progress = time.monotonic()
650
+ self.refreshed = 0.0
651
+ _LIVE.add(self)
652
+
653
+ @classmethod
654
+ def _reopen(
655
+ cls, cache: Cache, namespace: str, name: str, folder: Path, version: tuple[int, str | None] | None = None
656
+ ) -> "_Entry | None":
657
+ """The copy of this very file on disk -- of this `(size, version)`, if given -- or None."""
658
+ state = _read_state(folder)
659
+ if (
660
+ not _owned_by(state, namespace, name)
661
+ or "generation" not in state
662
+ or version not in (None, (state["size"], state["version"]))
663
+ ):
664
+ return None
665
+ fd = _open_data(folder, state)
666
+ if fd is None:
667
+ return None
668
+ return cls(
669
+ cache, namespace, name, folder, state["size"], state["version"], fd, state["generation"], state["ranges"]
670
+ )
671
+
672
+ @classmethod
673
+ def existing(cls, cache: Cache, namespace: str, name: str, folder: Path) -> "_Entry | None":
674
+ """The copy of this very file on disk, whatever its version, or None."""
675
+ try:
676
+ with _FileLock(folder):
677
+ return cls._reopen(cache, namespace, name, folder)
678
+ except OSError:
679
+ return None
680
+
681
+ @classmethod
682
+ def create(cls, cache: Cache, namespace: str, name: str, folder: Path, size: int, version: str | None) -> "_Entry":
683
+ """The copy of this version: the one on disk, or else a new, empty one."""
684
+ folder.mkdir(parents=True, exist_ok=True)
685
+ with _FileLock(folder):
686
+ if entry := cls._reopen(cache, namespace, name, folder, (size, version)):
687
+ entry.touch()
688
+ return entry
689
+ # Absent, stale or damaged: start afresh. A process still using the
690
+ # old copy keeps its own descriptor, and notices when it next publishes.
691
+ _reset(cache, folder, size)
692
+ fd = os.open(_data(folder), os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o644)
693
+ generation = uuid.uuid4().hex
694
+ try:
695
+ os.ftruncate(fd, size) # sparse: disk is used as ranges arrive
696
+ _write_state(folder, _state(namespace, name, size, version, generation, []))
697
+ except BaseException:
698
+ os.close(fd)
699
+ raise
700
+ return cls(cache, namespace, name, folder, size, version, fd, generation, [])
701
+
702
+ @staticmethod
703
+ def adopt(
704
+ cache: Cache, namespace: str, name: str, folder: Path, size: int, version: str | None, path: Path, *, link: bool
705
+ ) -> None:
706
+ """Make `path` the complete copy in `folder`: hard-linked where it can be, else copied."""
707
+ folder.mkdir(parents=True, exist_ok=True)
708
+ with _FileLock(folder):
709
+ _reset(cache, folder, size)
710
+ data = _data(folder)
711
+ try:
712
+ if link:
713
+ os.link(path, data)
714
+ except OSError: # across file systems, say
715
+ link = False
716
+ if not link:
717
+ shutil.copyfile(path, data)
718
+ with data.open("rb+") as handle:
719
+ os.fsync(handle.fileno()) # a range counts only once it is on disk
720
+ _write_state(folder, _state(namespace, name, size, version, uuid.uuid4().hex, [[0, size]] if size else []))
721
+
722
+ @property
723
+ def complete(self) -> bool:
724
+ return self.covers(0, self.size)
725
+
726
+ def covers(self, start: int, stop: int) -> bool:
727
+ with self.lock:
728
+ return self.readable.covers(start, stop)
729
+
730
+ def read(self, start: int, stop: int) -> np.ndarray:
731
+ out = np.empty(stop - start, np.uint8)
732
+ self.read_into(start, memoryview(out))
733
+ return out
734
+
735
+ def read_into(self, start: int, out: memoryview) -> None:
736
+ out = out.cast("B")
737
+ done = 0
738
+ while done < len(out):
739
+ n = os.preadv(self.fd, [out[done:]], start + done)
740
+ if n == 0:
741
+ raise EOFError(f"{_data(self.folder)}: ends before {start + done}")
742
+ done += n
743
+
744
+ def touch(self) -> None:
745
+ """Mark the copy used now, for eviction's sake."""
746
+ with contextlib.suppress(OSError):
747
+ os.utime(self.folder / _STATE)
748
+
749
+ # --- filling --------------------------------------------------------------
750
+
751
+ def fill(self, start: int, stop: int, fetch: Callable[[int, int], Buffer], *, write: bool = True) -> Buffer:
752
+ claimed = self._await(start, stop) if write else False
753
+ try:
754
+ with self.lock:
755
+ gaps = self.readable.gaps(start, stop)
756
+ if gaps == [(start, stop)]: # nothing here yet: no need to splice
757
+ data = _exact(fetch(start, stop), start, stop, self.name)
758
+ if write:
759
+ self.write(start, data)
760
+ return data
761
+ out = np.empty(stop - start, np.uint8)
762
+ at = start
763
+ for gap_start, gap_stop in gaps:
764
+ if at < gap_start:
765
+ self.read_into(at, memoryview(out[at - start : gap_start - start]))
766
+ data = _exact(fetch(gap_start, gap_stop), gap_start, gap_stop, self.name)
767
+ out[gap_start - start : gap_stop - start] = np.frombuffer(data, np.uint8)
768
+ if write:
769
+ self.write(gap_start, data)
770
+ at = gap_stop
771
+ if at < stop:
772
+ self.read_into(at, memoryview(out[at - start :]))
773
+ return out
774
+ finally:
775
+ if claimed:
776
+ self._release()
777
+
778
+ def _await(self, start: int, stop: int, *, cancel: threading.Event | None = None) -> bool:
779
+ """Claim the download, or wait while another process has it; whether this one claimed it."""
780
+ since = time.monotonic()
781
+ while not self.impatient:
782
+ check_cancel(cancel)
783
+ if self._claim():
784
+ return True
785
+ self._refresh()
786
+ if self.covers(start, stop):
787
+ return False
788
+ if time.monotonic() - max(since, self.progress) > self.cache.patience:
789
+ self.impatient = True
790
+ break
791
+ time.sleep(TICK)
792
+ return False
793
+
794
+ def _claim(self) -> bool:
795
+ with self.lock:
796
+ taken = not self.fill_held
797
+ if taken:
798
+ if not _flock(self.fill_fd, wait=False):
799
+ return False
800
+ self.fill_held = True
801
+ self.filling += 1
802
+ if taken: # whoever had it may have published since we last looked
803
+ self._refresh(force=True)
804
+ return True
805
+
806
+ def _release(self) -> None:
807
+ with self.lock:
808
+ self.filling -= 1
809
+ self.last_fill = time.monotonic()
810
+ idle = self.filling == 0
811
+ if idle: # kept a moment, so a load's next read does not have to compete for it
812
+ timer = threading.Timer(_FILL_LINGER, self._release_if_idle)
813
+ timer.daemon = True
814
+ timer.start()
815
+
816
+ def _release_if_idle(self) -> None:
817
+ with self.lock:
818
+ idle = time.monotonic() - self.last_fill >= _FILL_LINGER * 0.9
819
+ if not (self.fill_held and self.filling == 0 and idle):
820
+ return
821
+ # Published first: a process waiting for these ranges must not fetch them itself.
822
+ self.flush()
823
+ with self.lock:
824
+ if self.fill_held and self.filling == 0:
825
+ _unflock(self.fill_fd)
826
+ self.fill_held = False
827
+
828
+ def _refresh(self, *, force: bool = False) -> None:
829
+ now = time.monotonic()
830
+ if not force and now - self.refreshed < TICK:
831
+ return
832
+ self.refreshed = now
833
+ state = _read_state(self.folder)
834
+ if not self._ours(state):
835
+ self.impatient = True # replaced: no one is filling this copy
836
+ self.stop(None, replaced=True)
837
+ return
838
+ with self.lock:
839
+ before = self.readable.total
840
+ self.readable.update(_Ranges(state["ranges"]))
841
+ if self.readable.total > before:
842
+ self.progress = now
843
+
844
+ def write(self, start: int, data: Buffer) -> None:
845
+ if self.broken:
846
+ return
847
+ view = memoryview(data).cast("B")
848
+ try:
849
+ done = 0
850
+ while done < len(view):
851
+ done += os.pwrite(self.fd, view[done:], start + done)
852
+ except OSError as exc:
853
+ self.stop(f"writing it failed ({exc})")
854
+ return
855
+ with self.lock:
856
+ self.readable.add(start, start + len(view))
857
+ self.dirty = True
858
+ start_syncer = not self.syncing
859
+ self.syncing = True
860
+ if start_syncer:
861
+ threading.Thread(target=self._sync_loop, name="tensorferry-cache", daemon=True).start()
862
+
863
+ def _sync_loop(self) -> None:
864
+ while True:
865
+ time.sleep(_SYNC_INTERVAL)
866
+ self.flush()
867
+ with self.lock:
868
+ if not self.dirty or self.broken:
869
+ self.syncing = False
870
+ return
871
+
872
+ def flush(self) -> None:
873
+ with self.flushing:
874
+ with self.lock:
875
+ if not self.dirty or self.broken:
876
+ return
877
+ written = _Ranges()
878
+ written.update(self.readable) # taken before the flush, so all of it is flushed
879
+ self.dirty = False
880
+ try:
881
+ getattr(os, "fdatasync", os.fsync)(self.fd)
882
+ with _FileLock(self.folder):
883
+ state = _read_state(self.folder)
884
+ if not self._ours(state):
885
+ self.stop(None, replaced=True)
886
+ return
887
+ merged = _Ranges(state["ranges"])
888
+ merged.update(written)
889
+ state["ranges"] = merged.spans()
890
+ _write_state(self.folder, state)
891
+ except OSError as exc:
892
+ self.stop(f"recording it failed ({exc})")
893
+ return
894
+ with self.lock:
895
+ self.readable.update(merged)
896
+
897
+ def _ours(self, state: dict[str, Any] | None) -> TypeGuard[dict[str, Any]]:
898
+ return (
899
+ _owned_by(state, self.namespace, self.name)
900
+ and state.get("generation") == self.generation
901
+ and (state.get("size"), state.get("version")) == (self.size, self.version)
902
+ )
903
+
904
+ def stop(self, reason: str | None, *, replaced: bool = False) -> None:
905
+ """Stop writing this copy: what it holds stays readable, the rest comes from the store."""
906
+ with self.lock:
907
+ self.replaced |= replaced
908
+ if self.broken:
909
+ return
910
+ self.broken = True
911
+ if reason is not None:
912
+ warnings.warn(f"tensorferry: not caching {self.name}: {reason}", RuntimeWarning, stacklevel=3)
913
+
914
+
915
+ class _Ranges:
916
+ """Disjoint, sorted, half-open byte ranges."""
917
+
918
+ __slots__ = ("starts", "stops")
919
+
920
+ def __init__(self, spans: Iterable[Iterable[int]] = ()) -> None:
921
+ self.starts: list[int] = []
922
+ self.stops: list[int] = []
923
+ for start, stop in spans:
924
+ self.add(start, stop)
925
+
926
+ def add(self, start: int, stop: int) -> None:
927
+ if stop <= start:
928
+ return
929
+ # Every range that overlaps or touches [start, stop) merges into it.
930
+ lo = bisect.bisect_left(self.stops, start)
931
+ hi = bisect.bisect_right(self.starts, stop)
932
+ if lo < hi:
933
+ start = min(start, self.starts[lo])
934
+ stop = max(stop, self.stops[hi - 1])
935
+ self.starts[lo:hi] = [start]
936
+ self.stops[lo:hi] = [stop]
937
+
938
+ def update(self, other: "_Ranges") -> None:
939
+ for start, stop in zip(other.starts, other.stops, strict=True):
940
+ self.add(start, stop)
941
+
942
+ def gaps(self, start: int, stop: int) -> list[tuple[int, int]]:
943
+ out, at = [], start
944
+ i = bisect.bisect_right(self.stops, start) # the first range ending after `start`
945
+ while at < stop and i < len(self.starts) and self.starts[i] < stop:
946
+ if self.starts[i] > at:
947
+ out.append((at, self.starts[i]))
948
+ at = max(at, self.stops[i])
949
+ i += 1
950
+ if at < stop:
951
+ out.append((at, stop))
952
+ return out
953
+
954
+ def covers(self, start: int, stop: int) -> bool:
955
+ if stop <= start:
956
+ return True
957
+ i = bisect.bisect_right(self.starts, start) - 1
958
+ return i >= 0 and self.stops[i] >= stop
959
+
960
+ @property
961
+ def total(self) -> int:
962
+ return sum(stop - start for start, stop in zip(self.starts, self.stops, strict=True))
963
+
964
+ def spans(self) -> list[list[int]]:
965
+ return [[start, stop] for start, stop in zip(self.starts, self.stops, strict=True)]
966
+
967
+
968
+ class _FileLock:
969
+ """An exclusive lock on a copy's folder, between processes and threads alike."""
970
+
971
+ def __init__(self, folder: Path, *, wait: bool = True) -> None:
972
+ self.path = folder / "lock"
973
+ self.wait = wait
974
+ self.fd = -1
975
+
976
+ def __enter__(self) -> "_FileLock":
977
+ self.fd = os.open(self.path, os.O_RDWR | os.O_CREAT, 0o644)
978
+ try:
979
+ if not _flock(self.fd, wait=self.wait):
980
+ raise BlockingIOError(f"{self.path} is locked")
981
+ except BaseException:
982
+ os.close(self.fd)
983
+ raise
984
+ return self
985
+
986
+ def __exit__(self, *_: object) -> None:
987
+ os.close(self.fd) # closing releases the lock
988
+
989
+
990
+ def _exact(data: Buffer, start: int, stop: int, name: str) -> Buffer:
991
+ n = memoryview(data).nbytes
992
+ if n != stop - start:
993
+ raise EOFError(f"{name}: wanted bytes [{start}, {stop}), got {n}: did the file change?")
994
+ return data
995
+
996
+
997
+ def _stat(store: Store, name: str) -> tuple[int, str | None]:
998
+ method = getattr(store, "stat", None)
999
+ if method is not None:
1000
+ size, version = method(name)
1001
+ return int(size), version
1002
+ return int(store.size(name)), None
1003
+
1004
+
1005
+ def _owned_by(state: dict[str, Any] | None, namespace: str, name: str) -> TypeGuard[dict[str, Any]]:
1006
+ return state is not None and (state.get("namespace"), state.get("name")) == (namespace, name)
1007
+
1008
+
1009
+ def _read_state(folder: Path) -> dict[str, Any] | None:
1010
+ try:
1011
+ return json.loads((folder / _STATE).read_text())
1012
+ except (OSError, ValueError):
1013
+ return None
1014
+
1015
+
1016
+ def _write_state(folder: Path, state: dict[str, Any]) -> None:
1017
+ temporary = folder / f"{_STATE}.{os.getpid()}.{threading.get_ident()}"
1018
+ temporary.write_text(json.dumps(state))
1019
+ temporary.replace(folder / _STATE)
1020
+
1021
+
1022
+ def _state(
1023
+ namespace: str, name: str, size: int, version: str | None, generation: str, ranges: list[list[int]]
1024
+ ) -> dict[str, Any]:
1025
+ return {
1026
+ "namespace": namespace,
1027
+ "name": name,
1028
+ "size": size,
1029
+ "version": version,
1030
+ "generation": generation,
1031
+ "ranges": ranges,
1032
+ }
1033
+
1034
+
1035
+ def _reset(cache: Cache, folder: Path, size: int) -> None:
1036
+ """Delete `folder`'s copy, and make room for one of `size` bytes. Call it holding the lock."""
1037
+ for path in (folder / _STATE, _data(folder)):
1038
+ path.unlink(missing_ok=True)
1039
+ cache._make_room(size, keep=folder)
1040
+
1041
+
1042
+ def _open_data(folder: Path, state: dict[str, Any]) -> int | None:
1043
+ """The data file `state` describes; None if it is missing or not that size."""
1044
+ complete = _Ranges(state["ranges"]).covers(0, state["size"])
1045
+ try:
1046
+ fd = os.open(_data(folder), os.O_RDONLY if complete else os.O_RDWR)
1047
+ except FileNotFoundError:
1048
+ return None
1049
+ except PermissionError: # a read-only file, say an adopted one: fine while nothing is missing
1050
+ fd = os.open(_data(folder), os.O_RDONLY)
1051
+ if os.fstat(fd).st_size != state.get("size"):
1052
+ os.close(fd)
1053
+ return None
1054
+ return fd
1055
+
1056
+
1057
+ def _evict(folder: Path) -> bool:
1058
+ """Delete one cached copy, unless another process holds its lock right now."""
1059
+ try:
1060
+ with _FileLock(folder, wait=False):
1061
+ for path in (folder / _STATE, _data(folder)):
1062
+ path.unlink(missing_ok=True)
1063
+ except OSError: # locked by another process (BlockingIOError), or gone
1064
+ return False
1065
+ return True
1066
+
1067
+
1068
+ def _flock(fd: int, *, wait: bool = True) -> bool:
1069
+ """Lock `fd` exclusively; False if another holds it and `wait` is off."""
1070
+ import fcntl # POSIX only, as Cache checks
1071
+
1072
+ try:
1073
+ fcntl.flock(fd, fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB))
1074
+ except BlockingIOError:
1075
+ return False
1076
+ return True
1077
+
1078
+
1079
+ def _unflock(fd: int) -> None:
1080
+ import fcntl
1081
+
1082
+ fcntl.flock(fd, fcntl.LOCK_UN)
1083
+
1084
+
1085
+ def _close(*fds: int) -> None:
1086
+ for fd in fds:
1087
+ with contextlib.suppress(OSError):
1088
+ os.close(fd)
1089
+
1090
+
1091
+ # Every open copy, so that what was written is flushed and recorded at exit.
1092
+ _LIVE: "weakref.WeakSet[_Entry]" = weakref.WeakSet()
1093
+
1094
+
1095
+ @atexit.register
1096
+ def _flush_all() -> None:
1097
+ for entry in list(_LIVE):
1098
+ with contextlib.suppress(Exception): # nothing to report to at exit
1099
+ entry.flush()