pytorch训练过程中显存爆掉

发布时间 2023-11-16 09:17:02作者: dctwan

之前学c/c++,for循环中的变量只在for循环内部有效,for循环结束,则变量也被销毁。

for(int i = 0; i < 10; ++i){
	int x = i + 1;
}
cout << x << "\n";

//error: ‘x’ was not declared in this scope
//     cout << x << "\n";

python for循环中的变量作用域

在python中,for循环内部的变量,在for循环外部仍然存在

for i in range(10):
    x = i + 1
print(x)	# 10
print(i)	# 9

用pytorch做深度学习训练的时候,如果在训练过程中,epoch循环的内部(或者一个batch循环的内部)产生了较大的临时变量,要在此循环结束时删除这样的临时变量,否则会导致显存爆掉

for ...
  ...
  del x