# How to get rid of a memory-leak when solving equations modulo an integer with sage?

Hi,

I am running into a memory-leak if I execute the following sage code. I tried to get rid of the problem by using the garbage collector, but - after some time - my computer crashes anyway. I'd be thankful for any help.

p=3
r=2
n=7

import gc
gc.enable()

R=Integers(p^r)
elts=list(R)
elts

StrTotal=''
for i in [1..n-1]:
StrTotal=StrTotal+'a_'+str(i)+','

StrTotal=StrTotal+'a_'+str(n)
StrTotal=var(StrTotal)
m=matrix([[1,0],[0,1]])
for i in [1..n]:
m=matrix([[eval('a_'+str(i)),-1],[1,0]])*m

m_new = m + matrix([[1,0],[0,1]])
m_new

temp=[]
for t in [0..p^r-1]:
for u in [0..p^r-1]:
lll=solve_mod([a_1==t, a_2==u, m_new[0][0]==0, m_new[0][1]==0, m_new[1][0]==0, m_new[1][1]==0],p^r)
LL=len(lll)
temp.append(LL)
print(LL)
print(t)
lll=0
#print("memory usage: " + str(get_memory_usage()))
gc.collect()

temp

TEMP=sum(temp)
TEMP

edit retag close merge delete

Sort by » oldest newest most voted

I'd suggest to report this issue to https://github.com/sagemath/sage/issues

A surprising workaround for memory leak issues is using multiprocessing, which thanks to spawning processes can force memory release in a hard way. As a positive side effect, it can also give code a noticeable speed-up.

Here is a rewrite of your loops using multiprocessing:

import multiprocessing

def my_solve_mod(tu):
t,u = tu
return t, solve_mod([a_1==t, a_2==u, m_new[0][0]==0, m_new[0][1]==0, m_new[1][0]==0, m_new[1][1]==0], p^r)

temp=[]
with multiprocessing.Pool() as pool:
for t,lll in pool.imap( my_solve_mod, Tuples((0..p^r-1),2) ):
LL=len(lll)
temp.append(LL)
print(LL)
print(t)


You may like to check documentation on multiprocessing for fine-tuning of this computation (e.g. forming bigger chunks of data for parallel processing).

PS. On a side note, you don't need to form lists like [A..B] in your loops, using generators (A..B) instead is faster and memory-savvy.

more