Max*_*wer 6 python deep-learning pytorch fast-ai
每当我导出 fastai 模型并重新加载它时,当我尝试使用重新加载的模型在新测试集上生成预测时,我会收到此错误(或非常相似的错误):
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same
Run Code Online (Sandbox Code Playgroud)
下面的最小可重复代码示例,您只需要将FILES_DIR
变量更新为 MNIST 数据存放在系统上的位置:
from fastai import *
from fastai.vision import *
# download data for reproduceable example
untar_data(URLs.MNIST_SAMPLE)
FILES_DIR = '/home/mepstein/.fastai/data/mnist_sample' # this is where command above deposits the MNIST data for me
# Create FastAI databunch for model training
tfms = get_transforms()
tr_val_databunch = ImageDataBunch.from_folder(path=FILES_DIR, # location of downloaded data shown in log of prev command
train = 'train',
valid_pct = 0.2,
ds_tfms = tfms).normalize()
# Create Model
conv_learner = cnn_learner(tr_val_databunch,
models.resnet34,
metrics=[error_rate]).to_fp16()
# Train Model
conv_learner.fit_one_cycle(4)
# Export Model
conv_learner.export() # saves model as 'export.pkl' in path associated with the learner
# Reload Model and use it for inference on new hold-out set
reloaded_model = load_learner(path = FILES_DIR,
test = ImageList.from_folder(path = f'{FILES_DIR}/valid'))
preds = reloaded_model.get_preds(ds_type=DatasetType.Test)
Run Code Online (Sandbox Code Playgroud)
输出:
“运行时错误:输入类型(torch.cuda.FloatTensor)和权重类型(torch.cuda.HalfTensor)应该相同”
逐条执行代码语句,一切正常,直到最后一行pred = ...
出现上面的火炬错误。
相关软件版本:
Python 3.7.3 fastai 1.0.57
火炬 1.2.0 火炬
视觉 0.4.0
所以这个问题的答案相对简单:
1)正如我的评论中所述,混合精度模式(设置conv_learner
to_fp16()
)下的训练导致导出/重新加载模型出现错误
2) 要在混合精度模式下进行训练(比常规训练更快)并能够无错误地导出/重新加载模型,只需在导出之前将模型设置回默认精度即可。
...在代码中,只需更改上面的示例:
# Export Model
conv_learner.export()
Run Code Online (Sandbox Code Playgroud)
到:
# Export Model (after converting back to default precision for safe export/reload
conv_learner = conv_learner.to_fp32()
conv_learner.export()
Run Code Online (Sandbox Code Playgroud)
...现在上面的完整(可重现)代码示例运行没有错误,包括模型重新加载后的预测。