Memory leak involving `with_data`

Open
#379 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
52/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
numpy, python

Research direction

The report points to repeated calls to compiled_model.with_data(y_data=response) in the sampling loop, but names no implementation file or test. Start by locating with_data and checking how its returned model handles data across repeated fits; use the supplied script to reproduce and track RSS. Done means memory use no longer grows across iterations after each posterior is deleted and garbage collection runs.

Written by the indexing model from the issue text.

Description

The following shows increasing memory usage:

import gc
import pathlib

import numpy as np
import nutpie
import pymc as pm

N = 5_000
P = 100
N_ITER = 20


def current_rss_mb() -> float | None:
    status_path = pathlib.Path("/proc/self/status")
    if not status_path.exists():
        return None
    for line in status_path.read_text().splitlines():
        if line.startswith("VmRSS:"):
            return float(line.split()[1]) / 1024
    return None


def log_memory(label: str) -> None:
    current = current_rss_mb()
    current_text = "unknown" if current is None else f"{current:.1f} MB"
    print(f"[memory] {label}: current_rss={current_text}", flush=True)

rng = np.random.default_rng(123)
X = rng.normal(size=(N, P)) # Fixed
true_beta = rng.normal(scale=0.5, size=P)
probabilities = 1 / (1 + np.exp(-(0.25 + X @ true_beta)))
responses = rng.binomial(1, probabilities, size=(N_ITER, N))

log_memory("before model construction")
with pm.Model() as model:
    y_data = pm.Data("y_data", responses[0])
    alpha = pm.Normal("alpha", sigma=2)
    beta = pm.Normal("beta", sigma=0.5, shape=P)
    pm.Bernoulli("y", logit_p=alpha + pm.math.dot(X, beta), observed=y_data)

log_memory("before compilation")
compiled_model = nutpie.compile_pymc_model(
    model, backend="numba", gradient_backend="pytensor", freeze_model=False
)
log_memory("after compilation")

for i, response in enumerate(responses):
    log_memory(f"before fit {i}")
    idata = nutpie.sample(
        compiled_model.with_data(y_data=response),
        draws=1000,
        tune=1000,
        chains=4,
        seed=123 + i - 1,
        save_warmup=False,
        progress_bar=False,
    )
    log_memory(f"after fit {i}, posterior retained")
    del idata
    gc.collect()
    log_memory(f"after fit {i}, posterior deleted and gc collected")

del compiled_model, model
gc.collect()
log_memory("after deleting models and gc collecting")
Dominant language
Python
Stars
214
Forks
31
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from pymc-devs/nutpie

All issues in pymc-devs/nutpie

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.