torch.h 1.39 KB
Newer Older
Zhekai Zhang's avatar
Zhekai Zhang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#pragma once

#include <torch/extension.h>

#include "common.h"
#include "Tensor.h"

class BufferTorchTensor : public Buffer {
public:
    BufferTorchTensor(at::Tensor tensor) : tensor(std::move(tensor)) {
        this->size = this->tensor.numel() * this->tensor.itemsize();
        this->ptr = this->tensor.data_ptr();
        this->device.type = this->tensor.is_cuda() ? Device::CUDA : Device::CPU;
        this->device.idx = this->tensor.get_device();
    }
Hyunsung Lee's avatar
Hyunsung Lee committed
16
    virtual bool isAsyncBuffer() override {
muyangli's avatar
muyangli committed
17
        // TODO: figure out how torch manages memory
18
        return this->device.type == Device::CUDA;
muyangli's avatar
muyangli committed
19
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
20
21
22
23
24
25
26
27
28
29
30
31
32
private:
    at::Tensor tensor;
};

class TorchOpContext {
public:
    TorchOpContext();
    TorchOpContext(const TorchOpContext &) = delete;
    TorchOpContext(TorchOpContext &&) = delete;
    ~TorchOpContext();
};

Tensor from_torch(at::Tensor input);
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
at::Tensor to_torch(Tensor input);

class TensorsProviderTorch : public TensorsProvider {
public:
    TensorsProviderTorch(std::map<std::string, at::Tensor> dict) : storage(std::move(dict)) {}

    virtual bool contains(const std::string &key) const override {
        return storage.contains(key);
    }
    virtual Tensor getTensor(const std::string &key) override {
        if (!storage.contains(key)) {
            return Tensor{};
        }
        return from_torch(storage.at(key));
    }

private:
    std::map<std::string, at::Tensor> storage;
};