torch.jit.trace_module¶
- torch.jit.trace_module(mod, inputs, optimize=None, check_trace=True, check_inputs=None, check_tolerance=1e-05, strict=True, _force_outplace=False, _module_class=None, _compilation_unit=<torch.jit.CompilationUnit object>, example_inputs_is_kwarg=False, _store_inputs=True)[source][source]¶
跟踪模块并返回可执行的
ScriptModule
,它将使用即时编译进行优化。当模块传递给
torch.jit.trace
时,仅运行和跟踪forward
方法。使用trace_module
,您可以指定方法名称到示例输入的字典以进行跟踪(请参阅下面的inputs
参数)。有关跟踪的更多信息,请参阅
torch.jit.trace
。- 参数
mod (torch.nn.Module) – 包含
torch.nn.Module
的方法,这些方法的名称在inputs
中指定。给定的方法将编译为单个 ScriptModule 的一部分。inputs (dict) – 一个字典,包含按
mod
中的方法名称索引的示例输入。在跟踪时,输入将传递给名称与输入键对应的方法。{ 'forward' : example_forward_input, 'method2': example_method2_input}
- 关键字参数
check_trace (
bool
, 可选) – 检查通过跟踪代码运行的相同输入是否产生相同的输出。默认值:True
。如果例如您的网络包含非确定性操作,或者您确定网络是正确的,即使检查器失败,您可能需要禁用此项。check_inputs (list of dicts, 可选) – 输入参数字典的列表,应该用于检查跟踪是否符合预期。每个元组等效于一组输入参数,这些参数将在
inputs
中指定。为了获得最佳结果,请传入一组检查输入,这些输入代表您期望网络看到的形状和输入类型空间。如果未指定,则原始inputs
用于检查check_tolerance (float, 可选) – 在检查器过程中使用的浮点比较容差。这可以用于在已知原因(例如算子融合)导致结果在数值上发散的情况下放宽检查器的严格性。
example_inputs_is_kwarg (
bool
, 可选) – 此参数指示示例输入是否为关键字参数包。默认值:False
。
- 返回值
具有单个
forward
方法的ScriptModule
对象,该方法包含跟踪的代码。当func
是torch.nn.Module
时,返回的ScriptModule
将具有与func
相同的子模块和参数集。
示例(跟踪具有多个方法的模块)
import torch import torch.nn as nn class Net(nn.Module): def __init__(self) -> None: super().__init__() self.conv = nn.Conv2d(1, 1, 3) def forward(self, x): return self.conv(x) def weighted_kernel_sum(self, weight): return weight * self.conv.weight n = Net() example_weight = torch.rand(1, 1, 3, 3) example_forward_input = torch.rand(1, 1, 3, 3) # Trace a specific method and construct `ScriptModule` with # a single `forward` method module = torch.jit.trace(n.forward, example_forward_input) # Trace a module (implicitly traces `forward`) and construct a # `ScriptModule` with a single `forward` method module = torch.jit.trace(n, example_forward_input) # Trace specific methods on a module (specified in `inputs`), constructs # a `ScriptModule` with `forward` and `weighted_kernel_sum` methods inputs = {'forward' : example_forward_input, 'weighted_kernel_sum' : example_weight} module = torch.jit.trace_module(n, inputs)