-
-
Notifications
You must be signed in to change notification settings - Fork 32.9k
Description
Bug report
Bug description:
I recently updated my python environment and discovered a weird bug that occurs between matplotlib, numpy, and multiprocessing.
Code to demonstrate the bug below. In the code I am running a multiprocessing pool, with a function that multiplies small matrices a large number of times. If run on its own this fully utilizes the expected number of threads/processes (num_threads). However if a plot is generated and saved before the multiprocessing loop begins, then all of the processing seems to be forced onto only 2 threads.
Time is used only to demonstrate that the code runs much slower when the bug is occurring, on my machine (48 cores/96 threads) it runs about 30 times slower when the bug occurs. The try/except is used just so the pool is closed properly if you keyboard interrupt.
import numpy as np
import multiprocessing as mp
from matplotlib import pyplot as plt
import time
def test_function(var):
test_mat=np.zeros((3,3))
for i in range(10**6):
np.matmul(test_mat,test_mat)
return()
def main():
print('starting')
test_array=np.arange(10)
fig=plt.figure()
plt.plot(test_array,test_array,'.')
plt.savefig('test_fig.png')
#plt.close('all')
#plt.close(fig)
# plt.close()
num_threads=mp.cpu_count()//2
pool=mp.Pool(num_threads)
try:
completed=0
tic=time.time()
for item in pool.imap(test_function,range(num_threads*2)):
completed+=1
print('%i completed'%(completed))
toc=time.time()-tic
print('Elapsed time %f seconds'%toc)
pool.close()
pool.join()
except:
pool.terminate()
pool.join()
if __name__=='__main__':
main()
This bug also occurs when using plt.close, although I tested a few different versions of matplotlib, and the behavior changes. With python 12 and matplotlib 3.10.0 the bug occurs with plt.close(fig) and plt.close('all'). With matplotlib 3.9.2 and 3.8.0 the bug does not occur with plt.close('all') but still occurs with plt.close(fig). The bug does not occur with a plain plt.close() in my testing.
This bug occurs in an important piece of code I am using at work so I am trying to find a working python environment where it does not occur. It seems like the bug does not occur in python 10, even running the same matplotlib versions listed above, so it seems to be a python bug, not a matplotlib bug. (I was previously working in Python 8, but had to update). Bug appears to be independent of matplotlib backend.
OS RHEL9.
CPython versions tested on:
3.12
Operating systems tested on:
Linux