diff --git a/S1/ZZZJ_#135/black_scholes_cuda.py b/S1/ZZZJ_#135/black_scholes_cuda.py new file mode 100644 index 00000000..ec7876a1 --- /dev/null +++ b/S1/ZZZJ_#135/black_scholes_cuda.py @@ -0,0 +1,130 @@ +import torch +import torch.nn as nn +from torch.utils.cpp_extension import load_inline + +cpp_src = """ +torch::Tensor black_scholes_cuda( + torch::Tensor price, torch::Tensor strike, + torch::Tensor t, torch::Tensor rate, torch::Tensor vol); +""" + +cuda_src = """ +#include +#include + +#define INV_SQRT2 0.707106781f + +__global__ void black_scholes_strict_kernel( + const float* __restrict__ price, + const float* __restrict__ strike, + const float* __restrict__ t, + const float* __restrict__ rate, + const float* __restrict__ vol, + float* __restrict__ output, + int total_vectors +) { + int idx = blockIdx.x * blockDim.x + threadIdx.x; + int stride = blockDim.x * gridDim.x; + + const float4* p_ptr = reinterpret_cast(price); + const float4* s_ptr = reinterpret_cast(strike); + const float4* t_ptr = reinterpret_cast(t); + const float4* r_ptr = reinterpret_cast(rate); + const float4* v_ptr = reinterpret_cast(vol); + float4* out_ptr = reinterpret_cast(output); + + for (int i = idx; i < total_vectors; i += stride) { + float4 vp = p_ptr[i]; + float4 vs = s_ptr[i]; + float4 vt = t_ptr[i]; + float4 vr = r_ptr[i]; + float4 vv = v_ptr[i]; + + float4 res; + + float* pp = (float*)&vp; + float* ps = (float*)&vs; + float* pt = (float*)&vt; + float* pr = (float*)&vr; + float* pv = (float*)&vv; + float* pres = (float*)&res; + + #pragma unroll + for (int j = 0; j < 4; ++j) { + float S = pp[j]; + float K = ps[j]; + float T = pt[j]; + float R = pr[j]; + float V = pv[j]; + + + float sqrt_T = sqrtf(T); + float log_val = logf(S / K); + float vol_term = R + 0.5f * V * V; + float num = log_val + vol_term * T; + float den = V * sqrt_T; + + float d1 = num / den; + float d2 = d1 - den; // d1 - V * sqrt_T + + float N_d1 = 0.5f * (1.0f + erff(d1 * INV_SQRT2)); + float N_d2 = 0.5f * (1.0f + erff(d2 * INV_SQRT2)); + + float exp_val = expf(-R * T); + pres[j] = S * N_d1 - K * exp_val * N_d2; + } + + out_ptr[i] = res; + } +} + +torch::Tensor black_scholes_cuda( + torch::Tensor price, torch::Tensor strike, + torch::Tensor t, torch::Tensor rate, torch::Tensor vol) +{ + int numel = price.numel(); + + price = price.contiguous(); + strike = strike.contiguous(); + t = t.contiguous(); + rate = rate.contiguous(); + vol = vol.contiguous(); + + auto output = torch::empty_like(price); + + 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; + + black_scholes_strict_kernel<<>>( + price.data_ptr(), + strike.data_ptr(), + t.data_ptr(), + rate.data_ptr(), + vol.data_ptr(), + output.data_ptr(), + total_vectors + ); + + return output; +} +""" + +class ModelNew(nn.Module): + def __init__(self): + super().__init__() + self.module = load_inline( + name="black_scholes_strict_nofma_v2", + cpp_sources=cpp_src, + cuda_sources=cuda_src, + functions=["black_scholes_cuda"], + verbose=False, + extra_cuda_cflags=["-O3", "--fmad=false"] + ) + + def forward(self, price, strike, t, rate, vol): + return self.module.black_scholes_cuda(price, strike, t, rate, vol) \ No newline at end of file diff --git a/S1/ZZZJ_#135/black_scholes_torch.py b/S1/ZZZJ_#135/black_scholes_torch.py new file mode 100644 index 00000000..ab4f6c11 --- /dev/null +++ b/S1/ZZZJ_#135/black_scholes_torch.py @@ -0,0 +1,36 @@ +import torch +import torch.nn as nn +import math + +class Model(nn.Module): + def __init__(self): + super().__init__() + + def forward(self, price: torch.Tensor, strike: torch.Tensor, t: torch.Tensor, rate: torch.Tensor, vol: torch.Tensor) -> torch.Tensor: + + sqrt_t = torch.sqrt(t) + log_val = torch.log(price / strike) + + d1 = (log_val + (rate + 0.5 * vol * vol) * t) / (vol * sqrt_t) + d2 = d1 - vol * sqrt_t + norm_d1 = 0.5 * (1.0 + torch.erf(d1 * 0.70710678)) + norm_d2 = 0.5 * (1.0 + torch.erf(d2 * 0.70710678)) + exp_val = torch.exp(-rate * t) + call_price = price * norm_d1 - strike * exp_val * norm_d2 + + return call_price + + +batch_size = 1024 * 1024 +shape = (batch_size, ) + +def get_inputs(): + price = torch.rand(shape, dtype=torch.float32) * 100.0 + 10.0 # S: 10~110 + strike = torch.rand(shape, dtype=torch.float32) * 100.0 + 10.0 # K + t = torch.rand(shape, dtype=torch.float32) + 0.1 # T: 0.1~1.1 年 + rate = torch.rand(shape, dtype=torch.float32) * 0.05 + 0.01 # r: 1%~6% + vol = torch.rand(shape, dtype=torch.float32) * 0.3 + 0.1 # v: 10%~40% + return [price, strike, t, rate, vol] + +def get_init_inputs(): + return [] \ No newline at end of file diff --git a/S1/ZZZJ_#135/prompt.txt b/S1/ZZZJ_#135/prompt.txt new file mode 100644 index 00000000..4ae13f0a --- /dev/null +++ b/S1/ZZZJ_#135/prompt.txt @@ -0,0 +1,44 @@ +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): + super().__init__() + + def forward(self, price: torch.Tensor, strike: torch.Tensor, t: torch.Tensor, rate: torch.Tensor, vol: torch.Tensor) -> torch.Tensor: + + sqrt_t = torch.sqrt(t) + log_val = torch.log(price / strike) + + d1 = (log_val + (rate + 0.5 * vol * vol) * t) / (vol * sqrt_t) + d2 = d1 - vol * sqrt_t + norm_d1 = 0.5 * (1.0 + torch.erf(d1 * 0.70710678)) + norm_d2 = 0.5 * (1.0 + torch.erf(d2 * 0.70710678)) + exp_val = torch.exp(-rate * t) + call_price = price * norm_d1 - strike * exp_val * norm_d2 + + return call_price + + +batch_size = 1024 * 1024 +shape = (batch_size, ) + +def get_inputs(): + price = torch.rand(shape, dtype=torch.float32) * 100.0 + 10.0 # S: 10~110 + strike = torch.rand(shape, dtype=torch.float32) * 100.0 + 10.0 # K + t = torch.rand(shape, dtype=torch.float32) + 0.1 # T: 0.1~1.1 年 + rate = torch.rand(shape, dtype=torch.float32) * 0.05 + 0.01 # r: 1%~6% + vol = torch.rand(shape, dtype=torch.float32) * 0.3 + 0.1 # v: 10%~40% + return [price, strike, t, rate, vol] + +def get_init_inputs(): + return [] +``` \ No newline at end of file diff --git a/S1/ZZZJ_#135/run_code.py b/S1/ZZZJ_#135/run_code.py new file mode 100644 index 00000000..679a35af --- /dev/null +++ b/S1/ZZZJ_#135/run_code.py @@ -0,0 +1,74 @@ +########################################################### +# 性能和精度验证程序 +########################################################### +import torch +import torch.nn as nn +import time +from black_scholes_torch import Model,get_inputs,get_init_inputs +from black_scholes_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