Ubuntu下PyTorch调试技巧汇总
print("变量名:", variable),输出变量值和执行流程,快速定位异常位置。logging.basicConfig(level=logging.DEBUG)开启DEBUG模式,使用logging.debug("变量详情: %s", variable)记录信息,适合生产环境或复杂项目。import pdb; pdb.set_trace(),程序运行到该行会暂停,支持以下命令:
n(next):执行下一行;s(step):进入函数内部;c(continue):继续执行到下一个断点;p 变量名(print):打印变量值;q(quit):退出调试。import ipdb; ipdb.set_trace())。launch.json:通过“Run and Debug”面板创建,默认包含Python调试配置;torch.autograd.set_detect_anomaly(True)启用自动异常检测,当梯度计算出现NaN/Inf或非法操作时,程序会抛出详细异常(如梯度爆炸/消失的原因),帮助快速定位梯度问题。torch.autograd.profiler分析模型性能瓶颈,例如:from torch.autograd import profiler
with profiler.profile(record_shapes=True) as prof:
    output = model(input_data)
print(prof.key_averages().table(sort_by="cuda_time_total"))
输出包含各操作的CUDA耗时、调用次数等信息,帮助优化模型速度。torch.utils.tensorboard记录训练指标(如损失、准确率),通过SummaryWriter写入日志,再通过tensorboard --logdir=runs启动服务,在浏览器中查看可视化曲线,直观了解训练过程。assert 条件, "错误信息",当条件不成立时抛出AssertionError,用于检查关键假设(如张量维度、数值范围)。例如:assert input_dim == model.input_size, "输入维度与模型不匹配"。unittest或pytest框架编写单元测试,验证模型各模块(如层、函数、数据加载器)的正确性。例如,测试数据加载器是否能正确读取数据:import unittest
class TestDataLoader(unittest.TestCase):
    def test_loader(self):
        loader = DataLoader(dataset, batch_size=32, num_workers=0)
        batch = next(iter(loader))
        self.assertEqual(batch[0].shape, (32, 3, 224, 224))  # 检查图像维度