Skip to main content

fuzzymemo

Adaptive 4-Layer Numeric Accelerator & Load-Shedding Governor for Python.

Python 3.10+ Version 0.4.0 License: MIT

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.

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.


The 4-Layer Architecture

  1. Layer 1 — Adaptive Auto-Router (turbo.py) 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.
  2. Layer 2 — Fuzzy Memoizer v4 (core.py) 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.
  3. Layer 3 — Micro-Superoptimizer (superopt.py) 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.
  4. Layer 4 — Background CPU & RAM Pressure Governor (governor.py) Polls host utilization via psutil or os.getloadavg() in an optional background daemon thread (zero hot-path syscalls) with hysteresis:
    • NORMAL (< 70% CPU): Tight tolerances with axial linear interpolation.
    • ELEVATED (70%–85% CPU): Flat nearest-bucket lookups ($1$ lookup vs. $D + 1$).
    • 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.
    • RAM PRESSURE ($\ge$ 85% RAM): Clears the primary cache and routes to a compact maxsize // 4 tier to prevent OOM kills.

Production Features (v0.4.0)

  • 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.
  • 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.
  • 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.
  • Zero-Dependency Observability: Call .prometheus_metrics() or .json_status() directly on any decorated function.

Verified Benchmarks

Measured on an 8-logical-CPU Windows 11 host (Python 3.11.9, Numba + psutil, 19/19 tests passing):

Workload Blind Python @auto_turbo Speedup Auto-Calibrated Strategy
Live BTC/USDT Stream (232 ticks) 66.70 ms 1.62 ms 41.1x njit_strict + Fuzzy v4 (CACHED)
Robotics 3D IK (20k frames) 0.7232 s 0.0472 s 15.3x njit_fastmath_np (BYPASS)
3-Regime Stress Test (30k ticks) 1.8904 s 0.1840 s 10.3x njit_strict + Fuzzy v4 + Chaos Bypass
Geo-Delivery Surge API (20k reqs) 0.5156 s 0.0931 s 5.5x njit_fastmath_np + Fuzzy v4 (CACHED)
Trivial Formula Guard (20k calls) 0.0019 s 0.0039 s 0.5x python (BYPASS guard — refused cache)

v0.4.0 Concurrency & Load-Shedding Verification:

  • Async Singleflight (400 concurrent asyncio.gather calls): Hit rate jumped from 0.0% to 90.5% (38 actual runs, 362 coalesced).
  • Live CPU Spike (multiprocessing): Caught 88.8% host CPU spike and transitioned NORMAL -> CRITICAL -> NORMAL automatically.
  • Live Drift Auditing: Audited 24 shadow samples and auto-tightened tolerances 3 times when error crossed max_error.

Installation

# Core zero-dependency package
pip install fuzzymemo

# Recommended: with Numba JIT superoptimizer and psutil CPU/RAM governor
pip install "fuzzymemo[jit,monitor]"

Quickstart

1. Synchronous Compute Kernel (Full 4-Layer Stack)

import math
from fuzzymemo import auto_turbo

@auto_turbo(
    tolerances=(0.25, None, 0.001, 0.005),  # None = exact match (e.g., strike)
    maxsize=4096,
    interpolate=True,
    use_superopt=True,
    enable_governor=True,
    background_governor=True,
    elevated_cpu_pct=70.0,
    critical_cpu_pct=85.0,
    ram_critical_pct=85.0,
    shared_state_path="/tmp/fuzzymemo_pressure.state",
    drift_sample_rate=500,
    max_error=0.01,
)
def price_option(spot, strike, t_expiry, vol):
    val = (spot - strike) * 0.01 + vol * math.sqrt(t_expiry)
    for _ in range(200):
        val = math.sin(val) + math.cos(val * 0.5)
    return val

result = price_option(59120.40, 59000.0, 0.082, 0.55)

# Inspect stats or export telemetry
print(price_option.turbo_info())
print(price_option.prometheus_metrics("price_option"))
print(price_option.json_status(event="heartbeat"))

2. Native Async with Singleflight Coalescing

import asyncio
from fuzzymemo import auto_turbo

@auto_turbo(tolerances=(0.25, 0.01), maxsize=2048, background_governor=True)
async def fetch_and_score(price: float, vol: float) -> float:
    await asyncio.sleep(0.01)  # Simulated async work
    return price * vol * 0.15

Documentation

  • See INTEGRATION_GUIDE.md for full production wiring templates (FastAPI + /metrics, WebSockets, multi-tenant Linux VMs with systemd, and tuning playbooks).
  • See fuzzy_memoizer_guide.pdf for the architectural whitepaper and detailed benchmark tables.

License

MIT License — Copyright (c) 2026 Ashutosh. See LICENSE for details.

Metadata

Release files for fuzzymemo 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fuzzymemo 0.4.0
File Size Uploaded Provenance Actions
fuzzymemo-0.4.0.tar.gz 96.9 kB Without provenance Details for fuzzymemo-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fuzzymemo 0.4.0
File Interpreter ABI Platform Actions
fuzzymemo-0.4.0-py3-none-any.whl Python 3 none any Details for fuzzymemo-0.4.0-py3-none-any.whl

Total release size: 113.1 kB

Release files / fuzzymemo-0.4.0.tar.gz

Download URL fuzzymemo-0.4.0.tar.gz
Size 96.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3942b8406d5948a6a160608d1dbda98dbd76abfe3464807f98bc803ff280054b
BLAKE2b-256 checksum
How to use checksums
cd01f1f48b9b6e27b0bd8b2c2448c690c52db06bc5b6e6ee6912572c4f33d01a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / fuzzymemo-0.4.0-py3-none-any.whl

Download URL fuzzymemo-0.4.0-py3-none-any.whl
Size 16.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
264f02a6bcbf742f7e6ca32bd89dda5d889afe769dfcf34b9607901fc36dd434
BLAKE2b-256 checksum
How to use checksums
b0899351e0f07d865d52832b28cc0dfb7b6f8403042856bcf9337ef5e59935e0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for fuzzymemo 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page