Skip to main content

npguard

NPGuard helps explain NumPy memory use through process-traced measurements and optional array metadata. It observes, analyzes, and suggests; it never rewrites code, monkey-patches NumPy, or changes array behavior. Application data stays local. Version 0.4.1 — Prism adds reliable nested and concurrent observation sessions, explicit measurement scope, and evidence-based diagnostics. See the changelog for release details.

Installation

Python 3.10+, NumPy 1.23.5–2.x (subject to each NumPy release's Python support).

python -m pip install "npguard==0.4.1"

See the compatibility matrix. Users upgrading from v0.3 should review the migration guide, including cases where memory measurements are now reported as None when they cannot be attributed.

Observe a NumPy workload

import numpy as np
import npguard as ng

with ng.capture("step") as observation:
    source = np.ones(100_000, dtype=np.float32)
    result = source.astype(np.float64)
    ng.register_array(source, "source")
    ng.register_array(result, "result", source=source)

print(observation["measurements"]["registered_arrays"]["logical_bytes"])
print(observation["signals"]["dtype_promotions"])
ng.report()
ng.suggest()

source= is optional and asserts a relationship supplied by the caller. Dtype findings include the two dtypes, shape/size evidence, storage-overlap bounds, and safe-cast information. They do not prove an implicit NumPy promotion or an unnecessary copy. High confidence applies to the dtype difference, not its cause.

What the numbers mean

Category v0.4 behavior
Python-traced memory Process-wide tracemalloc bytes; includes Python objects, supported NumPy buffers, other threads, and instrumentation
NumPy data-buffer allocations Not measured separately; NumPy-domain snapshots are planned for v0.5
Process memory / RSS Not measured
Registered array sizes Logical nbytes; views/shared buffers can be counted more than once
Temporary/intermediate allocations Unknown; registration does not establish allocation time or buffer lifetime
Object lifecycle Weak references observe whether a registered array object was released during observation; this does not prove its buffer was freed

peak_mb is a compatibility alias for the process-wide traced peak increase above the session's starting current traced bytes, in MiB. It is available only when NPGuard owns an exclusive, uninterrupted tracing interval. It is None for nested/overlapping sessions or an already-running external tracer. The process's raw peak remains available under measurements.python_traced.process_peak_bytes, with its scope and attribution reason. No individual session peak is invented from a shared high-water mark.

Public APIs

with ng.memory_watcher("block", warn_threshold_mb=10) as session:
    array = np.ones(100)
    ng.register_array(array, "array")

@ng.watch("function", silent=True)
def compute():
    return np.ones(100)

result = ng.profile(compute)
print(ng.last("signals.temporaries.status"))
ng.reset()
  • memory_watcher(tag="block", silent=False, warn_threshold_mb=10) yields a session handle. Warnings describe process-traced memory, not proven NumPy temporary pressure. Async functions can use @watch or await profile(fn).
  • capture(tag="block", **kwargs) yields a dict filled on exit, including on application exceptions. Capture is always silent and propagates exceptions.
  • register_array(arr, label="array", *, source=None, session=None) returns arr unchanged. Metadata only; no strong array references. The first registration of a live object in a session wins. Register a derived array separately. Registration timestamps are not allocation timestamps.
  • last_observation() and last(path=None) return defensive snapshots in the current execution context. Unknown dotted paths return None.
  • report() prints active/last-session logical sizes; with no completed session, it prints standalone registrations. suggest(temp_threshold_mb=5) prints conditional evidence-based advice; its legacy threshold controls the traced memory summary, not proof of temporary allocations.
  • reset() clears this context's last result and standalone metadata; it is rejected while a session is active. log exposes debug/info/warn/error output.

See API and measurement contracts for nesting, threads, tasks, exceptions, generator limitations, and tracing ownership.

Threads and nesting

New threads and new asyncio tasks have independent sessions/results. To register worker arrays in an existing session, share its handle explicitly:

from concurrent.futures import ThreadPoolExecutor

with ng.memory_watcher("workers", silent=True) as session:
    with ThreadPoolExecutor(max_workers=2) as pool:
        arrays = list(pool.map(
            lambda _: ng.register_array(np.ones(100), session=session), range(2)
        ))

Join workers before closing the session. Thread diversity alone does not prove simultaneous allocation. Nested sessions collect their own registrations; parents' process measurements necessarily include nested work. No NumPy memory is automatically attributed to a line of user code in v0.4.

Development and roadmap

From a source checkout, install the development dependencies in a virtual environment, then run the validation commands:

python -m pip install -e ".[dev]"
python -m pytest --cov=npguard --cov-report=term-missing
python -m flake8 npguard tests benchmarks --select=E9,F63,F7,F82
python main.py
python benchmarks/run.py --size 20000 --repeats 5 --output /tmp/npguard-benchmarks.json
python -m build

Automatic allocation tracking, AST-backed diagnostics, a profiling CLI, JSON/HTML profiling reports, optimization benchmarking, regression budgets, and native-profiler integrations are later-phase work. The internal AST helper is a syntactic hint only: it cannot establish that a binary expression uses NumPy. NPGuard does not identify all native/short-lived allocations or memory leaks.

MIT licensed. Contributions to detectors, testing, documentation, and benchmarks are welcome. Optional project support: https://patreon.com/PriyanshuRauth.

Metadata

Release files for npguard 0.4.1

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

Source distribution (sdist)

Source distribution for npguard 0.4.1
File Size Uploaded Provenance Actions
npguard-0.4.1.tar.gz 41.0 kB Without provenance Details for npguard-0.4.1.tar.gz

Built distribution (wheel)

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

Total release size: 58.2 kB

Release files / npguard-0.4.1.tar.gz

Download URL npguard-0.4.1.tar.gz
Size 41.0 kB
Tags Source
SHA-256 checksum
How to use checksums
3dd4debba9afc9d3f4bdb7df02e6ec91c3025d0c6d15a9a0667f5e775ed1a22e
BLAKE2b-256 checksum
How to use checksums
ea4f177f47ced7f40839caebb6d3531b201839710b642c4c8bf2738e4a784099
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.1

Release files / npguard-0.4.1-py3-none-any.whl

Download URL npguard-0.4.1-py3-none-any.whl
Size 17.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ddea776eefd1be9301d626ff9c2c163a229d2676ad5b3eabebac9c6b54b874ae
BLAKE2b-256 checksum
How to use checksums
15a57b4e9d01216718debe2a376e8050c00c08ff2861c2d5530b6aaa2a0bae7c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.1

Security for npguard 0.4.1

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