forked from ccf-ai-infra/GPUCodeForces
45 lines
1.4 KiB
Python
45 lines
1.4 KiB
Python
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 imitation_kernel(const float* pred_actions, const float* expert_actions, float* output, int size) {
|
|
int idx = blockIdx.x * blockDim.x + threadIdx.x;
|
|
if (idx < size) {
|
|
float diff = pred_actions[idx] - expert_actions[idx];
|
|
output[idx] = diff * diff;
|
|
}
|
|
}
|
|
|
|
torch::Tensor imitation_cuda(torch::Tensor pred_actions, torch::Tensor expert_actions) {
|
|
auto size = pred_actions.numel();
|
|
auto output = torch::empty_like(pred_actions);
|
|
const int block_size = 256;
|
|
int num_blocks = (size + block_size - 1) / block_size;
|
|
imitation_kernel<<<num_blocks, block_size>>>(pred_actions.data_ptr<float>(), expert_actions.data_ptr<float>(), output.data_ptr<float>(), size);
|
|
return output.mean();
|
|
}
|
|
"""
|
|
|
|
cpp_source = """
|
|
torch::Tensor imitation_cuda(torch::Tensor pred_actions, torch::Tensor expert_actions);
|
|
"""
|
|
|
|
il_module = load_inline(
|
|
name="imitation_loss",
|
|
cpp_sources=cpp_source,
|
|
cuda_sources=cuda_source,
|
|
functions=["imitation_cuda"],
|
|
verbose=True
|
|
)
|
|
|
|
class ModelNew(torch.nn.Module):
|
|
def __init__(self):
|
|
super(ModelNew, self).__init__()
|
|
self.il_module = il_module
|
|
|
|
def forward(self, pred_actions, expert_actions):
|
|
return self.il_module.imitation_cuda(pred_actions, expert_actions) |