GPUCodeForces/S1/uucoco_#72/SquaredHingeLoss_cuda.py

96 lines
3.2 KiB
Python

import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self._compile_cuda_kernel()
def _compile_cuda_kernel(self):
cpp_source = """
torch::Tensor squared_hinge_loss_cuda(torch::Tensor y_pred, torch::Tensor y_true);
"""
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
__device__ __forceinline__ float squared_hinge_loss_op(float y_pred, float y_true) {
float margin = 1.0f - y_true * y_pred;
float hinge = fmaxf(0.0f, margin);
// Squared Hinge Loss: hinge^2
return hinge * hinge;
}
__global__ void squared_hinge_loss_kernel(
const float* __restrict__ y_pred,
const float* __restrict__ y_true,
float* __restrict__ output,
const int n_elements)
{
const int tid = blockIdx.x * blockDim.x + threadIdx.x;
const int stride = blockDim.x * gridDim.x;
const int vec_loops = n_elements >> 2;
const float4* y_pred_vec = reinterpret_cast<const float4*>(y_pred);
const float4* y_true_vec = reinterpret_cast<const float4*>(y_true);
float4* out_vec = reinterpret_cast<float4*>(output);
for (int i = tid; i < vec_loops; i += stride) {
float4 yp = __ldg(&y_pred_vec[i]);
float4 yt = __ldg(&y_true_vec[i]);
float4 r;
r.x = squared_hinge_loss_op(yp.x, yt.x);
r.y = squared_hinge_loss_op(yp.y, yt.y);
r.z = squared_hinge_loss_op(yp.z, yt.z);
r.w = squared_hinge_loss_op(yp.w, yt.w);
out_vec[i] = r;
}
const int tail_start = vec_loops << 2;
for (int i = tail_start + tid; i < n_elements; i += stride) {
output[i] = squared_hinge_loss_op(y_pred[i], y_true[i]);
}
}
torch::Tensor squared_hinge_loss_cuda(torch::Tensor y_pred, torch::Tensor y_true) {
auto y_pred_c = y_pred.contiguous();
auto y_true_c = y_true.contiguous();
const int n_elements = y_pred_c.numel();
auto output = torch::empty_like(y_pred_c);
const int threads = 256;
const int max_blocks = 65535;
const int blocks = std::min((n_elements + threads * 4 - 1) / (threads * 4), max_blocks);
squared_hinge_loss_kernel<<<blocks, threads>>>(
y_pred_c.data_ptr<float>(),
y_true_c.data_ptr<float>(),
output.data_ptr<float>(),
n_elements
);
return output;
}
"""
self.op = load_inline(
name="squared_hinge_loss_v1",
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=["squared_hinge_loss_cuda"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False
)
def forward(self, y_pred, y_true):
loss_elementwise = self.op.squared_hinge_loss_cuda(y_pred, y_true)
return loss_elementwise.mean()