#include #include #include #define BLOCK_SIZE 256 __global__ void fused_mse_eq_kernel(const float* __restrict__ x, const float* __restrict__ target, float* __restrict__ output, int n) { __shared__ float sdata[BLOCK_SIZE]; int tid = threadIdx.x; int global_id = blockIdx.x * blockDim.x + threadIdx.x; int stride = gridDim.x * blockDim.x; float local_sum = 0.0f; for (int i = global_id; i < n; i += stride) { float eq_val = (x[i] == target[i]) ? 1.0f : 0.0f; float diff = eq_val - target[i]; local_sum += diff * diff; } sdata[tid] = local_sum; __syncthreads(); for (int s = BLOCK_SIZE / 2; s > 0; s >>= 1) { if (tid < s) { sdata[tid] += sdata[tid + s]; } __syncthreads(); } if (tid == 0) { atomicAdd(output, sdata[0]); } } torch::Tensor forward(torch::Tensor x, torch::Tensor target) { auto stream = at::cuda::getCurrentCUDAStream(); int n = x.numel(); auto output = torch::zeros({1}, x.options()); int num_blocks = (n + BLOCK_SIZE - 1) / BLOCK_SIZE; if (num_blocks > 4096) num_blocks = 4096; fused_mse_eq_kernel<<>>( x.data_ptr(), target.data_ptr(), output.data_ptr(), n ); auto result = output / static_cast(n); return result.squeeze(); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &forward, "Fused MSE of element-wise equality"); }