Serialization.h 1.56 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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#pragma once

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

class BufferMMap : public Buffer {
public:
    BufferMMap(void *ptr, size_t size, std::shared_ptr<void> parent) : parent(parent) {
        this->size = size;
        this->device.type = Device::CPU;
        this->ptr = ptr;
        // auto ret = cudaHostRegister(ptr, size, cudaHostRegisterPortable | cudaHostRegisterReadOnly);
        // if (ret == cudaSuccess) {
        //     this->registered = true;
        // } else {
        //     log(std::format("cudaHostRegister failed at {:p} (size={}): {}", ptr, size, cudaGetErrorString(cudaGetLastError())));
        //     this->registered = false;
        // }
    }
    virtual ~BufferMMap() {
        // if (registered) {
        //     checkCUDA(cudaHostUnregister(ptr));
        // }
    }
public:
    std::shared_ptr<void> parent;
    // bool registered;
};

class SafeTensors : public TensorsProvider, public std::enable_shared_from_this<SafeTensors> {
public:
32
    SafeTensors(const std::string &filename);
Zhekai Zhang's avatar
Zhekai Zhang committed
33
34
35
36
37
38
39
40
41
42
43
    ~SafeTensors();

    virtual bool contains(const std::string &key) const override { 
        return tensors.contains(key);
    }
    virtual Tensor getTensor(const std::string &key) override;

private:
    void parseHeader();

private:
44
45
46
47
    class MMapImpl;
    class MMapImplMio;
    class MMapImplPrivate;

Zhekai Zhang's avatar
Zhekai Zhang committed
48
49
50
51
52
53
54
55
    struct TensorInfo {
        TensorShape shape;
        Tensor::ScalarType type;
        size_t offset;
        size_t length;
        std::weak_ptr<BufferMMap> buffer;
    };
    std::map<std::string, TensorInfo> tensors;
56
    std::unique_ptr<MMapImpl> mapped;
Zhekai Zhang's avatar
Zhekai Zhang committed
57
};