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
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 Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!