checkpointer 2.0.2__py3-none-any.whl → 2.5.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.
- checkpointer/__init__.py +14 -3
- checkpointer/checkpoint.py +73 -30
- checkpointer/fn_ident.py +94 -0
- checkpointer/object_hash.py +186 -0
- checkpointer/storages/__init__.py +11 -0
- checkpointer/storages/bcolz_storage.py +6 -7
- checkpointer/storages/memory_storage.py +25 -11
- checkpointer/storages/pickle_storage.py +27 -13
- checkpointer/{types.py → storages/storage.py} +9 -5
- checkpointer/test_checkpointer.py +170 -0
- checkpointer/utils.py +103 -8
- {checkpointer-2.0.2.dist-info → checkpointer-2.5.0.dist-info}/METADATA +49 -21
- checkpointer-2.5.0.dist-info/RECORD +16 -0
- {checkpointer-2.0.2.dist-info → checkpointer-2.5.0.dist-info}/WHEEL +1 -1
- {checkpointer-2.0.2.dist-info → checkpointer-2.5.0.dist-info}/licenses/LICENSE +1 -1
- checkpointer/function_body.py +0 -46
- checkpointer-2.0.2.dist-info/RECORD +0 -13
checkpointer/__init__.py
CHANGED
@@ -1,9 +1,20 @@
|
|
1
|
-
|
2
|
-
from .types import Storage
|
3
|
-
from .function_body import get_function_hash
|
1
|
+
import gc
|
4
2
|
import tempfile
|
3
|
+
from typing import Callable
|
4
|
+
from .checkpoint import Checkpointer, CheckpointError, CheckpointFn
|
5
|
+
from .object_hash import ObjectHash
|
6
|
+
from .storages import MemoryStorage, PickleStorage, Storage
|
5
7
|
|
6
8
|
create_checkpointer = Checkpointer
|
7
9
|
checkpoint = Checkpointer()
|
10
|
+
capture_checkpoint = Checkpointer(capture=True)
|
8
11
|
memory_checkpoint = Checkpointer(format="memory", verbosity=0)
|
9
12
|
tmp_checkpoint = Checkpointer(root_path=tempfile.gettempdir() + "/checkpoints")
|
13
|
+
|
14
|
+
def cleanup_all(invalidated=True, expired=True):
|
15
|
+
for obj in gc.get_objects():
|
16
|
+
if isinstance(obj, CheckpointFn):
|
17
|
+
obj.cleanup(invalidated=invalidated, expired=expired)
|
18
|
+
|
19
|
+
def get_function_hash(fn: Callable, capture=False) -> str:
|
20
|
+
return CheckpointFn(Checkpointer(capture=capture), fn).fn_hash
|
checkpointer/checkpoint.py
CHANGED
@@ -1,22 +1,19 @@
|
|
1
1
|
from __future__ import annotations
|
2
2
|
import inspect
|
3
|
-
import
|
4
|
-
from typing import Generic, TypeVar, Type, TypedDict, Callable, Unpack, Literal, Any, cast, overload
|
5
|
-
from pathlib import Path
|
3
|
+
import re
|
6
4
|
from datetime import datetime
|
7
5
|
from functools import update_wrapper
|
8
|
-
from
|
9
|
-
from
|
10
|
-
from .
|
11
|
-
from .
|
12
|
-
from .storages.memory_storage import MemoryStorage
|
13
|
-
from .storages.bcolz_storage import BcolzStorage
|
6
|
+
from pathlib import Path
|
7
|
+
from typing import Any, Callable, Generic, Iterable, Literal, Type, TypedDict, TypeVar, Unpack, cast, overload
|
8
|
+
from .fn_ident import get_fn_ident
|
9
|
+
from .object_hash import ObjectHash
|
14
10
|
from .print_checkpoint import print_checkpoint
|
11
|
+
from .storages import STORAGE_MAP, Storage
|
12
|
+
from .utils import resolved_awaitable, sync_resolve_coroutine, unwrap_fn
|
15
13
|
|
16
14
|
Fn = TypeVar("Fn", bound=Callable)
|
17
15
|
|
18
16
|
DEFAULT_DIR = Path.home() / ".cache/checkpoints"
|
19
|
-
STORAGE_MAP: dict[str, Type[Storage]] = {"memory": MemoryStorage, "pickle": PickleStorage, "bcolz": BcolzStorage}
|
20
17
|
|
21
18
|
class CheckpointError(Exception):
|
22
19
|
pass
|
@@ -28,6 +25,7 @@ class CheckpointerOpts(TypedDict, total=False):
|
|
28
25
|
verbosity: Literal[0, 1]
|
29
26
|
path: Callable[..., str] | None
|
30
27
|
should_expire: Callable[[datetime], bool] | None
|
28
|
+
capture: bool
|
31
29
|
|
32
30
|
class Checkpointer:
|
33
31
|
def __init__(self, **opts: Unpack[CheckpointerOpts]):
|
@@ -37,6 +35,7 @@ class Checkpointer:
|
|
37
35
|
self.verbosity = opts.get("verbosity", 1)
|
38
36
|
self.path = opts.get("path")
|
39
37
|
self.should_expire = opts.get("should_expire")
|
38
|
+
self.capture = opts.get("capture", False)
|
40
39
|
|
41
40
|
@overload
|
42
41
|
def __call__(self, fn: Fn, **override_opts: Unpack[CheckpointerOpts]) -> CheckpointFn[Fn]: ...
|
@@ -51,20 +50,47 @@ class Checkpointer:
|
|
51
50
|
|
52
51
|
class CheckpointFn(Generic[Fn]):
|
53
52
|
def __init__(self, checkpointer: Checkpointer, fn: Fn):
|
54
|
-
wrapped = unwrap_fn(fn)
|
55
|
-
file_name = Path(wrapped.__code__.co_filename).name
|
56
|
-
update_wrapper(cast(Callable, self), wrapped)
|
57
|
-
storage = STORAGE_MAP[checkpointer.format] if isinstance(checkpointer.format, str) else checkpointer.format
|
58
53
|
self.checkpointer = checkpointer
|
59
54
|
self.fn = fn
|
60
|
-
|
61
|
-
|
55
|
+
|
56
|
+
def _set_ident(self, force=False):
|
57
|
+
if not hasattr(self, "fn_hash_raw") or force:
|
58
|
+
self.fn_hash_raw, self.depends = get_fn_ident(unwrap_fn(self.fn), self.checkpointer.capture)
|
59
|
+
return self
|
60
|
+
|
61
|
+
def _lazyinit(self):
|
62
|
+
wrapped = unwrap_fn(self.fn)
|
63
|
+
fn_file = Path(wrapped.__code__.co_filename).name
|
64
|
+
fn_name = re.sub(r"[^\w.]", "", wrapped.__qualname__)
|
65
|
+
update_wrapper(cast(Callable, self), wrapped)
|
66
|
+
store_format = self.checkpointer.format
|
67
|
+
Storage = STORAGE_MAP[store_format] if isinstance(store_format, str) else store_format
|
68
|
+
deep_hashes = [child._set_ident().fn_hash_raw for child in iterate_checkpoint_fns(self)]
|
69
|
+
self.fn_hash = str(ObjectHash().update_hash(self.fn_hash_raw, iter=deep_hashes))
|
70
|
+
self.fn_subdir = f"{fn_file}/{fn_name}/{self.fn_hash[:16]}"
|
62
71
|
self.is_async = inspect.iscoroutinefunction(wrapped)
|
63
|
-
self.storage =
|
72
|
+
self.storage = Storage(self)
|
73
|
+
self.cleanup = self.storage.cleanup
|
74
|
+
|
75
|
+
def __getattribute__(self, name: str) -> Any:
|
76
|
+
return object.__getattribute__(self, "_getattribute")(name)
|
77
|
+
|
78
|
+
def _getattribute(self, name: str) -> Any:
|
79
|
+
setattr(self, "_getattribute", super().__getattribute__)
|
80
|
+
self._lazyinit()
|
81
|
+
return self._getattribute(name)
|
82
|
+
|
83
|
+
def reinit(self, recursive=False):
|
84
|
+
pointfns = list(iterate_checkpoint_fns(self)) if recursive else [self]
|
85
|
+
for pointfn in pointfns:
|
86
|
+
pointfn._set_ident(True)
|
87
|
+
for pointfn in pointfns:
|
88
|
+
pointfn._lazyinit()
|
64
89
|
|
65
90
|
def get_checkpoint_id(self, args: tuple, kw: dict) -> str:
|
66
91
|
if not callable(self.checkpointer.path):
|
67
|
-
|
92
|
+
call_hash = ObjectHash(self.fn_hash, args, kw, digest_size=16)
|
93
|
+
return f"{self.fn_subdir}/{call_hash}"
|
68
94
|
checkpoint_id = self.checkpointer.path(*args, **kw)
|
69
95
|
if not isinstance(checkpoint_id, str):
|
70
96
|
raise CheckpointError(f"path function must return a string, got {type(checkpoint_id)}")
|
@@ -73,13 +99,13 @@ class CheckpointFn(Generic[Fn]):
|
|
73
99
|
async def _store_on_demand(self, args: tuple, kw: dict, rerun: bool):
|
74
100
|
checkpoint_id = self.get_checkpoint_id(args, kw)
|
75
101
|
checkpoint_path = self.checkpointer.root_path / checkpoint_id
|
76
|
-
|
102
|
+
verbose = self.checkpointer.verbosity > 0
|
77
103
|
refresh = rerun \
|
78
104
|
or not self.storage.exists(checkpoint_path) \
|
79
105
|
or (self.checkpointer.should_expire and self.checkpointer.should_expire(self.storage.checkpoint_date(checkpoint_path)))
|
80
106
|
|
81
107
|
if refresh:
|
82
|
-
print_checkpoint(
|
108
|
+
print_checkpoint(verbose, "MEMORIZING", checkpoint_id, "blue")
|
83
109
|
data = self.fn(*args, **kw)
|
84
110
|
if inspect.iscoroutine(data):
|
85
111
|
data = await data
|
@@ -88,12 +114,12 @@ class CheckpointFn(Generic[Fn]):
|
|
88
114
|
|
89
115
|
try:
|
90
116
|
data = self.storage.load(checkpoint_path)
|
91
|
-
print_checkpoint(
|
117
|
+
print_checkpoint(verbose, "REMEMBERED", checkpoint_id, "green")
|
92
118
|
return data
|
93
119
|
except (EOFError, FileNotFoundError):
|
94
|
-
|
95
|
-
|
96
|
-
|
120
|
+
pass
|
121
|
+
print_checkpoint(verbose, "CORRUPTED", checkpoint_id, "yellow")
|
122
|
+
return await self._store_on_demand(args, kw, True)
|
97
123
|
|
98
124
|
def _call(self, args: tuple, kw: dict, rerun=False):
|
99
125
|
if not self.checkpointer.when:
|
@@ -101,12 +127,29 @@ class CheckpointFn(Generic[Fn]):
|
|
101
127
|
coroutine = self._store_on_demand(args, kw, rerun)
|
102
128
|
return coroutine if self.is_async else sync_resolve_coroutine(coroutine)
|
103
129
|
|
130
|
+
def _get(self, args, kw) -> Any:
|
131
|
+
checkpoint_path = self.checkpointer.root_path / self.get_checkpoint_id(args, kw)
|
132
|
+
try:
|
133
|
+
val = self.storage.load(checkpoint_path)
|
134
|
+
return resolved_awaitable(val) if self.is_async else val
|
135
|
+
except Exception as ex:
|
136
|
+
raise CheckpointError("Could not load checkpoint") from ex
|
137
|
+
|
138
|
+
def exists(self, *args: tuple, **kw: dict) -> bool:
|
139
|
+
return self.storage.exists(self.checkpointer.root_path / self.get_checkpoint_id(args, kw))
|
140
|
+
|
104
141
|
__call__: Fn = cast(Fn, lambda self, *args, **kw: self._call(args, kw))
|
105
142
|
rerun: Fn = cast(Fn, lambda self, *args, **kw: self._call(args, kw, True))
|
143
|
+
get: Fn = cast(Fn, lambda self, *args, **kw: self._get(args, kw))
|
106
144
|
|
107
|
-
def
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
145
|
+
def __repr__(self) -> str:
|
146
|
+
return f"<CheckpointFn {self.fn.__name__} {self.fn_hash[:6]}>"
|
147
|
+
|
148
|
+
def iterate_checkpoint_fns(pointfn: CheckpointFn, visited: set[CheckpointFn] = set()) -> Iterable[CheckpointFn]:
|
149
|
+
visited = visited or set()
|
150
|
+
if pointfn not in visited:
|
151
|
+
yield pointfn
|
152
|
+
visited.add(pointfn)
|
153
|
+
for depend in pointfn.depends:
|
154
|
+
if isinstance(depend, CheckpointFn):
|
155
|
+
yield from iterate_checkpoint_fns(depend, visited)
|
checkpointer/fn_ident.py
ADDED
@@ -0,0 +1,94 @@
|
|
1
|
+
import dis
|
2
|
+
import inspect
|
3
|
+
from collections.abc import Callable
|
4
|
+
from itertools import takewhile
|
5
|
+
from pathlib import Path
|
6
|
+
from types import CodeType, FunctionType, MethodType
|
7
|
+
from typing import Any, Generator, Type, TypeGuard
|
8
|
+
from .object_hash import ObjectHash
|
9
|
+
from .utils import AttrDict, distinct, get_cell_contents, iterate_and_upcoming, transpose, unwrap_fn
|
10
|
+
|
11
|
+
cwd = Path.cwd()
|
12
|
+
|
13
|
+
def is_class(obj) -> TypeGuard[Type]:
|
14
|
+
# isinstance works too, but needlessly triggers __getattribute__
|
15
|
+
return issubclass(type(obj), type)
|
16
|
+
|
17
|
+
def extract_classvars(code: CodeType, scope_vars: AttrDict) -> dict[str, dict[str, Type]]:
|
18
|
+
attr_path: tuple[str, ...] = ()
|
19
|
+
scope_obj = None
|
20
|
+
classvars: dict[str, dict[str, Type]] = {}
|
21
|
+
for instr, upcoming_instrs in iterate_and_upcoming(dis.get_instructions(code)):
|
22
|
+
if instr.opname in scope_vars and not attr_path:
|
23
|
+
attrs = takewhile(lambda instr: instr.opname == "LOAD_ATTR", upcoming_instrs)
|
24
|
+
attr_path = (instr.opname, instr.argval, *(str(x.argval) for x in attrs))
|
25
|
+
elif instr.opname == "CALL":
|
26
|
+
obj = scope_vars.get_at(attr_path)
|
27
|
+
attr_path = ()
|
28
|
+
if is_class(obj):
|
29
|
+
scope_obj = obj
|
30
|
+
elif instr.opname in ("STORE_FAST", "STORE_DEREF") and scope_obj:
|
31
|
+
load_key = instr.opname.replace("STORE", "LOAD")
|
32
|
+
classvars.setdefault(load_key, {})[instr.argval] = scope_obj
|
33
|
+
scope_obj = None
|
34
|
+
return classvars
|
35
|
+
|
36
|
+
def extract_scope_values(code: CodeType, scope_vars: AttrDict) -> Generator[tuple[tuple[str, ...], Any], None, None]:
|
37
|
+
classvars = extract_classvars(code, scope_vars)
|
38
|
+
scope_vars = scope_vars.set({k: scope_vars[k].set(v) for k, v in classvars.items()})
|
39
|
+
for instr, upcoming_instrs in iterate_and_upcoming(dis.get_instructions(code)):
|
40
|
+
if instr.opname in scope_vars:
|
41
|
+
attrs = takewhile(lambda instr: instr.opname == "LOAD_ATTR", upcoming_instrs)
|
42
|
+
attr_path: tuple[str, ...] = (instr.opname, instr.argval, *(str(x.argval) for x in attrs))
|
43
|
+
val = scope_vars.get_at(attr_path)
|
44
|
+
if val is not None:
|
45
|
+
yield attr_path, val
|
46
|
+
for const in code.co_consts:
|
47
|
+
if isinstance(const, CodeType):
|
48
|
+
yield from extract_scope_values(const, scope_vars)
|
49
|
+
|
50
|
+
def get_self_value(fn: Callable) -> type | object | None:
|
51
|
+
if isinstance(fn, MethodType):
|
52
|
+
return fn.__self__
|
53
|
+
parts = tuple(fn.__qualname__.split(".")[:-1])
|
54
|
+
cls = parts and AttrDict(fn.__globals__).get_at(parts)
|
55
|
+
if is_class(cls):
|
56
|
+
return cls
|
57
|
+
|
58
|
+
def get_fn_captured_vals(fn: Callable) -> list[Any]:
|
59
|
+
self_value = get_self_value(fn)
|
60
|
+
scope_vars = AttrDict({
|
61
|
+
"LOAD_FAST": AttrDict({"self": self_value} if self_value else {}),
|
62
|
+
"LOAD_DEREF": AttrDict(get_cell_contents(fn)),
|
63
|
+
"LOAD_GLOBAL": AttrDict(fn.__globals__),
|
64
|
+
})
|
65
|
+
vals = dict(extract_scope_values(fn.__code__, scope_vars))
|
66
|
+
return list(vals.values())
|
67
|
+
|
68
|
+
def is_user_fn(candidate_fn) -> TypeGuard[Callable]:
|
69
|
+
if not isinstance(candidate_fn, (FunctionType, MethodType)):
|
70
|
+
return False
|
71
|
+
fn_path = Path(inspect.getfile(candidate_fn)).resolve()
|
72
|
+
return cwd in fn_path.parents and ".venv" not in fn_path.parts
|
73
|
+
|
74
|
+
def get_depend_fns(fn: Callable, capture: bool, captured_vals_by_fn: dict[Callable, list[Any]] = {}) -> dict[Callable, list[Any]]:
|
75
|
+
from .checkpoint import CheckpointFn
|
76
|
+
captured_vals_by_fn = captured_vals_by_fn or {}
|
77
|
+
captured_vals = get_fn_captured_vals(fn)
|
78
|
+
captured_vals_by_fn[fn] = [val for val in captured_vals if not callable(val)] * capture
|
79
|
+
child_fns = (unwrap_fn(val, checkpoint_fn=True) for val in captured_vals if callable(val))
|
80
|
+
for child_fn in child_fns:
|
81
|
+
if isinstance(child_fn, CheckpointFn):
|
82
|
+
captured_vals_by_fn[child_fn] = []
|
83
|
+
elif child_fn not in captured_vals_by_fn and is_user_fn(child_fn):
|
84
|
+
get_depend_fns(child_fn, capture, captured_vals_by_fn)
|
85
|
+
return captured_vals_by_fn
|
86
|
+
|
87
|
+
def get_fn_ident(fn: Callable, capture: bool) -> tuple[str, list[Callable]]:
|
88
|
+
from .checkpoint import CheckpointFn
|
89
|
+
captured_vals_by_fn = get_depend_fns(fn, capture)
|
90
|
+
depends, depend_captured_vals = transpose(captured_vals_by_fn.items(), 2)
|
91
|
+
depends = distinct(fn.__func__ if isinstance(fn, MethodType) else fn for fn in depends)
|
92
|
+
unwrapped_depends = [fn for fn in depends if not isinstance(fn, CheckpointFn)]
|
93
|
+
fn_hash = str(ObjectHash(fn, unwrapped_depends).update(depend_captured_vals, tolerate_errors=True))
|
94
|
+
return fn_hash, depends
|
@@ -0,0 +1,186 @@
|
|
1
|
+
import ctypes
|
2
|
+
import hashlib
|
3
|
+
import io
|
4
|
+
import re
|
5
|
+
from collections.abc import Iterable
|
6
|
+
from contextlib import nullcontext
|
7
|
+
from decimal import Decimal
|
8
|
+
from itertools import chain
|
9
|
+
from pickle import HIGHEST_PROTOCOL as PROTOCOL
|
10
|
+
from types import BuiltinFunctionType, FunctionType, GeneratorType, MethodType, ModuleType, UnionType
|
11
|
+
from typing import Any, TypeAliasType, TypeVar
|
12
|
+
from .utils import ContextVar, get_fn_body
|
13
|
+
|
14
|
+
try:
|
15
|
+
import numpy as np
|
16
|
+
except:
|
17
|
+
np = None
|
18
|
+
try:
|
19
|
+
import torch
|
20
|
+
except:
|
21
|
+
torch = None
|
22
|
+
|
23
|
+
def encode_type(t: type | FunctionType) -> str:
|
24
|
+
return f"{t.__module__}:{t.__qualname__}"
|
25
|
+
|
26
|
+
def encode_val(v: Any) -> str:
|
27
|
+
return encode_type(type(v))
|
28
|
+
|
29
|
+
class ObjectHashError(Exception):
|
30
|
+
def __init__(self, obj: Any, cause: Exception):
|
31
|
+
super().__init__(f"{type(cause).__name__} error when hashing {obj}")
|
32
|
+
self.obj = obj
|
33
|
+
|
34
|
+
class ObjectHash:
|
35
|
+
def __init__(self, *obj: Any, iter: Iterable[Any] = [], digest_size=64, tolerate_errors=False) -> None:
|
36
|
+
self.hash = hashlib.blake2b(digest_size=digest_size)
|
37
|
+
self.current: dict[int, int] = {}
|
38
|
+
self.tolerate_errors = ContextVar(tolerate_errors)
|
39
|
+
self.update(iter=chain(obj, iter))
|
40
|
+
|
41
|
+
def copy(self) -> "ObjectHash":
|
42
|
+
new = ObjectHash(tolerate_errors=self.tolerate_errors.value)
|
43
|
+
new.hash = self.hash.copy()
|
44
|
+
return new
|
45
|
+
|
46
|
+
def hexdigest(self) -> str:
|
47
|
+
return self.hash.hexdigest()
|
48
|
+
|
49
|
+
__str__ = hexdigest
|
50
|
+
|
51
|
+
def update_hash(self, *data: bytes | str, iter: Iterable[bytes | str] = []) -> "ObjectHash":
|
52
|
+
for d in chain(data, iter):
|
53
|
+
self.hash.update(d.encode() if isinstance(d, str) else d)
|
54
|
+
return self
|
55
|
+
|
56
|
+
def header(self, *args: Any) -> "ObjectHash":
|
57
|
+
return self.update_hash(":".join(map(str, args)))
|
58
|
+
|
59
|
+
def update(self, *objs: Any, iter: Iterable[Any] = [], tolerate_errors: bool | None=None) -> "ObjectHash":
|
60
|
+
with nullcontext() if tolerate_errors is None else self.tolerate_errors.set(tolerate_errors):
|
61
|
+
for obj in chain(objs, iter):
|
62
|
+
try:
|
63
|
+
self._update_one(obj)
|
64
|
+
except Exception as ex:
|
65
|
+
if self.tolerate_errors.value:
|
66
|
+
self.header("error").update(type(ex))
|
67
|
+
continue
|
68
|
+
raise ObjectHashError(obj, ex) from ex
|
69
|
+
return self
|
70
|
+
|
71
|
+
def _update_one(self, obj: Any) -> None:
|
72
|
+
match obj:
|
73
|
+
case None:
|
74
|
+
self.header("null")
|
75
|
+
|
76
|
+
case bool() | int() | float() | complex() | Decimal() | ObjectHash():
|
77
|
+
self.header("number", encode_val(obj), obj)
|
78
|
+
|
79
|
+
case str() | bytes() | bytearray() | memoryview():
|
80
|
+
self.header("bytes", encode_val(obj), len(obj)).update_hash(obj)
|
81
|
+
|
82
|
+
case set() | frozenset():
|
83
|
+
self.header("set", encode_val(obj), len(obj))
|
84
|
+
try:
|
85
|
+
items = sorted(obj)
|
86
|
+
except:
|
87
|
+
self.header("unsortable")
|
88
|
+
items = sorted(str(ObjectHash(item, tolerate_errors=self.tolerate_errors.value)) for item in obj)
|
89
|
+
self.update(iter=items)
|
90
|
+
|
91
|
+
case TypeVar():
|
92
|
+
self.header("TypeVar").update(obj.__name__, obj.__bound__, obj.__constraints__, obj.__contravariant__, obj.__covariant__)
|
93
|
+
|
94
|
+
case TypeAliasType():
|
95
|
+
self.header("TypeAliasType").update(obj.__name__, obj.__value__)
|
96
|
+
|
97
|
+
case UnionType():
|
98
|
+
self.header("UnionType").update(obj.__args__)
|
99
|
+
|
100
|
+
case BuiltinFunctionType():
|
101
|
+
self.header("builtin", obj.__qualname__)
|
102
|
+
|
103
|
+
case FunctionType():
|
104
|
+
self.header("function", encode_type(obj)).update(get_fn_body(obj), obj.__defaults__, obj.__kwdefaults__, obj.__annotations__)
|
105
|
+
|
106
|
+
case MethodType():
|
107
|
+
self.header("method").update(obj.__func__, obj.__self__.__class__)
|
108
|
+
|
109
|
+
case ModuleType():
|
110
|
+
self.header("module", obj.__name__, obj.__file__)
|
111
|
+
|
112
|
+
case GeneratorType():
|
113
|
+
self.header("generator", obj.__qualname__)._update_iterator(obj)
|
114
|
+
|
115
|
+
case io.TextIOWrapper() | io.FileIO() | io.BufferedRandom() | io.BufferedWriter() | io.BufferedReader():
|
116
|
+
self.header("file", encode_val(obj)).update(obj.name, obj.mode, obj.tell())
|
117
|
+
|
118
|
+
case type():
|
119
|
+
self.header("type", encode_type(obj))
|
120
|
+
|
121
|
+
case _ if np and isinstance(obj, np.dtype):
|
122
|
+
self.header("dtype").update(obj.__class__, obj.descr)
|
123
|
+
|
124
|
+
case _ if np and isinstance(obj, np.ndarray):
|
125
|
+
self.header("ndarray", encode_val(obj), obj.shape, obj.strides).update(obj.dtype)
|
126
|
+
if obj.dtype.hasobject:
|
127
|
+
self.update(obj.__reduce_ex__(PROTOCOL))
|
128
|
+
else:
|
129
|
+
array = np.ascontiguousarray(obj if obj.base is None else obj.base).view(np.uint8)
|
130
|
+
self.update_hash(array.data)
|
131
|
+
|
132
|
+
case _ if torch and isinstance(obj, torch.Tensor):
|
133
|
+
self.header("tensor", encode_val(obj), str(obj.dtype), tuple(obj.shape), obj.stride(), str(obj.device))
|
134
|
+
if obj.device.type != "cpu":
|
135
|
+
obj = obj.cpu()
|
136
|
+
storage = obj.storage()
|
137
|
+
buffer = (ctypes.c_ubyte * (storage.nbytes())).from_address(storage.data_ptr())
|
138
|
+
self.update_hash(memoryview(buffer))
|
139
|
+
|
140
|
+
case _ if id(obj) in self.current:
|
141
|
+
self.header("circular", self.current[id(obj)])
|
142
|
+
|
143
|
+
case _:
|
144
|
+
try:
|
145
|
+
self.current[id(obj)] = len(self.current)
|
146
|
+
match obj:
|
147
|
+
case list() | tuple():
|
148
|
+
self.header("list", encode_val(obj), len(obj)).update(iter=obj)
|
149
|
+
case dict():
|
150
|
+
try:
|
151
|
+
items = sorted(obj.items())
|
152
|
+
except:
|
153
|
+
items = sorted((str(ObjectHash(key, tolerate_errors=self.tolerate_errors.value)), val) for key, val in obj.items())
|
154
|
+
self.header("dict", encode_val(obj), len(obj)).update(iter=chain.from_iterable(items))
|
155
|
+
case _:
|
156
|
+
self._update_object(obj)
|
157
|
+
finally:
|
158
|
+
del self.current[id(obj)]
|
159
|
+
|
160
|
+
def _update_iterator(self, obj: Iterable) -> None:
|
161
|
+
self.header("iterator", encode_val(obj)).update(iter=obj).header(b"iterator-end")
|
162
|
+
|
163
|
+
def _update_object(self, obj: object) -> "ObjectHash":
|
164
|
+
self.header("instance", encode_val(obj))
|
165
|
+
try:
|
166
|
+
reduced = obj.__reduce_ex__(PROTOCOL) if hasattr(obj, "__reduce_ex__") else obj.__reduce__()
|
167
|
+
except:
|
168
|
+
reduced = None
|
169
|
+
if isinstance(reduced, str):
|
170
|
+
return self.header("reduce-str").update(reduced)
|
171
|
+
if reduced:
|
172
|
+
reduced = list(reduced)
|
173
|
+
it = reduced.pop(3) if len(reduced) >= 4 else None
|
174
|
+
self.header("reduce").update(reduced)
|
175
|
+
if it is not None:
|
176
|
+
self._update_iterator(it)
|
177
|
+
return self
|
178
|
+
if state := hasattr(obj, "__getstate__") and obj.__getstate__():
|
179
|
+
return self.header("getstate").update(state)
|
180
|
+
if len(getattr(obj, "__slots__", [])):
|
181
|
+
slots = {slot: getattr(obj, slot, None) for slot in getattr(obj, "__slots__")}
|
182
|
+
return self.header("slots").update(slots)
|
183
|
+
if d := getattr(obj, "__dict__", {}):
|
184
|
+
return self.header("dict").update(d)
|
185
|
+
repr_str = re.sub(r"\s+(at\s+0x[0-9a-fA-F]+)(>)$", r"\2", repr(obj))
|
186
|
+
return self.header("repr").update(repr_str)
|
@@ -0,0 +1,11 @@
|
|
1
|
+
from typing import Type
|
2
|
+
from .storage import Storage
|
3
|
+
from .pickle_storage import PickleStorage
|
4
|
+
from .memory_storage import MemoryStorage
|
5
|
+
from .bcolz_storage import BcolzStorage
|
6
|
+
|
7
|
+
STORAGE_MAP: dict[str, Type[Storage]] = {
|
8
|
+
"pickle": PickleStorage,
|
9
|
+
"memory": MemoryStorage,
|
10
|
+
"bcolz": BcolzStorage,
|
11
|
+
}
|
@@ -1,7 +1,7 @@
|
|
1
1
|
import shutil
|
2
2
|
from pathlib import Path
|
3
3
|
from datetime import datetime
|
4
|
-
from
|
4
|
+
from .storage import Storage
|
5
5
|
|
6
6
|
def get_data_type_str(x):
|
7
7
|
if isinstance(x, tuple):
|
@@ -73,9 +73,8 @@ class BcolzStorage(Storage):
|
|
73
73
|
|
74
74
|
def delete(self, path):
|
75
75
|
# NOTE: Not recursive
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
pass
|
76
|
+
shutil.rmtree(get_metapath(path), ignore_errors=True)
|
77
|
+
shutil.rmtree(path, ignore_errors=True)
|
78
|
+
|
79
|
+
def cleanup(self, invalidated=True, expired=True):
|
80
|
+
raise NotImplementedError("cleanup() not implemented for bcolz storage")
|
@@ -1,25 +1,39 @@
|
|
1
1
|
from typing import Any
|
2
2
|
from pathlib import Path
|
3
3
|
from datetime import datetime
|
4
|
-
from
|
4
|
+
from .storage import Storage
|
5
5
|
|
6
|
-
item_map: dict[str, tuple[datetime, Any]] = {}
|
6
|
+
item_map: dict[Path, dict[str, tuple[datetime, Any]]] = {}
|
7
|
+
|
8
|
+
def get_short_path(path: Path):
|
9
|
+
return path.parts[-1]
|
7
10
|
|
8
11
|
class MemoryStorage(Storage):
|
9
|
-
def
|
10
|
-
return
|
12
|
+
def get_dict(self):
|
13
|
+
return item_map.setdefault(self.checkpointer.root_path / self.checkpoint_fn.fn_subdir, {})
|
14
|
+
|
15
|
+
def store(self, path, data):
|
16
|
+
self.get_dict()[get_short_path(path)] = (datetime.now(), data)
|
11
17
|
|
12
18
|
def exists(self, path):
|
13
|
-
return
|
19
|
+
return get_short_path(path) in self.get_dict()
|
14
20
|
|
15
21
|
def checkpoint_date(self, path):
|
16
|
-
return
|
17
|
-
|
18
|
-
def store(self, path, data):
|
19
|
-
item_map[self.get_short_path(path)] = (datetime.now(), data)
|
22
|
+
return self.get_dict()[get_short_path(path)][0]
|
20
23
|
|
21
24
|
def load(self, path):
|
22
|
-
return
|
25
|
+
return self.get_dict()[get_short_path(path)][1]
|
23
26
|
|
24
27
|
def delete(self, path):
|
25
|
-
del
|
28
|
+
del self.get_dict()[get_short_path(path)]
|
29
|
+
|
30
|
+
def cleanup(self, invalidated=True, expired=True):
|
31
|
+
curr_key = self.checkpointer.root_path / self.checkpoint_fn.fn_subdir
|
32
|
+
for key, calldict in list(item_map.items()):
|
33
|
+
if key.parent == curr_key.parent:
|
34
|
+
if invalidated and key != curr_key:
|
35
|
+
del item_map[key]
|
36
|
+
elif expired and self.checkpointer.should_expire:
|
37
|
+
for callid, (date, _) in list(calldict.items()):
|
38
|
+
if self.checkpointer.should_expire(date):
|
39
|
+
del calldict[callid]
|
@@ -1,31 +1,45 @@
|
|
1
1
|
import pickle
|
2
|
+
import shutil
|
2
3
|
from pathlib import Path
|
3
4
|
from datetime import datetime
|
4
|
-
from
|
5
|
+
from .storage import Storage
|
5
6
|
|
6
7
|
def get_path(path: Path):
|
7
8
|
return path.with_name(f"{path.name}.pkl")
|
8
9
|
|
9
10
|
class PickleStorage(Storage):
|
10
|
-
def exists(self, path):
|
11
|
-
return get_path(path).exists()
|
12
|
-
|
13
|
-
def checkpoint_date(self, path):
|
14
|
-
return datetime.fromtimestamp(get_path(path).stat().st_mtime)
|
15
|
-
|
16
11
|
def store(self, path, data):
|
17
12
|
full_path = get_path(path)
|
18
13
|
full_path.parent.mkdir(parents=True, exist_ok=True)
|
19
14
|
with full_path.open("wb") as file:
|
20
15
|
pickle.dump(data, file, -1)
|
21
16
|
|
17
|
+
def exists(self, path):
|
18
|
+
return get_path(path).exists()
|
19
|
+
|
20
|
+
def checkpoint_date(self, path):
|
21
|
+
return datetime.fromtimestamp(get_path(path).stat().st_mtime)
|
22
|
+
|
22
23
|
def load(self, path):
|
23
|
-
|
24
|
-
with full_path.open("rb") as file:
|
24
|
+
with get_path(path).open("rb") as file:
|
25
25
|
return pickle.load(file)
|
26
26
|
|
27
27
|
def delete(self, path):
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
28
|
+
get_path(path).unlink(missing_ok=True)
|
29
|
+
|
30
|
+
def cleanup(self, invalidated=True, expired=True):
|
31
|
+
version_path = self.checkpointer.root_path.resolve() / self.checkpoint_fn.fn_subdir
|
32
|
+
fn_path = version_path.parent
|
33
|
+
if invalidated:
|
34
|
+
old_dirs = [path for path in fn_path.iterdir() if path.is_dir() and path != version_path]
|
35
|
+
for path in old_dirs:
|
36
|
+
shutil.rmtree(path)
|
37
|
+
print(f"Removed {len(old_dirs)} invalidated directories for {self.checkpoint_fn.__qualname__}")
|
38
|
+
if expired and self.checkpointer.should_expire:
|
39
|
+
count = 0
|
40
|
+
for pkl_path in fn_path.rglob("*.pkl"):
|
41
|
+
path = pkl_path.with_suffix("")
|
42
|
+
if self.checkpointer.should_expire(self.checkpoint_date(path)):
|
43
|
+
count += 1
|
44
|
+
self.delete(path)
|
45
|
+
print(f"Removed {count} expired checkpoints for {self.checkpoint_fn.__qualname__}")
|
@@ -4,20 +4,24 @@ from pathlib import Path
|
|
4
4
|
from datetime import datetime
|
5
5
|
|
6
6
|
if TYPE_CHECKING:
|
7
|
-
from
|
7
|
+
from ..checkpoint import Checkpointer, CheckpointFn
|
8
8
|
|
9
9
|
class Storage:
|
10
10
|
checkpointer: Checkpointer
|
11
|
+
checkpoint_fn: CheckpointFn
|
11
12
|
|
12
|
-
def __init__(self,
|
13
|
-
self.checkpointer = checkpointer
|
13
|
+
def __init__(self, checkpoint_fn: CheckpointFn):
|
14
|
+
self.checkpointer = checkpoint_fn.checkpointer
|
15
|
+
self.checkpoint_fn = checkpoint_fn
|
16
|
+
|
17
|
+
def store(self, path: Path, data: Any) -> None: ...
|
14
18
|
|
15
19
|
def exists(self, path: Path) -> bool: ...
|
16
20
|
|
17
21
|
def checkpoint_date(self, path: Path) -> datetime: ...
|
18
22
|
|
19
|
-
def store(self, path: Path, data: Any) -> None: ...
|
20
|
-
|
21
23
|
def load(self, path: Path) -> Any: ...
|
22
24
|
|
23
25
|
def delete(self, path: Path) -> None: ...
|
26
|
+
|
27
|
+
def cleanup(self, invalidated=True, expired=True): ...
|
@@ -0,0 +1,170 @@
|
|
1
|
+
import asyncio
|
2
|
+
import pytest
|
3
|
+
from riprint import riprint as print
|
4
|
+
from types import MethodType, MethodWrapperType
|
5
|
+
from . import checkpoint
|
6
|
+
from .checkpoint import CheckpointError
|
7
|
+
from .utils import AttrDict
|
8
|
+
|
9
|
+
def global_multiply(a, b):
|
10
|
+
return a * b
|
11
|
+
|
12
|
+
@pytest.fixture(autouse=True)
|
13
|
+
def run_before_and_after_tests(tmpdir):
|
14
|
+
global checkpoint
|
15
|
+
checkpoint = checkpoint(root_path=tmpdir)
|
16
|
+
yield
|
17
|
+
|
18
|
+
def test_basic_caching():
|
19
|
+
@checkpoint
|
20
|
+
def square(x: int) -> int:
|
21
|
+
return x ** 2
|
22
|
+
|
23
|
+
result1 = square(4)
|
24
|
+
result2 = square(4)
|
25
|
+
|
26
|
+
assert result1 == result2 == 16
|
27
|
+
|
28
|
+
def test_cache_invalidation():
|
29
|
+
@checkpoint
|
30
|
+
def multiply(a, b):
|
31
|
+
return a * b
|
32
|
+
|
33
|
+
@checkpoint
|
34
|
+
def helper(x):
|
35
|
+
return multiply(x + 1, 2)
|
36
|
+
|
37
|
+
@checkpoint
|
38
|
+
def compute(a, b):
|
39
|
+
return helper(a) + helper(b)
|
40
|
+
|
41
|
+
result1 = compute(3, 4)
|
42
|
+
assert result1 == 18
|
43
|
+
|
44
|
+
def test_layered_caching():
|
45
|
+
dev_checkpoint = checkpoint(when=True)
|
46
|
+
|
47
|
+
@checkpoint(format="memory")
|
48
|
+
@dev_checkpoint
|
49
|
+
def expensive_function(x):
|
50
|
+
return x ** 2
|
51
|
+
|
52
|
+
assert expensive_function(4) == 16
|
53
|
+
assert expensive_function(4) == 16
|
54
|
+
|
55
|
+
def test_recursive_caching1():
|
56
|
+
@checkpoint
|
57
|
+
def fib(n: int) -> int:
|
58
|
+
return fib(n - 1) + fib(n - 2) if n > 1 else n
|
59
|
+
|
60
|
+
assert fib(10) == 55
|
61
|
+
assert fib.get(10) == 55
|
62
|
+
assert fib.get(5) == 5
|
63
|
+
|
64
|
+
def test_recursive_caching2():
|
65
|
+
@checkpoint
|
66
|
+
def fib(n: int) -> int:
|
67
|
+
return fib.fn(n - 1) + fib.fn(n - 2) if n > 1 else n
|
68
|
+
|
69
|
+
assert fib(10) == 55
|
70
|
+
assert fib.get(10) == 55
|
71
|
+
with pytest.raises(CheckpointError):
|
72
|
+
fib.get(5)
|
73
|
+
|
74
|
+
@pytest.mark.asyncio
|
75
|
+
async def test_async_caching():
|
76
|
+
@checkpoint(format="memory")
|
77
|
+
async def async_square(x: int) -> int:
|
78
|
+
await asyncio.sleep(0.1)
|
79
|
+
return x ** 2
|
80
|
+
|
81
|
+
result1 = await async_square(3)
|
82
|
+
result2 = await async_square.get(3)
|
83
|
+
|
84
|
+
assert result1 == result2 == 9
|
85
|
+
|
86
|
+
def test_custom_path_caching():
|
87
|
+
def custom_path(a, b):
|
88
|
+
return f"add/{a}-{b}"
|
89
|
+
|
90
|
+
@checkpoint(path=custom_path)
|
91
|
+
def add(a, b):
|
92
|
+
return a + b
|
93
|
+
|
94
|
+
add(3, 4)
|
95
|
+
assert (checkpoint.root_path / "add/3-4.pkl").exists()
|
96
|
+
|
97
|
+
def test_force_recalculation():
|
98
|
+
@checkpoint
|
99
|
+
def square(x: int) -> int:
|
100
|
+
return x ** 2
|
101
|
+
|
102
|
+
assert square(5) == 25
|
103
|
+
square.rerun(5)
|
104
|
+
assert square.get(5) == 25
|
105
|
+
|
106
|
+
def test_multi_layer_decorator():
|
107
|
+
@checkpoint(format="memory")
|
108
|
+
@checkpoint(format="pickle")
|
109
|
+
def add(a, b):
|
110
|
+
return a + b
|
111
|
+
|
112
|
+
assert add(2, 3) == 5
|
113
|
+
assert add.get(2, 3) == 5
|
114
|
+
|
115
|
+
def test_capture():
|
116
|
+
item_dict = AttrDict({"a": 1, "b": 1})
|
117
|
+
|
118
|
+
@checkpoint(capture=True)
|
119
|
+
def test_whole():
|
120
|
+
return item_dict
|
121
|
+
|
122
|
+
@checkpoint(capture=True)
|
123
|
+
def test_a():
|
124
|
+
return item_dict.a + 1
|
125
|
+
|
126
|
+
init_hash_a = test_a.fn_hash
|
127
|
+
init_hash_whole = test_whole.fn_hash
|
128
|
+
item_dict.b += 1
|
129
|
+
test_whole.reinit()
|
130
|
+
test_a.reinit()
|
131
|
+
assert test_whole.fn_hash != init_hash_whole
|
132
|
+
assert test_a.fn_hash == init_hash_a
|
133
|
+
item_dict.a += 1
|
134
|
+
test_a.reinit()
|
135
|
+
assert test_a.fn_hash != init_hash_a
|
136
|
+
|
137
|
+
def test_depends():
|
138
|
+
def multiply_wrapper(a, b):
|
139
|
+
return global_multiply(a, b)
|
140
|
+
|
141
|
+
def helper(a, b):
|
142
|
+
return multiply_wrapper(a + 1, b + 1)
|
143
|
+
|
144
|
+
@checkpoint
|
145
|
+
def test_a(a, b):
|
146
|
+
return helper(a, b)
|
147
|
+
|
148
|
+
@checkpoint
|
149
|
+
def test_b(a, b):
|
150
|
+
return test_a(a, b) + multiply_wrapper(a, b)
|
151
|
+
|
152
|
+
assert set(test_a.depends) == {test_a.fn, helper, multiply_wrapper, global_multiply}
|
153
|
+
assert set(test_b.depends) == {test_b.fn, test_a, multiply_wrapper, global_multiply}
|
154
|
+
|
155
|
+
def test_lazy_init():
|
156
|
+
@checkpoint
|
157
|
+
def fn1(x):
|
158
|
+
return fn2(x)
|
159
|
+
|
160
|
+
@checkpoint
|
161
|
+
def fn2(x):
|
162
|
+
return fn1(x)
|
163
|
+
|
164
|
+
assert type(object.__getattribute__(fn1, "_getattribute")) == MethodType
|
165
|
+
with pytest.raises(AttributeError):
|
166
|
+
object.__getattribute__(fn1, "fn_hash")
|
167
|
+
assert fn1.fn_hash == object.__getattribute__(fn1, "fn_hash")
|
168
|
+
assert type(object.__getattribute__(fn1, "_getattribute")) == MethodWrapperType
|
169
|
+
assert set(fn1.depends) == {fn1.fn, fn2}
|
170
|
+
assert set(fn2.depends) == {fn1, fn2.fn}
|
checkpointer/utils.py
CHANGED
@@ -1,17 +1,112 @@
|
|
1
|
-
import
|
1
|
+
import inspect
|
2
|
+
import tokenize
|
3
|
+
from contextlib import contextmanager
|
4
|
+
from io import StringIO
|
5
|
+
from types import coroutine
|
6
|
+
from typing import Any, Callable, Coroutine, Generator, Iterable, cast
|
2
7
|
|
3
|
-
def
|
4
|
-
|
8
|
+
def distinct[T](seq: Iterable[T]) -> list[T]:
|
9
|
+
return list(dict.fromkeys(seq))
|
10
|
+
|
11
|
+
def transpose(tuples, default_num_returns=0):
|
12
|
+
output = tuple(zip(*tuples))
|
13
|
+
if not output:
|
14
|
+
return ([],) * default_num_returns
|
15
|
+
return tuple(map(list, output))
|
16
|
+
|
17
|
+
def get_fn_body(fn: Callable) -> str:
|
18
|
+
try:
|
19
|
+
source = inspect.getsource(fn)
|
20
|
+
except OSError:
|
21
|
+
return ""
|
22
|
+
tokens = tokenize.generate_tokens(StringIO(source).readline)
|
23
|
+
ignore_types = (tokenize.COMMENT, tokenize.NL)
|
24
|
+
return "".join("\0" + token.string for token in tokens if token.type not in ignore_types)
|
25
|
+
|
26
|
+
def get_cell_contents(fn: Callable) -> Generator[tuple[str, Any], None, None]:
|
27
|
+
for key, cell in zip(fn.__code__.co_freevars, fn.__closure__ or []):
|
28
|
+
try:
|
29
|
+
yield (key, cell.cell_contents)
|
30
|
+
except ValueError:
|
31
|
+
pass
|
32
|
+
|
33
|
+
def unwrap_fn[T: Callable](fn: T, checkpoint_fn=False) -> T:
|
34
|
+
from .checkpoint import CheckpointFn
|
35
|
+
while True:
|
36
|
+
if (checkpoint_fn and isinstance(fn, CheckpointFn)) or not hasattr(fn, "__wrapped__"):
|
37
|
+
return cast(T, fn)
|
5
38
|
fn = getattr(fn, "__wrapped__")
|
6
|
-
return fn
|
7
39
|
|
8
|
-
|
9
|
-
|
40
|
+
async def resolved_awaitable[T](value: T) -> T:
|
41
|
+
return value
|
42
|
+
|
43
|
+
@coroutine
|
44
|
+
def coroutine_as_generator[T](coroutine: Coroutine[None, None, T]) -> Generator[None, None, T]:
|
10
45
|
val = yield from coroutine
|
11
46
|
return val
|
12
47
|
|
13
|
-
def sync_resolve_coroutine(coroutine):
|
48
|
+
def sync_resolve_coroutine[T](coroutine: Coroutine[None, None, T]) -> T:
|
49
|
+
gen = cast(Generator, coroutine_as_generator(coroutine))
|
14
50
|
try:
|
15
|
-
|
51
|
+
while True:
|
52
|
+
next(gen)
|
16
53
|
except StopIteration as ex:
|
17
54
|
return ex.value
|
55
|
+
|
56
|
+
class AttrDict(dict):
|
57
|
+
def __init__(self, *args, **kwargs):
|
58
|
+
super().__init__(*args, **kwargs)
|
59
|
+
self.__dict__ = self
|
60
|
+
|
61
|
+
def __getattribute__(self, name: str) -> Any:
|
62
|
+
return super().__getattribute__(name)
|
63
|
+
|
64
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
65
|
+
return super().__setattr__(name, value)
|
66
|
+
|
67
|
+
def set(self, d: dict) -> "AttrDict":
|
68
|
+
if not d:
|
69
|
+
return self
|
70
|
+
return AttrDict({**self, **d})
|
71
|
+
|
72
|
+
def delete(self, *attrs: str) -> "AttrDict":
|
73
|
+
d = AttrDict(self)
|
74
|
+
for attr in attrs:
|
75
|
+
del d[attr]
|
76
|
+
return d
|
77
|
+
|
78
|
+
def get_at(self, attrs: tuple[str, ...]) -> Any:
|
79
|
+
d = self
|
80
|
+
for attr in attrs:
|
81
|
+
d = getattr(d, attr, None)
|
82
|
+
return d
|
83
|
+
|
84
|
+
class ContextVar[T]:
|
85
|
+
def __init__(self, value: T):
|
86
|
+
self.value = value
|
87
|
+
|
88
|
+
@contextmanager
|
89
|
+
def set(self, value: T):
|
90
|
+
self.value, old = value, self.value
|
91
|
+
try:
|
92
|
+
yield
|
93
|
+
finally:
|
94
|
+
self.value = old
|
95
|
+
|
96
|
+
class iterate_and_upcoming[T]:
|
97
|
+
def __init__(self, it: Iterable[T]) -> None:
|
98
|
+
self.it = iter(it)
|
99
|
+
self.previous: tuple[()] | tuple[T] = ()
|
100
|
+
|
101
|
+
def __iter__(self):
|
102
|
+
return self
|
103
|
+
|
104
|
+
def __next__(self) -> tuple[T, Iterable[T]]:
|
105
|
+
item = self.previous[0] if self.previous else next(self.it)
|
106
|
+
self.previous = ()
|
107
|
+
return item, self._tracked_iter()
|
108
|
+
|
109
|
+
def _tracked_iter(self):
|
110
|
+
for x in self.it:
|
111
|
+
self.previous = (x,)
|
112
|
+
yield x
|
@@ -1,25 +1,25 @@
|
|
1
|
-
Metadata-Version: 2.
|
1
|
+
Metadata-Version: 2.4
|
2
2
|
Name: checkpointer
|
3
|
-
Version: 2.0
|
3
|
+
Version: 2.5.0
|
4
4
|
Summary: A Python library for memoizing function results with support for multiple storage backends, async runtimes, and automatic cache invalidation
|
5
5
|
Project-URL: Repository, https://github.com/Reddan/checkpointer.git
|
6
6
|
Author: Hampus Hallman
|
7
|
-
License: Copyright
|
7
|
+
License: Copyright 2018-2025 Hampus Hallman
|
8
8
|
|
9
9
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
10
10
|
|
11
11
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
12
12
|
|
13
13
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
14
|
+
License-File: LICENSE
|
14
15
|
Requires-Python: >=3.12
|
15
|
-
Requires-Dist: relib
|
16
16
|
Description-Content-Type: text/markdown
|
17
17
|
|
18
18
|
# checkpointer · [](https://github.com/Reddan/checkpointer/blob/master/LICENSE) [](https://pypi.org/project/checkpointer/) [](https://pypi.org/project/checkpointer/)
|
19
19
|
|
20
20
|
`checkpointer` is a Python library for memoizing function results. It provides a decorator-based API with support for multiple storage backends. Use it for computationally expensive operations where caching can save time, or during development to avoid waiting for redundant computations.
|
21
21
|
|
22
|
-
Adding or removing `@checkpoint` doesn't change how your code works
|
22
|
+
Adding or removing `@checkpoint` doesn't change how your code works. You can apply it to any function, including ones you've already written, without altering their behavior or introducing side effects. The original function remains unchanged and can still be called directly when needed.
|
23
23
|
|
24
24
|
### Key Features:
|
25
25
|
- 🗂️ **Multiple Storage Backends**: Built-in support for in-memory and pickle-based storage, or create your own.
|
@@ -27,6 +27,7 @@ Adding or removing `@checkpoint` doesn't change how your code works, and it can
|
|
27
27
|
- 🔄 **Async and Sync Compatibility**: Works with synchronous functions and any Python async runtime (e.g., `asyncio`, `Trio`, `Curio`).
|
28
28
|
- ⏲️ **Custom Expiration Logic**: Automatically invalidate old checkpoints.
|
29
29
|
- 📂 **Flexible Path Configuration**: Control where checkpoints are stored.
|
30
|
+
- 📦 **Captured Variables Handling**: Optionally include captured variables in cache invalidation.
|
30
31
|
|
31
32
|
---
|
32
33
|
|
@@ -59,8 +60,10 @@ result = expensive_function(4) # Loads from the cache
|
|
59
60
|
When you use `@checkpoint`, the function's **arguments** (`args`, `kwargs`) are hashed to create a unique identifier for each call. This identifier is used to store and retrieve cached results. If the same arguments are passed again, `checkpointer` loads the cached result instead of recomputing.
|
60
61
|
|
61
62
|
Additionally, `checkpointer` ensures that caches are invalidated when a function's implementation or any of its dependencies change. Each function is assigned a hash based on:
|
63
|
+
|
62
64
|
1. **Its source code**: Changes to the function's code update its hash.
|
63
65
|
2. **Dependent functions**: If a function calls others, changes in those dependencies will also update the hash.
|
66
|
+
3. **Captured variables**: (Optional) If `capture=True`, changes to captured variables and global variables will also update the hash.
|
64
67
|
|
65
68
|
### Example: Cache Invalidation
|
66
69
|
|
@@ -105,7 +108,7 @@ Layer caches by stacking checkpoints:
|
|
105
108
|
@dev_checkpoint # Adds caching during development
|
106
109
|
def some_expensive_function():
|
107
110
|
print("Performing a time-consuming operation...")
|
108
|
-
return sum(i * i for i in range(10**
|
111
|
+
return sum(i * i for i in range(10**8))
|
109
112
|
```
|
110
113
|
|
111
114
|
- **In development**: Both `dev_checkpoint` and `memory` caches are active.
|
@@ -115,7 +118,17 @@ def some_expensive_function():
|
|
115
118
|
|
116
119
|
## Usage
|
117
120
|
|
121
|
+
### Basic Invocation and Caching
|
122
|
+
|
123
|
+
Call the decorated function as usual. On the first call, the result is computed and stored in the cache. Subsequent calls with the same arguments load the result from the cache:
|
124
|
+
|
125
|
+
```python
|
126
|
+
result = expensive_function(4) # Computes and stores the result
|
127
|
+
result = expensive_function(4) # Loads the result from the cache
|
128
|
+
```
|
129
|
+
|
118
130
|
### Force Recalculation
|
131
|
+
|
119
132
|
Force a recalculation and overwrite the stored checkpoint:
|
120
133
|
|
121
134
|
```python
|
@@ -123,6 +136,7 @@ result = expensive_function.rerun(4)
|
|
123
136
|
```
|
124
137
|
|
125
138
|
### Call the Original Function
|
139
|
+
|
126
140
|
Use `fn` to directly call the original, undecorated function:
|
127
141
|
|
128
142
|
```python
|
@@ -132,12 +146,25 @@ result = expensive_function.fn(4)
|
|
132
146
|
This is especially useful **inside recursive functions** to avoid redundant caching of intermediate steps while still caching the final result.
|
133
147
|
|
134
148
|
### Retrieve Stored Checkpoints
|
149
|
+
|
135
150
|
Access cached results without recalculating:
|
136
151
|
|
137
152
|
```python
|
138
153
|
stored_result = expensive_function.get(4)
|
139
154
|
```
|
140
155
|
|
156
|
+
### Refresh Function Hash
|
157
|
+
|
158
|
+
When using `capture=True`, changes to captured variables are included in the function's hash to determine cache invalidation. However, `checkpointer` does not automatically update this hash during a running Python session—it recalculates between sessions or when you explicitly refresh it.
|
159
|
+
|
160
|
+
Use the `reinit` method to manually refresh the function's hash within the same session:
|
161
|
+
|
162
|
+
```python
|
163
|
+
expensive_function.reinit()
|
164
|
+
```
|
165
|
+
|
166
|
+
This forces `checkpointer` to recalculate the hash of `expensive_function`, considering any changes to captured variables. It's useful when you've modified external variables that the function depends on and want the cache to reflect these changes immediately.
|
167
|
+
|
141
168
|
---
|
142
169
|
|
143
170
|
## Storage Backends
|
@@ -154,11 +181,11 @@ You can specify a storage backend using either its name (`"pickle"` or `"memory"
|
|
154
181
|
```python
|
155
182
|
from checkpointer import checkpoint, PickleStorage, MemoryStorage
|
156
183
|
|
157
|
-
@checkpoint(format="pickle") #
|
184
|
+
@checkpoint(format="pickle") # Short for format=PickleStorage
|
158
185
|
def disk_cached(x: int) -> int:
|
159
186
|
return x ** 2
|
160
187
|
|
161
|
-
@checkpoint(format="memory") #
|
188
|
+
@checkpoint(format="memory") # Short for format=MemoryStorage
|
162
189
|
def memory_cached(x: int) -> int:
|
163
190
|
return x * 10
|
164
191
|
```
|
@@ -174,9 +201,9 @@ from checkpointer import checkpoint, Storage
|
|
174
201
|
from datetime import datetime
|
175
202
|
|
176
203
|
class CustomStorage(Storage):
|
204
|
+
def store(self, path, data): ... # Save the checkpoint data
|
177
205
|
def exists(self, path) -> bool: ... # Check if a checkpoint exists at the given path
|
178
206
|
def checkpoint_date(self, path) -> datetime: ... # Return the date the checkpoint was created
|
179
|
-
def store(self, path, data): ... # Save the checkpoint data
|
180
207
|
def load(self, path): ... # Return the checkpoint data
|
181
208
|
def delete(self, path): ... # Delete the checkpoint
|
182
209
|
|
@@ -191,14 +218,15 @@ Using a custom backend lets you tailor storage to your application, whether it i
|
|
191
218
|
|
192
219
|
## Configuration Options ⚙️
|
193
220
|
|
194
|
-
| Option
|
195
|
-
|
196
|
-
| `
|
197
|
-
| `
|
198
|
-
| `
|
199
|
-
| `
|
200
|
-
| `
|
201
|
-
| `
|
221
|
+
| Option | Type | Default | Description |
|
222
|
+
|-----------------|-----------------------------------|----------------------|------------------------------------------------|
|
223
|
+
| `capture` | `bool` | `False` | Include captured variables in function hashes. |
|
224
|
+
| `format` | `"pickle"`, `"memory"`, `Storage` | `"pickle"` | Storage backend format. |
|
225
|
+
| `root_path` | `Path`, `str`, or `None` | ~/.cache/checkpoints | Root directory for storing checkpoints. |
|
226
|
+
| `when` | `bool` | `True` | Enable or disable checkpointing. |
|
227
|
+
| `verbosity` | `0` or `1` | `1` | Logging verbosity. |
|
228
|
+
| `path` | `Callable[..., str]` | `None` | Custom path for checkpoint storage. |
|
229
|
+
| `should_expire` | `Callable[[datetime], bool]` | `None` | Custom expiration logic. |
|
202
230
|
|
203
231
|
---
|
204
232
|
|
@@ -220,13 +248,13 @@ async def async_compute_sum(a: int, b: int) -> int:
|
|
220
248
|
|
221
249
|
async def main():
|
222
250
|
result1 = compute_square(5)
|
223
|
-
print(result1)
|
251
|
+
print(result1) # Outputs 25
|
224
252
|
|
225
253
|
result2 = await async_compute_sum(3, 7)
|
226
|
-
print(result2)
|
254
|
+
print(result2) # Outputs 10
|
227
255
|
|
228
|
-
result3 = async_compute_sum.get(3, 7)
|
229
|
-
print(result3)
|
256
|
+
result3 = await async_compute_sum.get(3, 7)
|
257
|
+
print(result3) # Outputs 10
|
230
258
|
|
231
259
|
asyncio.run(main())
|
232
260
|
```
|
@@ -0,0 +1,16 @@
|
|
1
|
+
checkpointer/__init__.py,sha256=ZJ6frUNgkklUi85b5uXTyTfRzMvZgQOJY-ZOnu7jh78,777
|
2
|
+
checkpointer/checkpoint.py,sha256=FeizwZf0r6j_xy8EOyDKXqcfCNNZnUYBziVbxPu9kwE,6284
|
3
|
+
checkpointer/fn_ident.py,sha256=_GyIfoUvEpjZ4dUAa04NK4pJdSmDAXuufjt7z2xQP8w,4316
|
4
|
+
checkpointer/object_hash.py,sha256=ekpKXtbKtHBl5e9s-uyng8qOHTFl9CCT6QHlQTZTQn8,6860
|
5
|
+
checkpointer/print_checkpoint.py,sha256=21aeqgM9CMjNAJyScqFmXCWWfh3jBIn7o7i5zJkZGaA,1369
|
6
|
+
checkpointer/test_checkpointer.py,sha256=qpG_p4DVMlOBxt71v93-GTKve08EQaExFAf6xSv0wUg,3821
|
7
|
+
checkpointer/utils.py,sha256=Rvm2NaJHtPTusM7fyHz_w9HUy_fqQfx8S1fr5CBWGL0,3047
|
8
|
+
checkpointer/storages/__init__.py,sha256=Kl4Og5jhYxn6m3tB_kTMsabf4_eWVLmFVAoC-pikNQE,301
|
9
|
+
checkpointer/storages/bcolz_storage.py,sha256=3QkSUSeG5s2kFuVV_LZpzMn1A5E7kqC7jk7w35c0NyQ,2314
|
10
|
+
checkpointer/storages/memory_storage.py,sha256=S5ayOZE_CyaFQJ-vSgObTanldPzG3gh3NksjNAc7vsk,1282
|
11
|
+
checkpointer/storages/pickle_storage.py,sha256=lJ0ton9ib3eifiny8XtPSNsx-w4Cm8oYUlbmKob34xU,1554
|
12
|
+
checkpointer/storages/storage.py,sha256=_m18Z8TKrdAbi6YYYQmuNOnhna4RB2sJDn1v3liaU3U,721
|
13
|
+
checkpointer-2.5.0.dist-info/METADATA,sha256=yd3D8zAWdCe4011MLBwknwDvSYx3LGGSmk6AzDXmMUg,10647
|
14
|
+
checkpointer-2.5.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
15
|
+
checkpointer-2.5.0.dist-info/licenses/LICENSE,sha256=9xVsdtv_-uSyY9Xl9yujwAPm4-mjcCLeVy-ljwXEWbo,1059
|
16
|
+
checkpointer-2.5.0.dist-info/RECORD,,
|
@@ -1,4 +1,4 @@
|
|
1
|
-
Copyright
|
1
|
+
Copyright 2018-2025 Hampus Hallman
|
2
2
|
|
3
3
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
4
4
|
|
checkpointer/function_body.py
DELETED
@@ -1,46 +0,0 @@
|
|
1
|
-
import inspect
|
2
|
-
import relib.hashing as hashing
|
3
|
-
from collections.abc import Callable
|
4
|
-
from types import FunctionType, CodeType
|
5
|
-
from pathlib import Path
|
6
|
-
from .utils import unwrap_fn
|
7
|
-
|
8
|
-
cwd = Path.cwd()
|
9
|
-
|
10
|
-
def get_fn_path(fn: Callable) -> Path:
|
11
|
-
return Path(inspect.getfile(fn)).resolve()
|
12
|
-
|
13
|
-
def get_function_body(fn: Callable) -> str:
|
14
|
-
# TODO: Strip comments
|
15
|
-
lines = inspect.getsourcelines(fn)[0]
|
16
|
-
lines = [line.rstrip() for line in lines]
|
17
|
-
lines = [line for line in lines if line]
|
18
|
-
return "\n".join(lines)
|
19
|
-
|
20
|
-
def get_code_children(code: CodeType) -> list[str]:
|
21
|
-
consts = [const for const in code.co_consts if isinstance(const, CodeType)]
|
22
|
-
children = [child for const in consts for child in get_code_children(const)]
|
23
|
-
return list(code.co_names) + children
|
24
|
-
|
25
|
-
def is_user_fn(candidate_fn, cleared_fns: set[Callable]) -> bool:
|
26
|
-
return isinstance(candidate_fn, FunctionType) \
|
27
|
-
and candidate_fn not in cleared_fns \
|
28
|
-
and cwd in get_fn_path(candidate_fn).parents
|
29
|
-
|
30
|
-
def append_fn_children(cleared_fns: set[Callable], fn: Callable) -> None:
|
31
|
-
code_children = get_code_children(fn.__code__)
|
32
|
-
fn_children = [unwrap_fn(fn.__globals__.get(co_name, None)) for co_name in code_children]
|
33
|
-
fn_children = [child for child in fn_children if is_user_fn(child, cleared_fns)]
|
34
|
-
cleared_fns.update(fn_children)
|
35
|
-
for child_fn in fn_children:
|
36
|
-
append_fn_children(cleared_fns, child_fn)
|
37
|
-
|
38
|
-
def get_fn_children(fn: Callable) -> list[Callable]:
|
39
|
-
cleared_fns: set[Callable] = set()
|
40
|
-
append_fn_children(cleared_fns, fn)
|
41
|
-
return sorted(cleared_fns, key=lambda fn: fn.__name__)
|
42
|
-
|
43
|
-
def get_function_hash(fn: Callable) -> str:
|
44
|
-
fns = [fn] + get_fn_children(fn)
|
45
|
-
fn_bodies = list(map(get_function_body, fns))
|
46
|
-
return hashing.hash(fn_bodies)
|
@@ -1,13 +0,0 @@
|
|
1
|
-
checkpointer/__init__.py,sha256=22K2KXw5OV6wARX_tC0JwOBjFolcAgetarPg8thN4pk,363
|
2
|
-
checkpointer/checkpoint.py,sha256=NE_3f0qGabovELFUespUZ31CnKJIbNuH6SllNL_dais,4703
|
3
|
-
checkpointer/function_body.py,sha256=92mnTY9d_JhKnKugeySYRP6qhU4fH6F6zesb7h2pEi0,1720
|
4
|
-
checkpointer/print_checkpoint.py,sha256=21aeqgM9CMjNAJyScqFmXCWWfh3jBIn7o7i5zJkZGaA,1369
|
5
|
-
checkpointer/types.py,sha256=SslunQTXxovFuGOR_VKfL7z5Vif9RD1PPx0J1FQdGLw,564
|
6
|
-
checkpointer/utils.py,sha256=UrQt689UHUjl7kXpTbUCGkHUgQZllByX2rbuvZdt9vk,368
|
7
|
-
checkpointer/storages/bcolz_storage.py,sha256=UoeREc3oS8skFClu9sULpgpqbIVcp3tVd8CeYfAe5yM,2220
|
8
|
-
checkpointer/storages/memory_storage.py,sha256=RQ4WTVapxJGVPv1DNlb9VFTifxtyQy8YVo8fwaRLfdk,692
|
9
|
-
checkpointer/storages/pickle_storage.py,sha256=nyrBWLXKnyzXgZIMwrpWUOAGRozpX3jL9pCyCV29e4E,787
|
10
|
-
checkpointer-2.0.2.dist-info/METADATA,sha256=kRrURoPrW0vf1xkMTHTxKR4QbclBF1zhUxbD-m8FsM4,9076
|
11
|
-
checkpointer-2.0.2.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
|
12
|
-
checkpointer-2.0.2.dist-info/licenses/LICENSE,sha256=0cmUKqBotzbBcysIexd52AhjwbphhlGYiWbvg5l2QAU,1054
|
13
|
-
checkpointer-2.0.2.dist-info/RECORD,,
|