File size: 2,742 Bytes
bdebe19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <torch/extension.h>
#include <ATen/EmptyTensor.h>
#include <ATen/cuda/EmptyTensor.h>
#include <c10/cuda/CUDAStream.h>
#include <c10/cuda/CUDAFunctions.h>
#include <c10/cuda/CUDACachingAllocator.h>
#include "kernel.h"
// Host entry: allocate the NCHW output and launch the custom tensor-core conv kernels (kernel.cu).
// HOST DIET: one sizes() fetch, raw impl data pointers, output shape / Ho / Wo cached per input (N, H, W).
// HOST OVERHEAD CUT: the output is allocated with at::detail::empty_generic straight from the CUDA caching
// allocator (cached pointer), skipping empty_cuda's CUDAGuard device switch/restore (cudaGetDevice/cudaSetDevice
// pair) and TensorOptions processing.  The caching allocator allocates on the CURRENT device, so this fast path is
// only taken when x lives on the current device (checked every call via c10::cuda::current_device()); otherwise
// the guarded empty_cuda is used.  The current stream lookup is a TLS read.  Still a fresh tensor every call.
struct HostKey { int64_t N, H, W, Ho, Wo; };
static HostKey g_hk = {-1, -1, -1, 0, 0};   // POD static (no CUDA object)
static c10::Allocator* g_alloc = nullptr;   // raw pointer to the global caching allocator (not owned)
torch::Tensor run(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {
    if (!x.is_contiguous()) x = x.contiguous();
    if (!weight.is_contiguous()) weight = weight.contiguous();
    if (!bias.is_contiguous()) bias = bias.contiguous();
    const auto xs = x.sizes();
    const int64_t N = xs[0], H = xs[2], W = xs[3];
    HostKey& k = g_hk;
    if (k.N != N || k.H != H || k.W != W) {
        k.N = N; k.H = H; k.W = W;
        k.Ho = (H + 2 - 3) / 2 + 1; k.Wo = (W + 2 - 3) / 2 + 1;
    }
    const int64_t sz[4] = {N, 64, k.Ho, k.Wo};
    const c10::Device dev = x.device();
    const c10::DeviceIndex di = dev.index();
    torch::Tensor y;
    if (di == c10::cuda::current_device()) {
        if (!g_alloc) g_alloc = c10::cuda::CUDACachingAllocator::get();
        y = at::Tensor(at::detail::empty_generic(c10::IntArrayRef(sz, 4), g_alloc,
                                                 c10::DispatchKeySet(c10::DispatchKey::CUDA), at::kFloat, c10::nullopt));
    } else {
        y = at::detail::empty_cuda(c10::IntArrayRef(sz, 4), at::kFloat, dev, c10::nullopt);
    }
    launch_conv((const float*)x.unsafeGetTensorImpl()->data(), (const float*)weight.unsafeGetTensorImpl()->data(),
                (const float*)bias.unsafeGetTensorImpl()->data(), (float*)y.unsafeGetTensorImpl()->mutable_data(),
                (int)N, (int)H, (int)W, (int)k.Ho, (int)k.Wo,
                c10::cuda::getCurrentCUDAStream(di).stream());
    return y;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run); }