torch.jit.load¶
- torch.jit.load(f, map_location=None, _extra_files=None, _restore_shapes=False)[源][源]¶
加载之前使用 torch.jit.save 保存的 ScriptModule 或 ScriptFunction。
所有之前保存的模块,无论其设备是什么,都会先加载到 CPU,然后再移动到它们保存时所在的设备。如果此操作失败(例如,因为运行时系统没有某些设备),则会引发异常。
- 参数
f – 一个文件状对象(必须实现 read、readline、tell 和 seek 方法),或者一个包含文件名的字符串
map_location (string or torch.device) – torch.jit.save 中
map_location
的简化版本,用于将存储动态重新映射到另一组设备。_extra_files (dictionary of filename to 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'])