exca 0.6.0__tar.gz → 0.6.2__tar.gz
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.
- {exca-0.6.0 → exca-0.6.2}/PKG-INFO +2 -2
- {exca-0.6.0 → exca-0.6.2}/README.md +1 -1
- {exca-0.6.0 → exca-0.6.2}/exca/base.py +2 -3
- exca-0.6.2/exca/cachedict/contiguous.py +187 -0
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/core.py +15 -15
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/dumpcontext.py +23 -7
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/handlers.py +25 -11
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/inflight.py +22 -14
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/registry.py +16 -4
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_cachedict.py +21 -6
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_contiguous.py +59 -11
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_dumpcontext.py +4 -0
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_registry.py +11 -8
- {exca-0.6.0 → exca-0.6.2}/exca/confdict.py +283 -88
- {exca-0.6.0 → exca-0.6.2}/exca/map.py +3 -2
- {exca-0.6.0 → exca-0.6.2}/exca/slurm.py +7 -16
- {exca-0.6.0 → exca-0.6.2}/exca/steps/backends.py +107 -18
- {exca-0.6.0 → exca-0.6.2}/exca/steps/base.py +54 -9
- {exca-0.6.0 → exca-0.6.2}/exca/steps/conftest.py +25 -4
- {exca-0.6.0 → exca-0.6.2}/exca/steps/helpers.py +12 -1
- {exca-0.6.0 → exca-0.6.2}/exca/steps/items.py +36 -23
- {exca-0.6.0 → exca-0.6.2}/exca/steps/patterns.py +5 -1
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_backends.py +85 -3
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_cache.py +22 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_helpers.py +3 -1
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_items.py +29 -9
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_patterns.py +7 -2
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_specs.py +14 -1
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_steps.py +51 -0
- {exca-0.6.0 → exca-0.6.2}/exca/task.py +5 -7
- {exca-0.6.0 → exca-0.6.2}/exca/test_confdict.py +148 -10
- {exca-0.6.0 → exca-0.6.2}/exca/test_map.py +1 -1
- {exca-0.6.0 → exca-0.6.2}/exca/test_utils.py +21 -1
- {exca-0.6.0 → exca-0.6.2}/exca/utils.py +10 -6
- {exca-0.6.0 → exca-0.6.2}/exca/workdir.py +21 -6
- {exca-0.6.0 → exca-0.6.2}/exca.egg-info/PKG-INFO +2 -2
- {exca-0.6.0 → exca-0.6.2}/pyproject.toml +1 -1
- exca-0.6.0/exca/cachedict/contiguous.py +0 -158
- {exca-0.6.0 → exca-0.6.2}/LICENSE +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/__init__.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/__init__.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_handlers.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/cachedict/test_inflight.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/helpers.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/logconf.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/py.typed +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/__init__.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/errors.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/identity.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/jobregistry.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_errors.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_perf.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/test_utils.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/steps/utils.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_base.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_compat.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_helpers.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_localmap.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_safeguard.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_submit.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_task.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca/test_workdir.py +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca.egg-info/SOURCES.txt +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca.egg-info/dependency_links.txt +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca.egg-info/requires.txt +0 -0
- {exca-0.6.0 → exca-0.6.2}/exca.egg-info/top_level.txt +0 -0
- {exca-0.6.0 → exca-0.6.2}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: exca
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.2
|
|
4
4
|
Summary: Execution and caching tool for python
|
|
5
5
|
Author: Meta FAIR
|
|
6
6
|
Project-URL: Source, https://github.com/facebookresearch/exca
|
|
@@ -40,7 +40,7 @@ Requires-Dist: sphinx-copybutton>=0.5.2; extra == "dev"
|
|
|
40
40
|
Requires-Dist: myst-parser>=3.0.1; extra == "dev"
|
|
41
41
|
Dynamic: license-file
|
|
42
42
|
|
|
43
|
-
#
|
|
43
|
+
<p align="center"><img src="https://raw.githubusercontent.com/facebookresearch/exca/main/docs/_static/exca-on-light.svg#gh-light-mode-only" alt="exca" height="90"><img src="https://raw.githubusercontent.com/facebookresearch/exca/main/docs/_static/exca-on-dark.svg#gh-dark-mode-only" alt="exca" height="90"></p>
|
|
44
44
|
|
|
45
45
|
Execute and cache seamlessly in python.
|
|
46
46
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#
|
|
1
|
+
<p align="center"><img src="https://raw.githubusercontent.com/facebookresearch/exca/main/docs/_static/exca-on-light.svg#gh-light-mode-only" alt="exca" height="90"><img src="https://raw.githubusercontent.com/facebookresearch/exca/main/docs/_static/exca-on-dark.svg#gh-dark-mode-only" alt="exca" height="90"></p>
|
|
2
2
|
|
|
3
3
|
Execute and cache seamlessly in python.
|
|
4
4
|
|
|
@@ -28,7 +28,7 @@ logger = logging.getLogger(__name__)
|
|
|
28
28
|
C = tp.TypeVar("C", bound=tp.Callable[..., tp.Any])
|
|
29
29
|
ExcludeCallable = tp.Callable[[tp.Any], tp.Iterable[str]]
|
|
30
30
|
Mapping = tp.MutableMapping[str, tp.Any] | tp.Iterable[tuple[str, tp.Any]]
|
|
31
|
-
#
|
|
31
|
+
# deprecated and ignored, only kept so that neuralset<=0.4 can still import it
|
|
32
32
|
DEFAULT_CHECK_SKIPS: list[tp.Callable[[str, tp.Any, tp.Any], bool]] = []
|
|
33
33
|
|
|
34
34
|
|
|
@@ -360,7 +360,7 @@ class BaseInfra(pydantic.BaseModel):
|
|
|
360
360
|
if len(args) > 1:
|
|
361
361
|
raise ValueError(f"Only one positional argument allowed, got {args}")
|
|
362
362
|
if kwargs:
|
|
363
|
-
msg = "Provide either args or kwargs, not both, got {args=} {kwargs=}"
|
|
363
|
+
msg = f"Provide either args or kwargs, not both, got {args=} {kwargs=}"
|
|
364
364
|
raise ValueError(msg)
|
|
365
365
|
kwargs = args[0]
|
|
366
366
|
cdict = self.config(exclude_defaults=True, uid=False)
|
|
@@ -452,7 +452,6 @@ class BaseInfraMethod:
|
|
|
452
452
|
if not self.exclude_from_cache_uid.startswith("method:"):
|
|
453
453
|
msg = "exclude_from_cache_uid should be a list/tuple/set, or a string starting with 'method:'"
|
|
454
454
|
raise TypeError(msg)
|
|
455
|
-
self.exclude_from_cache_uid = self.exclude_from_cache_uid
|
|
456
455
|
if not isinstance(self.exclude_from_cache_uid, str):
|
|
457
456
|
if not callable(self.exclude_from_cache_uid):
|
|
458
457
|
self.exclude_from_cache_uid = tuple(self.exclude_from_cache_uid)
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
# All rights reserved.
|
|
3
|
+
#
|
|
4
|
+
# This source code is licensed under the license found in the
|
|
5
|
+
# LICENSE file in the root directory of this source tree.
|
|
6
|
+
|
|
7
|
+
import collections
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
import typing as tp
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .dumpcontext import _get_store
|
|
16
|
+
|
|
17
|
+
_FILE_HANDLE_CACHE: threading.local = threading.local()
|
|
18
|
+
_SAFE_ATTRS = frozenset(
|
|
19
|
+
{"shape", "dtype", "ndim", "size", "strides", "itemsize", "nbytes"}
|
|
20
|
+
)
|
|
21
|
+
_VIEW_OPS = frozenset(
|
|
22
|
+
{"T", "reshape", "transpose", "swapaxes", "squeeze", "ravel", "view"}
|
|
23
|
+
)
|
|
24
|
+
_SKELETON = np.zeros(0, dtype=np.uint8)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _max_open_files() -> int:
|
|
28
|
+
env = os.environ.get("EXCA_CONTIGUOUS_MEMMAP_MAX_OPEN_FILES")
|
|
29
|
+
if env is not None:
|
|
30
|
+
return int(env)
|
|
31
|
+
try:
|
|
32
|
+
import resource
|
|
33
|
+
except ImportError: # Windows
|
|
34
|
+
return 256
|
|
35
|
+
soft = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
|
|
36
|
+
return 0 if soft == resource.RLIM_INFINITY else max(1, soft // 2)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _read(path: Path, offset: int, nbytes: int) -> np.ndarray:
|
|
40
|
+
"""Read *nbytes* at *offset* of *path*, keeping the file open in this thread's
|
|
41
|
+
least-recently-used cache (at most ``_max_open_files()`` files)."""
|
|
42
|
+
store = _get_store(_FILE_HANDLE_CACHE)
|
|
43
|
+
handles = store.setdefault("handles", collections.OrderedDict())
|
|
44
|
+
fh = handles.pop(path, None)
|
|
45
|
+
if fh is None:
|
|
46
|
+
limit = _max_open_files()
|
|
47
|
+
while 0 < limit <= len(handles):
|
|
48
|
+
handles.popitem(last=False)[1].close()
|
|
49
|
+
fh = path.open("rb", buffering=0) # noqa: SIM115
|
|
50
|
+
handles[path] = fh
|
|
51
|
+
buf = np.empty(nbytes, dtype=np.uint8)
|
|
52
|
+
fh.seek(offset)
|
|
53
|
+
n = 0
|
|
54
|
+
while n < nbytes: # short raw reads
|
|
55
|
+
read = fh.readinto(buf.data[n:])
|
|
56
|
+
if not read:
|
|
57
|
+
raise IOError(
|
|
58
|
+
f"ContiguousMemmap: short read on {path} "
|
|
59
|
+
f"(expected {nbytes} bytes at offset {offset}, got {n})"
|
|
60
|
+
)
|
|
61
|
+
n += read
|
|
62
|
+
return buf
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class ContiguousMemmap:
|
|
66
|
+
"""Lazy array over the bytes at *offset* of the file at *path*.
|
|
67
|
+
|
|
68
|
+
Nothing is read until ``np.asarray``, which reads into a regular array.
|
|
69
|
+
Unlike ``np.memmap``: reading does not grow RSS, and instances hold no
|
|
70
|
+
file descriptor nor mapping.
|
|
71
|
+
|
|
72
|
+
Usage::
|
|
73
|
+
|
|
74
|
+
x = proxy[10:20] # lazy: basic indexing returns a ContiguousMemmap
|
|
75
|
+
y = x.T # lazy: T, reshape, transpose, swapaxes, squeeze, ravel, view
|
|
76
|
+
np.asarray(y) # reads x's bytes once, returns np.ndarray
|
|
77
|
+
proxy[::2] # TypeError (strided): np.asarray(proxy)[::2]
|
|
78
|
+
proxy.mean() # AttributeError: np.asarray(proxy).mean()
|
|
79
|
+
|
|
80
|
+
Open files are cached per thread, at most
|
|
81
|
+
``EXCA_CONTIGUOUS_MEMMAP_MAX_OPEN_FILES`` (default: half the soft
|
|
82
|
+
``RLIMIT_NOFILE``; 0 = no limit).
|
|
83
|
+
|
|
84
|
+
Note — vs ``MemmapArray``, 10k files on Lustre, items kept in RAM, random
|
|
85
|
+
51 KB reads: same speed, RSS growth 0 vs 1.3 GB.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
__slots__ = ("_arr", "_path", "_offset")
|
|
89
|
+
|
|
90
|
+
def __init__(
|
|
91
|
+
self,
|
|
92
|
+
path: Path,
|
|
93
|
+
offset: int,
|
|
94
|
+
shape: tp.Sequence[int],
|
|
95
|
+
dtype: tp.Any,
|
|
96
|
+
strides: tp.Sequence[int] | None = None,
|
|
97
|
+
) -> None:
|
|
98
|
+
global _SKELETON
|
|
99
|
+
dtype = np.dtype(dtype)
|
|
100
|
+
nbytes = int(np.prod(shape)) * dtype.itemsize
|
|
101
|
+
if _SKELETON.size < nbytes:
|
|
102
|
+
_SKELETON = np.zeros(max(nbytes, 2 * _SKELETON.size, 2**26), np.uint8)
|
|
103
|
+
# geometry only: a view on a shared zero buffer, never read
|
|
104
|
+
self._arr = np.ndarray(tuple(shape), dtype, buffer=_SKELETON, strides=strides)
|
|
105
|
+
self._path = path
|
|
106
|
+
self._offset = offset
|
|
107
|
+
|
|
108
|
+
def __reduce__(self) -> tuple[tp.Any, ...]:
|
|
109
|
+
arr = self._arr
|
|
110
|
+
return type(self), (self._path, self._offset, arr.shape, arr.dtype, arr.strides)
|
|
111
|
+
|
|
112
|
+
def _view(self, arr: np.ndarray) -> "ContiguousMemmap":
|
|
113
|
+
if arr.size and not np.may_share_memory(arr, self._arr):
|
|
114
|
+
raise TypeError(
|
|
115
|
+
"ContiguousMemmap operation would copy data "
|
|
116
|
+
"— use np.asarray(arr) to read data first."
|
|
117
|
+
)
|
|
118
|
+
out = ContiguousMemmap.__new__(ContiguousMemmap)
|
|
119
|
+
out._arr, out._path = arr, self._path
|
|
120
|
+
out._offset = self._offset + arr.ctypes.data - self._arr.ctypes.data
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
def __len__(self) -> int:
|
|
124
|
+
return len(self._arr)
|
|
125
|
+
|
|
126
|
+
def __repr__(self) -> str:
|
|
127
|
+
return f"ContiguousMemmap(shape={self._arr.shape}, dtype={self._arr.dtype})"
|
|
128
|
+
|
|
129
|
+
def __getitem__(self, key: tp.Any) -> tp.Any:
|
|
130
|
+
keys = key if isinstance(key, tuple) else (key,)
|
|
131
|
+
if any(isinstance(k, (list, np.ndarray)) for k in keys):
|
|
132
|
+
raise TypeError(
|
|
133
|
+
"ContiguousMemmap does not support fancy indexing "
|
|
134
|
+
"— use np.asarray(arr)[key] to read data first."
|
|
135
|
+
)
|
|
136
|
+
result = self._arr[key]
|
|
137
|
+
if not isinstance(result, np.ndarray): # scalar: read it from the file
|
|
138
|
+
return np.asarray(self._view(self._arr[(*keys, ...)]))[()]
|
|
139
|
+
if result.size == 0:
|
|
140
|
+
return np.empty(result.shape, dtype=result.dtype)
|
|
141
|
+
span = sum((n - 1) * abs(s) for n, s in zip(result.shape, result.strides))
|
|
142
|
+
if span + result.itemsize != result.nbytes or any(s < 0 for s in result.strides):
|
|
143
|
+
raise TypeError("Non-contiguous read — use np.asarray(arr)[key] instead.")
|
|
144
|
+
return self._view(result)
|
|
145
|
+
|
|
146
|
+
def __array__(
|
|
147
|
+
self, dtype: np.dtype[tp.Any] | None = None, copy: bool | None = None
|
|
148
|
+
) -> np.ndarray:
|
|
149
|
+
arr = self._arr
|
|
150
|
+
if arr.size == 0:
|
|
151
|
+
result = np.empty(arr.shape, dtype=arr.dtype)
|
|
152
|
+
else:
|
|
153
|
+
buf = _read(self._path, self._offset, arr.nbytes)
|
|
154
|
+
view = np.ndarray(arr.shape, arr.dtype, buffer=buf, strides=arr.strides)
|
|
155
|
+
result = np.asarray(view, order="C")
|
|
156
|
+
return result if dtype is None else result.astype(dtype)
|
|
157
|
+
|
|
158
|
+
def __array_ufunc__(
|
|
159
|
+
self,
|
|
160
|
+
ufunc: np.ufunc,
|
|
161
|
+
method: str,
|
|
162
|
+
*inputs: tp.Any,
|
|
163
|
+
**kwargs: tp.Any,
|
|
164
|
+
) -> tp.Any:
|
|
165
|
+
raise TypeError(
|
|
166
|
+
f"ContiguousMemmap does not support ufunc '{ufunc.__name__}' directly "
|
|
167
|
+
f"— use np.asarray(arr) to read data first."
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def __getattr__(self, name: str) -> tp.Any:
|
|
171
|
+
if name in _SAFE_ATTRS:
|
|
172
|
+
return getattr(self._arr, name)
|
|
173
|
+
if name in _VIEW_OPS:
|
|
174
|
+
val = getattr(self._arr, name)
|
|
175
|
+
if callable(val):
|
|
176
|
+
|
|
177
|
+
def _wrap(*a: tp.Any, **kw: tp.Any) -> "ContiguousMemmap":
|
|
178
|
+
return self._view(val(*a, **kw))
|
|
179
|
+
|
|
180
|
+
return _wrap
|
|
181
|
+
return self._view(val)
|
|
182
|
+
if hasattr(np.ndarray, name):
|
|
183
|
+
raise AttributeError(
|
|
184
|
+
f"ContiguousMemmap does not support '.{name}' directly "
|
|
185
|
+
f"— use np.asarray(arr).{name} to read data first."
|
|
186
|
+
)
|
|
187
|
+
raise AttributeError(f"'ContiguousMemmap' has no attribute {name!r}")
|
|
@@ -57,7 +57,7 @@ class DumpInfo:
|
|
|
57
57
|
default=(), repr=False, compare=False
|
|
58
58
|
)
|
|
59
59
|
|
|
60
|
-
def delete_info(self, *, ignore_errors: bool = False) -> None:
|
|
60
|
+
def delete_info(self, ctx: DumpContext, *, ignore_errors: bool = False) -> None:
|
|
61
61
|
"""Blank this entry so ``JsonlReader`` treats it as deleted.
|
|
62
62
|
|
|
63
63
|
When *ignore_errors* is True, silently ignores missing/locked files."""
|
|
@@ -65,12 +65,12 @@ class DumpInfo:
|
|
|
65
65
|
if start == end:
|
|
66
66
|
return
|
|
67
67
|
try:
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
68
|
+
f = ctx.index_file(self.jsonl)
|
|
69
|
+
f.seek(start)
|
|
70
|
+
f.write(b" ") # atomic mark — survives partial bulk write
|
|
71
|
+
f.flush()
|
|
72
|
+
if end - start > 2:
|
|
73
|
+
f.write(b" " * (end - start - 2)) # blank out
|
|
74
74
|
except (FileNotFoundError, OSError):
|
|
75
75
|
if not ignore_errors:
|
|
76
76
|
raise
|
|
@@ -140,13 +140,12 @@ class CacheDict(tp.Generic[X]):
|
|
|
140
140
|
# json info file reading
|
|
141
141
|
self._folder_modified = -1.0
|
|
142
142
|
self._jsonl_readers: dict[str, JsonlReader] = {}
|
|
143
|
-
self._jsonl_reading_allowance = float("inf")
|
|
144
143
|
# DumpContext for this folder (load/delete; writes use per-thread _write_ctx)
|
|
145
144
|
self._dumper: DumpContext | None = None
|
|
146
145
|
self._recorded_jsonls: set[Path] = set() # one per writer, not per key
|
|
147
146
|
if self.folder is not None:
|
|
148
147
|
self._dumper = DumpContext(self.folder)
|
|
149
|
-
self._local = threading.local() # per-thread write context
|
|
148
|
+
self._local = threading.local() # per-thread write context and freeze
|
|
150
149
|
|
|
151
150
|
def __repr__(self) -> str:
|
|
152
151
|
name = self.__class__.__name__
|
|
@@ -210,7 +209,8 @@ class CacheDict(tp.Generic[X]):
|
|
|
210
209
|
if self.folder is None or not self.folder.exists():
|
|
211
210
|
return
|
|
212
211
|
readings = max((r.readings for r in self._jsonl_readers.values()), default=0)
|
|
213
|
-
|
|
212
|
+
allowance = getattr(self._local, "reading_allowance", float("inf"))
|
|
213
|
+
if not force and allowance <= readings:
|
|
214
214
|
return # bypass reloading info files
|
|
215
215
|
modified = self.folder.lstat().st_mtime
|
|
216
216
|
nothing_new = self._folder_modified == modified
|
|
@@ -289,7 +289,7 @@ class CacheDict(tp.Generic[X]):
|
|
|
289
289
|
if self._dumper is None:
|
|
290
290
|
raise RuntimeError("This should not happen")
|
|
291
291
|
if key not in self._key_info:
|
|
292
|
-
|
|
292
|
+
self._read_info_files()
|
|
293
293
|
dinfo = self._key_info[key]
|
|
294
294
|
if dinfo.jsonl not in self._recorded_jsonls: # index + payloads: one batch
|
|
295
295
|
if not self._recorded_jsonls: # record is per folder, stamps per index
|
|
@@ -351,7 +351,7 @@ class CacheDict(tp.Generic[X]):
|
|
|
351
351
|
if self.folder is not None and self._write_ctx is None:
|
|
352
352
|
raise RuntimeError("Cannot write outside of a write() context")
|
|
353
353
|
if self._folder_modified <= 0:
|
|
354
|
-
|
|
354
|
+
self._read_info_files()
|
|
355
355
|
if key in self._ram_data or key in self._key_info:
|
|
356
356
|
raise ValueError(f"Overwriting a key is currently not implemented ({key=})")
|
|
357
357
|
if self._keep_in_ram and self.folder is None:
|
|
@@ -388,7 +388,7 @@ class CacheDict(tp.Generic[X]):
|
|
|
388
388
|
self._ram_data.pop(key, None)
|
|
389
389
|
dinfo = self._key_info.pop(key)
|
|
390
390
|
for info in (dinfo, *dinfo._duplicates):
|
|
391
|
-
info.delete_info(ignore_errors=True)
|
|
391
|
+
info.delete_info(self._write_ctx, ignore_errors=True)
|
|
392
392
|
self._dumper.delete(info.content)
|
|
393
393
|
|
|
394
394
|
def __contains__(self, key: str) -> bool:
|
|
@@ -409,11 +409,11 @@ class CacheDict(tp.Generic[X]):
|
|
|
409
409
|
items, which could trigger thousands of file rereads
|
|
410
410
|
"""
|
|
411
411
|
readings = max((r.readings for r in self._jsonl_readers.values()), default=0)
|
|
412
|
-
self.
|
|
412
|
+
self._local.reading_allowance = readings + 1
|
|
413
413
|
try:
|
|
414
414
|
yield
|
|
415
415
|
finally:
|
|
416
|
-
self.
|
|
416
|
+
self._local.reading_allowance = float("inf")
|
|
417
417
|
|
|
418
418
|
|
|
419
419
|
class JsonlReader:
|
|
@@ -31,15 +31,17 @@ import orjson
|
|
|
31
31
|
logger = logging.getLogger(__name__)
|
|
32
32
|
|
|
33
33
|
_UNSAFE_TABLE = {ord(char): "-" for char in "/\\\n\t "}
|
|
34
|
+
_NUM_CREATED_FILES = 0
|
|
34
35
|
|
|
35
36
|
|
|
36
37
|
def _get_store(tls: threading.local) -> dict[tp.Hashable, tp.Any]:
|
|
37
|
-
"""Return the per-thread dict from *tls*,
|
|
38
|
-
|
|
38
|
+
"""Return the per-thread dict from *tls*, reset after fork and whenever
|
|
39
|
+
this process creates a shared file."""
|
|
40
|
+
state = (os.getpid(), _NUM_CREATED_FILES)
|
|
39
41
|
d = tp.cast(dict[tp.Hashable, tp.Any], tls.__dict__)
|
|
40
|
-
if d.get("
|
|
42
|
+
if d.get("__state__") != state:
|
|
41
43
|
d.clear()
|
|
42
|
-
d["
|
|
44
|
+
d["__state__"] = state
|
|
43
45
|
return d
|
|
44
46
|
|
|
45
47
|
|
|
@@ -120,7 +122,8 @@ class DumpContext:
|
|
|
120
122
|
self._prefix = f"{socket.gethostname()}-{self._thread_id}"
|
|
121
123
|
self._stack: contextlib.ExitStack | None = None
|
|
122
124
|
self._files: dict[str, tp.IO[bytes]] = {}
|
|
123
|
-
self.
|
|
125
|
+
self._index_files: dict[Path, tp.IO[bytes]] = {} # opened "rb+" to blank
|
|
126
|
+
self._created_files: set[Path] = set()
|
|
124
127
|
self._dump_count: int = 0
|
|
125
128
|
# read-side cache (per-thread, fork-safe via _get_store)
|
|
126
129
|
self._resource_cache: threading.local = threading.local()
|
|
@@ -199,12 +202,14 @@ class DumpContext:
|
|
|
199
202
|
self._stack.__exit__(*exc)
|
|
200
203
|
finally:
|
|
201
204
|
self._files.clear()
|
|
205
|
+
self._index_files.clear()
|
|
202
206
|
self._created_files.clear()
|
|
203
207
|
|
|
204
208
|
def shared_file(self, suffix: str) -> tuple[tp.IO[bytes], str]:
|
|
205
209
|
"""Open a shared file for appending. Returns (handle, relative_name).
|
|
206
210
|
Content files go under DATA_DIR/; info files (-info.jsonl)
|
|
207
211
|
stay in the root folder. Reused across calls with the same suffix."""
|
|
212
|
+
global _NUM_CREATED_FILES
|
|
208
213
|
is_info = suffix == self.INFO_SUFFIX
|
|
209
214
|
if not is_info and not suffix.startswith("."):
|
|
210
215
|
msg = f"suffix must start with '.' to be reclaimable, got {suffix!r}"
|
|
@@ -219,11 +224,22 @@ class DumpContext:
|
|
|
219
224
|
path = self.folder / name
|
|
220
225
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
221
226
|
f = path.open("ab")
|
|
227
|
+
if f.tell() == 0:
|
|
228
|
+
_NUM_CREATED_FILES += 1
|
|
222
229
|
self._stack.enter_context(f)
|
|
223
230
|
self._files[name] = f
|
|
224
|
-
self._created_files.
|
|
231
|
+
self._created_files.add(path)
|
|
225
232
|
return self._files[name], name
|
|
226
233
|
|
|
234
|
+
def index_file(self, path: Path) -> tp.IO[bytes]:
|
|
235
|
+
"""Open an info file (any writer's) for blanking deleted entries.
|
|
236
|
+
Reused across calls with the same path."""
|
|
237
|
+
if self._stack is None:
|
|
238
|
+
raise RuntimeError("DumpContext must be used as a context manager for writes")
|
|
239
|
+
if path not in self._index_files:
|
|
240
|
+
self._index_files[path] = self._stack.enter_context(path.open("rb+"))
|
|
241
|
+
return self._index_files[path]
|
|
242
|
+
|
|
227
243
|
def key_path(self, suffix: str = "") -> str:
|
|
228
244
|
"""Create a unique path from ctx.key for one-file-per-entry handlers.
|
|
229
245
|
Returns the relative name (e.g. "data/key-hash.pkl"); use
|
|
@@ -245,7 +261,7 @@ class DumpContext:
|
|
|
245
261
|
# File written by a concurrent worker; handlers use
|
|
246
262
|
# temporary_save_path (atomic rename) so this is safe.
|
|
247
263
|
logger.debug("Concurrent write detected for %s, proceeding", basename)
|
|
248
|
-
self._created_files.
|
|
264
|
+
self._created_files.add(path)
|
|
249
265
|
return name
|
|
250
266
|
|
|
251
267
|
# -- Dispatch --
|
|
@@ -89,22 +89,36 @@ class MemmapArray:
|
|
|
89
89
|
|
|
90
90
|
@DumpContext.register
|
|
91
91
|
class ContiguousMemmapArray:
|
|
92
|
-
"""
|
|
93
|
-
data via file I/O instead of faulting memmap pages into RSS.
|
|
92
|
+
"""Load MemmapArray files as lazy ``ContiguousMemmap`` arrays.
|
|
94
93
|
|
|
95
|
-
|
|
96
|
-
memmap
|
|
97
|
-
|
|
98
|
-
|
|
94
|
+
Reads copy only the requested bytes into regular arrays, so memory stays
|
|
95
|
+
flat while items are kept (memmap pages stay resident as long as the item
|
|
96
|
+
lives).
|
|
97
|
+
|
|
98
|
+
Warnings
|
|
99
|
+
--------
|
|
100
|
+
Items are not ndarrays: methods, ufuncs, fancy and strided indexing need
|
|
101
|
+
``np.asarray(item)`` first.
|
|
102
|
+
|
|
103
|
+
See Also
|
|
104
|
+
--------
|
|
105
|
+
MemmapArray : same files, loaded as memmaps.
|
|
106
|
+
"""
|
|
99
107
|
|
|
100
108
|
@classmethod
|
|
101
109
|
def __dump_info__(cls, ctx: DumpContext, value: tp.Any) -> dict[str, tp.Any]:
|
|
102
110
|
return MemmapArray.__dump_info__(ctx, value)
|
|
103
111
|
|
|
104
112
|
@classmethod
|
|
105
|
-
def __load_from_info__(
|
|
106
|
-
|
|
107
|
-
|
|
113
|
+
def __load_from_info__(
|
|
114
|
+
cls,
|
|
115
|
+
ctx: DumpContext,
|
|
116
|
+
filename: str,
|
|
117
|
+
offset: int,
|
|
118
|
+
shape: tp.Sequence[int],
|
|
119
|
+
dtype: str,
|
|
120
|
+
) -> ContiguousMemmap:
|
|
121
|
+
return ContiguousMemmap((ctx.folder / filename).absolute(), offset, shape, dtype)
|
|
108
122
|
|
|
109
123
|
|
|
110
124
|
@DumpContext.register
|
|
@@ -386,7 +400,7 @@ class Auto:
|
|
|
386
400
|
else:
|
|
387
401
|
for v in val.values():
|
|
388
402
|
cls._delete_value(ctx, v)
|
|
389
|
-
elif isinstance(val, list):
|
|
403
|
+
elif isinstance(val, (list, tuple)):
|
|
390
404
|
for item in val:
|
|
391
405
|
cls._delete_value(ctx, item)
|
|
392
406
|
|
|
@@ -396,7 +410,7 @@ class Auto:
|
|
|
396
410
|
if "#type" in val:
|
|
397
411
|
return ctx.load(val)
|
|
398
412
|
return {k: cls._load_value(ctx, v) for k, v in val.items()}
|
|
399
|
-
if isinstance(val, list):
|
|
413
|
+
if isinstance(val, (list, tuple)):
|
|
400
414
|
return [cls._load_value(ctx, item) for item in val]
|
|
401
415
|
return val
|
|
402
416
|
|
|
@@ -125,6 +125,8 @@ class Slurm(Liveness):
|
|
|
125
125
|
if self.job is None:
|
|
126
126
|
return None
|
|
127
127
|
try:
|
|
128
|
+
if self.job.state == "UNKNOWN": # not in sacct (yet, or anymore)
|
|
129
|
+
return None
|
|
128
130
|
return not self.job.done()
|
|
129
131
|
except Exception:
|
|
130
132
|
return False
|
|
@@ -145,6 +147,17 @@ class Slurm(Liveness):
|
|
|
145
147
|
return f"{self.job_id.split('_')[0]} [slurm:{state}]"
|
|
146
148
|
|
|
147
149
|
|
|
150
|
+
def submitit_liveness(job: submitit.Job[tp.Any]) -> Liveness:
|
|
151
|
+
"""What runs the submitted submitit *job*."""
|
|
152
|
+
if isinstance(job, submitit.SlurmJob):
|
|
153
|
+
return Slurm(job_id=str(job.job_id), folder=str(job.paths.folder))
|
|
154
|
+
if isinstance(job, submitit.LocalJob): # job_id: the subprocess pid
|
|
155
|
+
return Pid(host=socket.gethostname(), pid=int(job.job_id))
|
|
156
|
+
here = Liveness.here() # debug job: runs in this process, like the claimer
|
|
157
|
+
assert here is not None, "Pid always detects"
|
|
158
|
+
return here
|
|
159
|
+
|
|
160
|
+
|
|
148
161
|
@dataclasses.dataclass(frozen=True)
|
|
149
162
|
class WorkerInfo:
|
|
150
163
|
"""Identity of the worker that claimed an item.
|
|
@@ -431,18 +444,13 @@ class InflightClaim:
|
|
|
431
444
|
def __getstate__(self) -> dict[str, tp.Any]:
|
|
432
445
|
return {**self.__dict__, "_reg": None}
|
|
433
446
|
|
|
434
|
-
def
|
|
435
|
-
"""Stamp
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
if
|
|
440
|
-
|
|
441
|
-
elif isinstance(job, submitit.LocalJob): # job_id: the subprocess pid
|
|
442
|
-
liveness = Pid(host=socket.gethostname(), pid=int(job.job_id))
|
|
443
|
-
else: # in-process (debug): the claimer's stays
|
|
444
|
-
return
|
|
445
|
-
self._reg.update_liveness(list(uids), liveness)
|
|
447
|
+
def record_liveness(self, liveness: Liveness, uids: tp.Sequence[str]) -> None:
|
|
448
|
+
"""Stamp *liveness*, what runs *uids*, on their rows: e.g. `submitit_liveness`
|
|
449
|
+
of a submitit job, or a job queue's task whose runner then calls
|
|
450
|
+
``WriteTask.run_and_cache``. Processes reading the rows must import its kind
|
|
451
|
+
(else unclaimed)."""
|
|
452
|
+
if self._reg is not None:
|
|
453
|
+
self._reg.update_liveness(list(uids), liveness)
|
|
446
454
|
|
|
447
455
|
def hand_off(self, uids: tp.Iterable[str]) -> None:
|
|
448
456
|
"""Leave the release of *uids* to the work running them."""
|
|
@@ -460,8 +468,8 @@ def inflight_session(
|
|
|
460
468
|
When *reg* is ``None`` (no cache folder), yields an unblocked claim
|
|
461
469
|
so that callers never need a ``None`` guard.
|
|
462
470
|
|
|
463
|
-
Callers should call ``claim.
|
|
464
|
-
block when submitit jobs
|
|
471
|
+
Callers should call ``claim.record_liveness`` inside the ``with``
|
|
472
|
+
block when other work (e.g. submitit jobs) runs the claimed items.
|
|
465
473
|
"""
|
|
466
474
|
if reg is None:
|
|
467
475
|
yield InflightClaim(tuple(item_uids))
|
|
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
|
|
|
19
19
|
T = tp.TypeVar("T")
|
|
20
20
|
QUERY_BATCH_SIZE = 500
|
|
21
21
|
|
|
22
|
-
#
|
|
22
|
+
# DatabaseError substrings that mean the DB is unusable (vs transient
|
|
23
23
|
# lock/I-O hiccups). Triggers a reset; advisory layer can afford to lose rows.
|
|
24
24
|
_CORRUPTION_HINTS = (
|
|
25
25
|
"malformed",
|
|
@@ -67,6 +67,7 @@ class AdvisoryRegistry:
|
|
|
67
67
|
def __init__(self, folder: Path | str) -> None:
|
|
68
68
|
self.db_path = Path(folder) / self._DB_NAME
|
|
69
69
|
self._conn: sqlite3.Connection | None = None
|
|
70
|
+
self._conn_inode: int | None = None
|
|
70
71
|
|
|
71
72
|
def _connect(self, *, create: bool = False) -> sqlite3.Connection | None:
|
|
72
73
|
"""Lazy-open the DB connection, creating the table if needed.
|
|
@@ -78,19 +79,24 @@ class AdvisoryRegistry:
|
|
|
78
79
|
no-op-write paths leave the folder untouched). Writers that
|
|
79
80
|
materialise rows pass ``True``.
|
|
80
81
|
"""
|
|
82
|
+
try: # before connecting: a swap in between only reconnects
|
|
83
|
+
inode: int | None = self.db_path.stat().st_ino
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
inode = None
|
|
81
86
|
if self._conn is not None:
|
|
82
|
-
if self.
|
|
87
|
+
if inode == self._conn_inode:
|
|
83
88
|
return self._conn
|
|
84
89
|
logger.warning(
|
|
85
|
-
"%s registry DB deleted externally, reconnecting: %s",
|
|
90
|
+
"%s registry DB deleted or replaced externally, reconnecting: %s",
|
|
86
91
|
self._LABEL,
|
|
87
92
|
self.db_path,
|
|
88
93
|
)
|
|
89
94
|
self.close()
|
|
90
|
-
if
|
|
95
|
+
if inode is None:
|
|
91
96
|
if not create:
|
|
92
97
|
return None
|
|
93
98
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
self.db_path.touch() # per umask; sqlite alone forces 0o644
|
|
94
100
|
# Autocommit lets subclasses choose per-op between implicit
|
|
95
101
|
# per-statement transactions and explicit BEGIN IMMEDIATE.
|
|
96
102
|
conn = sqlite3.connect(
|
|
@@ -102,6 +108,7 @@ class AdvisoryRegistry:
|
|
|
102
108
|
# WAL needs cross-host shared memory (broken on NFS) -> DELETE journal
|
|
103
109
|
conn.execute("PRAGMA journal_mode=DELETE")
|
|
104
110
|
conn.executescript(self._SCHEMA)
|
|
111
|
+
self._conn_inode = self.db_path.stat().st_ino if inode is None else inode
|
|
105
112
|
self._conn = conn
|
|
106
113
|
return conn
|
|
107
114
|
|
|
@@ -211,6 +218,11 @@ class AdvisoryRegistry:
|
|
|
211
218
|
elif operational and any(h in msg for h in _CORRUPTION_HINTS):
|
|
212
219
|
reason = "corruption detected, resetting"
|
|
213
220
|
self._try_reset()
|
|
221
|
+
elif isinstance(e, sqlite3.DatabaseError) and any(
|
|
222
|
+
h in msg for h in _CORRUPTION_HINTS
|
|
223
|
+
): # maybe a transient NFS misread: connect gate decides
|
|
224
|
+
reason = "corruption suspected, reconnecting"
|
|
225
|
+
self.close()
|
|
214
226
|
else:
|
|
215
227
|
reason = str(e) # unexpected I/O hiccup, programming bug, ...
|
|
216
228
|
# traceback only for the unexpected (non-OperationalError) failures
|
|
@@ -9,6 +9,7 @@ import gc
|
|
|
9
9
|
import logging
|
|
10
10
|
import os
|
|
11
11
|
import pickle
|
|
12
|
+
import threading
|
|
12
13
|
import time
|
|
13
14
|
import typing as tp
|
|
14
15
|
from concurrent import futures
|
|
@@ -259,11 +260,19 @@ def test_jsonl_reader_resets_on_rewrite_or_truncate(tmp_path: Path) -> None:
|
|
|
259
260
|
def test_2_caches(tmp_path: Path) -> None:
|
|
260
261
|
cache: cd.CacheDict[int] = cd.CacheDict(folder=tmp_path, keep_in_ram=False)
|
|
261
262
|
cache2: cd.CacheDict[int] = cd.CacheDict(folder=tmp_path, keep_in_ram=False)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
263
|
+
|
|
264
|
+
def freeze_and_write() -> None:
|
|
265
|
+
with cache2.frozen_cache_folder(), cache.write():
|
|
266
|
+
cache["x"] = 0
|
|
267
|
+
|
|
268
|
+
with cache2.frozen_cache_folder():
|
|
269
|
+
with cache.write():
|
|
270
|
+
cache["blublu"] = 12
|
|
271
|
+
assert "blublu" in cache2
|
|
272
|
+
with futures.ThreadPoolExecutor(max_workers=1) as ex:
|
|
273
|
+
ex.submit(freeze_and_write).result()
|
|
274
|
+
assert "x" not in cache2, "another thread's freeze must not unfreeze this one"
|
|
275
|
+
assert "x" in cache2
|
|
267
276
|
|
|
268
277
|
|
|
269
278
|
def test_2_caches_memmap(tmp_path: Path) -> None:
|
|
@@ -304,9 +313,15 @@ def test_orphaned_data_file_cleanup(
|
|
|
304
313
|
cache: cd.CacheDict[tp.Any] = cd.CacheDict(
|
|
305
314
|
folder=tmp_path, keep_in_ram=False, cache_type=cache_type
|
|
306
315
|
)
|
|
316
|
+
barrier = threading.Barrier(3) # 3 live threads -> 3 writers/info files
|
|
317
|
+
|
|
318
|
+
def write(c: str) -> None:
|
|
319
|
+
barrier.wait()
|
|
320
|
+
_write_items(cache, [f"{c}1", f"{c}2"], data)
|
|
321
|
+
|
|
307
322
|
with futures.ThreadPoolExecutor(max_workers=3) as ex:
|
|
308
323
|
for c in "abc":
|
|
309
|
-
ex.submit(
|
|
324
|
+
ex.submit(write, c)
|
|
310
325
|
assert len(list(tmp_path.glob("*-info.jsonl"))) == 3
|
|
311
326
|
if read_before_delete:
|
|
312
327
|
assert len(set(cache.keys())) == 6
|