Compare commits
2 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
9189819772 | |
|
|
06e3b1680c |
|
|
@ -1,35 +0,0 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
"""
|
||||
Model that performs matrix multiplication followed by ReLU activation.
|
||||
"""
|
||||
def __init__(self, weight):
|
||||
super(Model, self).__init__()
|
||||
self.weight = nn.Parameter(weight)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Performs matrix multiplication and applies ReLU activation.
|
||||
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor of shape [batch_size, input_dim]
|
||||
|
||||
Returns:
|
||||
torch.Tensor: Output tensor of shape [batch_size, output_dim]
|
||||
"""
|
||||
x = torch.matmul(x, self.weight)
|
||||
return torch.relu(x)
|
||||
|
||||
batch_size = 16
|
||||
input_dim = 1024
|
||||
output_dim = 2048
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, input_dim)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
weight = torch.randn(input_dim, output_dim)
|
||||
return [weight]
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
You write custom CUDA kernels to replace the pytorch operators in the given architecture to get speedups.
|
||||
|
||||
You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining matmul+relu), or algorithmic changes (such as online softmax). You are only limited by your imagination.
|
||||
|
||||
Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
|
||||
|
||||
```python
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
|
||||
def forward(self, a, b):
|
||||
return a + b
|
||||
|
||||
|
||||
def get_inputs():
|
||||
# randomly generate input tensors based on the model architecture
|
||||
a = torch.randn(1, 128).cuda()
|
||||
b = torch.randn(1, 128).cuda()
|
||||
return [a, b]
|
||||
|
||||
|
||||
def get_init_inputs():
|
||||
# randomly generate tensors required for initialization based on the model architecture
|
||||
return []
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
1. 根据example_torchcode.py的格式,提供一个torch实现的op,命名为torchcode.py
|
||||
2. 仿照prompt.txt的写法,利用llm(deepseek、通义千问、GPT、Gemini等大模型)生成一个初始的cuda算子,按照example_cudacode.py的格式组织成一个可以运行的cuda op,命名为cudacode_ori.py,并且利用run_code.py 检查算子精度
|
||||
3. 在符合精度要求的cudacode_ori.py基础上,进行cuda算子性能优化,用run_code.py检查算子精度和加速比,形成最终的最优性能的cuda算子实现,命名为cudacode_opt.py,格式符合example_cudacode.py
|
||||
4. 针对每一个op,参赛者需要提供四个文件,torchcode.py、prompt.txt、cudacode_ori.py、example_cudacode.py
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
|
||||
# 更简单的实现:只优化ReLU部分,矩阵乘法使用PyTorch
|
||||
import torch
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
relu_source = """
|
||||
#include <torch/extension.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
|
@ -38,12 +36,9 @@ relu = load_inline(
|
|||
)
|
||||
|
||||
class ModelNew(torch.nn.Module):
|
||||
def __init__(self, weight):
|
||||
def __init__(self):
|
||||
super(ModelNew, self).__init__()
|
||||
self.weight = nn.Parameter(weight)
|
||||
self.relu = relu # The module containing the kernel
|
||||
|
||||
def forward(self, x):
|
||||
# 使用PyTorch的矩阵乘法,只优化ReLU部分
|
||||
x = torch.matmul(x, self.weight)
|
||||
return self.relu.relu_cuda(x)
|
||||
return self.relu.relu_cuda(x)
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
class Model(nn.Module):
|
||||
"""
|
||||
Simple model that performs a ReLU activation.
|
||||
"""
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Applies ReLU activation to the input tensor.
|
||||
|
||||
Args:
|
||||
x (torch.Tensor): Input tensor of any shape.
|
||||
|
||||
Returns:
|
||||
torch.Tensor: Output tensor with ReLU applied, same shape as input.
|
||||
"""
|
||||
return torch.relu(x)
|
||||
|
||||
batch_size = 16
|
||||
dim = 16384
|
||||
|
||||
def get_inputs():
|
||||
x = torch.randn(batch_size, dim)
|
||||
return [x]
|
||||
|
||||
def get_init_inputs():
|
||||
return [] # No special initialization inputs needed
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from example_torchcode import Model, get_inputs, get_init_inputs
|
||||
from example_torchcode import Model,get_inputs,get_init_inputs
|
||||
from example_cudacode import ModelNew
|
||||
|
||||
def run_benchmark():
|
||||
|
|
@ -33,30 +33,17 @@ def run_benchmark():
|
|||
|
||||
print("-------------------- 精度对齐验证 --------------------")
|
||||
with torch.no_grad():
|
||||
output_torch = torch_model(*inputs)
|
||||
output_torch = torch_model( *inputs)
|
||||
output_cuda = cuda_model(*inputs)
|
||||
|
||||
# 更严格的精度检查
|
||||
abs_diff = (output_torch - output_cuda).abs()
|
||||
max_diff = abs_diff.max().item()
|
||||
mean_diff = abs_diff.mean().item()
|
||||
|
||||
print(f"最大差异: {max_diff:.6f}")
|
||||
print(f"平均差异: {mean_diff:.6f}")
|
||||
|
||||
precision_flag = torch.allclose(output_torch, output_cuda, rtol=1e-05, atol=1e-05)
|
||||
precision_flag = torch.allclose(output_torch, output_cuda,rtol=1e-03)
|
||||
if precision_flag:
|
||||
print("✅ 精度对齐:两个模型的输出结果非常接近。")
|
||||
else:
|
||||
print("❌ 精度不一致!")
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量
|
||||
|
||||
# Warm up
|
||||
for _ in range(100):
|
||||
_ = torch_model(*inputs)
|
||||
_ = cuda_model(*inputs)
|
||||
num_iterations = 100
|
||||
|
||||
# PyTorch 模型计时
|
||||
torch.cuda.synchronize()
|
||||
|
|
@ -74,15 +61,14 @@ def run_benchmark():
|
|||
torch.cuda.synchronize()
|
||||
cuda_time = (time.time() - start_time) / num_iterations
|
||||
|
||||
print(f"PyTorch (matmul + relu) 平均执行时间: {torch_time:.6f} 秒")
|
||||
print(f"自定义 CUDA ReLU 平均执行时间: {cuda_time:.6f} 秒")
|
||||
print(f"PyTorch torch.relu 平均执行时间: {torch_time:.6f} 秒")
|
||||
print(f"自定义 CUDA 内核 平均执行时间: {cuda_time:.6f} 秒")
|
||||
speedup = 0
|
||||
if cuda_time > 0:
|
||||
speedup = torch_time / cuda_time
|
||||
print(f"加速比 (Speedup): {speedup:.2f}x")
|
||||
else:
|
||||
print("CUDA 内核执行时间为0,无法计算加速比。")
|
||||
return precision_flag, speedup
|
||||
|
||||
return precision_flag,speedup
|
||||
if __name__ == "__main__":
|
||||
precision_flag, speedup = run_benchmark()
|
||||
precision_flag,speedup = run_benchmark()
|
||||
Loading…
Reference in New Issue