在Ubuntu上调试PyTorch代码可以通过多种方法进行,以下是一些常用的调试步骤和工具:
使用Python的调试器(pdb):
import pdb; pdb.set_trace() # 设置断点
程序会在该行暂停执行,你可以使用pdb提供的命令进行调试。
使用IPython:
import ipython ipython.embed() # 启动IPython交互式环境
IPython提供了更多的交互式功能,如自动补全、历史记录等。
使用PyCharm:
使用Jupyter Notebook:
%debug
Jupyter Notebook是一个交互式文档,可以在其中编写代码并实时查看结果,也支持调试功能。
使用PyTorch的调试工具:
from torch.autograd import profiler
with profiler.profile(record_shapes=True) as prof:
Your model inference code here
output = model(input)
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter('runs/experiment-1')
writer.add_scalar('Loss/train', loss.item(), epoch)
writer.close()
tensorboard --logdir=runs
日志记录:
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')
使用Python的logging模块记录日志,可以帮助跟踪代码的执行流程和变量的状态。
单元测试: 编写单元测试并使用测试框架(如unittest或pytest)运行,可以确保代码的各个部分按预期工作。
import unittest
class TestMyCode(unittest.TestCase):
def test_something(self):
self.assertEqual(my_function(), expected_result)
if __name__ == '__main__':
unittest.main()