torch.h 1.41 KB
Newer Older
Zhekai Zhang's avatar
Zhekai Zhang committed
1
2
3
4
5
6
7
8
9
10
#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)) {
Muyang Li's avatar
Muyang Li committed
11
12
        this->size        = this->tensor.numel() * this->tensor.itemsize();
        this->ptr         = this->tensor.data_ptr();
Zhekai Zhang's avatar
Zhekai Zhang committed
13
        this->device.type = this->tensor.is_cuda() ? Device::CUDA : Device::CPU;
Muyang Li's avatar
Muyang Li committed
14
        this->device.idx  = this->tensor.get_device();
Zhekai Zhang's avatar
Zhekai Zhang committed
15
    }
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
    }
Muyang Li's avatar
Muyang Li committed
20

Zhekai Zhang's avatar
Zhekai Zhang committed
21
22
23
24
25
26
27
28
private:
    at::Tensor tensor;
};

class TorchOpContext {
public:
    TorchOpContext();
    TorchOpContext(const TorchOpContext &) = delete;
Muyang Li's avatar
Muyang Li committed
29
    TorchOpContext(TorchOpContext &&)      = delete;
Zhekai Zhang's avatar
Zhekai Zhang committed
30
31
32
33
    ~TorchOpContext();
};

Tensor from_torch(at::Tensor input);
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;
Muyang Li's avatar
Muyang Li committed
52
};