finish complex_conj_mul_div #84

This commit is contained in:
uucoco 2025-12-10 19:04:20 +08:00
parent 10eed82956
commit 308151aadd
4 changed files with 301 additions and 0 deletions

View File

@ -0,0 +1,91 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void complex_conj_mul_div_kernel(
const float* __restrict__ a,
const float* __restrict__ b,
const float* __restrict__ c,
float* __restrict__ output,
int N, float eps
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < N) {
int offset = idx * 2;
// Input A = Xa + iYa
float Xa = a[offset];
float Ya = a[offset + 1];
// Input B = Xb + iYb
float Xb = b[offset];
float Yb = b[offset + 1];
// Input C = Xc + iYc
float Xc = c[offset];
float Yc = c[offset + 1];
// Step 1 & 2: P = conj(A) * B = Xp + iYp
// Xp = Xa*Xb + Ya*Yb
// Yp = Xa*Yb - Ya*Xb
float Xp = fmaf(Xa, Xb, Ya * Yb);
float Yp = fmaf(Xa, Yb, -Ya * Xb);
// Step 3: Division Out = P / C
// Denominator D = |C|^2 = Xc^2 + Yc^2
float D = fmaf(Xc, Xc, Yc * Yc);
float inv_D = 1.0f / (D + eps);
// Out_Re = (Xp*Xc + Yp*Yc) / D
// Out_Im = (Yp*Xc - Xp*Yc) / D
float Out_Re = fmaf(Xp, Xc, Yp * Yc) * inv_D;
float Out_Im = fmaf(Yp, Xc, -Xp * Yc) * inv_D;
output[offset] = Out_Re;
output[offset + 1] = Out_Im;
}
}
torch::Tensor complex_conj_mul_div_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c) {
auto output = torch::empty_like(a);
int N = a.size(0);
const int block_size = 256;
int num_blocks = (N + block_size - 1) / block_size;
complex_conj_mul_div_kernel<<<num_blocks, block_size>>>(
a.data_ptr<float>(),
b.data_ptr<float>(),
c.data_ptr<float>(),
output.data_ptr<float>(),
N, 1e-12f
);
return output;
}
"""
cpp_source = """
torch::Tensor complex_conj_mul_div_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c);
"""
module = load_inline(
name="complex_conj_mul_div",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["complex_conj_mul_div_cuda"],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.module = module
def forward(self, a, b, c):
return self.module.complex_conj_mul_div_cuda(a, b, c)

View File

@ -0,0 +1,30 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, a, b, c):
a_c = torch.complex(a[..., 0], a[..., 1])
b_c = torch.complex(b[..., 0], b[..., 1])
c_c = torch.complex(c[..., 0], c[..., 1])
out_c = (torch.conj(a_c) * b_c) / c_c
return torch.stack([out_c.real, out_c.imag], dim=-1)
batch_size = 1024
def get_inputs():
a = torch.randn(batch_size, 2)
b = torch.randn(batch_size, 2)
c = torch.randn(batch_size, 2) + 1.0 # Bias away from zero
return [a, b, c]
def get_init_inputs():
return []

103
S1/uucoco_#84/prompt.txt Normal file
View File

@ -0,0 +1,103 @@
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.
# Technologies Used in This Code
## Core Libraries
- **PyTorch**: Deep learning framework
- **CUDA**: NVIDIA GPU parallel computing
- **C++**: Kernel implementation
## CUDA Components
- **CUDA kernel**: `complex_conj_mul_div_kernel`
- **FMA optimization**: `fmaf()` for fused multiply-add operations
- **Complex arithmetic**: Interleaved real/imaginary representation
- **Element-wise parallelism**: One thread per complex number
## Complex Number Operations
1. **Complex conjugate**: conj(A) = Xa - iYa
2. **Complex multiplication**: conj(A) × B
3. **Complex division**: P / C with regularization
- **Three-input operation**: Combines three complex tensors
## Mathematical Formulas
- **Conjugate multiplication**: (XaXb + YaYb) + i(XaYb - YaXb)
- **Complex division**: ( (XpXc + YpYc) + i(YpXc - XpYc) ) / |C|²
- **Denominator**: D = Xc² + Yc² + eps (regularized)
- **Fused operations**: Using `fmaf()` for better precision
## Architecture
- **3-element processing**: Each thread handles 3 complex numbers (6 floats)
- **Standard 1D grid**: Simple block/grid configuration
- **Memory pattern**: Coalesced access to interleaved complex data
- **Numerical stability**: Epsilon (1e-12) prevents division by zero
## CUDA Optimizations
- **FMA usage**: `fmaf()` for multiply-add with single rounding
- **Efficient division**: Precompute reciprocal to avoid multiple divisions
- **Regularization**: Epsilon protects against division by small magnitudes
## Performance Features
- **GPU acceleration**: Parallel computation across complex numbers
- **Precision optimization**: FMA reduces rounding errors
- **Memory efficiency**: Single kernel for three operations
- **Numerical robustness**: Regularized division
## Numerical Considerations
- **Division safety**: Epsilon prevents division by zero/near-zero
- **Precision**: FMA improves accuracy of complex operations
- **Overflow/underflow**: Magnitude squared could overflow for large values
- **Complex representation**: Interleaved format [real, imag, real, imag, ...]
## Use Case Applications
- **Signal processing**: Complex correlation/division operations
- **Communications**: Complex number manipulations
- **Physics simulations**: Complex arithmetic in wave equations
- **Computer vision**: Complex filter operations
## Mathematical Properties
- **Linearity**: Operation is linear in B, conjugate-linear in A
- **Scale invariance**: Division normalizes by |C|²
- **Complex algebra**: Proper handling of complex arithmetic
- **Three-input function**: Unique combination of complex operations
## Implementation Details
- **Tensor shape**: Expects same shape for a, b, c (N complex numbers)
- **Output format**: Same interleaved complex format as input
- **Batch processing**: Handles multiple complex numbers in parallel
- **Fixed epsilon**: Hardcoded 1e-12 for numerical stability
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, a, b, c):
a_c = torch.complex(a[..., 0], a[..., 1])
b_c = torch.complex(b[..., 0], b[..., 1])
c_c = torch.complex(c[..., 0], c[..., 1])
out_c = (torch.conj(a_c) * b_c) / c_c
return torch.stack([out_c.real, out_c.imag], dim=-1)
batch_size = 1024
def get_inputs():
a = torch.randn(batch_size, 2)
b = torch.randn(batch_size, 2)
c = torch.randn(batch_size, 2) + 1.0 # Bias away from zero
return [a, b, c]
def get_init_inputs():
return []

77
S1/uucoco_#84/run_code.py Normal file
View File

@ -0,0 +1,77 @@
###########################################################
# 性能和精度验证程序
###########################################################
import torch
import torch.nn as nn
import time
from complex_conj_mul_div_torch import Model, get_inputs, get_init_inputs
from complex_conj_mul_div_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()