0
votes

Python runs out of memory when starting a multiprocessing application inside a for loop. The allocated memory grows bigger with each additional loop. How do I fix this problem?

I am performing large Monte Carlo simulations with thousands of simulations each. To get a performance boost, I am using the multiprocessing module and run the individual simulations parallel on 10 cores. Every Monte Carlo simulation uses the same model, but different model inputs. I am basically looping over an input list and start a new Monte Carlo simulation with the next models inputs after the previous Monte Carlo simulation finished.

The weird thing is, that the allocated memory from the previous Monte Carlo simulation is not released after it finished. The allocated memory simply grows bigger with each additional Monte Carlo simulation until python runs out of memory. Every python object from the previous Monte Carlo simulation is overwritten by the the object from the next Monte Carlo simulation. Deleting the objects at the end of the loop using del or calling gc.collect() is not helping.

My current solution: realization of the for loop in a bash script which calls python with every loop.

The code is very large consisting of several different classes. Basically this is whats happening:

from monte_carlo import mc_class

input_list = [input1, input2, ...]
model_parameters = ...

for inpt in input_list:
    mc = mc_class(model_parameters=model_parameters, model_inputs=inpt)
    mc.run()
    mc.save_results()
    mc.generate_plots()
    del mc

mc.run() starts the Monte Carlo simulation. This call creates several processes, runs them and collects the results. The code is basically identical to https://github.com/lbl-srg/EstimationPy/blob/master/estimationpy/fmu_utils/fmu_pool.py

I expected the memory to be released after multiprocessing finished. I thought python will garbage collect, especially after del mc.

2

2 Answers

0
votes

The garbage collector does its work independently from the code. While del deletes an object, it does not invoke the garbage collector.

You can import gc to get a quite extensive API to the garbage collector, including running the garbage collector explicitly (e.g. after your del mc) and tools for debugging leaky programs.

See: https://docs.python.org/3/library/gc.html

0
votes

del will only remove the binding assignment between the variable (identifier) and the object, so the object will still exist in memory.

Try mc=None instead of del mc