python内存溢出机制

之前跑程序的时候,遇到了机箱的红灯一直亮着并且机器卡死的情况,通过排查ubuntu系统之中的系统监视器以及任务管理器之中的显存,排查的结果发现由于内存的不断增长导致机器出现卡死的问题,这里就引出一个机制,就是python相应的内存溢出
核心代码

for batch_token_ids,batch_labels in tqdm(content_dataset,colour='blue'):
	batch_token_ids = torch.tensor([batch_token_ids.tolist()],dtype=long).to(device)
	batch_labels = torch.tensor([batch_labels.tolist()],dtype=long).to(device)

这一句的调用过程之中出现了内存不断增长的情况,经过分析之后发现batch_token_ids.tolist()这一操作数据是在内存之中操作的,所以如果想要内存不满机器不死机的情况下,就必须进行清理
如果修改成为如下的内容

for batch_token_ids,batch_labels in tqdm(content_dataset,colour='blue'):
	curent_batch_token_ids = batch_token_ids.tolist()
	current_batch_labels = batch_labels.tolist()
	......
	

但是这样操作然仍不行,需要定时清除相应的内存内容

for batch_token_ids,batch_labels in tqdm(content_dataset,colour='blue'):
	current_batch_token_ids = batch_token_ids.tolist()
	current_batch_labels = batch_labels.tolist()
	...
	del(current_batch_token_ids)
	del(current_batch_labels)
	gc.collect()

另外如果出现问题的前面代码运行时间过长导致排查程序的速度过慢,可以考虑优化前面部分的代码,减少前面部分代码的运行时间,从而能够尽快的发现问题。

Guess you like

Origin blog.csdn.net/znevegiveup1/article/details/119714480