快捷方式

torch.jit.freeze

torch.jit.freeze(mod, preserved_attrs=None, optimize_numerics=True)[source][source]

凍結 ScriptModule,內聯子模組,並將屬性作為常數。

凍結 ScriptModule 將會複製它,並且嘗試將複製後的模組的子模組、參數和屬性內聯為 TorchScript IR Graph 中的常數。 預設情況下,forward 會被保留,以及 preserved_attrs 中指定的屬性和方法。此外,任何在保留方法中被修改的屬性也會被保留。

目前凍結僅接受處於 eval 模式的 ScriptModule。

凍結會應用通用的優化,無論在何種機器上,都能夠加速您的模型。 若要使用特定伺服器的設定進行進一步的優化,請在凍結後執行 optimize_for_inference

參數
  • mod (ScriptModule) – 要凍結的模組

  • preserved_attrs (Optional[List[str]]) – 除了 forward 方法外,要保留的屬性清單。 在保留方法中被修改的屬性也將被保留。

  • optimize_numerics (bool) – 如果 True,將會執行一組不嚴格保留數值的優化過程。 有關優化的完整詳細資訊,請參閱 torch.jit.run_frozen_optimizations

返回值

凍結的 ScriptModule

範例 (凍結具有參數的簡單模組)

    def forward(self, input):
        output = self.weight.mm(input)
        output = self.linear(output)
        return output

scripted_module = torch.jit.script(MyModule(2, 3).eval())
frozen_module = torch.jit.freeze(scripted_module)
# parameters have been removed and inlined into the Graph as constants
assert len(list(frozen_module.named_parameters())) == 0
# See the compiled graph as Python code
print(frozen_module.code)

範例 (凍結具有保留屬性的模組)

    def forward(self, input):
        self.modified_tensor += 1
        return input + self.modified_tensor

scripted_module = torch.jit.script(MyModule2().eval())
frozen_module = torch.jit.freeze(scripted_module, preserved_attrs=["version"])
# we've manually preserved `version`, so it still exists on the frozen module and can be modified
assert frozen_module.version == 1
frozen_module.version = 2
# `modified_tensor` is detected as being mutated in the forward, so freezing preserves
# it to retain model semantics
assert frozen_module(torch.tensor(1)) == torch.tensor(12)
# now that we've run it once, the next result will be incremented by one
assert frozen_module(torch.tensor(1)) == torch.tensor(13)

注意

也支援凍結子模組屬性:frozen_module = torch.jit.freeze(scripted_module, preserved_attrs=[“submodule.version”])

注意

如果您不確定為什麼屬性沒有被內聯為常數,您可以在 frozen_module.forward.graph 上執行 dump_alias_db 以查看凍結是否檢測到該屬性正在被修改。

注意

由於凍結會將權重設為常數並移除模組層次結構,因此 to 和其他 nn.Module 方法來操作裝置或 dtype 將不再起作用。作為一種變通方法,您可以通過在 torch.jit.load 中指定 map_location 來重新映射裝置,但是特定於裝置的邏輯可能已經嵌入到模型中。

文件

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources