forked from horovod/horovod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.py
113 lines (96 loc) · 3.76 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import datetime
import errno
import os
import threading
import cloudpickle
class Cache(object):
"""
Cache the function calls
"""
def __init__(self, cache_folder, cache_staleness_threshold_in_minutes,
parameters_hash):
self._cache_file = os.path.join(cache_folder, 'cache.bin')
try:
# If folder exists, does not do anything.
os.makedirs(cache_folder)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if not os.path.isfile(self._cache_file):
with open(self._cache_file, 'wb') as cf:
cloudpickle.dump({'parameters_hash': parameters_hash}, cf)
with open(self._cache_file, 'rb') as cf:
try:
content = cloudpickle.load(cf)
except Exception as e:
print(
'There is an error with reading cache file. You '
'can delete the corrupt file: {cache_file}.'.format(
cache_file=self._cache_file))
raise
if content.get('parameters_hash', None) == parameters_hash:
# If previous cache was for the same set of parameters, use it.
self._content = content
else:
self._content = {'parameters_hash': parameters_hash}
self._cache_staleness_threshold = \
datetime.timedelta(minutes=cache_staleness_threshold_in_minutes)
self._lock = threading.Lock()
def get(self, key):
self._lock.acquire()
timestamp, val = self._content.get(key, (None, None))
self._lock.release()
if timestamp:
if timestamp >= datetime.datetime.now() - self._cache_staleness_threshold:
return val
else:
return None
def put(self, key, val):
self._lock.acquire()
self._content[key] = (datetime.datetime.now(), val)
try:
with open(self._cache_file, 'wb') as cf:
cloudpickle.dump(self._content, cf)
finally:
self._lock.release()
def use_cache():
"""
If used to decorate a function and if fn_cache is set, it will store the
output of the function if the output is not None. If a function output
is None, the execution result will not be cached.
:return:
"""
def wrap(func):
def wrap_f(*args, **kwargs):
fn_cache = kwargs.pop('fn_cache')
if fn_cache is None:
results = func(*args, **kwargs)
else:
cached_result = fn_cache.get(
(func.__name__, tuple(args[0]), frozenset(kwargs.items())))
if cached_result is not None:
return cached_result
else:
results = func(*args, **kwargs)
if results is not None:
fn_cache.put(
(func.__name__, tuple(args[0]),
frozenset(kwargs.items())),
results)
return results
return wrap_f
return wrap