











在 PyTorch 中,Eager 模式(也称为 动态图模式 或 即时模式)和 编译模式(如 torch.compile)是两种不同的执行模式,它们在模型的执行和优化方面有不同的行为。下面是对这两种模式的详细解释,特别是关于 Eager 模式 的含义。
Eager 模式 是 PyTorch 的默认执行模式。在这种模式下,每个操作都会立即执行,并且计算图是动态构建的。这意味着:
编译模式(例如使用 torch.compile)通过将模型编译成优化的内核来提高性能。在这种模式下,模型的执行过程如下:
为了更好地理解这两种模式的区别,以下是一个简单的对比示例:
import torch
import torch.nn as nn
# 定义一个简单的模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)
model = SimpleModel()
input_data = torch.randn(1, 10)
# 前向传播
output = model(input_data)
print(output)
# 反向传播
output.backward()
print(model.fc.weight.grad)
在这个示例中,每个操作(如 model(input_data) 和 output.backward())都会立即执行。
import torch
import torch.nn as nn
import torch._dynamo as dynamo
# 定义一个简单的模型
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(10, 1)
def forward(self, x):
return self.fc(x)
model = SimpleModel()
input_data = torch.randn(1, 10)
# 使用 torch.compile 编译模型
compiled_model = torch.compile(model)
# 第一次前向传播(包含编译开销)
output = compiled_model(input_data)
print(output)
# 反向传播
output.backward()
print(model.fc.weight.grad)
# 第二次前向传播(编译后的执行)
output = compiled_model(input_data)
print(output)
在这个示例中,torch.compile 会编译模型,第一次执行时会有额外的编译开销,但后续执行会更快。
Eager 模式(即时模式):
编译模式(如 torch.compile):
torch.compile 比 Eager 更慢初次执行?正如教程中提到的,torch.compile 在初次执行时会花费更多时间,原因如下:
torch.compile 需要将模型编译成优化的内核,这需要额外的时间。然而,一旦模型被编译,后续的执行会显著加快,因为编译后的内核已经经过优化,可以直接使用。
Generated by Qwen2-Math-72B-Instruct
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。