-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensor.cuh
More file actions
2324 lines (2081 loc) · 77.3 KB
/
tensor.cuh
File metadata and controls
2324 lines (2081 loc) · 77.3 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef TENSOR_CUH
#define TENSOR_CUH
#include <random>
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <cublas_v2.h>
#include <cusolverDn.h>
#include <stdexcept>
#include <memory>
#include <optional>
#include <cassert>
#include <fstream>
/**
* Define defaults
*/
#define DEFAULT_FPX double
#define THREADS_PER_BLOCK 512
#if (__cplusplus >= 201703L) ///< if c++17 or above
#define TEMPLATE_WITH_TYPE_T template<typename T = DEFAULT_FPX>
#else
#define TEMPLATE_WITH_TYPE_T template<typename T>
#endif
#if (__cplusplus >= 202002L) ///< if c++20 or above
#define TEMPLATE_CONSTRAINT_REQUIRES_FPX requires std::floating_point<T>
#else
#define TEMPLATE_CONSTRAINT_REQUIRES_FPX
#endif
static std::random_device RND_DEVICE;
/**
* Generate vector of random elements
* @tparam T
* @param n
* @param low
* @param hi
* @return
*/
TEMPLATE_WITH_TYPE_T
TEMPLATE_CONSTRAINT_REQUIRES_FPX
std::vector<T> generateRealRandomVector(size_t n, T low, T hi) {
std::mt19937_64 mersenne_engine(RND_DEVICE());
std::uniform_real_distribution<T> dist(low, hi);
auto gen = [&dist, &mersenne_engine]() {
return dist(mersenne_engine);
};
std::vector<T> vec(n);
generate(begin(vec), end(vec), gen);
return vec;
}
inline std::vector<int> generateIntRandomVector(size_t n, int low, int hi) {
std::mt19937_64 mersenne_engine(RND_DEVICE());
std::uniform_int_distribution dist(low, hi);
auto gen = [&dist, &mersenne_engine]() {
return dist(mersenne_engine);
};
std::vector<int> vec(n);
generate(begin(vec), end(vec), gen);
return vec;
}
/**
* Determines the number of blocks needed for a given number of tasks, n,
* and number of threads per block
*
* @param n problem size
* @param threads_per_block threads per block (defaults to THREADS_PER_BLOCK)
* @return number of blocks
*/
constexpr size_t numBlocks(size_t n, size_t threads_per_block = THREADS_PER_BLOCK) {
return (n / threads_per_block + (n % threads_per_block != 0));
}
/**
* Check for errors when calling GPU functions
*/
#define gpuErrChk(status) { gpuAssert((status), __FILE__, __LINE__); } while(false)
TEMPLATE_WITH_TYPE_T
inline void gpuAssert(T code, const char *file, int line, bool abort = true) {
if constexpr (std::is_same_v<T, cudaError_t>) {
if (code != cudaSuccess) {
std::cerr << "cuda error. String: " << cudaGetErrorString(code)
<< ", file: " << file << ", line: " << line << "\n";
if (abort) exit(code);
}
} else if constexpr (std::is_same_v<T, cublasStatus_t>) {
if (code != CUBLAS_STATUS_SUCCESS) {
std::cerr << "cublas error. Name: " << cublasGetStatusName(code)
<< ", string: " << cublasGetStatusString(code)
<< ", file: " << file << ", line: " << line << "\n";
if (abort) exit(code);
}
} else if constexpr (std::is_same_v<T, cusolverStatus_t>) {
if (code != CUSOLVER_STATUS_SUCCESS) {
std::cerr << "cusolver error. Status: " << code
<< ", file: " << file << ", line: " << line << "\n";
if (abort) exit(code);
}
} else {
std::cerr << "Error: library status parser not implemented" << "\n";
}
}
/* ================================================================================================
* SESSION
* ================================================================================================ */
/**
* Total number of allocated streams
* Can be changed with Session::setStreams()
*/
static size_t s_numStreams = 1;
/**
* Singleton for Cuda library handles.
* Cuda library functions require a handle.
* A project requires exactly one handle per Cuda library.
* This class is created as a singleton, and contains a unique handle for each library.
* The cuBlas handle can be accessed anywhere by `Session::getInstance().cuBlasHandle()`
* The cuSolver handle can be accessed anywhere by `Session::getInstance().cuSolverHandle()`
*/
class Session {
public:
/**
* Sets the total number of available streams
* @param numStreams number of streams (default: 1)
*/
static void setStreams(size_t numStreams) {
s_numStreams = numStreams;
}
/**
* Returns the unique instance of Session (constructed upon first
* invocation)
* @return instance of Session
*/
static Session &getInstance() {
static Session instance(s_numStreams);
return instance;
}
private:
Session(size_t numStreams) {
m_numCublasHandlesStreams = numStreams;
m_cublasHandles.resize(m_numCublasHandlesStreams);
m_cublasStreams.resize(m_numCublasHandlesStreams);
m_cusolverHandles.resize(m_numCublasHandlesStreams);
for (size_t i = 0; i < m_numCublasHandlesStreams; i++) {
gpuErrChk(cublasCreate(&m_cublasHandles[i]));
gpuErrChk(cudaStreamCreate(&m_cublasStreams[i]));
gpuErrChk(cublasSetStream(m_cublasHandles[i], m_cublasStreams[i]));
gpuErrChk(cusolverDnCreate(&m_cusolverHandles[i]));
gpuErrChk(cusolverDnSetStream(m_cusolverHandles[i], m_cublasStreams[i]));
}
}
~Session() {
for (size_t i = 0; i < m_numCublasHandlesStreams; i++) {
gpuErrChk(cublasDestroy(m_cublasHandles[i]));
gpuErrChk(cusolverDnDestroy(m_cusolverHandles[i]));
}
}
std::vector<cublasHandle_t> m_cublasHandles;
std::vector<cudaStream_t> m_cublasStreams;
std::vector<cusolverDnHandle_t> m_cusolverHandles;
size_t m_bytesAllocated = 0;
size_t m_numCublasHandlesStreams = 1;
public:
Session(Session const &) = delete;
void operator=(Session const &) = delete;
/**
* cuBLAS handle
* @param idx index of stream
* @return cuBLAS handle
*/
cublasHandle_t &cuBlasHandle(size_t idx = 0) { return m_cublasHandles[idx]; }
/**
* cuSolver handle
* @param idx index of stream
* @return cuSolver handle
*/
cusolverDnHandle_t &cuSolverHandle(size_t idx = 0) { return m_cusolverHandles[idx]; }
/**
*
* @param idx index of stream
* @return stream
*/
cudaStream_t &stream(size_t idx = 0) { return m_cublasStreams[idx]; }
/**
* Preferred method for CUDA memory allocation; it allocated memory on the device
* and counts the allocated bytes (you can then call #totalAllocatedBytes()).
* In essence, this is a wrapper for cudaMalloc.
*
* @param d pointer to memory address to be allocated
* @param s size to be allocated
* @return CUDA error
*/
cudaError_t cudaAllocate(void **d, size_t s) {
cudaError_t err = cudaMalloc(d, s);
if (err == cudaSuccess) {
m_bytesAllocated += s;
}
return err;
}
/**
* @return Total allocated bytes
*/
size_t totalAllocatedBytes() const { return m_bytesAllocated; }
/**
* Increment counter of allocated bytes
* @param s allocated bytes (can be negative)
*/
void incrementAllocatedBytes(int s) { m_bytesAllocated += s; }
/**
* Synchronize stream
* @param idx stream index
*/
void synchronizeStream(size_t idx = 0) const {
if (idx >= m_numCublasHandlesStreams) {
throw std::runtime_error("stream index out of range");
}
gpuErrChk(cudaStreamSynchronize(m_cublasStreams[idx]));
}
/**
* Synchronize all streams
*/
void synchronizeAllStreams() const {
for (size_t i = 0; i < m_numCublasHandlesStreams; i++) {
synchronizeStream(i);
}
}
};
/* ================================================================================================
* TENSOR
* ================================================================================================ */
/**
* Storage mode for the data of a matrix
*/
enum StorageMode {
columnMajor, ///< column major storage (default)
rowMajor, ///< row major storage
defaultMajor = columnMajor
};
/**
* This library uses tensors to store and manipulate data on a GPU device.
* A tensor has three axes: [rows (m) x columns (n) x matrices (k)].
* An (m,n,1)-tensor is a matrix, and an (m,1,1)-tensor is a vector.
* Tensors can be used to do a batched operation on many similar-sized matrices or vectors in parallel.
* @tparam T type of data stored in tensor
*/
TEMPLATE_WITH_TYPE_T
class DTensor {
private:
T *m_d_data = nullptr; ///< Pointer to device data
T **m_d_ptrMatrices = nullptr; ///< Pointer to matrices in tensor
size_t m_numRows = 0; ///< Number of rows
size_t m_numCols = 0; ///< Number of columns
size_t m_numMats = 0; ///< Number of matrices
bool m_doDestroyData = false; ///< Whether to destroy memory
bool m_doDestroyPtrMatrices = false; ///< Whether to destroy memory
size_t m_idxStream = 0; ///< Stream index (defaults to 0)
void destroy() {
if (m_doDestroyData) {
if (m_d_data) gpuErrChk(cudaFree(m_d_data));
m_d_data = nullptr;
Session::getInstance().incrementAllocatedBytes(-m_numRows * m_numCols * m_numMats * sizeof(T));
}
if (m_doDestroyPtrMatrices) {
if (m_d_ptrMatrices) gpuErrChk(cudaFree(m_d_ptrMatrices));
m_d_ptrMatrices = nullptr;
Session::getInstance().incrementAllocatedBytes(-m_numMats * sizeof(T *));
}
}
/**
* Allocate `size` number of `T` data on the device.
* @param size number of data elements to allocate
* @param zero sets allocated data to `0`
*/
void allocateOnDevice(size_t size, bool zero = false);
/**
* Create column-major `std::vector` from a row-major one.
* @param rm row-major stored data
* @param cm column-major storage
*/
void rm2cm(const std::vector<T> &rm, std::vector<T> &cm) {
size_t n = m_numRows * m_numCols;
for (size_t k = 0; k < m_numMats; k++) {
size_t idx = k * n;
for (size_t r = 0; r < m_numRows; r++) {
for (size_t c = 0; c < m_numCols; c++) {
cm[idx + (r + c * m_numRows)] = rm[idx + (c + r * m_numCols)];
}
}
}
}
/**
* Appends this tensor to `std::ostream` object, in the format it represents.
* @param out `std::ostream` object for appending data to be printed
* @return tensor in `std::ostream` data format
*/
std::ostream &print(std::ostream &out) const;
/**
* Initialises an array of pointers to the sub-matrices of the
* tensor (on the device). No allocation takes place if the tensor
* has only one matrix.
*/
void initialisePointersToMatricesData();
public:
/**
* Set the stream ID
*/
DTensor<T> setStreamIdx(size_t);
size_t streamIdx() const { return m_idxStream; }
/**
* Create a tensor with random elements
* @param numRows number of rows
* @param numCols number of columns
* @param numMats number of matrices
* @param low minimum value of random elements
* @param hi maximum value of random elements
*
* @throws std::invalid_argument if T is other than double, float, or int
*/
static DTensor<T> createRandomTensor(size_t numRows, size_t numCols, size_t numMats, T low, T hi);
/**
* Parse data from text file and create an instance of DTensor
*
* This static function reads data from a text file, creates a DTensor and uploads the data to the device.
*
* The data may be stored in a text file or a binary file. Binary files must have the extension .bt.
*
* @param path_to_file path to file as string
* @param mode storage mode (default: StorageMode::defaultMajor)
* @return instance of DTensor
*
* @throws std::invalid_argument if the file is not found
*/
static DTensor<T> parseFromFile(std::string path_to_file,
StorageMode mode = StorageMode::defaultMajor);
/**
* Constructs a DTensor object.
*/
DTensor() = default;
/**
* Destroys a DTensor object.
*/
~DTensor() {
destroy();
}
/**
* Constructs (m,n,k)-tensor and allocates memory.
* @param m number of rows
* @param n number of columns
* @param k number of matrices
* @param zero sets allocated data to `0`
*/
DTensor(size_t m, size_t n = 1, size_t k = 1, bool zero = false);
/**
* Constructs (m,n,k)-tensor and uploads data to device.
* @param data `std::vector` of data to upload to the device
* @param m number of rows
* @param n number of columns
* @param k number of matrices
*/
DTensor(const std::vector<T> &data, size_t m, size_t n = 1, size_t k = 1,
StorageMode mode = StorageMode::defaultMajor);
/**
* Copy constructor.
* @param other tensor to copy to newly constructed tensor
*/
DTensor(const DTensor &other);
/**
* Move constructor.
* @param other tensor to move to newly constructed tensor
*/
DTensor(DTensor &&other);
/**
* Slice constructor.
* @param other other tensor with the same template type
* @param axis axis to slice (0=rows, 1=columns, 2=matrices)
* @param from index to slice axis from (zero-indexed)
* @param to index to slice axis to (inclusive)
*/
DTensor(const DTensor &other, size_t axis, size_t from, size_t to);
/**
* @return raw pointer to the first element of this tensor on the device
*/
T *raw() const;
/**
* Pointers to matrices (on device)
* @return
*/
T **ptrMatrices() const;
/**
* @return number of rows
*/
size_t numRows() const;
/**
* @return number of columns
*/
size_t numCols() const;
/**
* @return number of matrices
*/
size_t numMats() const;
/**
* @return number of elements
*/
size_t numEl() const;
/**
* Upload from `std::vector` to device.
* @param vec data source to upload
* @return true iff upload is successful
*/
bool upload(const std::vector<T> &vec, StorageMode mode = StorageMode::defaultMajor);
/**
* Download from device to `std::vector`.
* @param vec destination vector
*/
void download(std::vector<T> &vec) const;
/**
* Device-to-device copy.
* @param other target tensor
*/
void deviceCopyTo(DTensor<T> &other) const;
/**
* Slices rows from specified matrix.
* @param rowsFrom index to slice rows from (zero-indexed)
* @param rowsTo index to slice rows to (inclusive)
* @param matIdx index of matrix to slice rows from (zero-indexed)
* @return slice of rows
*/
DTensor<T> getRows(size_t rowsFrom, size_t rowsTo, size_t matIdx) const;
/**
* Transposes each (m,n)-matrix of this tensor.
* Each transposed matrix is stored at same k-index in new tensor.
* @return tensor of transposed matrices
*/
DTensor<T> tr() const;
/**
* Frobenius dot product.
* @param other other tensor of compatible dimensions
* @return value of Frobenius dot product
*/
T dotF(const DTensor &other);
/**
* Frobenius norm.
* The square root of the sum of squares of all elements.
* A.k.a. the Euclidean norm, if this is a vector.
* @return norm as same data type
*/
T normF() const;
/**
* Sum of absolute of all elements.
* @return sum as same data type
*/
T sumAbs() const;
/**
* Maximum of absolute of all elements.
* Equivalent to inf-norm, max(|x_i|) for all i.
* @return max of absolute as same data type
*/
T maxAbs() const;
/**
* Minimum of absolute of all elements, min(|x_i|) for all i.
* @return min of absolute as same data type
*/
T minAbs() const;
/**
* Applied the Givens rotation G(i, j, c, s) on row i and column j,
* with cos θ = c, and sin θ = s. The rotation is applied in-place
* to all slices of the tensor. Recall that the Givens rotation is
*
* i j
* |1 0 ... 0 |
* |0 1 ... 0 |
* | |
* | 1 |
* i | c s |
* G' = ' '
* j | -s c |
* | 1 |
* | |
* | 0 |
*
* The right Givens rotation consists in multiplying from the right
* by G.
*
* Equivalently, the right Givens transformation performs the following
* operation on the i and j columns of this matrix:
*
* A[:, i] <-- c * A[:, i] - s * A[:, j]
* A[:, j] <-- s * A[:, i] + c * A[:, j]
*
* @param i first column index
* @param j second column index
* @param c cos θ
* @param minus_s minus sin θ
* @throws std::invalid_argument if either i or j is greater or equal ncols
*/
void applyRightGivensRotation(size_t i, size_t j, const T *c, const T *minus_s);
/**
* Performs a Givens rotation (left multiplication by G')
*
* @param i first row index
* @param j second row index
* @param c cos θ
* @param minus_s minus sin θ
* @throws std::invalid_argument if either i or j is greater or equal nrows
*/
void applyLeftGivensRotation(size_t i, size_t j, const T *c, const T *minus_s);
/**
* Batch solves `A \ b`.
* Solves `bi <- Ai \ bi` for each k-index `i`.
* A is this (m,n,k)-tensor and b is the provided (m,1,k)-tensor.
* A and b must have compatible dimensions (same number of rows and matrices).
* A must be a square or tall matrix (m>=n).
* @param b provided tensor
* @return least squares solutions (overwrites (n,1,k)-part of b)
*/
void leastSquaresBatched(DTensor &b);
/**
* Batched `C <- bC + a*A*B`.
* Performs the operation `Ci <- bCi + a*Ai*Bi` for each k-index `i`.
* C is this tensor.
* A and B are tensors of compatible dimensions.
* @param A tensor A
* @param B tensor B
* @param alpha scalar to scale AB
* @param beta scalar to scale C
*/
void addAB(const DTensor<T> &A, const DTensor<T> &B, T alpha = 1, T beta = 0);
/**
* Reshapes the tensor
*
* If the new number of tensors is larger than the current one,
* this method will allocate a device array of type T* and length
* equal to the new number of matrices.
*
* No new memory is allocated if newNumMats = 1
*
* @param newNumRows new number of rows
* @param newNumCols new number of columns
* @param newNumMats new number of matrices
*
* @throws std::invalid_argument if the provided dimensions are incompatible
*/
void reshape(size_t newNumRows, size_t newNumCols, size_t newNumMats = 1);
/**
* Saves the current instance of DTensor to a (text) file
*
* If the file extension is .bt, the data will be stored in a binary file.
* Writing to and reading from a binary file is significantly faster and
* the generated binary files tend to have a smaller size (about 40% of the
* size of text files for data of type double and float).
*
* @param pathToFile path to file
*/
void saveToFile(std::string pathToFile);
/* ------------- OPERATORS ------------- */
DTensor &operator=(const DTensor &other);
T operator()(size_t i, size_t j = 0, size_t k = 0) const;
DTensor &operator*=(T scalar);
DTensor &operator+=(const DTensor &rhs);
DTensor &operator-=(const DTensor &rhs);
/* ------------- FRIENDS ------------- */
friend DTensor operator+(DTensor &first, const DTensor &second) {
DTensor result(first);
result += second;
return result;
}
friend DTensor operator-(DTensor &first, const DTensor &second) {
DTensor result(first);
result -= second;
return result;
}
friend DTensor<T> operator*(DTensor &A, DTensor &B) {
size_t nrA = A.m_numRows, ncB = B.m_numCols, nmB = B.m_numMats;
DTensor<T> result(nrA, ncB, nmB);
result.addAB(A, B);
return result;
}
friend DTensor<T> operator*(T a, DTensor &B) {
DTensor<T> result(B);
result *= a;
return result;
}
friend std::ostream &operator<<(std::ostream &out, const DTensor<T> &data) {
return data.print(out);
}
}; /* END OF DTENSOR */
template<typename T>
DTensor<T> DTensor<T>::setStreamIdx(size_t idx) {
if (idx >= s_numStreams) {
throw std::invalid_argument("Invalid stream index; it exceeds the max allocated streams");
}
m_idxStream = idx;
return *this;
}
template<typename T>
void DTensor<T>::initialisePointersToMatricesData() {
/* Make sure m_d_ptrMatrices has been allocated */
if (m_numMats <= 1 || !m_d_ptrMatrices || !m_doDestroyPtrMatrices) {
return;
}
/* Host-based vector of pointers */
std::vector<T *> h_pointers(m_numMats);
size_t numelMat = m_numRows * m_numCols;
h_pointers[0] = m_d_data;
for (size_t i = 1; i < m_numMats; i++) {
h_pointers[i] = m_d_data + i * numelMat;
}
/* Upload data to m_d_ptrMatrices */
size_t buffer_size = m_numMats * sizeof(T *);
gpuErrChk(cudaMemcpy(m_d_ptrMatrices, h_pointers.data(), buffer_size, cudaMemcpyHostToDevice));
}
template<typename T>
DTensor<T> DTensor<T>::createRandomTensor(size_t numRows, size_t numCols, size_t numMats, T low, T hi) {
if constexpr (std::is_floating_point<T>::value) {
auto randVec = generateRealRandomVector(numRows * numCols * numMats, low, hi);
DTensor<T> a(randVec, numRows, numCols, numMats);
return a;
} else if constexpr (std::is_same_v<T, int>) {
auto randVec = generateIntRandomVector(numRows * numCols * numMats, low, hi);
DTensor<T> a(randVec, numRows, numCols, numMats);
return a;
}
throw std::invalid_argument("[createRandomTensor] unsupported type T");
}
template<typename T>
struct data_t {
size_t numRows;
size_t numCols;
size_t numMats;
std::vector<T> data;
};
template<typename T>
data_t<T> vectorFromTextFile(std::string path_to_file) {
data_t<T> dataStruct;
std::ifstream file;
file.open(path_to_file, std::ios::in);
if (!file.is_open()) { throw std::invalid_argument("[vectorFromTextFile] the file does not exist"); }
std::string line;
getline(file, line);
dataStruct.numRows = atoi(line.c_str());
getline(file, line);
dataStruct.numCols = atoi(line.c_str());
getline(file, line);
dataStruct.numMats = atoi(line.c_str());
size_t numElements = dataStruct.numRows * dataStruct.numCols * dataStruct.numMats;
std::vector<T> vecDataFromFile(numElements);
size_t i = 0;
while (getline(file, line)) {
if constexpr (std::is_same_v<T, int>) {
vecDataFromFile[i] = atoi(line.c_str());
} else if constexpr (std::is_same_v<T, double>) {
vecDataFromFile[i] = std::stod(line.c_str());
} else if constexpr (std::is_same_v<T, float>) {
vecDataFromFile[i] = std::stof(line.c_str());
} else if constexpr (std::is_same_v<T, long double>) {
vecDataFromFile[i] = std::stold(line.c_str());
} else if constexpr (std::is_same_v<T, long>) {
vecDataFromFile[i] = std::stol(line.c_str());
} else if constexpr (std::is_same_v<T, long long>) {
vecDataFromFile[i] = std::stoll(line.c_str());
} else if constexpr (std::is_same_v<T, unsigned long>) {
vecDataFromFile[i] = std::stoul(line.c_str());
} else if constexpr (std::is_same_v<T, unsigned long long>) {
vecDataFromFile[i] = std::stoull(line.c_str());
} else if constexpr (std::is_same_v<T, size_t>) {
sscanf(line.c_str(), "%zu", &vecDataFromFile[i]);
} else {
throw std::invalid_argument("data type not supported");
}
if (++i == numElements) break;
}
dataStruct.data = vecDataFromFile;
file.close();
return dataStruct;
}
template<typename T>
data_t<T> vectorFromBinaryFile(std::string path_to_file) {
data_t<T> dataStruct;
/* Read from binary file */
std::ifstream inFile;
inFile.open(path_to_file, std::ios::binary);
if (!inFile.is_open()) { throw std::invalid_argument("[vectorFromBinaryFile] the file does not exist"); }
inFile.read(reinterpret_cast<char *>(&(dataStruct.numRows)), sizeof(uint64_t));
inFile.read(reinterpret_cast<char *>(&(dataStruct.numCols)), sizeof(uint64_t));
inFile.read(reinterpret_cast<char *>(&(dataStruct.numMats)), sizeof(uint64_t));
uint64_t numElements = dataStruct.numRows * dataStruct.numCols * dataStruct.numMats;
std::vector<T> vecDataFromFile(numElements);
for (size_t i = 0; i < numElements; i++) {
T el;
inFile.read(reinterpret_cast<char *>(&el), sizeof(T));
vecDataFromFile[i] = el;
}
inFile.close();
dataStruct.data = vecDataFromFile;
return dataStruct;
}
template<typename T>
DTensor<T> DTensor<T>::parseFromFile(std::string path_to_file,
StorageMode mode) {
// Figure out file extension
size_t pathToFileLength = path_to_file.length();
std::string fileNameExtension = path_to_file.substr(pathToFileLength - 3);
typedef data_t<T> (*PARSER)(std::string);
PARSER parser = (fileNameExtension == ".bt") ? vectorFromBinaryFile<T> : vectorFromTextFile<T>;
auto parsedData = parser(path_to_file);
DTensor<T> tensorFromData(parsedData.data, parsedData.numRows, parsedData.numCols, parsedData.numMats, mode);
return tensorFromData;
}
template<typename T>
void DTensor<T>::saveToFile(std::string pathToFile) {
std::vector<T> myData(numEl());
download(myData);
// Figure out file extension
size_t pathToFileLength = pathToFile.length();
std::string fileNameExtension = pathToFile.substr(pathToFileLength - 3);
// If the extension is .bt...
if (fileNameExtension == ".bt") {
uint64_t nr = (uint64_t) numRows(),
nc = (uint64_t) numCols(),
nm = (uint64_t) numMats();
std::ofstream outFile;
outFile.open(pathToFile, std::ios::binary);
outFile.write(reinterpret_cast<const char *>(&nr), sizeof(uint64_t));
outFile.write(reinterpret_cast<const char *>(&nc), sizeof(uint64_t));
outFile.write(reinterpret_cast<const char *>(&nm), sizeof(uint64_t));
for (const T &el: myData) outFile.write(reinterpret_cast<const char *>(&el), sizeof(T));
outFile.close();
} else {
std::ofstream file(pathToFile);
file << numRows() << std::endl << numCols() << std::endl << numMats() << std::endl;
if constexpr (std::is_floating_point<T>::value) {
file << std::setprecision(std::numeric_limits<T>::max_digits10);
}
for (const T &el: myData) file << el << std::endl;
}
}
template<typename T>
void DTensor<T>::reshape(size_t newNumRows, size_t newNumCols, size_t newNumMats) {
if (m_numRows == newNumRows && m_numCols == newNumCols && m_numMats == newNumMats) return;
size_t newNumElements = newNumRows * newNumCols * newNumMats;
/* Check whether dimensions are compatible */
if (numEl() != newNumElements) {
char errMessage[256];
sprintf(errMessage,
"DTensor[%lu x %lu x %lu] with %lu elements cannot be reshaped into DTensor[%lu x %lu x %lu] (%lu elements)",
numRows(), numCols(), numMats(), numEl(), newNumRows, newNumCols, newNumMats, newNumElements);
throw std::invalid_argument(errMessage);
}
/* Only free/reallocate if newNumMats > m_numMats
* otherwise, reuse the already allocated memory space */
if (newNumMats > m_numMats) {
/* Free the memory for m_d_ptrMatrices */
if (m_d_ptrMatrices && m_doDestroyPtrMatrices) {
gpuErrChk(cudaFree(m_d_ptrMatrices));
m_d_ptrMatrices = nullptr;
m_doDestroyPtrMatrices = false;
}
/* Reallocate memory for m_d_ptrMatrices, if necessary */
if (newNumMats > 1) {
gpuErrChk(Session::getInstance().cudaAllocate((void**)&m_d_ptrMatrices, newNumMats * sizeof(T *)));
m_doDestroyPtrMatrices = true;
}
}
m_numRows = newNumRows;
m_numCols = newNumCols;
m_numMats = newNumMats;
initialisePointersToMatricesData();
}
template<typename T>
DTensor<T>::DTensor(size_t m, size_t n, size_t k, bool zero) {
m_numRows = m;
m_numCols = n;
m_numMats = k;
size_t size = m * n * k;
allocateOnDevice(size, zero);
/* Initialise m_d_ptrMatrices */
initialisePointersToMatricesData();
}
template<typename T>
DTensor<T>::DTensor(const std::vector<T> &data, size_t m, size_t n, size_t k, StorageMode mode) {
m_numRows = m;
m_numCols = n;
m_numMats = k;
size_t size = m * n * k;
allocateOnDevice(size);
upload(data, mode);
/* Initialise m_d_ptrMatrices */
initialisePointersToMatricesData();
}
template<typename T>
DTensor<T>::DTensor(const DTensor<T> &other) {
m_numMats = other.m_numMats;
m_numRows = other.m_numRows;
m_numCols = other.m_numCols;
m_idxStream = other.m_idxStream;
allocateOnDevice(m_numRows * m_numCols * m_numMats);
gpuErrChk(cudaMemcpy(m_d_data, other.raw(), m_numRows * m_numCols * m_numMats * sizeof(T),
cudaMemcpyDeviceToDevice));
/* Initialise m_d_ptrMatrices */
initialisePointersToMatricesData();
}
template<typename T>
DTensor<T>::DTensor(const DTensor<T> &other, size_t axis, size_t from, size_t to) {
if (from > to) throw std::invalid_argument("from > to");
size_t offset = 0, len = to - from + 1;
m_d_ptrMatrices = nullptr;
if (axis == 2) {
offset = other.m_numRows * other.m_numCols * from;
m_numRows = other.m_numRows;
m_numCols = other.m_numCols;
m_numMats = len;
m_d_ptrMatrices = other.m_d_ptrMatrices + from;
} else if (axis == 1) {
offset = other.m_numRows * from;
m_numRows = other.m_numRows;
m_numCols = len;
m_numMats = 1;
} else if (axis == 0) {
offset = from;
m_numRows = to - from + 1;
m_numCols = 1;
m_numMats = 1;
}
m_d_data = other.m_d_data + offset;
m_doDestroyData = false;
m_doDestroyPtrMatrices = false;
m_idxStream = other.m_idxStream;
}
template<typename T>
DTensor<T>::DTensor(DTensor<T> &&other) {
/* Steal everything from other */
m_numCols = other.m_numCols;
m_numRows = other.m_numRows;
m_numMats = other.m_numMats;
m_d_data = other.m_d_data;
m_doDestroyData = other.m_doDestroyData;
m_doDestroyPtrMatrices = other.m_doDestroyPtrMatrices;
m_d_ptrMatrices = other.m_d_ptrMatrices;
m_idxStream = other.m_idxStream;
/* Invalidate other */
other.m_doDestroyPtrMatrices = false;
other.m_doDestroyData = false;
other.m_d_ptrMatrices = nullptr;
other.m_d_data = nullptr;
other.m_numCols = 0;
other.m_numRows = 0;
other.m_numMats = 0;
}
template<typename T>
inline size_t DTensor<T>::numRows() const {
return m_numRows;
}
template<typename T>
inline size_t DTensor<T>::numCols() const {
return m_numCols;
}
template<typename T>
inline size_t DTensor<T>::numMats() const {
return m_numMats;
}
template<typename T>
inline size_t DTensor<T>::numEl() const {
return m_numRows * m_numCols * m_numMats;
}
template<>
inline double DTensor<double>::dotF(const DTensor<double> &other) {
if (m_numRows != other.m_numRows || m_numCols != other.m_numCols || m_numMats != other.m_numMats)
throw std::invalid_argument("[dotF] incompatible dimensions");
size_t n = numEl();
double result;
gpuErrChk(cublasDdot(Session::getInstance().cuBlasHandle(m_idxStream), n,
raw(), 1,
other.raw(), 1,
&result));
return result;
}
template<>
inline float DTensor<float>::dotF(const DTensor<float> &other) {
if (m_numRows != other.m_numRows || m_numCols != other.m_numCols || m_numMats != other.m_numMats)
throw std::invalid_argument("[dotF] incompatible dimensions");
size_t n = numEl();
float result;
gpuErrChk(cublasSdot(Session::getInstance().cuBlasHandle(m_idxStream), n,
raw(), 1,
other.raw(), 1,
&result));
return result;
}