Looping over LAMMPS instances in a python script causes a memory leak, specifically when using the create_box
command. Here’s a minimum reproducible example that shows the leak:
"""
Simple example to reproduce memory leak using the LAMMPS-Python interface.
Usage:
python mem-leak.py
"""
import lammps
import os, psutil
#import gc
process = psutil.Process(os.getpid())
print(f"Memory before loop: {process.memory_info().rss}") # bytes
mem_before = process.memory_info().rss
nloops = 1000
for l in range(1,nloops+1):
lmp = lammps.lammps(cmdargs=["-screen", "none"])
lmp.command("clear")
lmp.command("units metal")
lmp.command("atom_style atomic")
lmp.command("boundary p p p")
region_command = "region pybox prism 0 10 0 10 0 10 0 0 0"
lmp.command(region_command)
# memory leak happens due to create_box, comment this command out to see
lmp.command("create_box 1 pybox")
# attempts to clean up lmp object:
#lmp.command("clear")
lmp.close()
#del lmp
#gc.collect()
print(f"Loop {l} memory: {process.memory_info().rss}") # bytes
mem_after = process.memory_info().rss
print(f"Memory leaked: {mem_after - mem_before}") # bytes
See that the memory increases with each loop.
I thought LAMMPS would automatically deallocate everything with the clear
command, and that lmp.close()
would clean things up on the python side, but that does not seem to be the case.
Maybe whatever is being allocated with create_box
is not being deallocated during lmp.close()
. I am happy to change the C++ library functions to deallocate more things if necessary - anyone ever seen this before or know why it happens?