使用 pytorch-lightning 进行简单预测的示例

example of doing simple prediction with pytorch-lightning

我有一个现有的模型,我在其中加载一些预训练的权重,然后在 pytorch 中进行预测(一次一张图像)。我试图基本上将它转换为 pytorch 闪电模块,但对一些事情感到困惑。

所以目前,我的 __init__ 模型方法如下所示:

self._load_config_file(cfg_file)
# just creates the pytorch network
self.create_network()  

self.load_weights(weights_file)

self.cuda(device=0)  # assumes GPU and uses one. This is probably suboptimal
self.eval()  # prediction mode

我可以从闪电文档中收集到的信息,我几乎可以做同样的事情,除了不进行 cuda() 调用。所以像:

self.create_network()

self.load_weights(weights_file)
self.freeze()  # prediction mode

所以,我的第一个问题是,这是否是正确的闪电使用方式?闪电如何知道它是否需要使用 GPU?我猜这需要在某处指定。

现在,对于预测,我有以下设置:

def infer(frame):
    img = transform(frame)  # apply some transformation to the input
    img = torch.from_numpy(img).float().unsqueeze(0).cuda(device=0)
    with torch.no_grad():
        output = self.__call__(Variable(img)).data.cpu().numpy()
    return output

这是让我感到困惑的地方。我需要重写哪些函数才能进行与闪电兼容的预测?

另外,目前,输入是一个 numpy 数组。这是 lightning 模块可能实现的东西,还是总是必须使用某种数据加载器?

在某些时候,我想扩展这个模型实现来进行训练,所以想确保我做对了,但是虽然大多数例子都集中在训练模型上,但一个简单的例子只是在生产时进行预测在单个 image/data 点上可能会有用。

我在带有 cuda 10.1 的 GPU 上使用 0.7.5 和 pytorch 1.4.0

LightningModuletorch.nn.Module 的子 class,因此同一个模型 class 将适用于推理和训练。因此,您可能应该在 __init__.

之外调用 cuda()eval() 方法

因为它只是一个 nn.Module 引擎盖下的东西,一旦你加载了你的权重,你不需要重写任何方法来执行推理,只需调用模型实例。这是您可以使用的玩具示例:

import torchvision.models as models
from pytorch_lightning.core import LightningModule

class MyModel(LightningModule):
    def __init__(self):
        super().__init__()
        self.resnet = models.resnet18(pretrained=True, progress=False)
    
    def forward(self, x):
        return self.resnet(x)

model = MyModel().eval().cuda(device=0)

然后实际上 运行 推断您不需要方法,只需执行以下操作:

for frame in video:
    img = transform(frame)
    img = torch.from_numpy(img).float().unsqueeze(0).cuda(0)
    output = model(img).data.cpu().numpy()
    # Do something with the output

PyTorchLighting 的主要好处是您还可以使用相同的 class 进行训练,方法是在 class 上实施 training_step()configure_optimizers()train_dataloader() ].您可以在 PyTorchLightning docs.

中找到一个简单的示例