exca 0.6.1__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.1 → exca-0.6.2}/PKG-INFO +2 -2
- {exca-0.6.1 → exca-0.6.2}/README.md +1 -1
- exca-0.6.2/exca/cachedict/contiguous.py +187 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/core.py +2 -2
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/dumpcontext.py +9 -4
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/handlers.py +25 -11
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/inflight.py +22 -14
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/registry.py +1 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_contiguous.py +46 -16
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_dumpcontext.py +4 -0
- {exca-0.6.1 → exca-0.6.2}/exca/confdict.py +283 -88
- {exca-0.6.1 → exca-0.6.2}/exca/map.py +3 -2
- {exca-0.6.1 → exca-0.6.2}/exca/steps/backends.py +10 -13
- {exca-0.6.1 → exca-0.6.2}/exca/steps/helpers.py +6 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_backends.py +55 -2
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_helpers.py +3 -1
- {exca-0.6.1 → exca-0.6.2}/exca/task.py +5 -7
- {exca-0.6.1 → exca-0.6.2}/exca/test_confdict.py +148 -10
- {exca-0.6.1 → exca-0.6.2}/exca/test_map.py +1 -1
- {exca-0.6.1 → exca-0.6.2}/exca.egg-info/PKG-INFO +2 -2
- {exca-0.6.1 → exca-0.6.2}/pyproject.toml +1 -1
- exca-0.6.1/exca/cachedict/contiguous.py +0 -164
- {exca-0.6.1 → exca-0.6.2}/LICENSE +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/__init__.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/base.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/__init__.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_cachedict.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_handlers.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_inflight.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/cachedict/test_registry.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/helpers.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/logconf.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/py.typed +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/slurm.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/__init__.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/base.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/conftest.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/errors.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/identity.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/items.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/jobregistry.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/patterns.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_cache.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_errors.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_items.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_patterns.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_perf.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_specs.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_steps.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/test_utils.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/steps/utils.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_base.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_compat.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_helpers.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_localmap.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_safeguard.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_submit.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_task.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_utils.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/test_workdir.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/utils.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca/workdir.py +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca.egg-info/SOURCES.txt +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca.egg-info/dependency_links.txt +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca.egg-info/requires.txt +0 -0
- {exca-0.6.1 → exca-0.6.2}/exca.egg-info/top_level.txt +0 -0
- {exca-0.6.1 → 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
|
|
|
@@ -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}")
|
|
@@ -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:
|
|
@@ -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
|
|
|
@@ -207,6 +209,7 @@ class DumpContext:
|
|
|
207
209
|
"""Open a shared file for appending. Returns (handle, relative_name).
|
|
208
210
|
Content files go under DATA_DIR/; info files (-info.jsonl)
|
|
209
211
|
stay in the root folder. Reused across calls with the same suffix."""
|
|
212
|
+
global _NUM_CREATED_FILES
|
|
210
213
|
is_info = suffix == self.INFO_SUFFIX
|
|
211
214
|
if not is_info and not suffix.startswith("."):
|
|
212
215
|
msg = f"suffix must start with '.' to be reclaimable, got {suffix!r}"
|
|
@@ -221,6 +224,8 @@ class DumpContext:
|
|
|
221
224
|
path = self.folder / name
|
|
222
225
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
223
226
|
f = path.open("ab")
|
|
227
|
+
if f.tell() == 0:
|
|
228
|
+
_NUM_CREATED_FILES += 1
|
|
224
229
|
self._stack.enter_context(f)
|
|
225
230
|
self._files[name] = f
|
|
226
231
|
self._created_files.add(path)
|
|
@@ -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))
|
|
@@ -96,6 +96,7 @@ class AdvisoryRegistry:
|
|
|
96
96
|
if not create:
|
|
97
97
|
return None
|
|
98
98
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
self.db_path.touch() # per umask; sqlite alone forces 0o644
|
|
99
100
|
# Autocommit lets subclasses choose per-op between implicit
|
|
100
101
|
# per-statement transactions and explicit BEGIN IMMEDIATE.
|
|
101
102
|
conn = sqlite3.connect(
|
|
@@ -7,10 +7,13 @@
|
|
|
7
7
|
"""Tests for ContiguousMemmap."""
|
|
8
8
|
|
|
9
9
|
import io
|
|
10
|
+
import pickle
|
|
11
|
+
import shutil
|
|
10
12
|
import typing as tp
|
|
11
13
|
from pathlib import Path
|
|
12
14
|
|
|
13
15
|
import numpy as np
|
|
16
|
+
import psutil
|
|
14
17
|
import pytest
|
|
15
18
|
|
|
16
19
|
from .contiguous import ContiguousMemmap
|
|
@@ -18,11 +21,13 @@ from .dumpcontext import DumpContext
|
|
|
18
21
|
|
|
19
22
|
|
|
20
23
|
def _make_cm(tmp_path: Path, arr: np.ndarray) -> ContiguousMemmap:
|
|
21
|
-
"""Dump an array via
|
|
24
|
+
"""Dump an array via ContiguousMemmapArray and load it back."""
|
|
22
25
|
ctx = DumpContext(tmp_path)
|
|
23
26
|
with ctx:
|
|
24
|
-
info = ctx.dump(arr, cache_type="
|
|
25
|
-
|
|
27
|
+
info = ctx.dump(arr, cache_type="ContiguousMemmapArray")
|
|
28
|
+
cm = ctx.load(info)
|
|
29
|
+
assert isinstance(cm, ContiguousMemmap)
|
|
30
|
+
return cm
|
|
26
31
|
|
|
27
32
|
|
|
28
33
|
# =============================================================================
|
|
@@ -49,8 +54,13 @@ def test_roundtrip(tmp_path: Path) -> None:
|
|
|
49
54
|
sub = cm[1:3]
|
|
50
55
|
assert isinstance(sub, ContiguousMemmap)
|
|
51
56
|
np.testing.assert_array_equal(np.asarray(sub), original[1:3])
|
|
57
|
+
np.testing.assert_array_equal(
|
|
58
|
+
np.asarray(pickle.loads(pickle.dumps(sub))), original[1:3]
|
|
59
|
+
)
|
|
52
60
|
# scalar access returns plain value
|
|
53
|
-
assert cm[
|
|
61
|
+
assert cm[3, 29] == original[3, 29]
|
|
62
|
+
assert cm[-1][-2] == original[-1, -2]
|
|
63
|
+
assert np.asarray(cm[3, 29, ...]).shape == (), "0-d read must stay 0-d"
|
|
54
64
|
assert not isinstance(cm[0, 0], ContiguousMemmap)
|
|
55
65
|
# asarray with dtype conversion
|
|
56
66
|
result = np.asarray(cm, dtype=np.float32)
|
|
@@ -59,6 +69,12 @@ def test_roundtrip(tmp_path: Path) -> None:
|
|
|
59
69
|
# empty slice returns plain ndarray
|
|
60
70
|
empty = cm[2:2]
|
|
61
71
|
assert isinstance(empty, np.ndarray) and empty.shape == (0, 30)
|
|
72
|
+
shutil.rmtree(tmp_path / "data")
|
|
73
|
+
np.testing.assert_array_equal(
|
|
74
|
+
np.asarray(_make_cm(tmp_path, -original)),
|
|
75
|
+
-original,
|
|
76
|
+
err_msg="stale handle on a file recreated under the same name",
|
|
77
|
+
)
|
|
62
78
|
|
|
63
79
|
|
|
64
80
|
# =============================================================================
|
|
@@ -88,6 +104,8 @@ def test_view_ops(tmp_path: Path) -> None:
|
|
|
88
104
|
np.testing.assert_array_equal(np.asarray(cm.T), original.T)
|
|
89
105
|
with pytest.raises(TypeError, match="Non-contiguous"):
|
|
90
106
|
cm.T[0]
|
|
107
|
+
with pytest.raises(TypeError, match="copy"):
|
|
108
|
+
cm.T.reshape(-1)
|
|
91
109
|
|
|
92
110
|
|
|
93
111
|
# =============================================================================
|
|
@@ -120,12 +138,6 @@ def test_options_replace(tmp_path: Path) -> None:
|
|
|
120
138
|
# =============================================================================
|
|
121
139
|
|
|
122
140
|
|
|
123
|
-
def test_requires_memmap_backed() -> None:
|
|
124
|
-
"""Wrapping a plain ndarray raises TypeError."""
|
|
125
|
-
with pytest.raises(TypeError, match="memmap-backed"):
|
|
126
|
-
ContiguousMemmap(np.arange(10))
|
|
127
|
-
|
|
128
|
-
|
|
129
141
|
@pytest.mark.parametrize(
|
|
130
142
|
"key,match",
|
|
131
143
|
[
|
|
@@ -186,12 +198,34 @@ def test_no_shared_memory_with_memmap(tmp_path: Path) -> None:
|
|
|
186
198
|
# raw memmap: shares memory with the mapped file
|
|
187
199
|
assert np.shares_memory(np.asarray(raw), raw)
|
|
188
200
|
# ContiguousMemmap: does NOT share memory — data came from file I/O
|
|
189
|
-
cm =
|
|
201
|
+
cm = ctx.load({**info, "#type": "ContiguousMemmapArray"})
|
|
190
202
|
materialized = np.asarray(cm)
|
|
191
203
|
assert not np.shares_memory(materialized, raw)
|
|
192
204
|
np.testing.assert_array_equal(materialized, original)
|
|
193
205
|
|
|
194
206
|
|
|
207
|
+
def test_open_files_bounded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
208
|
+
process = psutil.Process()
|
|
209
|
+
monkeypatch.setenv("EXCA_CONTIGUOUS_MEMMAP_MAX_OPEN_FILES", "3")
|
|
210
|
+
(tmp_path / "data").mkdir()
|
|
211
|
+
ctx = DumpContext(tmp_path)
|
|
212
|
+
arrays = [np.full((4, 5), k, dtype=np.float32) for k in range(10)]
|
|
213
|
+
loaded = []
|
|
214
|
+
for k, arr in enumerate(arrays):
|
|
215
|
+
(tmp_path / "data" / f"{k}.data").write_bytes(arr.tobytes())
|
|
216
|
+
info = dict(filename=f"data/{k}.data", offset=0, shape=(4, 5), dtype="float32")
|
|
217
|
+
loaded.append(ctx.load({"#type": "ContiguousMemmapArray", **info}))
|
|
218
|
+
|
|
219
|
+
def num_open() -> int:
|
|
220
|
+
return sum(Path(f.path).is_relative_to(tmp_path) for f in process.open_files())
|
|
221
|
+
|
|
222
|
+
assert num_open() == 0, "loaded proxies must not hold files open"
|
|
223
|
+
for _ in range(2): # 2nd pass reads evicted files
|
|
224
|
+
for cm, arr in zip(loaded, arrays):
|
|
225
|
+
np.testing.assert_array_equal(np.asarray(cm[1:]), arr[1:])
|
|
226
|
+
assert num_open() <= 3, "more open files than the cap"
|
|
227
|
+
|
|
228
|
+
|
|
195
229
|
class _ShortReads(io.FileIO):
|
|
196
230
|
def readinto(self, buffer: tp.Any, /) -> tp.Any:
|
|
197
231
|
return super().readinto(memoryview(buffer)[:7])
|
|
@@ -200,11 +234,7 @@ class _ShortReads(io.FileIO):
|
|
|
200
234
|
def test_short_reads(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
201
235
|
original = np.arange(12, dtype=np.float64).reshape(3, 4)
|
|
202
236
|
cm = _make_cm(tmp_path, original)
|
|
203
|
-
monkeypatch.setattr(
|
|
204
|
-
"exca.cachedict.contiguous.open",
|
|
205
|
-
lambda path, *args, **kwargs: _ShortReads(path),
|
|
206
|
-
raising=False,
|
|
207
|
-
)
|
|
237
|
+
monkeypatch.setattr(Path, "open", lambda self, *args, **kwargs: _ShortReads(self))
|
|
208
238
|
np.testing.assert_array_equal(np.asarray(cm[1:]), original[1:])
|
|
209
239
|
|
|
210
240
|
|
|
@@ -299,6 +299,10 @@ def test_auto(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
|
299
299
|
np.testing.assert_array_almost_equal(loaded["metrics"]["loss"], [0.5, 0.3, 0.1])
|
|
300
300
|
np.testing.assert_array_almost_equal(loaded["weights"], [[1.0, 2.0], [3.0, 4.0]])
|
|
301
301
|
|
|
302
|
+
with ctx:
|
|
303
|
+
info = ctx.dump((np.array([1.0, 2.0]), 3), cache_type="Auto")
|
|
304
|
+
np.testing.assert_array_equal(ctx.load(info)[0], [1.0, 2.0])
|
|
305
|
+
|
|
302
306
|
|
|
303
307
|
class _Opaque:
|
|
304
308
|
"""Module-level class so it's picklable (local classes are not)."""
|