forked from ccf-ai-infra/GPUCodeForces
Merge pull request 'finish FusedAdamStep #121' (#769) from ZZZJ/GPUCodeForces:FusedAdamStep into main
This commit is contained in:
commit
70bb79e993
|
|
@ -0,0 +1,159 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.cpp_extension import load_inline
|
||||
import math
|
||||
|
||||
|
||||
cpp_src = """
|
||||
torch::Tensor adam_step_cuda(
|
||||
torch::Tensor param, torch::Tensor grad,
|
||||
torch::Tensor exp_avg, torch::Tensor exp_avg_sq,
|
||||
float lr, float beta1, float beta2, float eps,
|
||||
float bias_correction1, float bias_correction2
|
||||
);
|
||||
"""
|
||||
|
||||
cuda_src = """
|
||||
#include <cuda_runtime.h>
|
||||
#include <cmath>
|
||||
|
||||
__global__ void adam_step_strict_kernel(
|
||||
const float* __restrict__ param,
|
||||
const float* __restrict__ grad,
|
||||
const float* __restrict__ exp_avg,
|
||||
const float* __restrict__ exp_avg_sq,
|
||||
float* __restrict__ output,
|
||||
int total_vectors,
|
||||
float lr,
|
||||
float beta1,
|
||||
float beta2,
|
||||
float eps,
|
||||
float bias_correction1,
|
||||
float bias_correction2_sqrt
|
||||
) {
|
||||
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
int stride = blockDim.x * gridDim.x;
|
||||
|
||||
|
||||
const float4* p_ptr = reinterpret_cast<const float4*>(param);
|
||||
const float4* g_ptr = reinterpret_cast<const float4*>(grad);
|
||||
const float4* m_ptr = reinterpret_cast<const float4*>(exp_avg);
|
||||
const float4* v_ptr = reinterpret_cast<const float4*>(exp_avg_sq);
|
||||
float4* out_ptr = reinterpret_cast<float4*>(output);
|
||||
|
||||
float one_minus_beta1 = 1.0f - beta1;
|
||||
float one_minus_beta2 = 1.0f - beta2;
|
||||
float step_size = lr / bias_correction1;
|
||||
|
||||
for (int i = idx; i < total_vectors; i += stride) {
|
||||
|
||||
float4 vp = p_ptr[i];
|
||||
float4 vg = g_ptr[i];
|
||||
float4 vm = m_ptr[i];
|
||||
float4 vv = v_ptr[i];
|
||||
|
||||
float4 res;
|
||||
|
||||
float* pp = (float*)&vp;
|
||||
float* pg = (float*)&vg;
|
||||
float* pm = (float*)&vm;
|
||||
float* pv = (float*)&vv;
|
||||
float* pres = (float*)&res;
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
float p_val = pp[j];
|
||||
float g_val = pg[j];
|
||||
float m_val = pm[j];
|
||||
float v_val = pv[j];
|
||||
|
||||
float m_new = beta1 * m_val + one_minus_beta1 * g_val;
|
||||
|
||||
float g2 = g_val * g_val;
|
||||
float v_new = beta2 * v_val + one_minus_beta2 * g2;
|
||||
|
||||
float v_root = sqrtf(v_new);
|
||||
float denom = v_root / bias_correction2_sqrt + eps;
|
||||
|
||||
float update = step_size * (m_new / denom);
|
||||
|
||||
pres[j] = p_val - update;
|
||||
|
||||
|
||||
}
|
||||
|
||||
out_ptr[i] = res;
|
||||
}
|
||||
}
|
||||
|
||||
torch::Tensor adam_step_cuda(
|
||||
torch::Tensor param, torch::Tensor grad,
|
||||
torch::Tensor exp_avg, torch::Tensor exp_avg_sq,
|
||||
float lr, float beta1, float beta2, float eps,
|
||||
float bias_correction1, float bias_correction2
|
||||
) {
|
||||
int numel = param.numel();
|
||||
|
||||
param = param.contiguous();
|
||||
grad = grad.contiguous();
|
||||
exp_avg = exp_avg.contiguous();
|
||||
exp_avg_sq = exp_avg_sq.contiguous();
|
||||
|
||||
auto output = torch::empty_like(param);
|
||||
|
||||
if (numel % 4 != 0) { }
|
||||
|
||||
int total_vectors = numel / 4;
|
||||
const int block_size = 256;
|
||||
|
||||
int grid_size = (total_vectors + block_size - 1) / block_size;
|
||||
if (grid_size > 2048) grid_size = 2048;
|
||||
|
||||
float bias_correction2_sqrt = sqrtf(bias_correction2);
|
||||
|
||||
adam_step_strict_kernel<<<grid_size, block_size>>>(
|
||||
param.data_ptr<float>(),
|
||||
grad.data_ptr<float>(),
|
||||
exp_avg.data_ptr<float>(),
|
||||
exp_avg_sq.data_ptr<float>(),
|
||||
output.data_ptr<float>(),
|
||||
total_vectors,
|
||||
lr,
|
||||
beta1,
|
||||
beta2,
|
||||
eps,
|
||||
bias_correction1,
|
||||
bias_correction2_sqrt
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
"""
|
||||
|
||||
class ModelNew(nn.Module):
|
||||
def __init__(self, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, step=1):
|
||||
super().__init__()
|
||||
self.lr = lr
|
||||
self.beta1 = beta1
|
||||
self.beta2 = beta2
|
||||
self.eps = eps
|
||||
self.step = step
|
||||
|
||||
self.bias_correction1 = 1.0 - beta1 ** step
|
||||
self.bias_correction2 = 1.0 - beta2 ** step
|
||||
|
||||
self.module = load_inline(
|
||||
name="fused_adam_strict_v1",
|
||||
cpp_sources=cpp_src,
|
||||
cuda_sources=cuda_src,
|
||||
functions=["adam_step_cuda"],
|
||||
verbose=False,
|
||||
extra_cuda_cflags=["-O3", "--fmad=false"]
|
||||
)
|
||||
|
||||
def forward(self, param, grad, exp_avg, exp_avg_sq):
|
||||
return self.module.adam_step_cuda(
|
||||
param, grad, exp_avg, exp_avg_sq,
|
||||
self.lr, self.beta1, self.beta2, self.eps,
|
||||
self.bias_correction1, self.bias_correction2
|
||||
)
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
import torch
|
||||
import torch.nn as nn
|
||||
import math
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, step=1):
|
||||
super().__init__()
|
||||
self.lr = lr
|
||||
self.beta1 = beta1
|
||||
self.beta2 = beta2
|
||||
self.eps = eps
|
||||
self.step = step
|
||||
|
||||
def forward(self, param: torch.Tensor, grad: torch.Tensor, exp_avg: torch.Tensor, exp_avg_sq: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
new_exp_avg = self.beta1 * exp_avg + (1 - self.beta1) * grad
|
||||
|
||||
new_exp_avg_sq = self.beta2 * exp_avg_sq + (1 - self.beta2) * (grad * grad)
|
||||
|
||||
bias_correction1 = 1 - self.beta1 ** self.step
|
||||
bias_correction2 = 1 - self.beta2 ** self.step
|
||||
|
||||
step_size = self.lr / bias_correction1
|
||||
|
||||
denom = torch.sqrt(new_exp_avg_sq) / math.sqrt(bias_correction2) + self.eps
|
||||
|
||||
new_param = param - step_size * (new_exp_avg / denom)
|
||||
|
||||
return new_param
|
||||
|
||||
num_params = 1024 * 1024
|
||||
shape = (num_params, )
|
||||
|
||||
def get_inputs():
|
||||
param = torch.randn(shape, dtype=torch.float32)
|
||||
grad = torch.randn(shape, dtype=torch.float32) * 0.01
|
||||
exp_avg = torch.randn(shape, dtype=torch.float32) * 0.1
|
||||
exp_avg_sq = torch.rand(shape, dtype=torch.float32)
|
||||
return [param, grad, exp_avg, exp_avg_sq]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
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 math
|
||||
|
||||
class Model(nn.Module):
|
||||
def __init__(self, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, step=1):
|
||||
super().__init__()
|
||||
self.lr = lr
|
||||
self.beta1 = beta1
|
||||
self.beta2 = beta2
|
||||
self.eps = eps
|
||||
self.step = step
|
||||
|
||||
def forward(self, param: torch.Tensor, grad: torch.Tensor, exp_avg: torch.Tensor, exp_avg_sq: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
new_exp_avg = self.beta1 * exp_avg + (1 - self.beta1) * grad
|
||||
|
||||
new_exp_avg_sq = self.beta2 * exp_avg_sq + (1 - self.beta2) * (grad * grad)
|
||||
|
||||
bias_correction1 = 1 - self.beta1 ** self.step
|
||||
bias_correction2 = 1 - self.beta2 ** self.step
|
||||
|
||||
step_size = self.lr / bias_correction1
|
||||
|
||||
denom = torch.sqrt(new_exp_avg_sq) / math.sqrt(bias_correction2) + self.eps
|
||||
|
||||
new_param = param - step_size * (new_exp_avg / denom)
|
||||
|
||||
return new_param
|
||||
|
||||
num_params = 1024 * 1024
|
||||
shape = (num_params, )
|
||||
|
||||
def get_inputs():
|
||||
param = torch.randn(shape, dtype=torch.float32)
|
||||
grad = torch.randn(shape, dtype=torch.float32) * 0.01
|
||||
exp_avg = torch.randn(shape, dtype=torch.float32) * 0.1
|
||||
exp_avg_sq = torch.rand(shape, dtype=torch.float32)
|
||||
return [param, grad, exp_avg, exp_avg_sq]
|
||||
|
||||
def get_init_inputs():
|
||||
return []
|
||||
```
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
###########################################################
|
||||
# 性能和精度验证程序
|
||||
###########################################################
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import time
|
||||
from fused_adam_step_torch import Model,get_inputs,get_init_inputs
|
||||
from fused_adam_step_cuda import ModelNew
|
||||
|
||||
def run_benchmark():
|
||||
# 检查 CUDA 是否可用
|
||||
if not torch.cuda.is_available():
|
||||
print("CUDA 不可用,请确保您有可用的 NVIDIA GPU 并已正确安装 PyTorch CUDA 版本。")
|
||||
return
|
||||
else:
|
||||
device = torch.device("cuda")
|
||||
|
||||
# 初始化模型
|
||||
init_inputs = get_init_inputs()
|
||||
init_inputs = [
|
||||
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in init_inputs
|
||||
]
|
||||
inputs = get_inputs()
|
||||
inputs = [
|
||||
x.cuda(device=device) if isinstance(x, torch.Tensor) else x for x in inputs
|
||||
]
|
||||
|
||||
torch_model = Model(*init_inputs).cuda()
|
||||
cuda_model = ModelNew(*init_inputs).cuda()
|
||||
|
||||
torch_model.eval()
|
||||
cuda_model.eval()
|
||||
|
||||
print("-------------------- 精度对齐验证 --------------------")
|
||||
with torch.no_grad():
|
||||
output_torch = torch_model( *inputs)
|
||||
output_cuda = cuda_model(*inputs)
|
||||
|
||||
precision_flag = torch.allclose(output_torch, output_cuda,rtol=1e-03)
|
||||
if precision_flag:
|
||||
print("✅ 精度对齐:两个模型的输出结果非常接近。")
|
||||
else:
|
||||
print("❌ 精度不一致!")
|
||||
|
||||
print("\n-------------------- 性能加速比测试 --------------------")
|
||||
num_iterations = 100
|
||||
|
||||
# PyTorch 模型计时
|
||||
torch.cuda.synchronize()
|
||||
start_time = time.time()
|
||||
for _ in range(num_iterations):
|
||||
_ = torch_model(*inputs)
|
||||
torch.cuda.synchronize()
|
||||
torch_time = (time.time() - start_time) / num_iterations
|
||||
|
||||
# 自定义 CUDA 内核计时
|
||||
torch.cuda.synchronize()
|
||||
start_time = time.time()
|
||||
for _ in range(num_iterations):
|
||||
_ = cuda_model(*inputs)
|
||||
torch.cuda.synchronize()
|
||||
cuda_time = (time.time() - start_time) / num_iterations
|
||||
|
||||
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
|
||||
if __name__ == "__main__":
|
||||
precision_flag,speedup = run_benchmark()
|
||||
Loading…
Reference in New Issue