finish MsewithLogitLoss #100

This commit is contained in:
uucoco 2025-12-10 19:26:50 +08:00
parent 10eed82956
commit 398b36178f
4 changed files with 303 additions and 0 deletions

View File

@ -0,0 +1,147 @@
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.reduction = reduction
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor logits_loss_cuda(
torch::Tensor student, torch::Tensor teacher,
int reduction_mode);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
__global__ void logits_loss_reduction_kernel(
const float* __restrict__ student,
const float* __restrict__ teacher,
float* __restrict__ output,
const int64_t n_elements)
{
extern __shared__ float sdata[];
unsigned int tid = threadIdx.x;
unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;
unsigned int gridSize = blockDim.x * gridDim.x;
float local_sum = 0.0f;
int64_t n_vec = n_elements / 4;
const float4* stu_4 = reinterpret_cast<const float4*>(student);
const float4* tea_4 = reinterpret_cast<const float4*>(teacher);
for (int64_t i = idx; i < n_vec; i += gridSize) {
float4 s = stu_4[i];
float4 t = tea_4[i];
float d1 = s.x - t.x;
float d2 = s.y - t.y;
float d3 = s.z - t.z;
float d4 = s.w - t.w;
local_sum += d1 * d1 + d2 * d2 + d3 * d3 + d4 * d4;
}
for (int64_t i = n_vec * 4 + idx; i < n_elements; i += gridSize) {
float diff = student[i] - teacher[i];
local_sum += diff * diff;
}
sdata[tid] = local_sum;
__syncthreads();
for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) {
sdata[tid] += sdata[tid + s];
}
__syncthreads();
}
if (tid == 0) {
atomicAdd(output, sdata[0]);
}
}
__global__ void logits_loss_elementwise_kernel(
const float* __restrict__ student,
const float* __restrict__ teacher,
float* __restrict__ output,
const int64_t n_elements)
{
int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n_elements) {
float diff = student[idx] - teacher[idx];
output[idx] = diff * diff;
}
}
torch::Tensor logits_loss_cuda(
torch::Tensor student, torch::Tensor teacher,
int reduction_mode)
{
TORCH_CHECK(student.is_cuda(), "student must be on CUDA");
TORCH_CHECK(teacher.is_cuda(), "teacher must be on CUDA");
int64_t n = student.numel();
TORCH_CHECK(teacher.numel() == n, "Size mismatch");
auto student_c = student.contiguous();
auto teacher_c = teacher.contiguous();
if (reduction_mode == 0) {
auto output = torch::empty_like(student_c);
int threads = 256;
int blocks = (n + threads - 1) / threads;
logits_loss_elementwise_kernel<<<blocks, threads>>>(
student_c.data_ptr<float>(), teacher_c.data_ptr<float>(),
output.data_ptr<float>(), n
);
return output;
} else {
auto output = torch::zeros({1}, student.options());
int threads = 256;
int blocks = min((int64_t)((n + threads - 1) / threads), (int64_t)1024);
size_t shared_mem = threads * sizeof(float);
logits_loss_reduction_kernel<<<blocks, threads, shared_mem>>>(
student_c.data_ptr<float>(), teacher_c.data_ptr<float>(),
output.data_ptr<float>(), n
);
if (reduction_mode == 1) {
return output / (float)n;
} else {
return output;
}
}
}
"""
self.op = load_inline(
name="logits_loss_op",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["logits_loss_cuda"],
extra_cuda_cflags=["-O3"],
verbose=False
)
def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor:
if not logits_student.is_cuda:
logits_student = logits_student.cuda()
logits_teacher = logits_teacher.cuda()
mode = 0
if self.reduction == 'mean':
mode = 1
elif self.reduction == 'sum':
mode = 2
return self.op.logits_loss_cuda(logits_student, logits_teacher, mode)

View File

@ -0,0 +1,26 @@
import torch
import torch.nn as nn
class Model(nn.Module):
def __init__(self, reduction='mean'):
super().__init__()
self.reduction = reduction
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor:
return self.mse_loss(logits_student, logits_teacher)
batch_size = 256
num_classes = 1000
def get_inputs():
logits_student = torch.randn(batch_size, num_classes, dtype=torch.float32)
logits_teacher = torch.randn(batch_size, num_classes, dtype=torch.float32)
return [logits_student, logits_teacher]
def get_init_inputs():
return ['mean']

53
S1/uucoco_#100/prompt.txt Normal file
View File

@ -0,0 +1,53 @@
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.
PyTorch C++/CUDA Extension: Inline compilation using torch.utils.cpp_extension.load_inline.
DualKernel Strategy:
Elementwise Kernel: Computes perelement squared difference (student - teacher)^2 for reduction='none'.
Vectorized Reduction Kernel: Uses float4 loads for highthroughput, sharedmemory tree reduction for 'mean'/'sum'.
Vectorized Processing: Main loop uses float4 (4element SIMDstyle) memory loads/stores for aligned data.
SharedMemory Parallel Reduction: Treebased sum across threads with extern __shared__ memory.
Atomic Finalization: atomicAdd accumulates block sums into a singleelement tensor.
Reduction Mode Control: Python passes integer mode (0=none, 1=mean, 2=sum) to select kernel and postprocessing.
Automatic GPU Transfer: Moves tensors to CUDA if not already on GPU.
Block/Thread Configuration: 256 threads per block, grid size capped at 1024 for reduction kernel.
Numerical Safety: Checks tensor sizes and CUDA device before kernel launch.
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, reduction='mean'):
super().__init__()
self.reduction = reduction
self.mse_loss = nn.MSELoss(reduction=reduction)
def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor:
return self.mse_loss(logits_student, logits_teacher)
batch_size = 256
num_classes = 1000
def get_inputs():
logits_student = torch.randn(batch_size, num_classes, dtype=torch.float32)
logits_teacher = torch.randn(batch_size, num_classes, dtype=torch.float32)
return [logits_student, logits_teacher]
def get_init_inputs():
return ['mean']

View File

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