Google Colab:从本地上传 Pytorch 模型后“无法连接到运行时”

Fra*_*cis 5 data-persistence pytorch google-colaboratory

我正在使用一种简单(不一定有效)的方法来保存 Pytorch 模型。

import torch
from google.colab import files

torch.save(model, filename) # save a trained model on the VM
files.download(filename) # download the model to local

best_model = files.upload() # select the model just downloaded
best_model[filename] # access the model
Run Code Online (Sandbox Code Playgroud)

Colab 在执行最后一行期间断开连接,并且点击RECONNECTTab 总是显示ALLOCATING-> CONNECTING(失败,左下角显示“无法连接到运行时”消息)-> RECONNECT。同时,执行任何一个单元格都会给出错误消息“无法执行单元格,无法向运行时发送执行消息:[对象关闭事件]”

我知道它与最后一行有关,因为我可以成功连接到其他不执行该操作的 google 帐户。

为什么会发生?似乎已执行最后一行的 google 帐户无法再连接到运行时。

编辑:

一晚后,我可以在会话到期后重新连接 google 帐户。我只是尝试了评论中的方法,发现只有files.upload()Pytorch 模型会导致问题。上传完成后,Colab 会断开连接。

小智 7

尝试禁用您的广告拦截器。为我工作


phi*_*phi 1

(我在阅读您的更新之前写了这个答案。认为它可能会有所帮助。)

files.upload()仅用于上传文件。我们没有理由期望它返回一些pytorch type/model.

当您调用 时a = files.upload()a是一个文件名字典 - 一个大字节数组。

{'my_image.png': b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR....' }
type(a['my_image.png'])
Run Code Online (Sandbox Code Playgroud)

就像你做的时候一样open('my_image', 'b').read()

所以,我认为下一行best_model[filename]尝试打印整个巨大的字节数组,这会导致 colab 出现问题。