Tensor.h 18.3 KB
Newer Older
fengzch-das's avatar
fengzch-das committed
1
#include "hip/hip_runtime.h"
Zhekai Zhang's avatar
Zhekai Zhang committed
2
3
4
5
6
#pragma once

#include "common.h"

struct Device {
Muyang Li's avatar
Muyang Li committed
7
    enum Type { INVALID_DEVICE_TYPE = 0, CPU, CUDA };
Zhekai Zhang's avatar
Zhekai Zhang committed
8
9

    Type type = INVALID_DEVICE_TYPE;
Muyang Li's avatar
Muyang Li committed
10
    int idx   = 0;
Zhekai Zhang's avatar
Zhekai Zhang committed
11
12
13
14
15
16
17
18
19
20
21
22
23

    static constexpr Device cpu(int idx = 0) {
        return Device{CPU, idx};
    }
    static constexpr Device cuda(int idx = 0) {
        return Device{CUDA, idx};
    }
};

// template<bool readonly>
class Buffer : public std::enable_shared_from_this<Buffer> {
public:
    virtual ~Buffer() {}
Muyang Li's avatar
Muyang Li committed
24
25
26
27

    void *getPtr() {
        return ptr;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
28
29

    template<typename T>
Muyang Li's avatar
Muyang Li committed
30
31
32
    T *getPtr() {
        return reinterpret_cast<T *>(ptr);
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
33

Muyang Li's avatar
Muyang Li committed
34
35
36
37
38
39
    size_t getSize() {
        return size;
    }
    Device getDevice() {
        return device;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
40

Muyang Li's avatar
Muyang Li committed
41
    virtual bool isAsyncBuffer() {
muyangli's avatar
muyangli committed
42
43
44
        return false;
    }

Zhekai Zhang's avatar
Zhekai Zhang committed
45
protected:
Muyang Li's avatar
Muyang Li committed
46
    template<typename Derived>
Zhekai Zhang's avatar
Zhekai Zhang committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    std::shared_ptr<Derived> shared_from_base() {
        return std::static_pointer_cast<Derived>(shared_from_this());
    }

protected:
    // std::conditional_t<readonly, const void *, void *> ptr;
    void *ptr;
    size_t size;
    Device device;
};

// using Buffer = BufferTemplate<false>;
// using BufferReadonly = BufferTemplate<true>;

class BufferMalloc : public Buffer {
public:
    BufferMalloc(size_t size) {
Muyang Li's avatar
Muyang Li committed
64
        this->size        = size;
Zhekai Zhang's avatar
Zhekai Zhang committed
65
        this->device.type = Device::CPU;
Muyang Li's avatar
Muyang Li committed
66
        this->ptr         = malloc(size);
Zhekai Zhang's avatar
Zhekai Zhang committed
67
68
69
70
71
72
73
74
75
    }
    virtual ~BufferMalloc() {
        free(this->ptr);
    }
};

class BufferHost : public Buffer {
public:
    BufferHost(size_t size) {
Muyang Li's avatar
Muyang Li committed
76
        this->size        = size;
Zhekai Zhang's avatar
Zhekai Zhang committed
77
        this->device.type = Device::CPU;
fengzch-das's avatar
fengzch-das committed
78
        checkCUDA(hipHostMalloc(&this->ptr, size, hipHostMallocPortable));
Zhekai Zhang's avatar
Zhekai Zhang committed
79
80
    }
    virtual ~BufferHost() {
fengzch-das's avatar
fengzch-das committed
81
        checkCUDA(hipHostFree(this->ptr));
Zhekai Zhang's avatar
Zhekai Zhang committed
82
83
84
85
86
87
    }
};

class BufferCUDA : public Buffer {
public:
    BufferCUDA(size_t size) {
Muyang Li's avatar
Muyang Li committed
88
        this->size        = size;
Zhekai Zhang's avatar
Zhekai Zhang committed
89
        this->device.type = Device::CUDA;
fengzch-das's avatar
fengzch-das committed
90
        // checkCUDA(hipGetDevice(&this->device.idx));
91
        this->device.idx = CUDADeviceContext::getDevice();
Zhekai Zhang's avatar
Zhekai Zhang committed
92
93
94
        if (size == 0) {
            this->ptr = nullptr;
        }
muyangli's avatar
muyangli committed
95
        // TODO: buffer used in multiple streams?
fengzch-das's avatar
fengzch-das committed
96
        checkCUDA(hipMallocAsync(&this->ptr, size, getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
97
98
99
100
101
102
    }
    virtual ~BufferCUDA() {
        if (this->size == 0) {
            assert(!this->ptr);
            return;
        }
fengzch-das's avatar
fengzch-das committed
103
        checkCUDA(hipFreeAsync(this->ptr, getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
104
    }
Muyang Li's avatar
Muyang Li committed
105
    virtual bool isAsyncBuffer() override {
muyangli's avatar
muyangli committed
106
107
        return true;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
108
109
110
111
112
};

class BufferCUDASync : public Buffer {
public:
    BufferCUDASync(size_t size) {
Muyang Li's avatar
Muyang Li committed
113
        this->size        = size;
Zhekai Zhang's avatar
Zhekai Zhang committed
114
        this->device.type = Device::CUDA;
fengzch-das's avatar
fengzch-das committed
115
116
        checkCUDA(hipGetDevice(&this->device.idx));
        checkCUDA(hipMalloc(&this->ptr, size));
Zhekai Zhang's avatar
Zhekai Zhang committed
117
118
    }
    virtual ~BufferCUDASync() {
fengzch-das's avatar
fengzch-das committed
119
        checkCUDA(hipFree(this->ptr));
Zhekai Zhang's avatar
Zhekai Zhang committed
120
121
122
123
124
125
126
    }
};

class BufferView : public Buffer {
public:
    BufferView(std::shared_ptr<Buffer> reference, size_t offset, size_t size) : reference(reference) {
        assert(offset + size <= reference->getSize());
Muyang Li's avatar
Muyang Li committed
127
128
        this->ptr    = (void *)((std::uint8_t *)reference->getPtr() + offset);
        this->size   = size;
Zhekai Zhang's avatar
Zhekai Zhang committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
        this->device = reference->getDevice();
    }

private:
    std::shared_ptr<Buffer> reference;
};

struct TensorShape {
    std::vector<int> dataExtent;
    std::vector<int> dataStride;
    int64_t offset = 0;

    TensorShape() {}
    TensorShape(std::vector<int> shape) : dataExtent(std::move(shape)) {}
    TensorShape(std::initializer_list<int> dims) : dataExtent(dims) {}

    bool is_contiguous() const {
        if (dataStride.empty()) {
            return true;
        }
        if (size() == 0) {
            return true;
        }
        int64_t prod = 1;
        for (int i = dataExtent.size() - 1; i >= 0; i--) {
            if (dataExtent[i] > 1 && dataStride[i] != prod) {
                return false;
            }
            prod *= dataExtent[i];
        }
        return true;
    }
    int ndims() const {
        return dataExtent.size();
    }
    const int &operator[](int idx) const {
        if (idx < 0) {
            return dataExtent.at(dataExtent.size() + idx);
        } else {
            return dataExtent.at(idx);
        }
    }
    int &operator[](int idx) {
        return const_cast<int &>(const_cast<const TensorShape *>(this)->operator[](idx));
    }

    size_t stride(int idx) const {
        if (!dataStride.empty()) {
            if (idx < 0) {
                return dataStride.at(dataStride.size() + idx);
            } else {
                return dataStride.at(idx);
            }
        }

        if (idx < 0) {
            idx = dataExtent.size() + idx;
        }
        assert(idx >= 0 && (size_t)idx < dataExtent.size());
        size_t result = 1;
        for (size_t i = idx + 1; i < dataExtent.size(); i++) {
            assert(dataExtent[i] >= 0);
            result *= dataExtent[i];
        }
        return result;
    }

    size_t size() const {
        if (dataExtent.empty()) {
            return 0;
        }
        size_t result = 1;
        for (int dim : dataExtent) {
            assert(dim >= 0);
            result *= dim;
        }
        return result;
    }

    std::string str() const {
        if (dataExtent.empty()) {
            return "[]";
        }
        std::stringstream ss;
        ss << "[" << dataExtent[0];
        for (size_t i = 1; i < dataExtent.size(); i++) {
            ss << ", " << dataExtent[i];
        }
        ss << "]";
        return ss.str();
    }
};

class Tensor {
public:
    enum ScalarType {
        INVALID_SCALAR_TYPE,
Muyang Li's avatar
Muyang Li committed
226
227
228
229
230
231
232
233
234
        INT8,
        INT16,
        INT32,
        INT64,
        FP16,
        FP32,
        BF16,
        FP8_E4M3,
        FP8_E5M2,
Zhekai Zhang's avatar
Zhekai Zhang committed
235
236
237
238
239
240
    };

    struct TensorOptions {
        Device device_;
        ScalarType dtype_;

Muyang Li's avatar
Muyang Li committed
241
242
243
244
245
246
        Device device() const {
            return device_;
        }
        ScalarType dtype() const {
            return dtype_;
        }
Zhekai Zhang's avatar
Zhekai Zhang committed
247
248
249
250
251
252
253
254
255
256
257
258
259
260

        TensorOptions device(Device dev) const {
            TensorOptions result(*this);
            result.device_ = dev;
            return result;
        }
        TensorOptions dtype(ScalarType type) const {
            TensorOptions result(*this);
            result.dtype_ = type;
            return result;
        }
    };

    static const std::map<ScalarType, size_t> scalarSize;
Muyang Li's avatar
Muyang Li committed
261

Zhekai Zhang's avatar
Zhekai Zhang committed
262
263
264
265
266
267
public:
    TensorShape shape;
    ScalarType scalarType;
    std::shared_ptr<Buffer> buffer;

public:
Muyang Li's avatar
Muyang Li committed
268
269
270
271
272
273
274
275
276
277
278
279
    bool valid() const {
        return shape.dataExtent.size() > 0;
    }
    int size(int dim) const {
        return shape[dim];
    }
    bool is_contiguous() const {
        return shape.is_contiguous();
    }
    std::vector<int> sizes() const {
        return shape.dataExtent;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
280

Muyang Li's avatar
Muyang Li committed
281
282
283
    bool is_cuda() const {
        return device().type == Device::CUDA;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
284

Muyang Li's avatar
Muyang Li committed
285
286
287
288
289
290
    TensorOptions options() const {
        return TensorOptions{device(), dtype()};
    }
    int get_device() const {
        return device().idx;
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
291
292

    template<typename T>
Muyang Li's avatar
Muyang Li committed
293
294
295
    T *data_ptr() {
        return reinterpret_cast<T *>(data_ptr());
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
296
    template<typename T>
Muyang Li's avatar
Muyang Li committed
297
298
299
    const T *data_ptr() const {
        return reinterpret_cast<const T *>(data_ptr());
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
300

Muyang Li's avatar
Muyang Li committed
301
302
303
304
305
306
    const void *data_ptr() const {
        return buffer->getPtr<char>() + shape.offset * scalar_size();
    }
    void *data_ptr() {
        return buffer->getPtr<char>() + shape.offset * scalar_size();
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
307

Muyang Li's avatar
Muyang Li committed
308
309
310
311
312
313
314
315
316
317
    Device device() const {
        return buffer->getDevice();
    }

    ScalarType scalar_type() const {
        return scalarType;
    }
    ScalarType dtype() const {
        return scalar_type();
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
318

Muyang Li's avatar
Muyang Li committed
319
320
321
    size_t stride(int dim) const {
        return shape.stride(dim);
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
322

Muyang Li's avatar
Muyang Li committed
323
324
325
326
327
328
    size_t numel() const {
        return shape.size();
    }
    size_t ndims() const {
        return shape.ndims();
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
329

Muyang Li's avatar
Muyang Li committed
330
331
332
    size_t dim() const {
        return ndims();
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
333

Muyang Li's avatar
Muyang Li committed
334
335
336
    size_t scalar_size() const {
        return scalarSize.at(scalarType);
    }
Zhekai Zhang's avatar
Zhekai Zhang committed
337
338
339
340

    Tensor operator[](int idx) const {
        assert(ndims() > 1);
        Tensor result;
Muyang Li's avatar
Muyang Li committed
341
342
343
        result.shape      = std::vector<int>(this->shape.dataExtent.begin() + 1, this->shape.dataExtent.end());
        size_t size       = stride(0) * scalar_size();
        result.buffer     = std::make_shared<BufferView>(this->buffer, idx * size, size);
Zhekai Zhang's avatar
Zhekai Zhang committed
344
345
346
347
348
        result.scalarType = this->scalarType;
        return result;
    }

    template<typename T>
Muyang Li's avatar
Muyang Li committed
349
    const T &at(const std::vector<int> &idx) const {
Zhekai Zhang's avatar
Zhekai Zhang committed
350
351
352
353
354
355
356
357
358
359
        assert(ndims() == idx.size());
        int64_t offset = 0;
        for (size_t i = 0; i < ndims(); i++) {
            offset += idx.at(i) * stride(i);
        }
        assert(offset >= 0 && offset < numel());
        return this->data_ptr<T>()[offset];
    }

    template<typename T>
Muyang Li's avatar
Muyang Li committed
360
    T &at(const std::vector<int> &idx) {
Zhekai Zhang's avatar
Zhekai Zhang committed
361
362
363
364
365
366
        return const_cast<T &>(const_cast<const Tensor *>(this)->at<T>(idx));
    }

    Tensor slice(int dim, int from, int to) const {
        assert(from <= to);
        Tensor result;
Muyang Li's avatar
Muyang Li committed
367
        result.buffer     = this->buffer;
Zhekai Zhang's avatar
Zhekai Zhang committed
368
369
        result.scalarType = this->scalarType;

Muyang Li's avatar
Muyang Li committed
370
        result.shape      = TensorShape(this->shape.dataExtent);
Zhekai Zhang's avatar
Zhekai Zhang committed
371
372
373
374
375
376
377
378
379
380
381
        result.shape[dim] = to - from;
        result.shape.dataStride.resize(result.shape.ndims());
        for (int i = 0; i < result.shape.ndims(); i++) {
            result.shape.dataStride[i] = this->shape.stride(i);
        }
        result.shape.offset = this->shape.offset + this->shape.stride(dim) * from;

        return result;
    }
    Tensor transpose(int dim1, int dim2) const {
        Tensor result;
Muyang Li's avatar
Muyang Li committed
382
        result.buffer     = this->buffer;
Zhekai Zhang's avatar
Zhekai Zhang committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
        result.scalarType = this->scalarType;

        result.shape = TensorShape(this->shape.dataExtent);
        result.shape.dataStride.resize(result.shape.ndims());
        for (int i = 0; i < result.shape.ndims(); i++) {
            result.shape.dataStride[i] = this->shape.stride(i);
        }
        result.shape.offset = this->shape.offset;

        std::swap(result.shape.dataExtent[dim1], result.shape.dataExtent[dim2]);
        std::swap(result.shape.dataStride[dim1], result.shape.dataStride[dim2]);

        return result;
    }

    Tensor view(TensorShape shape) const {
        assert(shape.size() == this->shape.size());
        assert(this->is_contiguous());
        Tensor result;
Muyang Li's avatar
Muyang Li committed
402
403
404
        result.buffer       = this->buffer;
        result.scalarType   = this->scalarType;
        result.shape        = shape;
Zhekai Zhang's avatar
Zhekai Zhang committed
405
406
407
408
409
410
411
412
413
414
415
416
417
418
        result.shape.offset = this->shape.offset;
        return result;
    }
    Tensor reshape(TensorShape shape) const {
        return view(shape);
    }

    // // NOT IMPLEMENTED!!! DONT USE
    // Tensor transpose(int a, int b) const {
    //     throw std::runtime_error("Not implemented");
    // }

    Tensor &zero_() {
        assert(this->is_contiguous());
fengzch-das's avatar
fengzch-das committed
419
420
        checkCUDA(hipMemsetAsync(
            data_ptr<char>() + shape.offset * scalar_size(), 0, shape.size() * scalar_size(), getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
        return *this;
    }
    Tensor &copy_(Tensor other) {
        assert(this->is_contiguous());
        assert(other.is_contiguous());
        assert(this->shape.dataExtent == other.shape.dataExtent);
        assert(this->dtype() == other.dtype());

        assert((shape.offset + shape.size()) * scalar_size() <= buffer->getSize());
        assert((other.shape.offset + shape.size()) * scalar_size() <= other.buffer->getSize());

        if (shape.size() == 0) {
            return *this;
        }

436
437
438
439
440
441
442
        std::optional<CUDADeviceContext> operation_ctx_guard;

        if (this->device().type == Device::CUDA) {
        } else if (other.device().type == Device::CUDA) {
            operation_ctx_guard.emplace(other.device().idx);
        }

Zhekai Zhang's avatar
Zhekai Zhang committed
443
        if (this->device().type == Device::CPU && other.device().type == Device::CPU) {
Muyang Li's avatar
Muyang Li committed
444
            memcpy(data_ptr<char>(), other.data_ptr<char>(), shape.size() * scalar_size());
Zhekai Zhang's avatar
Zhekai Zhang committed
445
446
447
            return *this;
        }

fengzch-das's avatar
fengzch-das committed
448
449
450
        lockBuffer(this->buffer, getCurrentHIPStreamMasqueradingAsCUDA());
        lockBuffer(other.buffer, getCurrentHIPStreamMasqueradingAsCUDA());
        checkCUDA(hipMemcpyAsync(data_ptr<char>(),
Muyang Li's avatar
Muyang Li committed
451
452
453
                                  other.data_ptr<char>(),
                                  shape.size() * scalar_size(),
                                  getCopyKind(this->device(), other.device()),
fengzch-das's avatar
fengzch-das committed
454
                                  getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
        return *this;
    }

    // NOT IMPLEMENTED!!! DONT USE
    template<typename T>
    Tensor &fill_(T val) {
        throw std::runtime_error("Not implemented");
        return *this;
    }
    // NOT IMPLEMENTED!!! DONT USE
    Tensor index(std::vector<std::any> whatever) {
        throw std::runtime_error("Not implemented");
    }

public:
    static Tensor allocate(TensorShape shape, ScalarType scalarType, Device device, bool fill = false) {
        Tensor result;
        assert(shape.is_contiguous());
        if (device.type == Device::CPU) {
            result.buffer = std::make_shared<BufferMalloc>(shape.size() * scalarSize.at(scalarType));
        } else if (device.type == Device::CUDA) {
            // TODO: cross device allocate
477
            CUDADeviceContext ctx(device.idx);
Zhekai Zhang's avatar
Zhekai Zhang committed
478
479
480
481
482
            result.buffer = std::make_shared<BufferCUDA>(shape.size() * scalarSize.at(scalarType));
        } else {
            assert(false);
        }
        result.scalarType = scalarType;
Muyang Li's avatar
Muyang Li committed
483
        result.shape      = shape;
Zhekai Zhang's avatar
Zhekai Zhang committed
484
485
486
487
488

        if (fill) {
            if (device.type == Device::CPU) {
                memset(result.buffer->getPtr(), 0xCC, result.buffer->getSize());
            } else if (device.type == Device::CUDA) {
489
                CUDADeviceContext ctx(device.idx);
Muyang Li's avatar
Muyang Li committed
490
                checkCUDA(
fengzch-das's avatar
fengzch-das committed
491
                    hipMemsetAsync(result.buffer->getPtr(), 0xCC, result.buffer->getSize(), getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
492
493
494
495
496
497
498
499
500
501
502
503
504
505
            }
        }

        return result;
    }
    static Tensor empty(TensorShape shape, ScalarType scalarType, Device device) {
        return allocate(shape, scalarType, device);
    }
    static Tensor empty_like(const Tensor &tensor) {
        return empty(TensorShape(tensor.shape.dataExtent), tensor.scalarType, tensor.device());
    }
    static Tensor ones(TensorShape shape, ScalarType scalarType, Device device) {
        Tensor result = allocate(shape, scalarType, device);
        // FIXME FIXME FIXME
fengzch-das's avatar
fengzch-das committed
506
        checkCUDA(hipMemsetAsync(result.buffer->getPtr(), 1, result.buffer->getSize(), getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
507
508
        return result;
    }
Muyang Li's avatar
Muyang Li committed
509
510
    static Tensor
    allocate_view(TensorShape shape, ScalarType scalarType, std::shared_ptr<Buffer> buffer, size_t offset = 0) {
Zhekai Zhang's avatar
Zhekai Zhang committed
511
        Tensor result;
Muyang Li's avatar
Muyang Li committed
512
        result.buffer     = std::make_shared<BufferView>(buffer, offset, shape.size() * scalarSize.at(scalarType));
Zhekai Zhang's avatar
Zhekai Zhang committed
513
        result.scalarType = scalarType;
Muyang Li's avatar
Muyang Li committed
514
        result.shape      = shape;
Zhekai Zhang's avatar
Zhekai Zhang committed
515
516
517
518
519
520
521
522
523
524
525
        return result;
    }

public:
    Tensor copy(Device device) const {
        if (!buffer) {
            return *this;
        }
        Tensor result = allocate(this->shape.dataExtent, this->scalarType, device);
        result.copy_(*this);

fengzch-das's avatar
fengzch-das committed
526
527
528
529
530
531
        // lockBuffer(this->buffer, getCurrentHIPStreamMasqueradingAsCUDA());
        // lockBuffer(result.buffer, getCurrentHIPStreamMasqueradingAsCUDA());
        // checkCUDA(hipMemcpyAsync(result.data_ptr(), this->data_ptr(), result.buffer->getSize(), hipMemcpyDefault,
        // getCurrentHIPStreamMasqueradingAsCUDA())); if (this->device().type == Device::CPU && device.type == Device::CUDA) {
        //     checkCUDA(hipMemcpyAsync(result.data_ptr(), this->data_ptr(), result.buffer->getSize(),
        //     hipMemcpyHostToDevice, getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
532
        // } else if (this->device().type == Device::CUDA && device.type == Device::CPU) {
fengzch-das's avatar
fengzch-das committed
533
534
        //     checkCUDA(hipMemcpyAsync(result.data_ptr(), this->data_ptr(), result.buffer->getSize(),
        //     hipMemcpyDeviceToHost, getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
535
        // } else {
fengzch-das's avatar
fengzch-das committed
536
537
        //     checkCUDA(hipMemcpyAsync(result.data_ptr(), this->data_ptr(), result.buffer->getSize(),
        //     hipMemcpyDefault, getCurrentHIPStreamMasqueradingAsCUDA()));
Zhekai Zhang's avatar
Zhekai Zhang committed
538
539
540
541
542
543
544
545
546
547
548
549
550
551
        // }
        return result;
    }

    // void copy_range(Tensor &dst, int dim, int lower_bound, int upper_bound) {
    //     if (upper_bound > shape[dim]) {
    //         upper_bound = shape[dim];
    //     }
    //     if (lower_bound >= upper_bound) {
    //         return;
    //     }
    //     auto shapeOut = this->shape;
    //     shapeOut[dim] = upper_bound - lower_bound;
    //     assert(dst.shape.data == shapeOut.data);
fengzch-das's avatar
fengzch-das committed
552
    //     checkCUDA(hipMemcpy2DAsync(
Zhekai Zhang's avatar
Zhekai Zhang committed
553
554
555
556
557
    //         dst.
    //     ));
    // }

private:
fengzch-das's avatar
fengzch-das committed
558
    static hipMemcpyKind getCopyKind(Device dst, Device src) {
Zhekai Zhang's avatar
Zhekai Zhang committed
559
        if (src.type == Device::CPU && dst.type == Device::CUDA) {
fengzch-das's avatar
fengzch-das committed
560
            return hipMemcpyHostToDevice;
Zhekai Zhang's avatar
Zhekai Zhang committed
561
562
        }
        if (src.type == Device::CUDA && dst.type == Device::CPU) {
fengzch-das's avatar
fengzch-das committed
563
            return hipMemcpyDeviceToHost;
Zhekai Zhang's avatar
Zhekai Zhang committed
564
565
        }
        if (src.type == Device::CUDA && dst.type == Device::CUDA) {
fengzch-das's avatar
fengzch-das committed
566
            return hipMemcpyDeviceToDevice;
Zhekai Zhang's avatar
Zhekai Zhang committed
567
568
        }
        if (src.type == Device::CPU && dst.type == Device::CPU) {
fengzch-das's avatar
fengzch-das committed
569
            return hipMemcpyHostToHost;
Zhekai Zhang's avatar
Zhekai Zhang committed
570
        }
fengzch-das's avatar
fengzch-das committed
571
        return hipMemcpyDefault;
Zhekai Zhang's avatar
Zhekai Zhang committed
572
573
    }

muyangli's avatar
muyangli committed
574
575
576
    // static bool isAsyncBuffer(Buffer *buffer) {
    //     return dynamic_cast<BufferCUDA *>(buffer);
    // }
Zhekai Zhang's avatar
Zhekai Zhang committed
577

fengzch-das's avatar
fengzch-das committed
578
    static inline std::map<hipStream_t, std::set<std::shared_ptr<Buffer>>> lockedBuffers;
Muyang Li's avatar
Muyang Li committed
579

Zhekai Zhang's avatar
Zhekai Zhang committed
580
public:
Muyang Li's avatar
Muyang Li committed
581
582
    // before launching an async operation, make sure to lock the buffer in case the buffer is freed before GPU
    // completes
fengzch-das's avatar
fengzch-das committed
583
    static void lockBuffer(std::shared_ptr<Buffer> buffer, hipStream_t stream) {
muyangli's avatar
muyangli committed
584
        if (!buffer->isAsyncBuffer()) {
Zhekai Zhang's avatar
Zhekai Zhang committed
585
586
587
588
589
590
591
592
            lockedBuffers[stream].insert(buffer);
        }
    }

    // we could unlock buffers after sync with GPU
    static void unlockBuffers() {
        lockedBuffers.clear();
    }
fengzch-das's avatar
fengzch-das committed
593
    static void unlockBuffers(hipStream_t stream) {
Zhekai Zhang's avatar
Zhekai Zhang committed
594
595
596
597
        lockedBuffers[stream].clear();
    }

    static void synchronizeDevice() {
fengzch-das's avatar
fengzch-das committed
598
        checkCUDA(hipDeviceSynchronize());
Zhekai Zhang's avatar
Zhekai Zhang committed
599
600
        unlockBuffers();
    }
fengzch-das's avatar
fengzch-das committed
601
602
    static void synchronizeStream(hipStream_t stream) {
        checkCUDA(hipStreamSynchronize(stream));
Zhekai Zhang's avatar
Zhekai Zhang committed
603
604
605
606
607
608
        unlockBuffers(stream);
    }
};

inline const std::map<Tensor::ScalarType, size_t> Tensor::scalarSize = {
    {INT8, 1},
609
    {INT16, 2},
Zhekai Zhang's avatar
Zhekai Zhang committed
610
611
612
613
614
    {INT32, 4},
    {INT64, 8},
    {FP16, 2},
    {FP32, 4},
    {BF16, 2},
615
616
    {FP8_E4M3, 1},
    {FP8_E5M2, 1},
Zhekai Zhang's avatar
Zhekai Zhang committed
617
618
619
620
621
};

struct TensorsProvider {
    virtual ~TensorsProvider() {}
    virtual bool contains(const std::string &key) const = 0;
Muyang Li's avatar
Muyang Li committed
622
623
    virtual Tensor getTensor(const std::string &key)    = 0;
};