fuzzymemo 0.4.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.
- fuzzymemo/__init__.py +21 -0
- fuzzymemo/core.py +280 -0
- fuzzymemo/governor.py +162 -0
- fuzzymemo/observability.py +51 -0
- fuzzymemo/py.typed +0 -0
- fuzzymemo/superopt.py +74 -0
- fuzzymemo/turbo.py +408 -0
- fuzzymemo-0.4.0.dist-info/METADATA +160 -0
- fuzzymemo-0.4.0.dist-info/RECORD +11 -0
- fuzzymemo-0.4.0.dist-info/WHEEL +4 -0
- fuzzymemo-0.4.0.dist-info/licenses/LICENSE +21 -0
fuzzymemo/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from .core import CacheStats, fuzzy_cache
|
|
2
|
+
from .governor import CPUGovernor, SystemGovernor, default_cpu_percent, default_ram_percent
|
|
3
|
+
from .observability import format_json_event, format_prometheus
|
|
4
|
+
from .superopt import SuperoptResult, superoptimize
|
|
5
|
+
from .turbo import TurboStats, auto_turbo
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"fuzzy_cache",
|
|
9
|
+
"CacheStats",
|
|
10
|
+
"superoptimize",
|
|
11
|
+
"SuperoptResult",
|
|
12
|
+
"CPUGovernor",
|
|
13
|
+
"SystemGovernor",
|
|
14
|
+
"default_cpu_percent",
|
|
15
|
+
"default_ram_percent",
|
|
16
|
+
"format_prometheus",
|
|
17
|
+
"format_json_event",
|
|
18
|
+
"auto_turbo",
|
|
19
|
+
"TurboStats",
|
|
20
|
+
]
|
|
21
|
+
__version__ = "0.4.0"
|
fuzzymemo/core.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import math
|
|
5
|
+
import threading
|
|
6
|
+
import time
|
|
7
|
+
from collections import OrderedDict
|
|
8
|
+
from typing import Any, Callable, NamedTuple, Sequence
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CacheStats(NamedTuple):
|
|
12
|
+
hits: int
|
|
13
|
+
misses: int
|
|
14
|
+
evictions: int
|
|
15
|
+
expirations: int
|
|
16
|
+
bypasses: int
|
|
17
|
+
currsize: int
|
|
18
|
+
maxsize: int
|
|
19
|
+
hit_rate: float
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _validate_config(
|
|
23
|
+
tolerances: float | int | None | Sequence[float | int | None],
|
|
24
|
+
maxsize: int,
|
|
25
|
+
ttl: float | None,
|
|
26
|
+
) -> tuple[float | None, ...]:
|
|
27
|
+
if isinstance(tolerances, (int, float)) or tolerances is None:
|
|
28
|
+
tol_tuple: tuple[float | None, ...] = (None if tolerances is None else float(tolerances),)
|
|
29
|
+
else:
|
|
30
|
+
tol_tuple = tuple(None if t is None else float(t) for t in tolerances)
|
|
31
|
+
|
|
32
|
+
if len(tol_tuple) == 0:
|
|
33
|
+
raise ValueError("tolerances must contain at least one element.")
|
|
34
|
+
|
|
35
|
+
for i, tol in enumerate(tol_tuple):
|
|
36
|
+
if tol is not None and (not math.isfinite(tol) or tol <= 0.0):
|
|
37
|
+
raise ValueError(f"Tolerance at index {i} must be a finite positive number or None, got {tol!r}.")
|
|
38
|
+
|
|
39
|
+
if not isinstance(maxsize, int) or maxsize <= 0:
|
|
40
|
+
raise ValueError(f"maxsize must be a positive integer, got {maxsize!r}.")
|
|
41
|
+
|
|
42
|
+
if ttl is not None and (not math.isfinite(ttl) or ttl <= 0.0):
|
|
43
|
+
raise ValueError(f"ttl must be a finite positive number or None, got {ttl!r}.")
|
|
44
|
+
|
|
45
|
+
return tol_tuple
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def fuzzy_cache(
|
|
49
|
+
tolerances: float | int | None | Sequence[float | int | None],
|
|
50
|
+
maxsize: int = 4096,
|
|
51
|
+
interpolate: bool = False,
|
|
52
|
+
ttl: float | None = None,
|
|
53
|
+
thread_safe: bool = True,
|
|
54
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
55
|
+
"""
|
|
56
|
+
Dynamically compiles a zero-overhead approximate memoization wrapper.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
tolerances: Bucket width per positional argument (float > 0) or None for exact match.
|
|
60
|
+
maxsize: Maximum number of cached grid points (O(1) LRU eviction).
|
|
61
|
+
interpolate: Enable axial linear interpolation (requires numeric scalar return values).
|
|
62
|
+
ttl: Optional time-to-live in seconds for cached entries.
|
|
63
|
+
thread_safe: Protect cache mutations with a threading.Lock (safe for multi-threaded apps).
|
|
64
|
+
"""
|
|
65
|
+
tol_tuple = _validate_config(tolerances, maxsize, ttl)
|
|
66
|
+
n = len(tol_tuple)
|
|
67
|
+
fuzzy_indices = [i for i, t in enumerate(tol_tuple) if t is not None]
|
|
68
|
+
use_interp = interpolate and len(fuzzy_indices) > 0
|
|
69
|
+
args_sig = ", ".join(f"a{i}" for i in range(n))
|
|
70
|
+
|
|
71
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
72
|
+
cache: OrderedDict[Any, Any] = OrderedDict()
|
|
73
|
+
# [hits, misses, evictions, expirations, bypasses]
|
|
74
|
+
stats = [0, 0, 0, 0, 0]
|
|
75
|
+
lock = threading.Lock() if thread_safe else None
|
|
76
|
+
miss_sentinel = object()
|
|
77
|
+
|
|
78
|
+
env: dict[str, Any] = {
|
|
79
|
+
"_func": func,
|
|
80
|
+
"_cache": cache,
|
|
81
|
+
"_stats": stats,
|
|
82
|
+
"_maxsize": maxsize,
|
|
83
|
+
"_MISS": miss_sentinel,
|
|
84
|
+
"_floor": math.floor,
|
|
85
|
+
"_isfinite": math.isfinite,
|
|
86
|
+
"_lock": lock,
|
|
87
|
+
"_monotonic": time.monotonic,
|
|
88
|
+
"_ttl": float(ttl) if ttl is not None else None,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
for i, tol in enumerate(tol_tuple):
|
|
92
|
+
if tol is not None:
|
|
93
|
+
env[f"_t{i}"] = tol
|
|
94
|
+
env[f"_inv{i}"] = 1.0 / tol
|
|
95
|
+
|
|
96
|
+
# Guard against NaN / Inf inputs on fuzzy dimensions
|
|
97
|
+
if fuzzy_indices:
|
|
98
|
+
finite_checks = " and ".join(f"_isfinite(a{i})" for i in fuzzy_indices)
|
|
99
|
+
guard_block = (
|
|
100
|
+
f" if not ({finite_checks}):\n"
|
|
101
|
+
f" _stats[4] += 1\n"
|
|
102
|
+
f" return _func({args_sig})\n"
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
guard_block = ""
|
|
106
|
+
|
|
107
|
+
# Build _get(key) helper (handles LRU + optional TTL + optional Lock)
|
|
108
|
+
call_parts = []
|
|
109
|
+
for i, tol in enumerate(tol_tuple):
|
|
110
|
+
key_ref = "key" if n == 1 else f"key[{i}]"
|
|
111
|
+
call_parts.append(key_ref if tol is None else f"{key_ref} * _t{i}")
|
|
112
|
+
call_expr = ", ".join(call_parts)
|
|
113
|
+
|
|
114
|
+
if thread_safe:
|
|
115
|
+
if ttl is None:
|
|
116
|
+
get_fn = f"""
|
|
117
|
+
def _get(key):
|
|
118
|
+
with _lock:
|
|
119
|
+
res = _cache.get(key, _MISS)
|
|
120
|
+
if res is not _MISS:
|
|
121
|
+
_cache.move_to_end(key)
|
|
122
|
+
_stats[0] += 1
|
|
123
|
+
return res
|
|
124
|
+
res = _func({call_expr})
|
|
125
|
+
with _lock:
|
|
126
|
+
_stats[1] += 1
|
|
127
|
+
if key not in _cache:
|
|
128
|
+
if len(_cache) >= _maxsize:
|
|
129
|
+
_cache.popitem(last=False)
|
|
130
|
+
_stats[2] += 1
|
|
131
|
+
_cache[key] = res
|
|
132
|
+
return res
|
|
133
|
+
""".strip()
|
|
134
|
+
else:
|
|
135
|
+
get_fn = f"""
|
|
136
|
+
def _get(key):
|
|
137
|
+
now = _monotonic()
|
|
138
|
+
with _lock:
|
|
139
|
+
entry = _cache.get(key, _MISS)
|
|
140
|
+
if entry is not _MISS:
|
|
141
|
+
if now < entry[1]:
|
|
142
|
+
_cache.move_to_end(key)
|
|
143
|
+
_stats[0] += 1
|
|
144
|
+
return entry[0]
|
|
145
|
+
del _cache[key]
|
|
146
|
+
_stats[3] += 1
|
|
147
|
+
res = _func({call_expr})
|
|
148
|
+
exp = _monotonic() + _ttl
|
|
149
|
+
with _lock:
|
|
150
|
+
_stats[1] += 1
|
|
151
|
+
if key not in _cache and len(_cache) >= _maxsize:
|
|
152
|
+
_cache.popitem(last=False)
|
|
153
|
+
_stats[2] += 1
|
|
154
|
+
_cache[key] = (res, exp)
|
|
155
|
+
return res
|
|
156
|
+
""".strip()
|
|
157
|
+
else:
|
|
158
|
+
if ttl is None:
|
|
159
|
+
get_fn = f"""
|
|
160
|
+
def _get(key):
|
|
161
|
+
res = _cache.get(key, _MISS)
|
|
162
|
+
if res is not _MISS:
|
|
163
|
+
_cache.move_to_end(key)
|
|
164
|
+
_stats[0] += 1
|
|
165
|
+
return res
|
|
166
|
+
_stats[1] += 1
|
|
167
|
+
res = _func({call_expr})
|
|
168
|
+
if len(_cache) >= _maxsize:
|
|
169
|
+
_cache.popitem(last=False)
|
|
170
|
+
_stats[2] += 1
|
|
171
|
+
_cache[key] = res
|
|
172
|
+
return res
|
|
173
|
+
""".strip()
|
|
174
|
+
else:
|
|
175
|
+
get_fn = f"""
|
|
176
|
+
def _get(key):
|
|
177
|
+
now = _monotonic()
|
|
178
|
+
entry = _cache.get(key, _MISS)
|
|
179
|
+
if entry is not _MISS:
|
|
180
|
+
if now < entry[1]:
|
|
181
|
+
_cache.move_to_end(key)
|
|
182
|
+
_stats[0] += 1
|
|
183
|
+
return entry[0]
|
|
184
|
+
del _cache[key]
|
|
185
|
+
_stats[3] += 1
|
|
186
|
+
_stats[1] += 1
|
|
187
|
+
res = _func({call_expr})
|
|
188
|
+
if len(_cache) >= _maxsize:
|
|
189
|
+
_cache.popitem(last=False)
|
|
190
|
+
_stats[2] += 1
|
|
191
|
+
_cache[key] = (res, now + _ttl)
|
|
192
|
+
return res
|
|
193
|
+
""".strip()
|
|
194
|
+
|
|
195
|
+
if not use_interp:
|
|
196
|
+
key_parts = []
|
|
197
|
+
for i, tol in enumerate(tol_tuple):
|
|
198
|
+
if tol is None:
|
|
199
|
+
key_parts.append(f"a{i}")
|
|
200
|
+
else:
|
|
201
|
+
key_parts.append(f"int(a{i} * _inv{i} + (0.5 if a{i} >= 0 else -0.5))")
|
|
202
|
+
key_expr = key_parts[0] if n == 1 else f"({', '.join(key_parts)})"
|
|
203
|
+
|
|
204
|
+
wrapper_fn = f"""
|
|
205
|
+
def wrapper({args_sig}):
|
|
206
|
+
{guard_block} return _get({key_expr})
|
|
207
|
+
""".strip()
|
|
208
|
+
else:
|
|
209
|
+
base_key_parts = []
|
|
210
|
+
setup_lines = []
|
|
211
|
+
for i, tol in enumerate(tol_tuple):
|
|
212
|
+
if tol is None:
|
|
213
|
+
base_key_parts.append(f"a{i}")
|
|
214
|
+
else:
|
|
215
|
+
base_key_parts.append(f"b{i}")
|
|
216
|
+
setup_lines.append(f" s{i} = a{i} * _inv{i}")
|
|
217
|
+
setup_lines.append(f" b{i} = _floor(s{i})")
|
|
218
|
+
setup_lines.append(f" w{i} = s{i} - b{i}")
|
|
219
|
+
|
|
220
|
+
base_key_expr = base_key_parts[0] if n == 1 else f"({', '.join(base_key_parts)})"
|
|
221
|
+
interp_lines = []
|
|
222
|
+
for idx in fuzzy_indices:
|
|
223
|
+
if n == 1:
|
|
224
|
+
neighbor_expr = f"b{idx} + 1"
|
|
225
|
+
else:
|
|
226
|
+
parts = list(base_key_parts)
|
|
227
|
+
parts[idx] = f"b{idx} + 1"
|
|
228
|
+
neighbor_expr = f"({', '.join(parts)})"
|
|
229
|
+
interp_lines.append(f" if w{idx}:")
|
|
230
|
+
interp_lines.append(f" val += w{idx} * (_get({neighbor_expr}) - base)")
|
|
231
|
+
|
|
232
|
+
wrapper_fn = f"""
|
|
233
|
+
def wrapper({args_sig}):
|
|
234
|
+
{guard_block}{chr(10).join(setup_lines)}
|
|
235
|
+
base = _get({base_key_expr})
|
|
236
|
+
val = base
|
|
237
|
+
{chr(10).join(interp_lines)}
|
|
238
|
+
return val
|
|
239
|
+
""".strip()
|
|
240
|
+
|
|
241
|
+
source = f"{get_fn}\n\n{wrapper_fn}"
|
|
242
|
+
exec(source, env)
|
|
243
|
+
wrapper = env["wrapper"]
|
|
244
|
+
functools.update_wrapper(wrapper, func)
|
|
245
|
+
|
|
246
|
+
def cache_info() -> CacheStats:
|
|
247
|
+
if lock is not None:
|
|
248
|
+
with lock:
|
|
249
|
+
h, m, e, x, b = stats
|
|
250
|
+
sz = len(cache)
|
|
251
|
+
else:
|
|
252
|
+
h, m, e, x, b = stats
|
|
253
|
+
sz = len(cache)
|
|
254
|
+
total = h + m
|
|
255
|
+
return CacheStats(
|
|
256
|
+
hits=h,
|
|
257
|
+
misses=m,
|
|
258
|
+
evictions=e,
|
|
259
|
+
expirations=x,
|
|
260
|
+
bypasses=b,
|
|
261
|
+
currsize=sz,
|
|
262
|
+
maxsize=maxsize,
|
|
263
|
+
hit_rate=(h / total * 100.0) if total else 0.0,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def cache_clear() -> None:
|
|
267
|
+
if lock is not None:
|
|
268
|
+
with lock:
|
|
269
|
+
cache.clear()
|
|
270
|
+
stats[:] = [0, 0, 0, 0, 0]
|
|
271
|
+
else:
|
|
272
|
+
cache.clear()
|
|
273
|
+
stats[:] = [0, 0, 0, 0, 0]
|
|
274
|
+
|
|
275
|
+
wrapper.cache_info = cache_info
|
|
276
|
+
wrapper.cache_clear = cache_clear
|
|
277
|
+
wrapper.generated_code = source
|
|
278
|
+
return wrapper
|
|
279
|
+
|
|
280
|
+
return decorator
|
fuzzymemo/governor.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import threading
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Callable
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import psutil
|
|
11
|
+
_HAS_PSUTIL = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
psutil = None
|
|
14
|
+
_HAS_PSUTIL = False
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def default_cpu_percent() -> float:
|
|
18
|
+
'''Returns current host CPU utilization percentage (0.0 - 100.0+).'''
|
|
19
|
+
if _HAS_PSUTIL:
|
|
20
|
+
return float(psutil.cpu_percent(interval=None))
|
|
21
|
+
if hasattr(os, "getloadavg"):
|
|
22
|
+
load_1m = os.getloadavg()[0]
|
|
23
|
+
cores = os.cpu_count() or 1
|
|
24
|
+
return (load_1m / cores) * 100.0
|
|
25
|
+
return 0.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def default_ram_percent() -> float:
|
|
29
|
+
'''Returns current host RAM utilization percentage (0.0 - 100.0).'''
|
|
30
|
+
if _HAS_PSUTIL:
|
|
31
|
+
return float(psutil.virtual_memory().percent)
|
|
32
|
+
return 0.0
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CPUGovernor:
|
|
36
|
+
'''
|
|
37
|
+
Monitors host CPU and RAM pressure with hysteresis, optional background
|
|
38
|
+
daemon polling (zero hot-path syscalls), and multi-process shared state.
|
|
39
|
+
States: "NORMAL" -> "ELEVATED" -> "CRITICAL" (brownout).
|
|
40
|
+
'''
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
elevated_pct: float = 70.0,
|
|
45
|
+
critical_pct: float = 85.0,
|
|
46
|
+
recovery_pct: float = 60.0,
|
|
47
|
+
ram_critical_pct: float = 85.0,
|
|
48
|
+
poll_interval: float = 1.0,
|
|
49
|
+
cpu_provider: Callable[[], float] | None = None,
|
|
50
|
+
ram_provider: Callable[[], float] | None = None,
|
|
51
|
+
on_pressure_change: Callable[[str, str, float], None] | None = None,
|
|
52
|
+
shared_state_path: str | Path | None = None,
|
|
53
|
+
background: bool = False,
|
|
54
|
+
) -> None:
|
|
55
|
+
if not (0.0 <= recovery_pct <= elevated_pct <= critical_pct):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"Thresholds must satisfy 0 <= recovery_pct <= elevated_pct <= critical_pct."
|
|
58
|
+
)
|
|
59
|
+
self.elevated_pct = float(elevated_pct)
|
|
60
|
+
self.critical_pct = float(critical_pct)
|
|
61
|
+
self.recovery_pct = float(recovery_pct)
|
|
62
|
+
self.ram_critical_pct = float(ram_critical_pct)
|
|
63
|
+
self.poll_interval = float(poll_interval)
|
|
64
|
+
self._cpu_provider = cpu_provider or default_cpu_percent
|
|
65
|
+
self._ram_provider = ram_provider or default_ram_percent
|
|
66
|
+
self._on_change = on_pressure_change
|
|
67
|
+
self._shared_path = Path(shared_state_path) if shared_state_path else None
|
|
68
|
+
|
|
69
|
+
self.state: str = "NORMAL"
|
|
70
|
+
self.last_cpu_pct: float = 0.0
|
|
71
|
+
self.last_ram_pct: float = 0.0
|
|
72
|
+
self.ram_pressure: bool = False
|
|
73
|
+
self.transitions: int = 0
|
|
74
|
+
self._last_poll: float = 0.0
|
|
75
|
+
|
|
76
|
+
self._stop_event = threading.Event()
|
|
77
|
+
self._thread: threading.Thread | None = None
|
|
78
|
+
|
|
79
|
+
if cpu_provider is None and _HAS_PSUTIL:
|
|
80
|
+
psutil.cpu_percent(interval=None)
|
|
81
|
+
|
|
82
|
+
if background:
|
|
83
|
+
self.start_background()
|
|
84
|
+
|
|
85
|
+
def start_background(self) -> None:
|
|
86
|
+
if self._thread is not None and self._thread.is_alive():
|
|
87
|
+
return
|
|
88
|
+
self._stop_event.clear()
|
|
89
|
+
interval = max(0.05, self.poll_interval)
|
|
90
|
+
|
|
91
|
+
def _loop() -> None:
|
|
92
|
+
while not self._stop_event.is_set():
|
|
93
|
+
self.poll(force=True)
|
|
94
|
+
self._stop_event.wait(interval)
|
|
95
|
+
|
|
96
|
+
self._thread = threading.Thread(target=_loop, name="fuzzymemo-governor", daemon=True)
|
|
97
|
+
self._thread.start()
|
|
98
|
+
|
|
99
|
+
def stop_background(self) -> None:
|
|
100
|
+
self._stop_event.set()
|
|
101
|
+
if self._thread is not None:
|
|
102
|
+
self._thread.join(timeout=1.0)
|
|
103
|
+
self._thread = None
|
|
104
|
+
|
|
105
|
+
def _sync_shared_state(self, local_state: str) -> str:
|
|
106
|
+
if self._shared_path is None:
|
|
107
|
+
return local_state
|
|
108
|
+
now = time.time()
|
|
109
|
+
ttl = max(3.0, self.poll_interval * 3.0)
|
|
110
|
+
try:
|
|
111
|
+
if local_state == "CRITICAL":
|
|
112
|
+
self._shared_path.write_text(f"CRITICAL:{now:.3f}", encoding="utf-8")
|
|
113
|
+
return "CRITICAL"
|
|
114
|
+
if self._shared_path.exists():
|
|
115
|
+
raw = self._shared_path.read_text(encoding="utf-8").strip()
|
|
116
|
+
parts = raw.split(":")
|
|
117
|
+
if len(parts) == 2 and parts[0] == "CRITICAL":
|
|
118
|
+
ts = float(parts[1])
|
|
119
|
+
if (now - ts) <= ttl:
|
|
120
|
+
return "CRITICAL"
|
|
121
|
+
except Exception:
|
|
122
|
+
pass
|
|
123
|
+
return local_state
|
|
124
|
+
|
|
125
|
+
def poll(self, force: bool = False) -> str:
|
|
126
|
+
now = time.monotonic()
|
|
127
|
+
if not force and (now - self._last_poll) < self.poll_interval:
|
|
128
|
+
return self.state
|
|
129
|
+
|
|
130
|
+
self._last_poll = now
|
|
131
|
+
cpu = float(self._cpu_provider())
|
|
132
|
+
ram = float(self._ram_provider())
|
|
133
|
+
self.last_cpu_pct = cpu
|
|
134
|
+
self.last_ram_pct = ram
|
|
135
|
+
self.ram_pressure = ram >= self.ram_critical_pct
|
|
136
|
+
|
|
137
|
+
old_state = self.state
|
|
138
|
+
new_state = old_state
|
|
139
|
+
|
|
140
|
+
if cpu >= self.critical_pct:
|
|
141
|
+
new_state = "CRITICAL"
|
|
142
|
+
elif cpu >= self.elevated_pct:
|
|
143
|
+
if old_state == "NORMAL":
|
|
144
|
+
new_state = "ELEVATED"
|
|
145
|
+
elif cpu <= self.recovery_pct:
|
|
146
|
+
new_state = "NORMAL"
|
|
147
|
+
else:
|
|
148
|
+
if old_state == "CRITICAL":
|
|
149
|
+
new_state = "ELEVATED"
|
|
150
|
+
|
|
151
|
+
new_state = self._sync_shared_state(new_state)
|
|
152
|
+
|
|
153
|
+
if new_state != old_state:
|
|
154
|
+
self.state = new_state
|
|
155
|
+
self.transitions += 1
|
|
156
|
+
if self._on_change is not None:
|
|
157
|
+
self._on_change(old_state, new_state, cpu)
|
|
158
|
+
|
|
159
|
+
return self.state
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
SystemGovernor = CPUGovernor
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
_STATE_MAP = {"DISABLED": -1, "NORMAL": 0, "ELEVATED": 1, "CRITICAL": 2}
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def format_prometheus(name: str, stats: Any) -> str:
|
|
11
|
+
'''Formats TurboStats into Prometheus text exposition format.'''
|
|
12
|
+
safe = "".join(c if (c.isalnum() or c == "_") else "_" for c in name)
|
|
13
|
+
p_code = _STATE_MAP.get(stats.pressure_state, 0)
|
|
14
|
+
lines = [
|
|
15
|
+
f'# HELP fuzzymemo_hit_rate Cache hit rate percentage for {safe}',
|
|
16
|
+
f'# TYPE fuzzymemo_hit_rate gauge',
|
|
17
|
+
f'fuzzymemo_hit_rate{{func="{safe}"}} {stats.cache_stats.hit_rate:.4f}',
|
|
18
|
+
f'fuzzymemo_cache_hits_total{{func="{safe}"}} {stats.cache_stats.hits}',
|
|
19
|
+
f'fuzzymemo_cache_misses_total{{func="{safe}"}} {stats.cache_stats.misses}',
|
|
20
|
+
f'fuzzymemo_bypass_calls_total{{func="{safe}"}} {stats.bypass_calls}',
|
|
21
|
+
f'fuzzymemo_cpu_percent{{func="{safe}"}} {stats.cpu_pct:.2f}',
|
|
22
|
+
f'fuzzymemo_ram_percent{{func="{safe}"}} {stats.ram_pct:.2f}',
|
|
23
|
+
f'fuzzymemo_pressure_state{{func="{safe}"}} {p_code}',
|
|
24
|
+
f'fuzzymemo_max_observed_error{{func="{safe}"}} {stats.max_observed_error:.8f}',
|
|
25
|
+
f'fuzzymemo_drift_tightens_total{{func="{safe}"}} {stats.drift_tightens}',
|
|
26
|
+
]
|
|
27
|
+
return "\n".join(lines) + "\n"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def format_json_event(name: str, event: str, stats: Any) -> str:
|
|
31
|
+
'''Formats TurboStats into a single-line JSON log event.'''
|
|
32
|
+
payload = {
|
|
33
|
+
"ts": round(time.time(), 3),
|
|
34
|
+
"component": "fuzzymemo",
|
|
35
|
+
"func": name,
|
|
36
|
+
"event": event,
|
|
37
|
+
"mode": stats.mode,
|
|
38
|
+
"pressure_state": stats.pressure_state,
|
|
39
|
+
"cpu_pct": round(stats.cpu_pct, 2),
|
|
40
|
+
"ram_pct": round(stats.ram_pct, 2),
|
|
41
|
+
"ram_pressure": stats.ram_pressure,
|
|
42
|
+
"backend": stats.winner_backend,
|
|
43
|
+
"hit_rate": round(stats.cache_stats.hit_rate, 2),
|
|
44
|
+
"hits": stats.cache_stats.hits,
|
|
45
|
+
"misses": stats.cache_stats.misses,
|
|
46
|
+
"bypass_calls": stats.bypass_calls,
|
|
47
|
+
"drift_samples": stats.drift_samples,
|
|
48
|
+
"max_observed_error": stats.max_observed_error,
|
|
49
|
+
"drift_tightens": stats.drift_tightens,
|
|
50
|
+
}
|
|
51
|
+
return json.dumps(payload, separators=(",", ":"))
|
fuzzymemo/py.typed
ADDED
|
File without changes
|
fuzzymemo/superopt.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Callable, NamedTuple
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
from numba import njit
|
|
9
|
+
_HAS_NUMBA = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
njit = None
|
|
12
|
+
_HAS_NUMBA = False
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SuperoptResult(NamedTuple):
|
|
16
|
+
kernel: Callable[..., Any]
|
|
17
|
+
winner_name: str
|
|
18
|
+
median_us: float
|
|
19
|
+
speedup_vs_python: float
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _time_kernel(fn: Callable[..., Any], sample_args: tuple[Any, ...], iters: int = 50) -> float:
|
|
23
|
+
fn(*sample_args)
|
|
24
|
+
t0 = time.perf_counter()
|
|
25
|
+
for _ in range(iters):
|
|
26
|
+
fn(*sample_args)
|
|
27
|
+
return (time.perf_counter() - t0) / iters
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def superoptimize(
|
|
31
|
+
func: Callable[..., Any],
|
|
32
|
+
sample_args: tuple[Any, ...],
|
|
33
|
+
allow_fastmath: bool = True,
|
|
34
|
+
rtol: float = 1e-5,
|
|
35
|
+
bench_iters: int = 50,
|
|
36
|
+
) -> SuperoptResult:
|
|
37
|
+
'''
|
|
38
|
+
Races pure Python against compiled Numba @njit variants on the local CPU,
|
|
39
|
+
validates accuracy against the Python baseline, and returns the fastest kernel.
|
|
40
|
+
'''
|
|
41
|
+
baseline_val = func(*sample_args)
|
|
42
|
+
base_time = _time_kernel(func, sample_args, iters=bench_iters)
|
|
43
|
+
|
|
44
|
+
best_kernel = func
|
|
45
|
+
best_name = "python"
|
|
46
|
+
best_time = base_time
|
|
47
|
+
|
|
48
|
+
if not _HAS_NUMBA:
|
|
49
|
+
return SuperoptResult(best_kernel, best_name, best_time * 1e6, 1.0)
|
|
50
|
+
|
|
51
|
+
candidates: list[tuple[str, dict[str, Any]]] = [
|
|
52
|
+
("njit_strict", {"fastmath": False, "nogil": True}),
|
|
53
|
+
]
|
|
54
|
+
if allow_fastmath:
|
|
55
|
+
candidates.append(("njit_fastmath", {"fastmath": True, "nogil": True}))
|
|
56
|
+
candidates.append(("njit_fastmath_np", {"fastmath": True, "error_model": "numpy", "nogil": True}))
|
|
57
|
+
|
|
58
|
+
for name, kwargs in candidates:
|
|
59
|
+
try:
|
|
60
|
+
compiled = njit(**kwargs)(func)
|
|
61
|
+
test_val = compiled(*sample_args)
|
|
62
|
+
if isinstance(baseline_val, (int, float)) and isinstance(test_val, (int, float)):
|
|
63
|
+
if not math.isclose(test_val, baseline_val, rel_tol=rtol, abs_tol=1e-9):
|
|
64
|
+
continue
|
|
65
|
+
t = _time_kernel(compiled, sample_args, iters=bench_iters)
|
|
66
|
+
if t < best_time:
|
|
67
|
+
best_time = t
|
|
68
|
+
best_kernel = compiled
|
|
69
|
+
best_name = name
|
|
70
|
+
except Exception:
|
|
71
|
+
continue
|
|
72
|
+
|
|
73
|
+
speedup = base_time / max(1e-12, best_time)
|
|
74
|
+
return SuperoptResult(best_kernel, best_name, best_time * 1e6, speedup)
|
fuzzymemo/turbo.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import functools
|
|
4
|
+
import inspect
|
|
5
|
+
import math
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Callable, NamedTuple, Sequence
|
|
10
|
+
|
|
11
|
+
from .core import CacheStats, _validate_config, fuzzy_cache
|
|
12
|
+
from .governor import CPUGovernor
|
|
13
|
+
from .observability import format_json_event, format_prometheus
|
|
14
|
+
from .superopt import _time_kernel, superoptimize
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TurboStats(NamedTuple):
|
|
18
|
+
mode: str
|
|
19
|
+
pressure_state: str
|
|
20
|
+
cpu_pct: float
|
|
21
|
+
pressure_transitions: int
|
|
22
|
+
winner_backend: str
|
|
23
|
+
kernel_us: float
|
|
24
|
+
cache_lookup_us: float
|
|
25
|
+
cache_worthwhile: bool
|
|
26
|
+
jit_speedup: float
|
|
27
|
+
switches: int
|
|
28
|
+
bypass_calls: int
|
|
29
|
+
cache_stats: CacheStats
|
|
30
|
+
ram_pct: float = 0.0
|
|
31
|
+
ram_pressure: bool = False
|
|
32
|
+
drift_samples: int = 0
|
|
33
|
+
max_observed_error: float = 0.0
|
|
34
|
+
drift_tightens: int = 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _scale_tolerances(
|
|
38
|
+
tol_tuple: tuple[float | None, ...],
|
|
39
|
+
mult: float,
|
|
40
|
+
) -> tuple[float | None, ...]:
|
|
41
|
+
return tuple(None if t is None else t * mult for t in tol_tuple)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def auto_turbo(
|
|
45
|
+
tolerances: float | int | None | Sequence[float | int | None],
|
|
46
|
+
maxsize: int = 4096,
|
|
47
|
+
interpolate: bool = True,
|
|
48
|
+
ttl: float | None = None,
|
|
49
|
+
thread_safe: bool = True,
|
|
50
|
+
use_superopt: bool = True,
|
|
51
|
+
allow_fastmath: bool = True,
|
|
52
|
+
min_hit_rate: float = 0.30,
|
|
53
|
+
check_interval: int = 200,
|
|
54
|
+
cooldown_calls: int = 400,
|
|
55
|
+
min_kernel_us: float | None = None,
|
|
56
|
+
enable_governor: bool = True,
|
|
57
|
+
elevated_cpu_pct: float = 70.0,
|
|
58
|
+
critical_cpu_pct: float = 85.0,
|
|
59
|
+
recovery_cpu_pct: float = 60.0,
|
|
60
|
+
ram_critical_pct: float = 85.0,
|
|
61
|
+
critical_tolerance_mult: float = 3.0,
|
|
62
|
+
governor_poll_interval: float = 1.0,
|
|
63
|
+
background_governor: bool = False,
|
|
64
|
+
shared_state_path: str | Path | None = None,
|
|
65
|
+
cpu_provider: Callable[[], float] | None = None,
|
|
66
|
+
ram_provider: Callable[[], float] | None = None,
|
|
67
|
+
on_pressure_change: Callable[[str, str, float], None] | None = None,
|
|
68
|
+
drift_sample_rate: int = 0,
|
|
69
|
+
max_error: float | None = None,
|
|
70
|
+
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
71
|
+
'''
|
|
72
|
+
4-Layer Adaptive Accelerator (v0.4.0):
|
|
73
|
+
1. Adaptive Auto-Router + Live Drift Auditing (shadow sampling)
|
|
74
|
+
2. Fuzzy Memoizer v4 (sync + native async support)
|
|
75
|
+
3. Micro-Superoptimizer (Numba JIT/SIMD race)
|
|
76
|
+
4. Background CPU/RAM Pressure Governor + Multi-Process Coordination + Observability
|
|
77
|
+
'''
|
|
78
|
+
base_tols = _validate_config(tolerances, maxsize, ttl)
|
|
79
|
+
ram_maxsize = max(16, maxsize // 4)
|
|
80
|
+
|
|
81
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
82
|
+
is_async = inspect.iscoroutinefunction(func)
|
|
83
|
+
init_lock = threading.Lock()
|
|
84
|
+
initialized = False
|
|
85
|
+
|
|
86
|
+
current_tols = base_tols
|
|
87
|
+
mode = "CACHED"
|
|
88
|
+
winner_backend = "async_python" if is_async else "python"
|
|
89
|
+
kernel_us = 0.0
|
|
90
|
+
cache_lookup_us = 0.0
|
|
91
|
+
cache_worthwhile = True
|
|
92
|
+
jit_speedup = 1.0
|
|
93
|
+
switches = 0
|
|
94
|
+
bypass_calls = 0
|
|
95
|
+
|
|
96
|
+
# Drift auditing telemetry
|
|
97
|
+
drift_counter = 0
|
|
98
|
+
drift_samples = 0
|
|
99
|
+
max_observed_error = 0.0
|
|
100
|
+
drift_tightens = 0
|
|
101
|
+
|
|
102
|
+
governor = (
|
|
103
|
+
CPUGovernor(
|
|
104
|
+
elevated_pct=elevated_cpu_pct,
|
|
105
|
+
critical_pct=critical_cpu_pct,
|
|
106
|
+
recovery_pct=recovery_cpu_pct,
|
|
107
|
+
ram_critical_pct=ram_critical_pct,
|
|
108
|
+
poll_interval=governor_poll_interval,
|
|
109
|
+
cpu_provider=cpu_provider,
|
|
110
|
+
ram_provider=ram_provider,
|
|
111
|
+
on_pressure_change=on_pressure_change,
|
|
112
|
+
shared_state_path=shared_state_path,
|
|
113
|
+
background=background_governor,
|
|
114
|
+
)
|
|
115
|
+
if enable_governor
|
|
116
|
+
else None
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# --- ASYNC COROUTINE PATH (WITH SINGLEFLIGHT COALESCING) ---
|
|
120
|
+
if is_async:
|
|
121
|
+
import asyncio
|
|
122
|
+
|
|
123
|
+
async_cache: dict[tuple[Any, ...], Any] = {}
|
|
124
|
+
inflight: dict[tuple[Any, ...], asyncio.Future[Any]] = {}
|
|
125
|
+
a_hits = 0
|
|
126
|
+
a_misses = 0
|
|
127
|
+
|
|
128
|
+
def _quantize_key(args: tuple[Any, ...], tols: tuple[float | None, ...]) -> tuple[Any, ...] | None:
|
|
129
|
+
key = []
|
|
130
|
+
for v, t in zip(args, tols):
|
|
131
|
+
if t is None:
|
|
132
|
+
key.append(v)
|
|
133
|
+
else:
|
|
134
|
+
if not isinstance(v, (int, float)) or not math.isfinite(v):
|
|
135
|
+
return None
|
|
136
|
+
key.append(round(v / t))
|
|
137
|
+
return tuple(key)
|
|
138
|
+
|
|
139
|
+
@functools.wraps(func)
|
|
140
|
+
async def async_wrapper(*args: Any) -> Any:
|
|
141
|
+
nonlocal a_hits, a_misses, bypass_calls
|
|
142
|
+
if governor is not None and not background_governor:
|
|
143
|
+
governor.poll()
|
|
144
|
+
|
|
145
|
+
active_tols = (
|
|
146
|
+
_scale_tolerances(current_tols, critical_tolerance_mult)
|
|
147
|
+
if (governor is not None and governor.state == "CRITICAL")
|
|
148
|
+
else current_tols
|
|
149
|
+
)
|
|
150
|
+
cap = ram_maxsize if (governor is not None and governor.ram_pressure) else maxsize
|
|
151
|
+
while len(async_cache) > cap:
|
|
152
|
+
async_cache.pop(next(iter(async_cache)))
|
|
153
|
+
|
|
154
|
+
key = _quantize_key(args, active_tols)
|
|
155
|
+
if key is None:
|
|
156
|
+
bypass_calls += 1
|
|
157
|
+
return await func(*args)
|
|
158
|
+
|
|
159
|
+
if key in async_cache:
|
|
160
|
+
a_hits += 1
|
|
161
|
+
return async_cache[key]
|
|
162
|
+
|
|
163
|
+
# Coalesce concurrent callers for the same bucket (prevents cache stampede)
|
|
164
|
+
existing_fut = inflight.get(key)
|
|
165
|
+
if existing_fut is not None:
|
|
166
|
+
a_hits += 1
|
|
167
|
+
return await asyncio.shield(existing_fut)
|
|
168
|
+
|
|
169
|
+
a_misses += 1
|
|
170
|
+
loop = asyncio.get_running_loop()
|
|
171
|
+
fut: asyncio.Future[Any] = loop.create_future()
|
|
172
|
+
inflight[key] = fut
|
|
173
|
+
try:
|
|
174
|
+
res = await func(*args)
|
|
175
|
+
if len(async_cache) >= cap:
|
|
176
|
+
async_cache.pop(next(iter(async_cache)))
|
|
177
|
+
async_cache[key] = res
|
|
178
|
+
if not fut.done():
|
|
179
|
+
fut.set_result(res)
|
|
180
|
+
return res
|
|
181
|
+
except BaseException as exc:
|
|
182
|
+
if not fut.done():
|
|
183
|
+
fut.set_exception(exc)
|
|
184
|
+
raise
|
|
185
|
+
finally:
|
|
186
|
+
inflight.pop(key, None)
|
|
187
|
+
|
|
188
|
+
def async_info() -> TurboStats:
|
|
189
|
+
total = a_hits + a_misses
|
|
190
|
+
hr = (a_hits / total * 100.0) if total else 0.0
|
|
191
|
+
cs = CacheStats(a_hits, a_misses, 0, 0, bypass_calls, len(async_cache), maxsize, hr)
|
|
192
|
+
return TurboStats(
|
|
193
|
+
mode=mode,
|
|
194
|
+
pressure_state=governor.state if governor else "DISABLED",
|
|
195
|
+
cpu_pct=governor.last_cpu_pct if governor else 0.0,
|
|
196
|
+
pressure_transitions=governor.transitions if governor else 0,
|
|
197
|
+
winner_backend=winner_backend,
|
|
198
|
+
kernel_us=0.0,
|
|
199
|
+
cache_lookup_us=0.0,
|
|
200
|
+
cache_worthwhile=True,
|
|
201
|
+
jit_speedup=1.0,
|
|
202
|
+
switches=0,
|
|
203
|
+
bypass_calls=bypass_calls,
|
|
204
|
+
cache_stats=cs,
|
|
205
|
+
ram_pct=governor.last_ram_pct if governor else 0.0,
|
|
206
|
+
ram_pressure=governor.ram_pressure if governor else False,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
def async_clear() -> None:
|
|
210
|
+
nonlocal a_hits, a_misses
|
|
211
|
+
async_cache.clear()
|
|
212
|
+
a_hits = 0
|
|
213
|
+
a_misses = 0
|
|
214
|
+
|
|
215
|
+
async_wrapper.turbo_info = async_info
|
|
216
|
+
async_wrapper.cache_clear = async_clear
|
|
217
|
+
async_wrapper.prometheus_metrics = lambda name=func.__name__: format_prometheus(name, async_info())
|
|
218
|
+
async_wrapper.json_status = lambda event="status", name=func.__name__: format_json_event(name, event, async_info())
|
|
219
|
+
async_wrapper.stop_governor = lambda: governor.stop_background() if governor else None
|
|
220
|
+
return async_wrapper
|
|
221
|
+
|
|
222
|
+
# --- SYNC FAST PATH ---
|
|
223
|
+
raw_kernel: Callable[..., Any] = func
|
|
224
|
+
normal_cache: Callable[..., Any]
|
|
225
|
+
elevated_cache: Callable[..., Any]
|
|
226
|
+
critical_cache: Callable[..., Any]
|
|
227
|
+
ram_safe_cache: Callable[..., Any]
|
|
228
|
+
|
|
229
|
+
def _build_tiers(kernel: Callable[..., Any], tols: tuple[float | None, ...]) -> None:
|
|
230
|
+
nonlocal normal_cache, elevated_cache, critical_cache, ram_safe_cache
|
|
231
|
+
wide = _scale_tolerances(tols, critical_tolerance_mult)
|
|
232
|
+
normal_cache = fuzzy_cache(
|
|
233
|
+
tolerances=tols, maxsize=maxsize, interpolate=interpolate, ttl=ttl, thread_safe=thread_safe
|
|
234
|
+
)(kernel)
|
|
235
|
+
elevated_cache = fuzzy_cache(
|
|
236
|
+
tolerances=tols, maxsize=maxsize, interpolate=False, ttl=ttl, thread_safe=thread_safe
|
|
237
|
+
)(kernel)
|
|
238
|
+
critical_cache = fuzzy_cache(
|
|
239
|
+
tolerances=wide,
|
|
240
|
+
maxsize=maxsize,
|
|
241
|
+
interpolate=False,
|
|
242
|
+
ttl=(ttl * 2.0 if ttl is not None else None),
|
|
243
|
+
thread_safe=thread_safe,
|
|
244
|
+
)(kernel)
|
|
245
|
+
ram_safe_cache = fuzzy_cache(
|
|
246
|
+
tolerances=wide,
|
|
247
|
+
maxsize=ram_maxsize,
|
|
248
|
+
interpolate=False,
|
|
249
|
+
ttl=ttl,
|
|
250
|
+
thread_safe=thread_safe,
|
|
251
|
+
)(kernel)
|
|
252
|
+
|
|
253
|
+
_build_tiers(raw_kernel, current_tols)
|
|
254
|
+
|
|
255
|
+
window_calls = 0
|
|
256
|
+
prev_hits = 0
|
|
257
|
+
prev_misses = 0
|
|
258
|
+
bypass_since_switch = 0
|
|
259
|
+
|
|
260
|
+
def _active_cache() -> Callable[..., Any]:
|
|
261
|
+
if governor is None:
|
|
262
|
+
return normal_cache
|
|
263
|
+
if governor.ram_pressure:
|
|
264
|
+
return ram_safe_cache
|
|
265
|
+
st = governor.state
|
|
266
|
+
if st == "CRITICAL":
|
|
267
|
+
return critical_cache
|
|
268
|
+
if st == "ELEVATED":
|
|
269
|
+
return elevated_cache
|
|
270
|
+
return normal_cache
|
|
271
|
+
|
|
272
|
+
def _lazy_init(sample_args: tuple[Any, ...]) -> None:
|
|
273
|
+
nonlocal initialized, raw_kernel, winner_backend
|
|
274
|
+
nonlocal kernel_us, cache_lookup_us, cache_worthwhile, jit_speedup, mode
|
|
275
|
+
|
|
276
|
+
with init_lock:
|
|
277
|
+
if initialized:
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
if use_superopt:
|
|
281
|
+
res = superoptimize(func, sample_args, allow_fastmath=allow_fastmath)
|
|
282
|
+
raw_kernel = res.kernel
|
|
283
|
+
winner_backend = res.winner_name
|
|
284
|
+
kernel_us = res.median_us
|
|
285
|
+
jit_speedup = res.speedup_vs_python
|
|
286
|
+
_build_tiers(raw_kernel, current_tols)
|
|
287
|
+
else:
|
|
288
|
+
kernel_us = _time_kernel(raw_kernel, sample_args, iters=50) * 1e6
|
|
289
|
+
|
|
290
|
+
normal_cache(*sample_args)
|
|
291
|
+
t0 = time.perf_counter()
|
|
292
|
+
for _ in range(50):
|
|
293
|
+
normal_cache(*sample_args)
|
|
294
|
+
cache_lookup_us = ((time.perf_counter() - t0) / 50.0) * 1e6
|
|
295
|
+
normal_cache.cache_clear()
|
|
296
|
+
|
|
297
|
+
threshold_us = (cache_lookup_us * 1.15) if min_kernel_us is None else min_kernel_us
|
|
298
|
+
if kernel_us < threshold_us:
|
|
299
|
+
cache_worthwhile = False
|
|
300
|
+
mode = "BYPASS"
|
|
301
|
+
else:
|
|
302
|
+
cache_worthwhile = True
|
|
303
|
+
mode = "CACHED"
|
|
304
|
+
|
|
305
|
+
initialized = True
|
|
306
|
+
|
|
307
|
+
@functools.wraps(func)
|
|
308
|
+
def wrapper(*args: Any) -> Any:
|
|
309
|
+
nonlocal mode, switches, bypass_calls, window_calls, prev_hits, prev_misses, bypass_since_switch
|
|
310
|
+
nonlocal current_tols, drift_counter, drift_samples, max_observed_error, drift_tightens
|
|
311
|
+
|
|
312
|
+
if not initialized:
|
|
313
|
+
_lazy_init(args)
|
|
314
|
+
|
|
315
|
+
if governor is not None:
|
|
316
|
+
if not background_governor:
|
|
317
|
+
governor.poll()
|
|
318
|
+
if governor.ram_pressure:
|
|
319
|
+
if normal_cache.cache_info().currsize > 0:
|
|
320
|
+
normal_cache.cache_clear()
|
|
321
|
+
return ram_safe_cache(*args)
|
|
322
|
+
if governor.state == "CRITICAL":
|
|
323
|
+
return critical_cache(*args)
|
|
324
|
+
|
|
325
|
+
if mode == "CACHED":
|
|
326
|
+
cache_fn = _active_cache()
|
|
327
|
+
out = cache_fn(*args)
|
|
328
|
+
|
|
329
|
+
# Live Drift Auditing (shadow sampling)
|
|
330
|
+
if drift_sample_rate > 0:
|
|
331
|
+
drift_counter += 1
|
|
332
|
+
if drift_counter >= drift_sample_rate:
|
|
333
|
+
drift_counter = 0
|
|
334
|
+
exact = raw_kernel(*args)
|
|
335
|
+
if isinstance(out, (int, float)) and isinstance(exact, (int, float)):
|
|
336
|
+
err = abs(out - exact)
|
|
337
|
+
drift_samples += 1
|
|
338
|
+
if err > max_observed_error:
|
|
339
|
+
max_observed_error = err
|
|
340
|
+
if max_error is not None and err > max_error:
|
|
341
|
+
current_tols = _scale_tolerances(current_tols, 0.5)
|
|
342
|
+
_build_tiers(raw_kernel, current_tols)
|
|
343
|
+
drift_tightens += 1
|
|
344
|
+
|
|
345
|
+
window_calls += 1
|
|
346
|
+
if window_calls >= check_interval:
|
|
347
|
+
info = cache_fn.cache_info()
|
|
348
|
+
dh = info.hits - prev_hits
|
|
349
|
+
dm = info.misses - prev_misses
|
|
350
|
+
prev_hits, prev_misses = info.hits, info.misses
|
|
351
|
+
window_calls = 0
|
|
352
|
+
total = dh + dm
|
|
353
|
+
if total > 0 and (dh / total) < min_hit_rate:
|
|
354
|
+
mode = "BYPASS"
|
|
355
|
+
bypass_since_switch = 0
|
|
356
|
+
switches += 1
|
|
357
|
+
return out
|
|
358
|
+
|
|
359
|
+
bypass_calls += 1
|
|
360
|
+
if cache_worthwhile:
|
|
361
|
+
bypass_since_switch += 1
|
|
362
|
+
if bypass_since_switch >= cooldown_calls:
|
|
363
|
+
info = _active_cache().cache_info()
|
|
364
|
+
prev_hits, prev_misses = info.hits, info.misses
|
|
365
|
+
window_calls = 0
|
|
366
|
+
mode = "CACHED"
|
|
367
|
+
switches += 1
|
|
368
|
+
return raw_kernel(*args)
|
|
369
|
+
|
|
370
|
+
def turbo_info() -> TurboStats:
|
|
371
|
+
return TurboStats(
|
|
372
|
+
mode=mode,
|
|
373
|
+
pressure_state=governor.state if governor is not None else "DISABLED",
|
|
374
|
+
cpu_pct=governor.last_cpu_pct if governor is not None else 0.0,
|
|
375
|
+
pressure_transitions=governor.transitions if governor is not None else 0,
|
|
376
|
+
winner_backend=winner_backend,
|
|
377
|
+
kernel_us=kernel_us,
|
|
378
|
+
cache_lookup_us=cache_lookup_us,
|
|
379
|
+
cache_worthwhile=cache_worthwhile,
|
|
380
|
+
jit_speedup=jit_speedup,
|
|
381
|
+
switches=switches,
|
|
382
|
+
bypass_calls=bypass_calls,
|
|
383
|
+
cache_stats=_active_cache().cache_info(),
|
|
384
|
+
ram_pct=governor.last_ram_pct if governor is not None else 0.0,
|
|
385
|
+
ram_pressure=governor.ram_pressure if governor is not None else False,
|
|
386
|
+
drift_samples=drift_samples,
|
|
387
|
+
max_observed_error=max_observed_error,
|
|
388
|
+
drift_tightens=drift_tightens,
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
def cache_clear() -> None:
|
|
392
|
+
nonlocal prev_hits, prev_misses, window_calls
|
|
393
|
+
normal_cache.cache_clear()
|
|
394
|
+
elevated_cache.cache_clear()
|
|
395
|
+
critical_cache.cache_clear()
|
|
396
|
+
ram_safe_cache.cache_clear()
|
|
397
|
+
prev_hits = 0
|
|
398
|
+
prev_misses = 0
|
|
399
|
+
window_calls = 0
|
|
400
|
+
|
|
401
|
+
wrapper.turbo_info = turbo_info
|
|
402
|
+
wrapper.cache_clear = cache_clear
|
|
403
|
+
wrapper.prometheus_metrics = lambda name=func.__name__: format_prometheus(name, turbo_info())
|
|
404
|
+
wrapper.json_status = lambda event="status", name=func.__name__: format_json_event(name, event, turbo_info())
|
|
405
|
+
wrapper.stop_governor = lambda: governor.stop_background() if governor else None
|
|
406
|
+
return wrapper
|
|
407
|
+
|
|
408
|
+
return decorator
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fuzzymemo
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Adaptive 4-layer numeric accelerator with Live Drift Auditing, Async Singleflight, Background CPU/RAM Governor, and Prometheus observability.
|
|
5
|
+
Author: Ashutosh
|
|
6
|
+
Maintainer: Ashutosh
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: async,caching,fuzzy,interpolation,jit,load-shedding,memoization,numba,prometheus,quant
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Topic :: System :: Monitoring
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
26
|
+
Provides-Extra: jit
|
|
27
|
+
Requires-Dist: numba>=0.59; extra == 'jit'
|
|
28
|
+
Provides-Extra: monitor
|
|
29
|
+
Requires-Dist: psutil>=5.9; extra == 'monitor'
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# fuzzymemo
|
|
33
|
+
|
|
34
|
+
**Adaptive 4-Layer Numeric Accelerator & Load-Shedding Governor for Python.**
|
|
35
|
+
|
|
36
|
+
[](https://www.python.org/downloads/)
|
|
37
|
+
[](#)
|
|
38
|
+
[](LICENSE)
|
|
39
|
+
|
|
40
|
+
Standard memoization (`functools.lru_cache`) fails on continuous floating-point streams because minor market or sensor jitter causes near-zero hit rates. Meanwhile, OS-level CPU throttling freezes or stalls overloaded VMs rather than degrading gracefully.
|
|
41
|
+
|
|
42
|
+
`fuzzymemo` solves both problems with a single `@auto_turbo` decorator: it auto-calibrates on your hardware, stacks quantized axial interpolation with runtime Numba JIT compilation, sheds CPU/RAM load gracefully during VM spikes, and exposes Prometheus and JSON telemetry out of the box.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## The 4-Layer Architecture
|
|
47
|
+
|
|
48
|
+
1. **Layer 1 — Adaptive Auto-Router (`turbo.py`)**
|
|
49
|
+
Profiles your host CPU on the first call to compare compiled kernel latency against a warm cache lookup. If the kernel is already faster than $1.15\times$ the lookup cost, it locks into `BYPASS` mode (zero lookup tax, zero approximation error). When caching wins, it monitors sliding-window hit rates—automatically bypassing random "chaos storms" and probing back when inputs re-cluster.
|
|
50
|
+
2. **Layer 2 — Fuzzy Memoizer v4 (`core.py`)**
|
|
51
|
+
Compiles a zero-loop fast-path wrapper at decoration time with $O(1)$ bounded LRU eviction, `NaN`/`Inf` safety bypasses, optional TTL, thread safety, and **axial linear interpolation** ($D + 1$ neighbor lookups) to reduce quantization error by orders of magnitude.
|
|
52
|
+
3. **Layer 3 — Micro-Superoptimizer (`superopt.py`)**
|
|
53
|
+
Races pure Python against compiled Numba `@njit` variants (`njit_strict`, `njit_fastmath`, `njit_fastmath_np`), validates numerical accuracy against the Python baseline, and locks in the fastest binary. Falls back cleanly to pure Python when Numba is not installed.
|
|
54
|
+
4. **Layer 4 — Background CPU & RAM Pressure Governor (`governor.py`)**
|
|
55
|
+
Polls host utilization via `psutil` or `os.getloadavg()` in an optional background daemon thread (zero hot-path syscalls) with hysteresis:
|
|
56
|
+
* **`NORMAL` (< 70% CPU):** Tight tolerances with axial linear interpolation.
|
|
57
|
+
* **`ELEVATED` (70%–85% CPU):** Flat nearest-bucket lookups ($1$ lookup vs. $D + 1$).
|
|
58
|
+
* **`CRITICAL` ($\ge$ 85% CPU, Brownout):** Widens tolerances by `critical_tolerance_mult` (default $3\times$) and doubles TTL to drive hit rates toward 99%+ and shed compute before the VM stalls.
|
|
59
|
+
* **`RAM PRESSURE` ($\ge$ 85% RAM):** Clears the primary cache and routes to a compact `maxsize // 4` tier to prevent OOM kills.
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Production Features (v0.4.0)
|
|
64
|
+
|
|
65
|
+
* **Live Drift Auditing:** Shadow-samples 1 out of every `drift_sample_rate` hits against the exact kernel; if error exceeds `max_error`, tolerances automatically halve ($0.5\times$) and cache tiers rebuild.
|
|
66
|
+
* **Native `async`/`await` with Singleflight Coalescing:** Decorate `async def` coroutines directly. Concurrent callers hitting the same quantized bucket share a single in-flight `asyncio.Future`, preventing cache stampedes.
|
|
67
|
+
* **Multi-Process Shared VM State:** Point multiple Python services or workers at a shared `shared_state_path` so a CPU spike triggers coordinated load-shedding across the entire VM.
|
|
68
|
+
* **Zero-Dependency Observability:** Call `.prometheus_metrics()` or `.json_status()` directly on any decorated function.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Verified Benchmarks
|
|
73
|
+
|
|
74
|
+
Measured on an 8-logical-CPU Windows 11 host (Python 3.11.9, Numba + `psutil`, 19/19 tests passing):
|
|
75
|
+
|
|
76
|
+
| Workload | Blind Python | `@auto_turbo` | Speedup | Auto-Calibrated Strategy |
|
|
77
|
+
| :--- | ---: | ---: | ---: | :--- |
|
|
78
|
+
| **Live BTC/USDT Stream** (232 ticks) | `66.70 ms` | **`1.62 ms`** | **`41.1x`** | `njit_strict` + Fuzzy v4 (`CACHED`) |
|
|
79
|
+
| **Robotics 3D IK** (20k frames) | `0.7232 s` | **`0.0472 s`** | **`15.3x`** | `njit_fastmath_np` (`BYPASS`) |
|
|
80
|
+
| **3-Regime Stress Test** (30k ticks) | `1.8904 s` | **`0.1840 s`** | **`10.3x`** | `njit_strict` + Fuzzy v4 + Chaos Bypass |
|
|
81
|
+
| **Geo-Delivery Surge API** (20k reqs) | `0.5156 s` | **`0.0931 s`** | **`5.5x`** | `njit_fastmath_np` + Fuzzy v4 (`CACHED`) |
|
|
82
|
+
| **Trivial Formula Guard** (20k calls) | `0.0019 s` | `0.0039 s` | `0.5x` | `python` (`BYPASS` guard — refused cache) |
|
|
83
|
+
|
|
84
|
+
**v0.4.0 Concurrency & Load-Shedding Verification:**
|
|
85
|
+
* **Async Singleflight (400 concurrent `asyncio.gather` calls):** Hit rate jumped from `0.0%` to **`90.5%`** (38 actual runs, 362 coalesced).
|
|
86
|
+
* **Live CPU Spike (`multiprocessing`):** Caught `88.8%` host CPU spike and transitioned `NORMAL -> CRITICAL -> NORMAL` automatically.
|
|
87
|
+
* **Live Drift Auditing:** Audited 24 shadow samples and auto-tightened tolerances 3 times when error crossed `max_error`.
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## Installation
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# Core zero-dependency package
|
|
95
|
+
pip install fuzzymemo
|
|
96
|
+
|
|
97
|
+
# Recommended: with Numba JIT superoptimizer and psutil CPU/RAM governor
|
|
98
|
+
pip install "fuzzymemo[jit,monitor]"
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## Quickstart
|
|
104
|
+
|
|
105
|
+
### 1. Synchronous Compute Kernel (Full 4-Layer Stack)
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import math
|
|
109
|
+
from fuzzymemo import auto_turbo
|
|
110
|
+
|
|
111
|
+
@auto_turbo(
|
|
112
|
+
tolerances=(0.25, None, 0.001, 0.005), # None = exact match (e.g., strike)
|
|
113
|
+
maxsize=4096,
|
|
114
|
+
interpolate=True,
|
|
115
|
+
use_superopt=True,
|
|
116
|
+
enable_governor=True,
|
|
117
|
+
background_governor=True,
|
|
118
|
+
elevated_cpu_pct=70.0,
|
|
119
|
+
critical_cpu_pct=85.0,
|
|
120
|
+
ram_critical_pct=85.0,
|
|
121
|
+
shared_state_path="/tmp/fuzzymemo_pressure.state",
|
|
122
|
+
drift_sample_rate=500,
|
|
123
|
+
max_error=0.01,
|
|
124
|
+
)
|
|
125
|
+
def price_option(spot, strike, t_expiry, vol):
|
|
126
|
+
val = (spot - strike) * 0.01 + vol * math.sqrt(t_expiry)
|
|
127
|
+
for _ in range(200):
|
|
128
|
+
val = math.sin(val) + math.cos(val * 0.5)
|
|
129
|
+
return val
|
|
130
|
+
|
|
131
|
+
result = price_option(59120.40, 59000.0, 0.082, 0.55)
|
|
132
|
+
|
|
133
|
+
# Inspect stats or export telemetry
|
|
134
|
+
print(price_option.turbo_info())
|
|
135
|
+
print(price_option.prometheus_metrics("price_option"))
|
|
136
|
+
print(price_option.json_status(event="heartbeat"))
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 2. Native Async with Singleflight Coalescing
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
import asyncio
|
|
143
|
+
from fuzzymemo import auto_turbo
|
|
144
|
+
|
|
145
|
+
@auto_turbo(tolerances=(0.25, 0.01), maxsize=2048, background_governor=True)
|
|
146
|
+
async def fetch_and_score(price: float, vol: float) -> float:
|
|
147
|
+
await asyncio.sleep(0.01) # Simulated async work
|
|
148
|
+
return price * vol * 0.15
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Documentation
|
|
154
|
+
|
|
155
|
+
* See **[INTEGRATION_GUIDE.md](INTEGRATION_GUIDE.md)** for full production wiring templates (FastAPI + `/metrics`, WebSockets, multi-tenant Linux VMs with `systemd`, and tuning playbooks).
|
|
156
|
+
* See **`fuzzy_memoizer_guide.pdf`** for the architectural whitepaper and detailed benchmark tables.
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT License — Copyright (c) 2026 Ashutosh. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
fuzzymemo/__init__.py,sha256=KzJcqBHjn1EKYG-eT2xpspBxyFN__TX_rMsFB2ZxkZk,611
|
|
2
|
+
fuzzymemo/core.py,sha256=S7Z4lToTgu9Khp2x019kUboMYOqf2R0qqvrfXbAZ4xI,9364
|
|
3
|
+
fuzzymemo/governor.py,sha256=MfrRyt_hLj3pyRZJlykJmOucFBGOy0U5kUxiddAJP9o,5535
|
|
4
|
+
fuzzymemo/observability.py,sha256=2dZp5T46WMdAlq0WU_NCve8BhlsbeZk4azsvWBopFrY,2245
|
|
5
|
+
fuzzymemo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
fuzzymemo/superopt.py,sha256=rv6hisp1lS7LJje2qYGcwX-whhp6ASELZIxLfKfBYe8,2385
|
|
7
|
+
fuzzymemo/turbo.py,sha256=RALu1JcprNBty6dBh5cAyftO4_LwZF5IyO-a4PMWI_0,16572
|
|
8
|
+
fuzzymemo-0.4.0.dist-info/METADATA,sha256=USOyBuvO7CPfy07op2Zh61J9Si_rcFXGRecCOQcHSgs,8049
|
|
9
|
+
fuzzymemo-0.4.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
fuzzymemo-0.4.0.dist-info/licenses/LICENSE,sha256=xOXKzfVrNGOjbeJEt-qt8LfLxGw8qcpgP_hnWaRePmU,1086
|
|
11
|
+
fuzzymemo-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ashutosh
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|