【问题标题】:Debugging in Google Colab在 Google Colab 中调试
【发布时间】:2019-03-10 10:25:37
【问题描述】:

我在 google colab 的单个单元格中运行以下代码 sn-p:

%debug
# Create tensors of shape (10, 3) and (10, 2).
x = torch.randn(10, 3)
y = torch.randn(10, 2)

# Build a fully connected layer.
linear = nn.Linear(3, 2)
print ('w: ', linear.weight)
print ('b: ', linear.bias)

我希望调试一段代码(逐行逐行执行)以了解发生了什么。我希望进入函数 nn.Linear。

但是,当我单步执行时,它根本没有进入函数。有没有办法逐行遍历 nn.Linear?另外,我究竟如何在 nn.Linear 中设置断点?此外,我还希望逐行了解 sn-p。但是,如图所示,step 命令会自动单步执行并执行 print 语句。

【问题讨论】:

    标签: python deep-learning pytorch tensor google-colaboratory


    【解决方案1】:

    从 Python 3.7 开始,您可以使用内置的 breakpoint function。如果这不可用,您可以改用import pdb; pdb.set_trace()

    如果你想执行下一行,你可以尝试n(下一个)而不是s(步骤)。

    【讨论】:

      【解决方案2】:

      您可以使用内置的断点函数在 nn.Linear 中设置断点。

      import sys; sys.breakpoint()
      

      还有更多可用的交互式调试命令,

      Command  Description
      list     Show the current location in the file
      h(elp)   Show a list of commands, or find help on a specific command
      q(uit)   Quit the debugger and the program
      c(ontinue)  Quit the debugger, continue in the program
      n(ext)   Go to the next step of the program
      <enter>  Repeat the previous command
      p(rint)  Print variables
      s(tep)   Step into a subroutine
      r(eturn)    Return out of a subroutine
      

      【讨论】:

        【解决方案3】:

        根据以下命令使用pdb内置断点功能:

        import pdb; 
        pdb.set_trace()
        

        命令说明

        1. list 显示文件中的当前位置
        2. h(elp) 显示命令列表,或查找特定命令的帮助
        3. q(uit) 退出调试器和程序
        4. c(ontinue) 退出调试器,继续程序
        5. n(ext) 进入程序的下一步
        6. 重复上一条命令
        7. p(rint) 打印变量
        8. s(tep) 进入子程序
        9. r(eturn) 退出子程序

        【讨论】:

          猜你喜欢
          • 2022-12-21
          • 2019-06-25
          • 2021-01-29
          • 2021-05-17
          • 2022-01-07
          • 2019-12-06
          • 1970-01-01
          • 2021-08-14
          • 2020-09-11
          相关资源
          最近更新 更多