From 0dd45b3c4942a78f2cb71ac5ef04c20233a4c53c Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Tue, 9 Dec 2025 12:03:07 +0800 Subject: [PATCH 1/2] finish VIDLoss #142 --- S1/gsd123_#142/VIDLoss_cuda.py | 45 +++++++++++++++++++ S1/gsd123_#142/VIDLoss_torch.py | 22 ++++++++++ S1/gsd123_#142/prompt.txt | 47 ++++++++++++++++++++ S1/gsd123_#142/run_code.py | 77 +++++++++++++++++++++++++++++++++ 4 files changed, 191 insertions(+) create mode 100644 S1/gsd123_#142/VIDLoss_cuda.py create mode 100644 S1/gsd123_#142/VIDLoss_torch.py create mode 100644 S1/gsd123_#142/prompt.txt create mode 100644 S1/gsd123_#142/run_code.py diff --git a/S1/gsd123_#142/VIDLoss_cuda.py b/S1/gsd123_#142/VIDLoss_cuda.py new file mode 100644 index 00000000..4a72a28e --- /dev/null +++ b/S1/gsd123_#142/VIDLoss_cuda.py @@ -0,0 +1,45 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include + +__global__ void vid_loss_kernel(const float* m, const float* v, const float* t, float* out, int n) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < n) { + float var = v[idx] + 1e-6; + float diff = t[idx] - m[idx]; + out[idx] = logf(var) + (diff * diff) / var; + } +} + +torch::Tensor vid_loss_cuda_func(torch::Tensor m, torch::Tensor v, torch::Tensor t) { + auto n = m.numel(); + auto out = torch::empty_like(m); + const int block_size = 256; + int num_blocks = (n + block_size - 1) / block_size; + vid_loss_kernel<<>>(m.data_ptr(), v.data_ptr(), t.data_ptr(), out.data_ptr(), n); + return out.mean(); +} +""" + +cpp_source = """ +torch::Tensor vid_loss_cuda_func(torch::Tensor m, torch::Tensor v, torch::Tensor t); +""" + +vid_loss = load_inline( + name="vid_loss", + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=["vid_loss_cuda_func"], + verbose=False +) + +class ModelNew(nn.Module): + def __init__(self): + super(ModelNew, self).__init__() + + def forward(self, pred_mean, pred_var, target): + return vid_loss.vid_loss_cuda_func(pred_mean, pred_var, target) \ No newline at end of file diff --git a/S1/gsd123_#142/VIDLoss_torch.py b/S1/gsd123_#142/VIDLoss_torch.py new file mode 100644 index 00000000..c2effb0a --- /dev/null +++ b/S1/gsd123_#142/VIDLoss_torch.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, pred_mean, pred_var, target): + loss = torch.log(pred_var) + (target - pred_mean).pow(2) / (pred_var + 1e-6) + return loss.mean() + +batch_size = 32 +feature_dim = 128 + +def get_inputs(): + m = torch.randn(batch_size, feature_dim, requires_grad=True) + v = torch.abs(torch.randn(batch_size, feature_dim, requires_grad=True)) + 0.1 + t = torch.randn(batch_size, feature_dim) + return [m, v, t] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#142/prompt.txt b/S1/gsd123_#142/prompt.txt new file mode 100644 index 00000000..43a9ef53 --- /dev/null +++ b/S1/gsd123_#142/prompt.txt @@ -0,0 +1,47 @@ +You write custom CUDA kernels to replace the pytorch operators in the given GeGLU 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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. +Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline + +Variational information distillation (VID) loss computation (Gaussian negative log-likelihood) + +Element-wise parallelization using fixed block size (256 threads) + +NLL formula: log(variance) + (target - mean)² / variance + +Numerical stability with small epsilon added to variance + +Contiguous tensor handling for memory coalescing + +Dynamic grid sizing based on element count + +Mean reduction across all elements + +Logarithmic computation via logf for variance term + + + + +Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is: +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self): + super(Model, self).__init__() + + def forward(self, pred_mean, pred_var, target): + loss = torch.log(pred_var) + (target - pred_mean).pow(2) / (pred_var + 1e-6) + return loss.mean() + +batch_size = 32 +feature_dim = 128 + +def get_inputs(): + m = torch.randn(batch_size, feature_dim, requires_grad=True) + v = torch.abs(torch.randn(batch_size, feature_dim, requires_grad=True)) + 0.1 + t = torch.randn(batch_size, feature_dim) + return [m, v, t] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/gsd123_#142/run_code.py b/S1/gsd123_#142/run_code.py new file mode 100644 index 00000000..ef8891ef --- /dev/null +++ b/S1/gsd123_#142/run_code.py @@ -0,0 +1,77 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from VIDLoss_torch import Model, get_inputs, get_init_inputs +from VIDLoss_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() \ No newline at end of file From c6969cf595832056fe84b2ab686d8b3e1913081d Mon Sep 17 00:00:00 2001 From: gsd <2396583337@qq.com> Date: Wed, 10 Dec 2025 14:14:24 +0800 Subject: [PATCH 2/2] finish hamming_swish #142 --- S1/gsd123_#142/VIDLoss_cuda.py | 45 ------------- S1/gsd123_#142/VIDLoss_torch.py | 22 ------- S1/gsd123_#142/hamming_swish_cuda.py | 95 +++++++++++++++++++++++++++ S1/gsd123_#142/hamming_swish_torch.py | 22 +++++++ S1/gsd123_#142/prompt.txt | 38 +++++------ S1/gsd123_#142/run_code.py | 4 +- 6 files changed, 137 insertions(+), 89 deletions(-) delete mode 100644 S1/gsd123_#142/VIDLoss_cuda.py delete mode 100644 S1/gsd123_#142/VIDLoss_torch.py create mode 100644 S1/gsd123_#142/hamming_swish_cuda.py create mode 100644 S1/gsd123_#142/hamming_swish_torch.py diff --git a/S1/gsd123_#142/VIDLoss_cuda.py b/S1/gsd123_#142/VIDLoss_cuda.py deleted file mode 100644 index 4a72a28e..00000000 --- a/S1/gsd123_#142/VIDLoss_cuda.py +++ /dev/null @@ -1,45 +0,0 @@ -import torch -import torch.nn as nn -from torch.utils.cpp_extension import load_inline - -cuda_source = """ -#include -#include - -__global__ void vid_loss_kernel(const float* m, const float* v, const float* t, float* out, int n) { - int idx = blockIdx.x * blockDim.x + threadIdx.x; - if (idx < n) { - float var = v[idx] + 1e-6; - float diff = t[idx] - m[idx]; - out[idx] = logf(var) + (diff * diff) / var; - } -} - -torch::Tensor vid_loss_cuda_func(torch::Tensor m, torch::Tensor v, torch::Tensor t) { - auto n = m.numel(); - auto out = torch::empty_like(m); - const int block_size = 256; - int num_blocks = (n + block_size - 1) / block_size; - vid_loss_kernel<<>>(m.data_ptr(), v.data_ptr(), t.data_ptr(), out.data_ptr(), n); - return out.mean(); -} -""" - -cpp_source = """ -torch::Tensor vid_loss_cuda_func(torch::Tensor m, torch::Tensor v, torch::Tensor t); -""" - -vid_loss = load_inline( - name="vid_loss", - cpp_sources=cpp_source, - cuda_sources=cuda_source, - functions=["vid_loss_cuda_func"], - verbose=False -) - -class ModelNew(nn.Module): - def __init__(self): - super(ModelNew, self).__init__() - - def forward(self, pred_mean, pred_var, target): - return vid_loss.vid_loss_cuda_func(pred_mean, pred_var, target) \ No newline at end of file diff --git a/S1/gsd123_#142/VIDLoss_torch.py b/S1/gsd123_#142/VIDLoss_torch.py deleted file mode 100644 index c2effb0a..00000000 --- a/S1/gsd123_#142/VIDLoss_torch.py +++ /dev/null @@ -1,22 +0,0 @@ -import torch -import torch.nn as nn - -class Model(nn.Module): - def __init__(self): - super(Model, self).__init__() - - def forward(self, pred_mean, pred_var, target): - loss = torch.log(pred_var) + (target - pred_mean).pow(2) / (pred_var + 1e-6) - return loss.mean() - -batch_size = 32 -feature_dim = 128 - -def get_inputs(): - m = torch.randn(batch_size, feature_dim, requires_grad=True) - v = torch.abs(torch.randn(batch_size, feature_dim, requires_grad=True)) + 0.1 - t = torch.randn(batch_size, feature_dim) - return [m, v, t] - -def get_init_inputs(): - return [] \ No newline at end of file diff --git a/S1/gsd123_#142/hamming_swish_cuda.py b/S1/gsd123_#142/hamming_swish_cuda.py new file mode 100644 index 00000000..91bf64f6 --- /dev/null +++ b/S1/gsd123_#142/hamming_swish_cuda.py @@ -0,0 +1,95 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cuda_source = """ +#include +#include +#include + +__inline__ __device__ float warp_reduce(float val) { + for (int offset = 16; offset > 0; offset /= 2) + val += __shfl_down_sync(0xffffffff, val, offset); + return val; +} + +__global__ void hamming_swish_kernel( + const float* __restrict__ x, + const float* __restrict__ target, + float* __restrict__ y, + int batch_size, + int width) +{ + int row = blockIdx.x; + int tid = threadIdx.x; + + if (row >= batch_size) return; + + const float* row_x = x + row * width; + + float sum_abs = 0.0f; + + for (int i = tid; i < width; i += blockDim.x) { + float val = row_x[i]; + float t = target[i]; + sum_abs += fabsf(val - t); + } + + sum_abs = warp_reduce(sum_abs); + + static __shared__ float shared_mem[32]; + int lane = tid % 32; + int wid = tid / 32; + + if (lane == 0) shared_mem[wid] = sum_abs; + __syncthreads(); + + sum_abs = (tid < blockDim.x / 32) ? shared_mem[lane] : 0.0f; + if (wid == 0) sum_abs = warp_reduce(sum_abs); + + if (tid == 0) { + float swish = sum_abs / (1.0f + expf(-sum_abs)); + y[row] = swish; + } +} + +torch::Tensor launch_hamming_swish(torch::Tensor x, torch::Tensor target) { + auto batch_size = x.size(0); + auto width = x.size(1); + auto y = torch::empty({batch_size}, x.options()); + + const int threads = 256; + const int blocks = batch_size; + + hamming_swish_kernel<<>>( + x.data_ptr(), + target.data_ptr(), + y.data_ptr(), + batch_size, + width + ); + return y; +} +""" + +cpp_source = """ +torch::Tensor launch_hamming_swish(torch::Tensor x, torch::Tensor target); +""" + +hamming_swish_module = load_inline( + name='hamming_swish_op', + cpp_sources=cpp_source, + cuda_sources=cuda_source, + functions=['launch_hamming_swish'], + verbose=False +) + + +class ModelNew(nn.Module): + def __init__(self, target): + super(ModelNew, self).__init__() + self.target = nn.Parameter(target) + self.op = hamming_swish_module + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.op.launch_hamming_swish(x.contiguous(), self.target.contiguous()) \ No newline at end of file diff --git a/S1/gsd123_#142/hamming_swish_torch.py b/S1/gsd123_#142/hamming_swish_torch.py new file mode 100644 index 00000000..73c54bd1 --- /dev/null +++ b/S1/gsd123_#142/hamming_swish_torch.py @@ -0,0 +1,22 @@ +import torch +import torch.nn as nn + +class Model(nn.Module): + def __init__(self, target): + super(Model, self).__init__() + self.target = nn.Parameter(target) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + dist = torch.sum(torch.abs(x - self.target), dim=-1) + return dist * torch.sigmoid(dist) + +batch_size = 128 +input_dim = 1024 + +def get_inputs(): + x = torch.randn(batch_size, input_dim) + return [x] + +def get_init_inputs(): + target = torch.randn(input_dim) + return [target] \ No newline at end of file diff --git a/S1/gsd123_#142/prompt.txt b/S1/gsd123_#142/prompt.txt index 43a9ef53..07216664 100644 --- a/S1/gsd123_#142/prompt.txt +++ b/S1/gsd123_#142/prompt.txt @@ -1,23 +1,21 @@ You write custom CUDA kernels to replace the pytorch operators in the given GeGLU 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 chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination. -Custom CUDA kernel extension via torch.utils.cpp_extension.load_inline -Variational information distillation (VID) loss computation (Gaussian negative log-likelihood) +CUDA C++ kernel for L1 (Hamming‑like) distance with Swish activation -Element-wise parallelization using fixed block size (256 threads) +Element‑wise absolute differences: |x[i] – target[i]| accumulated across features -NLL formula: log(variance) + (target - mean)² / variance +Two‑level parallel reduction: warp‑level (__shfl_down_sync) + shared‑memory reduction -Numerical stability with small epsilon added to variance +Swish activation: distance / (1 + exp(-distance)) applied after reduction -Contiguous tensor handling for memory coalescing +Grid‑stride loops for coalesced memory access across feature dimension -Dynamic grid sizing based on element count +Block‑per‑sample processing with 256 threads per block -Mean reduction across all elements +PyTorch inline C++/CUDA extension via load_inline -Logarithmic computation via logf for variance term @@ -27,21 +25,21 @@ import torch import torch.nn as nn class Model(nn.Module): - def __init__(self): + def __init__(self, target): super(Model, self).__init__() + self.target = nn.Parameter(target) - def forward(self, pred_mean, pred_var, target): - loss = torch.log(pred_var) + (target - pred_mean).pow(2) / (pred_var + 1e-6) - return loss.mean() + def forward(self, x: torch.Tensor) -> torch.Tensor: + dist = torch.sum(torch.abs(x - self.target), dim=-1) + return dist * torch.sigmoid(dist) -batch_size = 32 -feature_dim = 128 +batch_size = 128 +input_dim = 1024 def get_inputs(): - m = torch.randn(batch_size, feature_dim, requires_grad=True) - v = torch.abs(torch.randn(batch_size, feature_dim, requires_grad=True)) + 0.1 - t = torch.randn(batch_size, feature_dim) - return [m, v, t] + x = torch.randn(batch_size, input_dim) + return [x] def get_init_inputs(): - return [] \ No newline at end of file + target = torch.randn(input_dim) + return [target] \ No newline at end of file diff --git a/S1/gsd123_#142/run_code.py b/S1/gsd123_#142/run_code.py index ef8891ef..af23e5e2 100644 --- a/S1/gsd123_#142/run_code.py +++ b/S1/gsd123_#142/run_code.py @@ -4,8 +4,8 @@ import torch import torch.nn as nn import time -from VIDLoss_torch import Model, get_inputs, get_init_inputs -from VIDLoss_cuda import ModelNew +from hamming_swish_torch import Model, get_inputs, get_init_inputs +from hamming_swish_cuda import ModelNew def run_benchmark():