torch.jit.load#
- torch.jit.load(f, map_location=None, _extra_files=None, _restore_shapes=False)[source]#
加载之前使用
torch.jit.save
保存的ScriptModule
或ScriptFunction
。所有先前保存的模块,无论其设备如何,都首先加载到 CPU,然后移动到它们保存时的设备。如果失败(例如,因为运行时系统没有某些设备),则会引发异常。
- 参数
f – 一个类似文件的对象(必须实现 read、readline、tell 和 seek),或者包含文件名的字符串
map_location (string 或 torch.device) –
torch.jit.save
中map_location
的简化版本,用于将存储动态映射到备用设备集。_extra_files (filename 到 content 的字典) – 映射中提供的额外文件名将被加载,并且其内容将存储在提供的映射中。
_restore_shapes (bool) – 在加载时使用存储的输入重新跟踪模块
- 返回
一个
ScriptModule
对象。
警告
有可能构造恶意的 pickle 数据,它会在 func:torch.jit.load 期间执行任意代码。切勿加载可能来自不受信任来源或可能被篡改的数据。只加载您信任的数据。
示例: .. testcode
import torch import io torch.jit.load('scriptmodule.pt') # Load ScriptModule from io.BytesIO object with open('scriptmodule.pt', 'rb') as f: buffer = io.BytesIO(f.read()) # Load all tensors to the original device torch.jit.load(buffer) # Load all tensors onto CPU, using a device buffer.seek(0) torch.jit.load(buffer, map_location=torch.device('cpu')) # Load all tensors onto CPU, using a string buffer.seek(0) torch.jit.load(buffer, map_location='cpu') # Load with extra files. extra_files = {'foo.txt': ''} # values will be replaced with data torch.jit.load('scriptmodule.pt', _extra_files=extra_files) print(extra_files['foo.txt'])