Memory accumulates when calling a matlab function multiple times using matlab.engine in python.

6 次查看(过去 30 天)
eng = matlab.engine.start_matlab()
# 设置路径到含有MRSTR.m文件的目录
matlab_path = os.path.join(rootpath, r'Matlab\2_D_oil_Water')
eng.addpath(matlab_path, nargout=0)
##函数中的一部分
# 调用 MATLAB 函数并计算损失
loss2, grad2 = eng.Physics_loss(m_inputs, m_outputs, m_c, nargout=2)
# eng.workspace.clear()
eng.eval('clear m_inputs m_outputs m_c', nargout=0)
eng.eval('clearvars', nargout=0)
# 清除 MATLAB 工作空间中的变量
# eng.eval('clearvars -except Physics_loss', nargout=0)
# 数据转化为 tensor
physics_grad = torch.tensor(grad2).cuda()
physics_loss = torch.tensor(loss2, requires_grad=True).cuda()
# 显式删除不再需要的变量
del outputs, inputs, outputs_m, inputs_m, C_m
del loss2, m_inputs, m_outputs, m_c, grad2
gc.collect()
torch.cuda.empty_cache()
即使不断的删除内存,只要多调用一次 eng.Physics_loss 内存就会累加
loss2, grad2 = eng.Physics_loss(m_inputs, m_outputs, m_c, nargout=2)
  4 个评论
Piyush Kumar
Piyush Kumar 2024-10-23
Since the problem does not occur if the assignment is done directly, without calling MATLAB, I suggest you to write the code in Python and then use the pyrunfile function in MATLAB.
If this does not resolve the issue, please share the complete code so that I can try reproducing the issue at my end. I can see that there is no definition of the "Physics_loss" function in the code snippet you have provided. Also, how have you calculated the MATLAB CPU memory usage and Python's CPU memory usage?

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by