From 9a38eca08a50d30b7d4b870da3b8a73009674345 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 4 Nov 2025 15:54:08 +0800 Subject: [PATCH 1/3] fixes switchablenorm #12 --- S1/12/prompt.txt | 95 ++++++++++++++++++++ S1/12/run_code.py | 88 +++++++++++++++++++ S1/12/switchablenorm_cuda.py | 161 ++++++++++++++++++++++++++++++++++ S1/12/switchablenorm_torch.py | 88 +++++++++++++++++++ 4 files changed, 432 insertions(+) create mode 100644 S1/12/prompt.txt create mode 100644 S1/12/run_code.py create mode 100644 S1/12/switchablenorm_cuda.py create mode 100644 S1/12/switchablenorm_torch.py diff --git a/S1/12/prompt.txt b/S1/12/prompt.txt new file mode 100644 index 0000000..21db499 --- /dev/null +++ b/S1/12/prompt.txt @@ -0,0 +1,95 @@ +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 +# switchablenorm_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + +# 定义输入尺寸 (N, C, H, W) +N, C, H, W = 16, 64, 32, 32 +EPS = 1e-5 + +class SN(nn.Module): + + def __init__(self, num_channels, eps): + super().__init__() + self.eps = eps + + self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) # gamma + self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) # beta + + self.w_in = nn.Parameter(torch.ones(num_channels)) + self.w_ln = nn.Parameter(torch.ones(num_channels)) + self.w_bn = nn.Parameter(torch.ones(num_channels)) + + self.register_buffer('running_mean', torch.zeros(num_channels)) + self.register_buffer('running_var', torch.ones(num_channels)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + ln_mean = x.mean(dim=[1, 2, 3], keepdim=True) + ln_var = x.var(dim=[1, 2, 3], keepdim=True) + + + in_mean = x.mean(dim=[2, 3], keepdim=True) + in_var = x.var(dim=[2, 3], keepdim=True) + + + bn_mean = self.running_mean.view(1, C, 1, 1) + bn_var = self.running_var.view(1, C, 1, 1) + + w_sum = self.w_in.abs() + self.w_ln.abs() + self.w_bn.abs() + w_in_norm = (self.w_in.abs() / w_sum).view(1, C, 1, 1) + w_ln_norm = (self.w_ln.abs() / w_sum).view(1, C, 1, 1) + w_bn_norm = (self.w_bn.abs() / w_sum).view(1, C, 1, 1) + + mean = w_in_norm * in_mean + w_ln_norm * ln_mean + w_bn_norm * bn_mean + + + var_in_M2 = in_var + in_mean.pow(2) + var_ln_M2 = ln_var + ln_mean.pow(2) + var_bn_M2 = bn_var + bn_mean.pow(2) + + aggregated_var_M2 = w_in_norm * var_in_M2 + w_ln_norm * var_ln_M2 + w_bn_norm * var_bn_M2 + var = aggregated_var_M2 - mean.pow(2) + + + x_norm = (x - mean) / torch.sqrt(var + self.eps) + return x_norm * self.weight + self.bias + + +class Model(nn.Module): + def __init__(self, weight, bias, w_in, w_ln, w_bn): + super().__init__() + self.sn = SN(C, EPS) + + with torch.no_grad(): + self.sn.weight.data.copy_(weight) + self.sn.bias.data.copy_(bias) + self.sn.w_in.data.copy_(w_in.squeeze()) + self.sn.w_ln.data.copy_(w_ln.squeeze()) + self.sn.w_bn.data.copy_(w_bn.squeeze()) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.sn(x) + + +def get_inputs(): + + x = torch.randn(N, C, H, W, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + + w_in = torch.ones(C) + w_ln = torch.ones(C) + w_bn = torch.ones(C) + weight = torch.ones(1, C, 1, 1) + bias = torch.zeros(1, C, 1, 1) + return [weight, bias, w_in, w_ln, w_bn] \ No newline at end of file diff --git a/S1/12/run_code.py b/S1/12/run_code.py new file mode 100644 index 0000000..8c4dd72 --- /dev/null +++ b/S1/12/run_code.py @@ -0,0 +1,88 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from switchablenorm_torch import Model, get_inputs, get_init_inputs +from switchablenorm_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) + + # 更严格的精度检查 + 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) + if precision_flag: + print("✅ 精度对齐:两个模型的输出结果非常接近。") + else: + print("❌ 精度不一致!") + + print("\n-------------------- 性能加速比测试 --------------------") + num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量 + + # Warm up + for _ in range(100): + _ = torch_model(*inputs) + _ = cuda_model(*inputs) + + # 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒") + print(f"自定义 CUDA ReLU 平均执行时间: {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() \ No newline at end of file diff --git a/S1/12/switchablenorm_cuda.py b/S1/12/switchablenorm_cuda.py new file mode 100644 index 0000000..b2d6429 --- /dev/null +++ b/S1/12/switchablenorm_cuda.py @@ -0,0 +1,161 @@ +# switchablenorm_cuda.py +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +from switchablenorm_torch import N, C, H, W, EPS + +class ModelNew(nn.Module): + + def __init__(self, weight, bias, w_in, w_ln, w_bn): + super().__init__() + self.register_buffer('weight', weight) + self.register_buffer('bias', bias) + self.register_buffer('w_in', w_in) + self.register_buffer('w_ln', w_ln) + self.register_buffer('w_bn', w_bn) + self.eps = EPS + self.register_buffer('running_mean', torch.zeros(C)) + self.register_buffer('running_var', torch.ones(C)) + self._compile_cuda_kernel() + + def _compile_cuda_kernel(self): + cpp_source = """ + #include + + torch::Tensor sn_forward_cuda( + torch::Tensor input, torch::Tensor weight, torch::Tensor bias, + torch::Tensor w_in, torch::Tensor w_ln, torch::Tensor w_bn, + torch::Tensor running_mean, torch::Tensor running_var, + float eps, int N, int C, int H, int W); + """ + + cuda_source = f""" + #include + #include + #include + + #define BLOCK_SIZE 256 + #define WARP_SIZE 32 + + __device__ __forceinline__ float warp_reduce_sum(float val) {{ + for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) + val += __shfl_down_sync(0xffffffff, val, offset); + return val; + }} + + __global__ void sn_normalize_kernel( + const float* __restrict__ x, + const float* __restrict__ ln_mean_ptr, const float* __restrict__ ln_var_ptr, + const float* __restrict__ in_mean_ptr, const float* __restrict__ in_var_ptr, + const float* __restrict__ bn_mean_ptr, const float* __restrict__ bn_var_ptr, + const float* __restrict__ weight_ptr, const float* __restrict__ bias_ptr, + const float* __restrict__ w_in_ptr, const float* __restrict__ w_ln_ptr, const float* __restrict__ w_bn_ptr, + float* __restrict__ output, + int N, int C, int H, int W, float eps + ) {{ + int n_elements = N * C * H * W; + int idx = blockIdx.x * blockDim.x + threadIdx.x; + + if (idx >= n_elements) return; + + int nc_idx = idx / (H * W); + int sample_idx = nc_idx / C; + int channel_idx = nc_idx % C; + + float w_in = w_in_ptr[channel_idx]; + float w_ln = w_ln_ptr[channel_idx]; + float w_bn = w_bn_ptr[channel_idx]; + + float w_sum = fabsf(w_in) + fabsf(w_ln) + fabsf(w_bn); + float w_in_norm = fabsf(w_in) / w_sum; + float w_ln_norm = fabsf(w_ln) / w_sum; + float w_bn_norm = fabsf(w_bn) / w_sum; + + float mean_ln = ln_mean_ptr[sample_idx]; + float var_ln = ln_var_ptr[sample_idx]; + + float mean_in = in_mean_ptr[nc_idx]; + float var_in = in_var_ptr[nc_idx]; + + float mean_bn = bn_mean_ptr[channel_idx]; + float var_bn = bn_var_ptr[channel_idx]; + + float agg_mean = w_in_norm * mean_in + w_ln_norm * mean_ln + w_bn_norm * mean_bn; + + float m2_in = var_in + mean_in * mean_in; + float m2_ln = var_ln + mean_ln * mean_ln; + float m2_bn = var_bn + mean_bn * mean_bn; + + float agg_m2 = w_in_norm * m2_in + w_ln_norm * m2_ln + w_bn_norm * m2_bn; + float agg_var = agg_m2 - agg_mean * agg_mean; + + float val = x[idx]; + float gamma = weight_ptr[channel_idx]; + float beta = bias_ptr[channel_idx]; + + float inv_std = rsqrtf(agg_var + eps); + float normalized = (val - agg_mean) * inv_std; + + output[idx] = normalized * gamma + beta; + }} + + + torch::Tensor sn_forward_cuda( + torch::Tensor input, torch::Tensor weight, torch::Tensor bias, + torch::Tensor w_in, torch::Tensor w_ln, torch::Tensor w_bn, + torch::Tensor running_mean, torch::Tensor running_var, + float eps, int N, int C, int H, int W) {{ + + + torch::Tensor in_mean = input.mean({{2, 3}}, true).squeeze(-1).squeeze(-1).contiguous(); + torch::Tensor in_var = input.var({{2, 3}}, true).squeeze(-1).squeeze(-1).contiguous(); + + torch::Tensor ln_mean = input.mean({{1, 2, 3}}, true).squeeze(-1).squeeze(-1).squeeze(-1).contiguous(); + torch::Tensor ln_var = input.var({{1, 2, 3}}, true).squeeze(-1).squeeze(-1).squeeze(-1).contiguous(); + + auto output = torch::empty_like(input).contiguous(); + + int n_elements = input.numel(); + const int blocks = (n_elements + BLOCK_SIZE - 1) / BLOCK_SIZE; + + sn_normalize_kernel<<>>( + input.data_ptr(), + ln_mean.data_ptr(), ln_var.data_ptr(), + in_mean.data_ptr(), in_var.data_ptr(), + running_mean.data_ptr(), running_var.data_ptr(), + weight.data_ptr(), bias.data_ptr(), + w_in.data_ptr(), w_ln.data_ptr(), w_bn.data_ptr(), + output.data_ptr(), + N, C, H, W, eps + ); + + return output; + }} + """ + + self.sn_op = load_inline( + name="sn_fused_op_logic_correct_v3", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["sn_forward_cuda"], + extra_cuda_cflags=["-O3", "--use_fast_math"], + verbose=True + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + weight = self.weight.squeeze().contiguous() + bias = self.bias.squeeze().contiguous() + w_in = self.w_in.contiguous() + w_ln = self.w_ln.contiguous() + w_bn = self.w_bn.contiguous() + running_mean = self.running_mean.contiguous() + running_var = self.running_var.contiguous() + + N, C, H, W = x.size(0), x.size(1), x.size(2), x.size(3) + + return self.sn_op.sn_forward_cuda( + x.contiguous(), weight, bias, w_in, w_ln, w_bn, + running_mean, running_var, self.eps, N, C, H, W + ) \ No newline at end of file diff --git a/S1/12/switchablenorm_torch.py b/S1/12/switchablenorm_torch.py new file mode 100644 index 0000000..c2fb09d --- /dev/null +++ b/S1/12/switchablenorm_torch.py @@ -0,0 +1,88 @@ +# switchablenorm_torch.py +import torch +import torch.nn as nn +import torch.nn.functional as F + +# 定义输入尺寸 (N, C, H, W) +N, C, H, W = 16, 64, 32, 32 +EPS = 1e-5 + +class SN(nn.Module): + + def __init__(self, num_channels, eps): + super().__init__() + self.eps = eps + + self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) # gamma + self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) # beta + + self.w_in = nn.Parameter(torch.ones(num_channels)) + self.w_ln = nn.Parameter(torch.ones(num_channels)) + self.w_bn = nn.Parameter(torch.ones(num_channels)) + + self.register_buffer('running_mean', torch.zeros(num_channels)) + self.register_buffer('running_var', torch.ones(num_channels)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + + ln_mean = x.mean(dim=[1, 2, 3], keepdim=True) + ln_var = x.var(dim=[1, 2, 3], keepdim=True) + + + in_mean = x.mean(dim=[2, 3], keepdim=True) + in_var = x.var(dim=[2, 3], keepdim=True) + + + bn_mean = self.running_mean.view(1, C, 1, 1) + bn_var = self.running_var.view(1, C, 1, 1) + + w_sum = self.w_in.abs() + self.w_ln.abs() + self.w_bn.abs() + w_in_norm = (self.w_in.abs() / w_sum).view(1, C, 1, 1) + w_ln_norm = (self.w_ln.abs() / w_sum).view(1, C, 1, 1) + w_bn_norm = (self.w_bn.abs() / w_sum).view(1, C, 1, 1) + + mean = w_in_norm * in_mean + w_ln_norm * ln_mean + w_bn_norm * bn_mean + + + var_in_M2 = in_var + in_mean.pow(2) + var_ln_M2 = ln_var + ln_mean.pow(2) + var_bn_M2 = bn_var + bn_mean.pow(2) + + aggregated_var_M2 = w_in_norm * var_in_M2 + w_ln_norm * var_ln_M2 + w_bn_norm * var_bn_M2 + var = aggregated_var_M2 - mean.pow(2) + + + x_norm = (x - mean) / torch.sqrt(var + self.eps) + return x_norm * self.weight + self.bias + + +class Model(nn.Module): + def __init__(self, weight, bias, w_in, w_ln, w_bn): + super().__init__() + self.sn = SN(C, EPS) + + with torch.no_grad(): + self.sn.weight.data.copy_(weight) + self.sn.bias.data.copy_(bias) + self.sn.w_in.data.copy_(w_in.squeeze()) + self.sn.w_ln.data.copy_(w_ln.squeeze()) + self.sn.w_bn.data.copy_(w_bn.squeeze()) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.sn(x) + + +def get_inputs(): + + x = torch.randn(N, C, H, W, dtype=torch.float32) + return [x] + + +def get_init_inputs(): + + w_in = torch.ones(C) + w_ln = torch.ones(C) + w_bn = torch.ones(C) + weight = torch.ones(1, C, 1, 1) + bias = torch.zeros(1, C, 1, 1) + return [weight, bias, w_in, w_ln, w_bn] \ No newline at end of file From af453c19b00ea7c6aa2996725dc2d24f711dfc17 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 4 Nov 2025 16:40:11 +0800 Subject: [PATCH 2/3] fixes switchable #12 --- S1/12/prompt.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/S1/12/prompt.txt b/S1/12/prompt.txt index 21db499..771ee7e 100644 --- a/S1/12/prompt.txt +++ b/S1/12/prompt.txt @@ -10,7 +10,6 @@ import torch import torch.nn as nn import torch.nn.functional as F -# 定义输入尺寸 (N, C, H, W) N, C, H, W = 16, 64, 32, 32 EPS = 1e-5 From 5dd881c63d66cbcdc89dfc5c2336d6b40eb36675 Mon Sep 17 00:00:00 2001 From: ZZZJ <3056485198@qq.com> Date: Tue, 4 Nov 2025 16:50:29 +0800 Subject: [PATCH 3/3] delete 11 --- S1/11/frn_cuda.py | 137 --------------------------------------------- S1/11/frn_torch.py | 40 ------------- S1/11/prompt.txt | 47 ---------------- S1/11/run_code.py | 88 ----------------------------- 4 files changed, 312 deletions(-) delete mode 100644 S1/11/frn_cuda.py delete mode 100644 S1/11/frn_torch.py delete mode 100644 S1/11/prompt.txt delete mode 100644 S1/11/run_code.py diff --git a/S1/11/frn_cuda.py b/S1/11/frn_cuda.py deleted file mode 100644 index 7582e1f..0000000 --- a/S1/11/frn_cuda.py +++ /dev/null @@ -1,137 +0,0 @@ -import torch -import torch.nn as nn -from torch.utils.cpp_extension import load_inline - -from frn_torch import N, C, H, W, EPS - -assert (H * W) % 4 == 0, "Instance size (H * W) must be a multiple of 4 for float4 vectorization" - -class ModelNew(nn.Module): - def __init__(self, frn_weight, frn_bias): - super().__init__() - self.weight = nn.Parameter(frn_weight.clone()) - self.bias = nn.Parameter(frn_bias.clone()) - - self.eps = EPS - self._compile_cuda_kernel() - - def _compile_cuda_kernel(self): - cpp_source = """ - #include - torch::Tensor frn_forward_cuda( - torch::Tensor input, torch::Tensor weight, torch::Tensor bias, - float eps); - """ - - cuda_source = """ - #include - #include - #include - - #define BLOCK_SIZE 256 - #define WARP_SIZE 32 - - __device__ __forceinline__ float warp_reduce_sum(float val) { - for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) - val += __shfl_down_sync(0xffffffff, val, offset); - return val; - } - - __global__ void frn_fused_vectorized_kernel( - const float* __restrict__ x, - const float* __restrict__ weight, - const float* __restrict__ bias, - float* __restrict__ y, - int N, int C, int H, int W, float eps - ) { - __shared__ float s_warp_sum_sqs[BLOCK_SIZE / WARP_SIZE]; - - int nc_idx = blockIdx.x; - if (nc_idx >= N * C) return; - - int sample_idx = nc_idx / C; - int channel_idx = nc_idx % C; - int instance_size = H * W; - const int instance_size_div4 = instance_size / 4; - - int instance_offset = (sample_idx * C + channel_idx) * instance_size; - - const float4* x4_ptr = reinterpret_cast(x + instance_offset); - float4* y4_ptr = reinterpret_cast(y + instance_offset); - - float thread_sum_sq = 0.0f; - for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) { - float4 val4 = x4_ptr[i_vec]; - thread_sum_sq += val4.x * val4.x; - thread_sum_sq += val4.y * val4.y; - thread_sum_sq += val4.z * val4.z; - thread_sum_sq += val4.w * val4.w; - } - - float warp_sum_sq = warp_reduce_sum(thread_sum_sq); - - int warp_id = threadIdx.x / WARP_SIZE; - int lane_id = threadIdx.x % WARP_SIZE; - if (lane_id == 0) s_warp_sum_sqs[warp_id] = warp_sum_sq; - __syncthreads(); - - warp_sum_sq = (threadIdx.x < BLOCK_SIZE / WARP_SIZE) ? s_warp_sum_sqs[lane_id] : 0.0f; - if (warp_id == 0) warp_sum_sq = warp_reduce_sum(warp_sum_sq); - - if (threadIdx.x == 0) { - float mean_sq = warp_sum_sq / instance_size; - s_warp_sum_sqs[0] = rsqrtf(mean_sq + eps); - } - __syncthreads(); - - float inv_stddev = s_warp_sum_sqs[0]; - - float w = weight[channel_idx]; - float b = bias[channel_idx]; - - for (int i_vec = threadIdx.x; i_vec < instance_size_div4; i_vec += BLOCK_SIZE) { - float4 x_val4 = x4_ptr[i_vec]; - - // FRN: y = x * inv_stddev * gamma + beta - x_val4.x = x_val4.x * inv_stddev * w + b; - x_val4.y = x_val4.y * inv_stddev * w + b; - x_val4.z = x_val4.z * inv_stddev * w + b; - x_val4.w = x_val4.w * inv_stddev * w + b; - - y4_ptr[i_vec] = x_val4; - } - } - - torch::Tensor frn_forward_cuda( - torch::Tensor input, torch::Tensor weight, torch::Tensor bias, - float eps) { - - const int N = input.size(0); - const int C = input.size(1); - const int H = input.size(2); - const int W = input.size(3); - auto output = torch::empty_like(input); - - const int blocks = N * C; - const int threads = BLOCK_SIZE; - size_t shared_mem_size = (threads / WARP_SIZE) * sizeof(float); - - frn_fused_vectorized_kernel<<>>( - input.data_ptr(), - weight.contiguous().view(-1).data_ptr(), - bias.contiguous().view(-1).data_ptr(), - output.data_ptr(), N, C, H, W, eps); - return output; - } - """ - self.frn_op = load_inline( - name="frn_fused_op_vectorized_final", - cpp_sources=cpp_source, cuda_sources=cuda_source, - functions=["frn_forward_cuda"], - extra_cuda_cflags=["-O3", "--use_fast_math"], verbose=False - ) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.frn_op.frn_forward_cuda( - x.contiguous(), self.weight, self.bias, self.eps - ) \ No newline at end of file diff --git a/S1/11/frn_torch.py b/S1/11/frn_torch.py deleted file mode 100644 index 75b4fe4..0000000 --- a/S1/11/frn_torch.py +++ /dev/null @@ -1,40 +0,0 @@ -# frn_torch.py -import torch -import torch.nn as nn -import torch.nn.functional as F - -# 定义维度常量 -N, C, H, W = 32, 64, 56, 56 -EPS = 1e-6 - -class FRN(nn.Module): - def __init__(self, num_channels, eps): - super().__init__() - self.eps = eps - self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) - self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True) - x_normalized = x / torch.sqrt(nu2 + self.eps) - return x_normalized * self.weight + self.bias - -class Model(nn.Module): - def __init__(self, frn_weight, frn_bias): - super().__init__() - self.frn = FRN(C, EPS) - with torch.no_grad(): - self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1)) - self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.frn(x) - -def get_inputs(): - x = torch.randn(N, C, H, W, dtype=torch.float32) - return [x] - -def get_init_inputs(): - frn_weight = torch.ones(1, C, 1, 1) - frn_bias = torch.zeros(1, C, 1, 1) - return [frn_weight, frn_bias] \ No newline at end of file diff --git a/S1/11/prompt.txt b/S1/11/prompt.txt deleted file mode 100644 index 6b17228..0000000 --- a/S1/11/prompt.txt +++ /dev/null @@ -1,47 +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 -# frn_torch.py -import torch -import torch.nn as nn -import torch.nn.functional as F - -# 定义维度常量 -N, C, H, W = 32, 64, 56, 56 -EPS = 1e-6 - -class FRN(nn.Module): - def __init__(self, num_channels, eps): - super().__init__() - self.eps = eps - self.weight = nn.Parameter(torch.ones(1, num_channels, 1, 1)) - self.bias = nn.Parameter(torch.zeros(1, num_channels, 1, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - nu2 = torch.mean(x * x, dim=[2, 3], keepdim=True) - x_normalized = x / torch.sqrt(nu2 + self.eps) - return x_normalized * self.weight + self.bias - -class Model(nn.Module): - def __init__(self, frn_weight, frn_bias): - super().__init__() - self.frn = FRN(C, EPS) - with torch.no_grad(): - self.frn.weight.data.copy_(frn_weight.view(1, C, 1, 1)) - self.frn.bias.data.copy_(frn_bias.view(1, C, 1, 1)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - return self.frn(x) - -def get_inputs(): - x = torch.randn(N, C, H, W, dtype=torch.float32) - return [x] - -def get_init_inputs(): - frn_weight = torch.ones(1, C, 1, 1) - frn_bias = torch.zeros(1, C, 1, 1) - return [frn_weight, frn_bias] \ No newline at end of file diff --git a/S1/11/run_code.py b/S1/11/run_code.py deleted file mode 100644 index cbf4e23..0000000 --- a/S1/11/run_code.py +++ /dev/null @@ -1,88 +0,0 @@ -########################################################### -# 性能和精度验证程序 -########################################################### -import torch -import torch.nn as nn -import time -from frn_torch import Model, get_inputs, get_init_inputs -from frn_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) - - # 更严格的精度检查 - 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) - if precision_flag: - print("✅ 精度对齐:两个模型的输出结果非常接近。") - else: - print("❌ 精度不一致!") - - print("\n-------------------- 性能加速比测试 --------------------") - num_iterations = 1000 # 增加迭代次数以获得更准确的时间测量 - - # Warm up - for _ in range(100): - _ = torch_model(*inputs) - _ = cuda_model(*inputs) - - # 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 (matmul + relu) 平均执行时间: {torch_time:.6f} 秒") - print(f"自定义 CUDA ReLU 平均执行时间: {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() \ No newline at end of file