Skip to content

Commit f6128ba

Browse files
committed
Add set_cache_tll
1 parent 24fc595 commit f6128ba

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

phiml/dataclasses/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,6 @@
4747
from ._dataclasses import sliceable, data_fields, non_data_fields, config_fields, special_fields, replace, copy, getitem, equal, data_eq
4848

4949
from ._parallel import parallel_compute, parallel_property
50-
from ._tensor_cache import on_load_into_memory, get_cache_files
50+
from ._tensor_cache import on_load_into_memory, get_cache_files, set_cache_ttl
5151

5252
__all__ = [key for key in globals().keys() if not key.startswith('_')]

phiml/dataclasses/_tensor_cache.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,12 +221,14 @@ def write_to_h5(t: Tensor, name: str, f: h5py.File, ref: H5Source):
221221
@dataclasses.dataclass
222222
class SoftCache:
223223
"""Temporarily keep strong references to data to prevent immediate garbage collection"""
224-
ttl: float # time to live (seconds)
224+
ttl: Optional[float] # time to live (seconds)
225225
strong: list # temporary strong references to cached data
226226
cleaner: Thread = None
227227
lock: Lock = Lock()
228228

229229
def add(self, value):
230+
if self.ttl is None:
231+
return
230232
expire_time = time.time() + self.ttl
231233
with self.lock:
232234
self.strong.append((value, expire_time))
@@ -250,3 +252,14 @@ def cleaner():
250252

251253

252254
_CACHE = SoftCache(2., [])
255+
256+
257+
def set_cache_ttl(ttl_seconds: Optional[float]):
258+
"""
259+
Sets the time to live (TTL) for data loaded into memory for disk-backed tensors.
260+
This function should be called before the tensor cache is used.
261+
262+
Args:
263+
ttl_seconds: Time to live. If `None`, data will be unallocated immediately after use.
264+
"""
265+
_CACHE.ttl = ttl_seconds

0 commit comments

Comments
 (0)