fuzzymemo 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fuzzymemo-0.4.0/.github/workflows/ci.yml +20 -0
- fuzzymemo-0.4.0/.gitignore +8 -0
- fuzzymemo-0.4.0/LICENSE +21 -0
- fuzzymemo-0.4.0/PKG-INFO +160 -0
- fuzzymemo-0.4.0/README.md +129 -0
- fuzzymemo-0.4.0/bench_auto_turbo.py +76 -0
- fuzzymemo-0.4.0/bench_heavy_stack.py +92 -0
- fuzzymemo-0.4.0/demo_v040.py +121 -0
- fuzzymemo-0.4.0/fuzzy_memoizer_guide.pdf +0 -0
- fuzzymemo-0.4.0/fuzzy_memoizer_guide.tex +190 -0
- fuzzymemo-0.4.0/live_suite.py +153 -0
- fuzzymemo-0.4.0/pyproject.toml +54 -0
- fuzzymemo-0.4.0/src/fuzzymemo/__init__.py +21 -0
- fuzzymemo-0.4.0/src/fuzzymemo/core.py +280 -0
- fuzzymemo-0.4.0/src/fuzzymemo/governor.py +162 -0
- fuzzymemo-0.4.0/src/fuzzymemo/observability.py +51 -0
- fuzzymemo-0.4.0/src/fuzzymemo/py.typed +0 -0
- fuzzymemo-0.4.0/src/fuzzymemo/superopt.py +74 -0
- fuzzymemo-0.4.0/src/fuzzymemo/turbo.py +408 -0
- fuzzymemo-0.4.0/stress_test_governor.py +111 -0
- fuzzymemo-0.4.0/tests/test_auto_turbo.py +84 -0
- fuzzymemo-0.4.0/tests/test_fuzzymemo.py +117 -0
- fuzzymemo-0.4.0/tests/test_governor.py +89 -0
- fuzzymemo-0.4.0/tests/test_v040_features.py +141 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.10", "3.11", "3.12"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: actions/setup-python@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python-version }}
|
|
19
|
+
- run: pip install -e ".[dev,monitor]"
|
|
20
|
+
- run: pytest -v
|
fuzzymemo-0.4.0/LICENSE
ADDED
|
@@ -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.
|
fuzzymemo-0.4.0/PKG-INFO
ADDED
|
@@ -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,129 @@
|
|
|
1
|
+
# fuzzymemo
|
|
2
|
+
|
|
3
|
+
**Adaptive 4-Layer Numeric Accelerator & Load-Shedding Governor for Python.**
|
|
4
|
+
|
|
5
|
+
[](https://www.python.org/downloads/)
|
|
6
|
+
[](#)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
|
|
9
|
+
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.
|
|
10
|
+
|
|
11
|
+
`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.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## The 4-Layer Architecture
|
|
16
|
+
|
|
17
|
+
1. **Layer 1 — Adaptive Auto-Router (`turbo.py`)**
|
|
18
|
+
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.
|
|
19
|
+
2. **Layer 2 — Fuzzy Memoizer v4 (`core.py`)**
|
|
20
|
+
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.
|
|
21
|
+
3. **Layer 3 — Micro-Superoptimizer (`superopt.py`)**
|
|
22
|
+
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.
|
|
23
|
+
4. **Layer 4 — Background CPU & RAM Pressure Governor (`governor.py`)**
|
|
24
|
+
Polls host utilization via `psutil` or `os.getloadavg()` in an optional background daemon thread (zero hot-path syscalls) with hysteresis:
|
|
25
|
+
* **`NORMAL` (< 70% CPU):** Tight tolerances with axial linear interpolation.
|
|
26
|
+
* **`ELEVATED` (70%–85% CPU):** Flat nearest-bucket lookups ($1$ lookup vs. $D + 1$).
|
|
27
|
+
* **`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.
|
|
28
|
+
* **`RAM PRESSURE` ($\ge$ 85% RAM):** Clears the primary cache and routes to a compact `maxsize // 4` tier to prevent OOM kills.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## Production Features (v0.4.0)
|
|
33
|
+
|
|
34
|
+
* **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.
|
|
35
|
+
* **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.
|
|
36
|
+
* **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.
|
|
37
|
+
* **Zero-Dependency Observability:** Call `.prometheus_metrics()` or `.json_status()` directly on any decorated function.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Verified Benchmarks
|
|
42
|
+
|
|
43
|
+
Measured on an 8-logical-CPU Windows 11 host (Python 3.11.9, Numba + `psutil`, 19/19 tests passing):
|
|
44
|
+
|
|
45
|
+
| Workload | Blind Python | `@auto_turbo` | Speedup | Auto-Calibrated Strategy |
|
|
46
|
+
| :--- | ---: | ---: | ---: | :--- |
|
|
47
|
+
| **Live BTC/USDT Stream** (232 ticks) | `66.70 ms` | **`1.62 ms`** | **`41.1x`** | `njit_strict` + Fuzzy v4 (`CACHED`) |
|
|
48
|
+
| **Robotics 3D IK** (20k frames) | `0.7232 s` | **`0.0472 s`** | **`15.3x`** | `njit_fastmath_np` (`BYPASS`) |
|
|
49
|
+
| **3-Regime Stress Test** (30k ticks) | `1.8904 s` | **`0.1840 s`** | **`10.3x`** | `njit_strict` + Fuzzy v4 + Chaos Bypass |
|
|
50
|
+
| **Geo-Delivery Surge API** (20k reqs) | `0.5156 s` | **`0.0931 s`** | **`5.5x`** | `njit_fastmath_np` + Fuzzy v4 (`CACHED`) |
|
|
51
|
+
| **Trivial Formula Guard** (20k calls) | `0.0019 s` | `0.0039 s` | `0.5x` | `python` (`BYPASS` guard — refused cache) |
|
|
52
|
+
|
|
53
|
+
**v0.4.0 Concurrency & Load-Shedding Verification:**
|
|
54
|
+
* **Async Singleflight (400 concurrent `asyncio.gather` calls):** Hit rate jumped from `0.0%` to **`90.5%`** (38 actual runs, 362 coalesced).
|
|
55
|
+
* **Live CPU Spike (`multiprocessing`):** Caught `88.8%` host CPU spike and transitioned `NORMAL -> CRITICAL -> NORMAL` automatically.
|
|
56
|
+
* **Live Drift Auditing:** Audited 24 shadow samples and auto-tightened tolerances 3 times when error crossed `max_error`.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## Installation
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Core zero-dependency package
|
|
64
|
+
pip install fuzzymemo
|
|
65
|
+
|
|
66
|
+
# Recommended: with Numba JIT superoptimizer and psutil CPU/RAM governor
|
|
67
|
+
pip install "fuzzymemo[jit,monitor]"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Quickstart
|
|
73
|
+
|
|
74
|
+
### 1. Synchronous Compute Kernel (Full 4-Layer Stack)
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import math
|
|
78
|
+
from fuzzymemo import auto_turbo
|
|
79
|
+
|
|
80
|
+
@auto_turbo(
|
|
81
|
+
tolerances=(0.25, None, 0.001, 0.005), # None = exact match (e.g., strike)
|
|
82
|
+
maxsize=4096,
|
|
83
|
+
interpolate=True,
|
|
84
|
+
use_superopt=True,
|
|
85
|
+
enable_governor=True,
|
|
86
|
+
background_governor=True,
|
|
87
|
+
elevated_cpu_pct=70.0,
|
|
88
|
+
critical_cpu_pct=85.0,
|
|
89
|
+
ram_critical_pct=85.0,
|
|
90
|
+
shared_state_path="/tmp/fuzzymemo_pressure.state",
|
|
91
|
+
drift_sample_rate=500,
|
|
92
|
+
max_error=0.01,
|
|
93
|
+
)
|
|
94
|
+
def price_option(spot, strike, t_expiry, vol):
|
|
95
|
+
val = (spot - strike) * 0.01 + vol * math.sqrt(t_expiry)
|
|
96
|
+
for _ in range(200):
|
|
97
|
+
val = math.sin(val) + math.cos(val * 0.5)
|
|
98
|
+
return val
|
|
99
|
+
|
|
100
|
+
result = price_option(59120.40, 59000.0, 0.082, 0.55)
|
|
101
|
+
|
|
102
|
+
# Inspect stats or export telemetry
|
|
103
|
+
print(price_option.turbo_info())
|
|
104
|
+
print(price_option.prometheus_metrics("price_option"))
|
|
105
|
+
print(price_option.json_status(event="heartbeat"))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 2. Native Async with Singleflight Coalescing
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import asyncio
|
|
112
|
+
from fuzzymemo import auto_turbo
|
|
113
|
+
|
|
114
|
+
@auto_turbo(tolerances=(0.25, 0.01), maxsize=2048, background_governor=True)
|
|
115
|
+
async def fetch_and_score(price: float, vol: float) -> float:
|
|
116
|
+
await asyncio.sleep(0.01) # Simulated async work
|
|
117
|
+
return price * vol * 0.15
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## Documentation
|
|
123
|
+
|
|
124
|
+
* See **[INTEGRATION_GUIDE.md](INTEGRATION_GUIDE.md)** for full production wiring templates (FastAPI + `/metrics`, WebSockets, multi-tenant Linux VMs with `systemd`, and tuning playbooks).
|
|
125
|
+
* See **`fuzzy_memoizer_guide.pdf`** for the architectural whitepaper and detailed benchmark tables.
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
MIT License — Copyright (c) 2026 Ashutosh. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import random
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fuzzymemo import auto_turbo, fuzzy_cache
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def heavy_kernel(spot, strike, t_expiry, vol):
|
|
9
|
+
val = (spot - strike) * 0.01 + vol * math.sqrt(t_expiry)
|
|
10
|
+
for _ in range(40):
|
|
11
|
+
val = math.sin(val) + math.cos(val * 0.5) + math.sqrt(abs(val) + 1.0)
|
|
12
|
+
return val
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run_benchmark():
|
|
16
|
+
rng = random.Random(42)
|
|
17
|
+
|
|
18
|
+
clustered = [
|
|
19
|
+
(100.0 + rng.gauss(0, 0.8), 100.0, 0.08 + rng.uniform(-0.001, 0.001), 0.45 + rng.gauss(0, 0.005))
|
|
20
|
+
for _ in range(15_000)
|
|
21
|
+
]
|
|
22
|
+
chaos = [
|
|
23
|
+
(rng.uniform(10.0, 5000.0), 100.0, rng.uniform(0.01, 2.0), rng.uniform(0.05, 1.5))
|
|
24
|
+
for _ in range(15_000)
|
|
25
|
+
]
|
|
26
|
+
recovery = [
|
|
27
|
+
(100.0 + rng.gauss(0, 0.8), 100.0, 0.08 + rng.uniform(-0.001, 0.001), 0.45 + rng.gauss(0, 0.005))
|
|
28
|
+
for _ in range(15_000)
|
|
29
|
+
]
|
|
30
|
+
stream = clustered + chaos + recovery
|
|
31
|
+
|
|
32
|
+
fuzzy_only = fuzzy_cache(tolerances=(0.25, None, 0.001, 0.005), maxsize=4096, interpolate=True)(heavy_kernel)
|
|
33
|
+
turbo = auto_turbo(
|
|
34
|
+
tolerances=(0.25, None, 0.001, 0.005),
|
|
35
|
+
maxsize=4096,
|
|
36
|
+
interpolate=True,
|
|
37
|
+
use_superopt=True,
|
|
38
|
+
min_hit_rate=0.35,
|
|
39
|
+
check_interval=300,
|
|
40
|
+
cooldown_calls=1500,
|
|
41
|
+
min_kernel_us=None, # Auto-calibrate on this CPU
|
|
42
|
+
)(heavy_kernel)
|
|
43
|
+
|
|
44
|
+
turbo(*stream[0])
|
|
45
|
+
turbo.cache_clear()
|
|
46
|
+
|
|
47
|
+
t0 = time.perf_counter()
|
|
48
|
+
res_blind = [heavy_kernel(*x) for x in stream]
|
|
49
|
+
t_blind = time.perf_counter() - t0
|
|
50
|
+
|
|
51
|
+
t0 = time.perf_counter()
|
|
52
|
+
res_fuzzy = [fuzzy_only(*x) for x in stream]
|
|
53
|
+
t_fuzzy = time.perf_counter() - t0
|
|
54
|
+
|
|
55
|
+
t0 = time.perf_counter()
|
|
56
|
+
res_turbo = [turbo(*x) for x in stream]
|
|
57
|
+
t_turbo = time.perf_counter() - t0
|
|
58
|
+
|
|
59
|
+
err_turbo = sum(abs(a - b) for a, b in zip(res_blind, res_turbo)) / len(stream)
|
|
60
|
+
info = turbo.turbo_info()
|
|
61
|
+
|
|
62
|
+
print("=== 3-REGIME STREAM BENCHMARK (AUTO-CALIBRATED @auto_turbo) ===")
|
|
63
|
+
print(f"1. Blind Python : {t_blind:.4f}s (1.0x)")
|
|
64
|
+
print(f"2. Fuzzy v4 Alone : {t_fuzzy:.4f}s ({t_blind / t_fuzzy:5.1f}x) | {fuzzy_only.cache_info()}")
|
|
65
|
+
print(f"3. @auto_turbo (3L) : {t_turbo:.4f}s ({t_blind / t_turbo:5.1f}x) | Avg Err: {err_turbo:.6f}")
|
|
66
|
+
print("-" * 78)
|
|
67
|
+
print(
|
|
68
|
+
f"Calibration : kernel={info.kernel_us:.2f} us vs cache_hit={info.cache_lookup_us:.2f} us "
|
|
69
|
+
f"-> cache_worthwhile={info.cache_worthwhile}"
|
|
70
|
+
)
|
|
71
|
+
print(f"Winner Backend : {info.winner_backend} ({info.jit_speedup:.1f}x JIT)")
|
|
72
|
+
print(f"Router Switches : {info.switches} | Bypassed Calls: {info.bypass_calls} | Final Mode: {info.mode}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
run_benchmark()
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import random
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
from fuzzymemo import auto_turbo, fuzzy_cache, superoptimize
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def heavy_400_kernel(spot, strike, t_expiry, vol):
|
|
9
|
+
# 400-step transcendental loop (Numba-friendly, ~8-15 us even after JIT)
|
|
10
|
+
val = (spot - strike) * 0.005 + vol * math.sqrt(t_expiry)
|
|
11
|
+
for _ in range(400):
|
|
12
|
+
val = math.sin(val) + math.cos(val * 0.5) + math.sqrt(abs(val) + 1.0)
|
|
13
|
+
return val
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run_benchmark():
|
|
17
|
+
rng = random.Random(42)
|
|
18
|
+
|
|
19
|
+
# 30,000 ticks: 10k Clustered -> 10k Chaos -> 10k Recovery
|
|
20
|
+
clustered = [
|
|
21
|
+
(100.0 + rng.gauss(0, 0.8), 100.0, 0.08 + rng.uniform(-0.001, 0.001), 0.45 + rng.gauss(0, 0.005))
|
|
22
|
+
for _ in range(10_000)
|
|
23
|
+
]
|
|
24
|
+
chaos = [
|
|
25
|
+
(rng.uniform(10.0, 5000.0), 100.0, rng.uniform(0.01, 2.0), rng.uniform(0.05, 1.5))
|
|
26
|
+
for _ in range(10_000)
|
|
27
|
+
]
|
|
28
|
+
recovery = [
|
|
29
|
+
(100.0 + rng.gauss(0, 0.8), 100.0, 0.08 + rng.uniform(-0.001, 0.001), 0.45 + rng.gauss(0, 0.005))
|
|
30
|
+
for _ in range(10_000)
|
|
31
|
+
]
|
|
32
|
+
stream = clustered + chaos + recovery
|
|
33
|
+
|
|
34
|
+
# 1. Pure JIT baseline (Layer 3 only)
|
|
35
|
+
jit_res = superoptimize(heavy_400_kernel, stream[0], allow_fastmath=True)
|
|
36
|
+
jit_only = jit_res.kernel
|
|
37
|
+
|
|
38
|
+
# 2. Fuzzy v4 Alone (Layer 2 only)
|
|
39
|
+
fuzzy_only = fuzzy_cache(tolerances=(0.25, None, 0.001, 0.005), maxsize=4096, interpolate=True)(heavy_400_kernel)
|
|
40
|
+
|
|
41
|
+
# 3. @auto_turbo (All 3 Layers: Auto-Router + Fuzzy v4 + JIT)
|
|
42
|
+
turbo = auto_turbo(
|
|
43
|
+
tolerances=(0.25, None, 0.001, 0.005),
|
|
44
|
+
maxsize=4096,
|
|
45
|
+
interpolate=True,
|
|
46
|
+
use_superopt=True,
|
|
47
|
+
min_hit_rate=0.35,
|
|
48
|
+
check_interval=250,
|
|
49
|
+
cooldown_calls=1000,
|
|
50
|
+
min_kernel_us=None, # Auto-calibrate break-even on this CPU
|
|
51
|
+
)(heavy_400_kernel)
|
|
52
|
+
|
|
53
|
+
# Warm up JIT & auto-calibration before timing
|
|
54
|
+
turbo(*stream[0])
|
|
55
|
+
turbo.cache_clear()
|
|
56
|
+
|
|
57
|
+
t0 = time.perf_counter()
|
|
58
|
+
res_blind = [heavy_400_kernel(*x) for x in stream]
|
|
59
|
+
t_blind = time.perf_counter() - t0
|
|
60
|
+
|
|
61
|
+
t0 = time.perf_counter()
|
|
62
|
+
res_jit = [jit_only(*x) for x in stream]
|
|
63
|
+
t_jit = time.perf_counter() - t0
|
|
64
|
+
|
|
65
|
+
t0 = time.perf_counter()
|
|
66
|
+
res_fuzzy = [fuzzy_only(*x) for x in stream]
|
|
67
|
+
t_fuzzy = time.perf_counter() - t0
|
|
68
|
+
|
|
69
|
+
t0 = time.perf_counter()
|
|
70
|
+
res_turbo = [turbo(*x) for x in stream]
|
|
71
|
+
t_turbo = time.perf_counter() - t0
|
|
72
|
+
|
|
73
|
+
err_turbo = sum(abs(a - b) for a, b in zip(res_blind, res_turbo)) / len(stream)
|
|
74
|
+
info = turbo.turbo_info()
|
|
75
|
+
|
|
76
|
+
print("=== 400-STEP HEAVY KERNEL BENCHMARK (30,000 TICKS: CLUSTERED -> CHAOS -> RECOVERY) ===")
|
|
77
|
+
print(f"1. Blind Python : {t_blind:.4f}s ( 1.0x)")
|
|
78
|
+
print(f"2. Pure JIT Only : {t_jit:.4f}s ({t_blind / t_jit:5.1f}x) | backend={jit_res.winner_name}")
|
|
79
|
+
print(f"3. Fuzzy v4 Alone : {t_fuzzy:.4f}s ({t_blind / t_fuzzy:5.1f}x) | evictions={fuzzy_only.cache_info().evictions}")
|
|
80
|
+
print(f"4. @auto_turbo (3L) : {t_turbo:.4f}s ({t_blind / t_turbo:5.1f}x) | Avg Err: {err_turbo:.6f}")
|
|
81
|
+
print("-" * 82)
|
|
82
|
+
print(
|
|
83
|
+
f"Calibration : kernel={info.kernel_us:.2f} us vs cache_hit={info.cache_lookup_us:.2f} us "
|
|
84
|
+
f"-> cache_worthwhile={info.cache_worthwhile}"
|
|
85
|
+
)
|
|
86
|
+
print(f"Winner Backend : {info.winner_backend} ({info.jit_speedup:.1f}x JIT)")
|
|
87
|
+
print(f"Router Switches : {info.switches} | Bypassed Calls: {info.bypass_calls} | Final Mode: {info.mode}")
|
|
88
|
+
print(f"Inner Cache Stats : {info.cache_stats}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
run_benchmark()
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import math
|
|
3
|
+
import random
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
from fuzzymemo import auto_turbo
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def demo_live_drift_auditing():
|
|
10
|
+
print("=" * 78)
|
|
11
|
+
print("1. LIVE DRIFT AUDITING (SHADOW SAMPLING + AUTO-TIGHTENING)")
|
|
12
|
+
print("=" * 78)
|
|
13
|
+
|
|
14
|
+
def steep_pricing_curve(x):
|
|
15
|
+
# Nonlinear curve where loose buckets cause noticeable error
|
|
16
|
+
return (x ** 2.4) * 0.01 + math.sin(x) * 2.5
|
|
17
|
+
|
|
18
|
+
fn = auto_turbo(
|
|
19
|
+
tolerances=1.0, # Intentionally loose starting tolerance
|
|
20
|
+
interpolate=False,
|
|
21
|
+
use_superopt=False,
|
|
22
|
+
min_kernel_us=0.0,
|
|
23
|
+
enable_governor=False,
|
|
24
|
+
drift_sample_rate=5, # Shadow-audit every 5th call
|
|
25
|
+
max_error=0.25, # Auto-tighten by 0.5x whenever error > 0.25
|
|
26
|
+
)(steep_pricing_curve)
|
|
27
|
+
|
|
28
|
+
rng = random.Random(7)
|
|
29
|
+
for _ in range(120):
|
|
30
|
+
fn(20.0 + rng.uniform(-0.8, 0.8))
|
|
31
|
+
|
|
32
|
+
info = fn.turbo_info()
|
|
33
|
+
print(f" Shadow Samples Audited : {info.drift_samples}")
|
|
34
|
+
print(f" Max Observed Error : {info.max_observed_error:.4f}")
|
|
35
|
+
print(f" Auto-Tighten Triggers : {info.drift_tightens} (tolerance halved each trigger)")
|
|
36
|
+
print(f" Final Cache Stats : hits={info.cache_stats.hits}, misses={info.cache_stats.misses}\n")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def demo_async_caching():
|
|
40
|
+
print("=" * 78)
|
|
41
|
+
print("2. NATIVE ASYNC / AWAIT CACHING (WEBSOCKET / FASTAPI SIMULATION)")
|
|
42
|
+
print("=" * 78)
|
|
43
|
+
|
|
44
|
+
io_calls = 0
|
|
45
|
+
|
|
46
|
+
@auto_turbo(tolerances=(0.25, 0.01), maxsize=1024, enable_governor=False)
|
|
47
|
+
async def async_risk_score(price, vol):
|
|
48
|
+
nonlocal io_calls
|
|
49
|
+
io_calls += 1
|
|
50
|
+
await asyncio.sleep(0.002) # Simulate 2ms async work
|
|
51
|
+
return math.log1p(price) * vol * 100.0
|
|
52
|
+
|
|
53
|
+
rng = random.Random(42)
|
|
54
|
+
t0 = time.perf_counter()
|
|
55
|
+
tasks = [
|
|
56
|
+
async_risk_score(100.0 + rng.gauss(0, 0.35), 0.45 + rng.gauss(0, 0.008))
|
|
57
|
+
for _ in range(400)
|
|
58
|
+
]
|
|
59
|
+
await asyncio.gather(*tasks)
|
|
60
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
61
|
+
|
|
62
|
+
info = async_risk_score.turbo_info()
|
|
63
|
+
print(f" 400 Async Calls Done : {elapsed_ms:.2f} ms")
|
|
64
|
+
print(f" Actual Compute Runs : {io_calls} (saved {400 - io_calls} redundant awaits)")
|
|
65
|
+
print(f" Async Hit Rate : {info.cache_stats.hit_rate:.1f}%\n")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def demo_ram_pressure_and_observability():
|
|
69
|
+
print("=" * 78)
|
|
70
|
+
print("3. BACKGROUND CPU/RAM GOVERNOR + PROMETHEUS & JSON TELEMETRY")
|
|
71
|
+
print("=" * 78)
|
|
72
|
+
|
|
73
|
+
fake_cpu = [24.0]
|
|
74
|
+
fake_ram = [45.0]
|
|
75
|
+
|
|
76
|
+
fn = auto_turbo(
|
|
77
|
+
tolerances=(0.1, 0.1),
|
|
78
|
+
maxsize=256,
|
|
79
|
+
use_superopt=True,
|
|
80
|
+
min_kernel_us=0.0,
|
|
81
|
+
enable_governor=True,
|
|
82
|
+
background_governor=True,
|
|
83
|
+
governor_poll_interval=0.05,
|
|
84
|
+
ram_critical_pct=85.0,
|
|
85
|
+
cpu_provider=lambda: fake_cpu[0],
|
|
86
|
+
ram_provider=lambda: fake_ram[0],
|
|
87
|
+
)(lambda x, y: math.sin(x) + math.cos(y))
|
|
88
|
+
|
|
89
|
+
try:
|
|
90
|
+
# Normal RAM (45%)
|
|
91
|
+
time.sleep(0.1)
|
|
92
|
+
for i in range(40):
|
|
93
|
+
fn(1.0 + (i % 5) * 0.02, 2.0 + (i % 4) * 0.02)
|
|
94
|
+
info_norm = fn.turbo_info()
|
|
95
|
+
print(f" [NORMAL RAM 45%] ram_pressure={info_norm.ram_pressure} | active maxsize={info_norm.cache_stats.maxsize}")
|
|
96
|
+
|
|
97
|
+
# Spike host RAM to 91% -> background thread triggers compact tier (256 // 4 = 64)
|
|
98
|
+
fake_ram[0] = 91.0
|
|
99
|
+
time.sleep(0.12)
|
|
100
|
+
for i in range(40):
|
|
101
|
+
fn(1.0 + (i % 5) * 0.02, 2.0 + (i % 4) * 0.02)
|
|
102
|
+
info_high = fn.turbo_info()
|
|
103
|
+
print(f" [SPIKED RAM 91%] ram_pressure={info_high.ram_pressure} | active maxsize={info_high.cache_stats.maxsize}\n")
|
|
104
|
+
|
|
105
|
+
print("--- PROMETHEUS EXPOSITION FORMAT ---")
|
|
106
|
+
print(fn.prometheus_metrics("live_pricing_kernel").strip())
|
|
107
|
+
|
|
108
|
+
print("\n--- STRUCTURED JSON TELEMETRY ---")
|
|
109
|
+
print(fn.json_status(event="ram_pressure_check", name="live_pricing_kernel"))
|
|
110
|
+
finally:
|
|
111
|
+
fn.stop_governor()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def main():
|
|
115
|
+
demo_live_drift_auditing()
|
|
116
|
+
asyncio.run(demo_async_caching())
|
|
117
|
+
demo_ram_pressure_and_observability()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == "__main__":
|
|
121
|
+
main()
|
|
Binary file
|