评价此页

torch.jit.load#

torch.jit.load(f, map_location=None, _extra_files=None, _restore_shapes=False)[source]#

加载之前使用 torch.jit.save 保存的 ScriptModuleScriptFunction

所有之前保存的模块,无论其设备如何,都会首先加载到 CPU,然后移动到它们保存时的设备。如果失败(例如,因为运行时系统没有某些设备),则会引发异常。

参数
  • f – 一个文件对象(必须实现 read, readline, tell, 和 seek),或一个包含文件名字符串

  • map_location (stringtorch.device) – torch.jit.savemap_location 的一个简化版本,用于动态地将存储重新映射到一组备用设备。

  • _extra_files (filename 到 content 的字典) – 在 map 中给出的额外文件名将被加载,并且其内容将存储在提供的 map 中。

  • _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'])