tensor.cpp 10.1 KB
Newer Older
PanZezhong's avatar
init  
PanZezhong committed
1
2
#include "../tensor.hpp"
#include "../utils.hpp"
3
#include <algorithm>
PanZezhong's avatar
init  
PanZezhong committed
4
5
6
#include <fstream>
#include <iostream>
#include <numeric>
PanZezhong's avatar
PanZezhong committed
7
#include <sstream>
PanZezhong's avatar
init  
PanZezhong committed
8
9
10
11
12
13
14
15
16
17

std::shared_ptr<TensorDesc>
TensorDesc::create(infiniDtype_t dtype, const std::vector<size_t> &shape,
                   const std::vector<ptrdiff_t> &strides) {
    auto desc = std::make_shared<TensorDesc>();
    infiniopCreateTensorDescriptor(&desc->_desc, shape.size(), shape.data(),
                                   strides.data(), dtype);
    return desc;
}

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
48
49
50
std::shared_ptr<TensorDesc>
TensorDesc::create(infiniDtype_t dtype, const std::vector<size_t> &shape) {
    auto ndim = shape.size();
    auto strides = std::vector<ptrdiff_t>(ndim);
    if (ndim > 0) {
        strides[ndim - 1] = 1;
        for (int i = ndim - 2; i >= 0; i--) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
    }
    return create(dtype, shape, strides);
}

std::shared_ptr<TensorDesc>
TensorDesc::createWithOrder(infiniDtype_t dtype, const std::vector<size_t> &shape,
                            const std::vector<size_t> &order) {
    ASSERT_EQ(shape.size(), order.size());
    auto ndim = shape.size();
    if (ndim == 0) {
        return create(dtype, shape);
    }
    auto strides = std::vector<ptrdiff_t>(order.size());
    auto idx = std::find(order.begin(), order.end(), size_t(ndim - 1));
    strides[std::distance(order.begin(), idx)] = 1;
    for (int i = ndim - 2; i >= 0; i--) {
        auto prev_dim = shape[std::distance(order.begin(), idx)];
        auto prev_stride = strides[std::distance(order.begin(), idx)];
        idx = std::find(order.begin(), order.end(), size_t(i));
        strides[std::distance(order.begin(), idx)] = prev_stride * prev_dim;
    }
    return create(dtype, shape, strides);
}

PanZezhong's avatar
init  
PanZezhong committed
51
52
53
54
55
56
57
58
TensorDesc::~TensorDesc() {
    infiniopDestroyTensorDescriptor(this->_desc);
}

const std::vector<size_t> &Tensor::shape() const { return this->_shape; }
const std::vector<ptrdiff_t> &Tensor::strides() const { return this->_strides; }
size_t Tensor::ndim() const { return this->_shape.size(); }
infiniDtype_t Tensor::dtype() const { return this->_dtype; }
PanZezhong's avatar
PanZezhong committed
59
60
infiniDevice_t Tensor::deviceType() const { return this->_storage->device_type; }
int Tensor::deviceId() const { return this->_storage->device_id; }
PanZezhong's avatar
init  
PanZezhong committed
61
62
Tensor::~Tensor() {}

PanZezhong's avatar
PanZezhong committed
63
ptrdiff_t Tensor::dataOffset() const {
PanZezhong's avatar
PanZezhong committed
64
    return _offset;
PanZezhong's avatar
init  
PanZezhong committed
65
66
67
68
69
70
71
72
73
74
}

std::shared_ptr<TensorDesc> Tensor::desc() const { return TensorDesc::create(this->_dtype, this->_shape, this->_strides); }

std::shared_ptr<Tensor> Tensor::buffer(infiniDtype_t dtype,
                                       const std::vector<size_t> &shape,
                                       infinirtStream_t stream) {
    std::shared_ptr<Tensor> tensor = std::make_shared<Tensor>();
    tensor->_dtype = dtype;
    auto ndim = shape.size();
PanZezhong's avatar
PanZezhong committed
75
76
    tensor->_shape = std::vector<size_t>(shape);

PanZezhong's avatar
init  
PanZezhong committed
77
78
    size_t size = std::accumulate(shape.begin(), shape.end(), dsize(dtype), std::multiplies<size_t>());
    auto strides = std::vector<ptrdiff_t>(ndim);
PanZezhong's avatar
PanZezhong committed
79
80
81
82
83
    if (ndim > 0) {
        strides[ndim - 1] = 1;
        for (int i = ndim - 2; i >= 0; i--) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
PanZezhong's avatar
init  
PanZezhong committed
84
85
    }
    tensor->_strides = strides;
PanZezhong's avatar
PanZezhong committed
86
87
    tensor->_storage = Storage::createAsync(size, stream);
    tensor->_data = tensor->_storage->memory;
PanZezhong's avatar
init  
PanZezhong committed
88
89
90
91
92
93
94
95
96
97
98
    infiniopCreateTensorDescriptor(&tensor->_desc, ndim, tensor->_shape.data(),
                                   strides.data(), dtype);
    tensor->_offset = 0;
    return tensor;
}

std::shared_ptr<Tensor> Tensor::weight(void *data, infiniDtype_t dtype,
                                       const std::vector<size_t> &shape) {
    std::shared_ptr<Tensor> tensor = std::make_shared<Tensor>();
    tensor->_dtype = dtype;
    auto ndim = shape.size();
PanZezhong's avatar
PanZezhong committed
99
    tensor->_shape = std::vector<size_t>(shape);
PanZezhong's avatar
init  
PanZezhong committed
100
101
    size_t size = std::accumulate(shape.begin(), shape.end(), dsize(dtype), std::multiplies<size_t>());
    auto strides = std::vector<ptrdiff_t>(ndim);
PanZezhong's avatar
PanZezhong committed
102
103
104
105
106
    if (ndim > 0) {
        strides[ndim - 1] = 1;
        for (int i = ndim - 2; i >= 0; i--) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
PanZezhong's avatar
init  
PanZezhong committed
107
108
    }
    tensor->_strides = strides;
PanZezhong's avatar
PanZezhong committed
109
110
    tensor->_storage = Storage::create(size);
    RUN_INFINI(infinirtMemcpy(tensor->_storage->memory,
PanZezhong's avatar
init  
PanZezhong committed
111
                              data, size, INFINIRT_MEMCPY_H2D));
PanZezhong's avatar
PanZezhong committed
112
    tensor->_data = tensor->_storage->memory;
PanZezhong's avatar
init  
PanZezhong committed
113
114
115
116
117
118
    infiniopCreateTensorDescriptor(&tensor->_desc, ndim, tensor->_shape.data(),
                                   strides.data(), dtype);
    tensor->_offset = 0;
    return tensor;
}

119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
std::shared_ptr<Tensor> Tensor::memShare(const std::vector<size_t> &shape, infiniDtype_t dtype) const {
    size_t size = std::accumulate(shape.begin(), shape.end(), dsize(dtype), std::multiplies<size_t>());
    ASSERT(size <= this->_storage->size);

    std::shared_ptr<Tensor> tensor = std::make_shared<Tensor>();
    tensor->_dtype = dtype == INFINI_DTYPE_INVALID ? this->_dtype : dtype;
    tensor->_shape = std::vector<size_t>(shape);
    auto ndim = shape.size();
    auto strides = std::vector<ptrdiff_t>(ndim);
    if (ndim > 0) {
        strides[ndim - 1] = 1;
        for (int i = ndim - 2; i >= 0; i--) {
            strides[i] = strides[i + 1] * shape[i + 1];
        }
    }
    tensor->_strides = strides;
    tensor->_storage = this->_storage;
    infiniopCreateTensorDescriptor(&tensor->_desc, ndim, tensor->_shape.data(),
                                   tensor->_strides.data(), tensor->_dtype);
    tensor->_offset = 0;
    return tensor;
}

PanZezhong's avatar
PanZezhong committed
142
void *Tensor::dataImpl(ptrdiff_t offset) const {
PanZezhong's avatar
init  
PanZezhong committed
143
144
145
146
    return (char *)(this->_data) + offset * dsize(this->dtype());
}

void *Tensor::data(ptrdiff_t offset) {
PanZezhong's avatar
PanZezhong committed
147
    return this->dataImpl(offset);
PanZezhong's avatar
init  
PanZezhong committed
148
149
150
}

const void *Tensor::data(ptrdiff_t offset) const {
PanZezhong's avatar
PanZezhong committed
151
    return this->dataImpl(offset);
PanZezhong's avatar
init  
PanZezhong committed
152
153
}

PanZezhong's avatar
PanZezhong committed
154
155
void Tensor::copyFrom(std::shared_ptr<Tensor const> src,
                      infiniopHandle_t handle, infinirtStream_t stream) {
PanZezhong's avatar
init  
PanZezhong committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
    ASSERT_EQ(this->shape(), src->shape());
    ASSERT_EQ(this->dtype(), src->dtype());
    infiniopRearrangeDescriptor_t desc;
    RUN_INFINI(infiniopCreateRearrangeDescriptor(
        handle, &desc, this->desc()->get(), src->desc()->get()));
    RUN_INFINI(infiniopRearrange(desc, this->data(), src->data(),
                                 stream));
    RUN_INFINI(infiniopDestroyRearrangeDescriptor(desc));
}

bool Tensor::is_contigous() const {
    auto ndim = this->ndim();
    auto shape = this->shape();
    auto strides = std::vector<ptrdiff_t>(ndim);
    strides[ndim - 1] = 1;
    for (int i = ndim - 2; i >= 0; i--) {
        strides[i] = strides[i + 1] * shape[i + 1];
    }
    ASSERT_EQ(strides.size(), this->_strides.size());
    return std::equal(strides.begin(), strides.end(), this->_strides.begin());
}

template <typename T>
void print_data(T *data, const std::vector<size_t> &shape,
                const std::vector<ptrdiff_t> &strides, size_t dim) {
    if (dim == shape.size() - 1) {
        for (size_t i = 0; i < shape[dim]; i++) {
            std::cout << data[i] << " ";
        }
        std::cout << std::endl;
    } else if (dim < shape.size() - 1) {
        for (size_t i = 0; i < shape[dim]; i++) {
            print_data(data + i * strides[dim], shape, strides, dim + 1);
        }
    }
}

template <>
void print_data(uint16_t const *data, const std::vector<size_t> &shape,
                const std::vector<ptrdiff_t> &strides, size_t dim) {
    if (dim == shape.size() - 1) {
        for (size_t i = 0; i < shape[dim]; i++) {
            std::cout << f16_to_f32(data[i * strides[dim]]) << " ";
        }
PanZezhong's avatar
PanZezhong committed
200
        std::cout << std::endl;
PanZezhong's avatar
init  
PanZezhong committed
201
202
203
204
205
206
207
    } else if (dim < shape.size() - 1) {
        for (size_t i = 0; i < shape[dim]; i++) {
            print_data(data + i * strides[dim], shape, strides, dim + 1);
        }
    }
}

PanZezhong's avatar
PanZezhong committed
208
209
210
211
212
std::string Tensor::info() const {
    std::stringstream ss;

    ss << "Tensor: "
       << "shape[ ";
PanZezhong's avatar
init  
PanZezhong committed
213
    for (auto s : this->shape()) {
PanZezhong's avatar
PanZezhong committed
214
        ss << s << " ";
PanZezhong's avatar
init  
PanZezhong committed
215
    }
PanZezhong's avatar
PanZezhong committed
216
    ss << "] strides[ ";
PanZezhong's avatar
init  
PanZezhong committed
217
    for (auto s : this->strides()) {
PanZezhong's avatar
PanZezhong committed
218
        ss << s << " ";
PanZezhong's avatar
init  
PanZezhong committed
219
    }
PanZezhong's avatar
PanZezhong committed
220
221
222
223
224
225
226
227
228
229
230
    ss << "] dtype=" << this->dtype()
       << " device=" << this->deviceType()
       << " device_id=" << this->deviceId();

    return ss.str();
}

void Tensor::debug(const std::string &filename) const {
    RUN_INFINI(
        infinirtDeviceSynchronize());
    std::cout << info() << std::endl;
PanZezhong's avatar
init  
PanZezhong committed
231
232
    auto dtype = this->dtype();
    void const *cpu_data;
PanZezhong's avatar
PanZezhong committed
233
    if (this->deviceType() != INFINI_DEVICE_CPU) {
PanZezhong's avatar
PanZezhong committed
234
235
236
        void *cpu_memory = std::malloc(this->_storage->size);
        RUN_INFINI(infinirtMemcpy(cpu_memory, this->_storage->memory,
                                  this->_storage->size, INFINIRT_MEMCPY_D2H));
PanZezhong's avatar
init  
PanZezhong committed
237
238
        cpu_data = cpu_memory;
    } else {
PanZezhong's avatar
PanZezhong committed
239
        cpu_data = this->_storage->memory;
PanZezhong's avatar
init  
PanZezhong committed
240
241
242
243
244
245
246
247
    }

    if (!filename.empty()) {
        std::ofstream outFile(filename, std::ios::binary);
        if (!outFile) {
            std::cerr << "Error opening file for writing: " << filename << "\n";
            return;
        }
PanZezhong's avatar
PanZezhong committed
248
        outFile.write(reinterpret_cast<const char *>(cpu_data), this->_storage->size);
PanZezhong's avatar
init  
PanZezhong committed
249
250
251
252
253
254
255
        outFile.close();
        std::cout << "Data written to file: " << filename << "\n";
        return;
    }

    switch (dtype) {
    case INFINI_DTYPE_F16:
PanZezhong's avatar
PanZezhong committed
256
        print_data((uint16_t const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
257
258
259
                   this->shape(), this->strides(), 0);
        break;
    case INFINI_DTYPE_F32:
PanZezhong's avatar
PanZezhong committed
260
        print_data((float const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
261
262
263
                   this->shape(), this->strides(), 0);
        break;
    case INFINI_DTYPE_U64:
PanZezhong's avatar
PanZezhong committed
264
        print_data((uint64_t const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
265
266
267
                   this->shape(), this->strides(), 0);
        break;
    case INFINI_DTYPE_I64:
PanZezhong's avatar
PanZezhong committed
268
        print_data((int64_t const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
269
270
271
                   this->shape(), this->strides(), 0);
        break;
    case INFINI_DTYPE_U32:
PanZezhong's avatar
PanZezhong committed
272
        print_data((uint32_t const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
273
274
275
                   this->shape(), this->strides(), 0);
        break;
    case INFINI_DTYPE_I32:
PanZezhong's avatar
PanZezhong committed
276
        print_data((int32_t const *)((char const *)cpu_data + dataOffset()),
PanZezhong's avatar
init  
PanZezhong committed
277
278
279
280
281
282
283
284
                   this->shape(), this->strides(), 0);
        break;
    default:
        PANIC("Unsupported data type");
    }
}

void Tensor::debug() const { this->debug(""); }