python
import torch
import torch.nn as nn
import time
import sys
# 尝试导入 thop 库
try:
from thop import profile
except ImportError:
print("Warning: thop library not found. FLOPs calculation will be skipped.")
print("Please install it using: pip install thop")
profile = None
# 1. 定义一个示例模型 (你可以替换成你自己的模型)
# 这是一个简单的卷积神经网络结构
class SimpleCNN(nn.Module):
def __init__(self, num_classes=10):
super(SimpleCNN, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2)
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.classifier = nn.Sequential(
nn.Linear(128, num_classes)
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
# 2. 测量模型开销的函数
def measure_model_metrics(model, input_shape, iterations=100, warmups=10):
"""
测量模型的 FLOPs (G), Parameters (M), 和推理时间 (ms)。
Args:
model (torch.nn.Module): 要测量的 PyTorch 模型。
input_shape (tuple): 输入张量的形状 (batch_size, channels, height, width, ...)。
iterations (int): 用于平均推理时间的测量次数。
warmups (int): 推理前的热身运行次数。
Returns:
dict: 包含 'flops', 'params', 'inference_time_ms' 的字典。
"""
print(f"--- Measuring Model Metrics ---")
# 1. 准备设备和输入数据
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
model.to(device)
model.eval() # 设置为评估模式 (不计算梯度,关闭 dropout 等)
# 创建一个虚拟输入张量
dummy_input = torch.randn(input_shape).to(device)
# 2. 计算 Parameters (M)
# sum(p.numel() for p in model.parameters()) 计算所有参数的数量
total_params = sum(p.numel() for p in model.parameters())
params_m = total_params / 1e6
print(f"Parameters: {params_m:.4f} M")
# 3. 计算 FLOPs (G)
flops_g = None
if profile is not None:
# thop.profile 返回 FLOPs 和 Params (Params可能与手动计算略有差异,我们主要用它算FLOPs)
# FLOPs 的定义可能因工具而异,thop 通常将乘加 (MAC) 计为 2 个 FLOPs。
try:
# profile 需要输入是 tuple
flops, _ = profile(model, inputs=(dummy_input,), verbose=False)
flops_g = flops / 1e9
print(f"FLOPs: {flops_g:.4f} G")
except Exception as e:
print(f"Error during FLOPs calculation: {e}")
else:
print("FLOPs calculation skipped because thop is not installed.")
# 4. 测量推理时间 (ms)
print(f"Measuring inference time over {iterations} iterations (with {warmups} warmups)...")
inference_time_ms = None
try:
with torch.no_grad(): # 不计算梯度,节省内存和时间
# 热身运行
for _ in range(warmups):
_ = model(dummy_input)
if device.type == 'cuda':
# GPU 计时需要同步
torch.cuda.synchronize()
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
start_event.record()
for _ in range(iterations):
_ = model(dummy_input)
end_event.record()
torch.cuda.synchronize() # 等待所有 GPU 任务完成
# elapsed_time 返回毫秒
average_time_ms = start_event.elapsed_time(end_event) / iterations
else: # CPU 计时
start_time = time.perf_counter()
for _ in range(iterations):
_ = model(dummy_input)
end_time = time.perf_counter()
# perf_counter 返回秒
average_time_ms = (end_time - start_time) * 1000 / iterations
inference_time_ms = average_time_ms
print(f"Average Inference Time: {inference_time_ms:.4f} ms")
except Exception as e:
print(f"Error during inference time measurement: {e}")
inference_time_ms = None # 计时失败
print(f"--- Measurement Complete ---")
return {
"flops": flops_g,
"params": params_m,
"inference_time_ms": inference_time_ms
}
# 3. 示例使用
if __name__ == "__main__":
# 示例:使用上面定义的 SimpleCNN 模型
model_to_measure = SimpleCNN(num_classes=10)
# 定义模型的输入形状 (Batch Size, Channels, Height, Width)
# 这里的 Batch Size 为 1,通常测试时使用 Batch Size 1
example_input_shape = (1, 3, 224, 224)
# 运行测量
metrics = measure_model_metrics(model_to_measure, example_input_shape, iterations=100, warmups=10)
# 打印最终结果
print("\n--- Final Results ---")
if metrics["flops"] is not None:
print(f"FLOPs: {metrics['flops']:.4f} G")
else:
print(f"FLOPs: N/A (thop not available)")
print(f"Parameters: {metrics['params']:.4f} M")
if metrics["inference_time_ms"] is not None:
print(f"Inference Time: {metrics['inference_time_ms']:.4f} ms (Avg over 100 runs)")
else:
print(f"Inference Time: N/A (Measurement failed)")
# 示例:使用 torchvision 中的预训练模型 (例如 ResNet18)
print("\n--- Measuring ResNet18 (from torchvision) ---")
try:
import torchvision.models as models
resnet18 = models.resnet18(pretrained=False) # 可以选择 pretrained=True
resnet_input_shape = (1, 3, 224, 224) # ResNet18 的标准输入尺寸
resnet_metrics = measure_model_metrics(resnet18, resnet_input_shape, iterations=100, warmups=10)
print("\n--- Final Results (ResNet18) ---")
if resnet_metrics["flops"] is not None:
print(f"FLOPs: {resnet_metrics['flops']:.4f} G")
else:
print(f"FLOPs: N/A (thop not available)")
print(f"Parameters: {resnet_metrics['params']:.4f} M")
if resnet_metrics["inference_time_ms"] is not None:
print(f"Inference Time: {resnet_metrics['inference_time_ms']:.4f} ms (Avg over 100 runs)")
else:
print(f"Inference Time: N/A (Measurement failed)")
except ImportError:
print("\nSkipping ResNet18 measurement: torchvision not found.")
except Exception as e:
print(f"\nError measuring ResNet18: {e}")
运行此脚本,你将看到为你指定的模型计算出的 Parameters (M)、FLOPs (G) 和平均 Inference Time (ms)。确保输入形状与你的模型实际接受的输入形状匹配。