-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvd_cuda_2.cu
More file actions
1448 lines (1135 loc) · 50.9 KB
/
svd_cuda_2.cu
File metadata and controls
1448 lines (1135 loc) · 50.9 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
/**
* **********************************************
* Singular Value Decomposition: Matrix Class (CUDA)
* **********************************************
* CSC 586B - Spring 2020 - Project: Interim Report #3
* Author: Spencer Rose
* GPGPU-enabled (CUDA) SVD solver
*
* Data Structures:
* - Matrix(): GPU Matrix
* - Slice{}: stores matrix indices for a slice
* **********************************************
**/
#include <iostream>
#include <iomanip>
#include <cassert>
#include <typeinfo>
#include "timing.h"
#include "matrix_gpu.h" // matrix class with operators
#include "svd_cpu.h" // CPU equivalent functions
#include "timing.h"
#define cuda_error_check(ans) { gpu_assert((ans), __FILE__, __LINE__); }
// GPU error checking
inline void gpu_assert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPU Error: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
namespace csc586 { // anonymous
namespace gpu {
// Data type for indexing matrix slices
struct MatrixCUDA {
size_t nrows; // matrix rows
size_t ncols; // matrix columns
float *elements; // data buffer
// word size of matrix
size_t size() {
return nrows * ncols;
}
// byte size of matrix
int alloc() {
return sizeof(float) * nrows * ncols;
}
// Set dimensions of 2D matrix
void set_dim(size_t const rows, size_t const cols) {
nrows = rows;
ncols = cols;
}
// Print CUDA matrix data to std::out
void print() {
auto A_cpu = Matrix<float>(1, size());
cudaMemcpy(&A_cpu[0][0], elements, alloc(), cudaMemcpyDeviceToHost);
A_cpu = A_cpu.reshape(nrows, ncols);
A_cpu.print();
}
};
// Data type for CUDA-enabled Householder reflector
// as projection vector w and scalar tau
struct ReflectionCUDA {
MatrixCUDA w; // Householder vector
MatrixCUDA w_T; // Householder vector (transposed)
MatrixCUDA tau; // scalar normalizer
};
/*
* ===============================================
* Initialize CUDA Matrix
* -----------------------------------------------
* Creates new MatrixCUDA matrix
*
* Input:
* - <float> m: row dimension
* - <float> n: column
* - <float>* buffer: CUDA buffer allocation
* Output:
* - MatrixCUDA A: CUDA matrix struct
* ===============================================
*/
MatrixCUDA create_matrix(size_t const m, size_t const n, float *&buffer_ptr, bool zero_set = false ) {
MatrixCUDA A = {m, n, buffer_ptr};
// Set allocation to zero if requested
if (zero_set)
cudaMemset(buffer_ptr, 0, A.alloc());
buffer_ptr += A.size();
return A;
}
// Message handler
void message( std::string message ) {
std::cout << "\n\n================\n" << message << "\n================\n\n" << std::endl;
}
/*
* ===============================================
* Constants
* ===============================================
*/
// Max number of threads per thread block = 2048.
size_t const tile_size = 32u;
// GPU block dimension (x, y, z)
dim3 const dimBlock( tile_size, tile_size, 1u );
// Grid size
dim3 dimGrid( 1, 1 );
// GPU cut-off
size_t min_width = 64u;
/*
* ===============================================
* Initialize Grid for invocation
* -----------------------------------------------
* Defines grid dimensions
*
* Input:
* - <float> m: y dimension
* - <float> n: x dimension
* ===============================================
*/
void init_grid( size_t const m, size_t const n ) {
// define number of blocks per grid
dimGrid.x = static_cast<int> (ceil(float(n + dimBlock.x - 1) / float(dimBlock.x)));
dimGrid.y = static_cast<int> (ceil(float(m + dimBlock.y - 1) / float(dimBlock.y)));
}
/*
* ===============================================
* Matrix Copy - CUDA Kernel
* -----------------------------------------------
* Copy matrix data slice: tgt <- src
*
* Input:
* - MatrixCUDA src (source m x n 1D-array)
* - MatrixCUDA tgt (target m x n 1D-array)
* - <Slice> range: Range dimensions
* Output:
* - tgt is overwritten with src
* ===============================================
*/
__global__
void static copy_kernel(MatrixCUDA src, MatrixCUDA tgt, Slice const src_range, Slice const tgt_range )
{
// read the matrix tile into shared memory
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
if((global_x < (tgt_range.j2 - tgt_range.j1)) && (global_y < (tgt_range.i2 - tgt_range.i1)))
{
auto const idx_src = (global_y + src_range.i1) * src.ncols + (global_x + src_range.j1);
auto const idx_tgt = (global_y + tgt_range.i1) * tgt.ncols + (global_x + tgt_range.j1);
tgt.elements[idx_tgt] = src.elements[idx_src];
}
}
/*
* ===============================================
* Matrix Copy - Set single value
* -----------------------------------------------
* Set value of single matrix data element
*
* Input:
* - MatrixCUDA arr (source m x n 1D-array)
* - <float> idx index of array element
* - <float>/<float>* value: new element value
* Output:
* - updates array in-place
* ===============================================
*/
__global__
void set_val_kernel(float *arr, size_t const idx, float const value ) {
arr[idx] = value;
}
__global__
void set_val_ptr_kernel(float *arr, size_t const idx, float* value) {
arr[idx] = value[0];
}
/*
* ===============================================
* Householder - Householder parameters
* -----------------------------------------------
* Change value of single matrix data element
* REFERENCE: NVIDIA Programming Guide (2017)
*
* Input:
* - <float>* w: householder vector
* - <float>* w_T: householder vector (transposed)
* - <float>* norm: inner product of householder vector
* - <float>* tau: scaling factor
* Output:
* - updates values in-place
* ===============================================
*/
__global__
void hh_kernel( float*w, float*w_T, size_t const m, size_t const n, float* tau, float* norm ) {
// Compute Euclidean normalization of w
// Get square root of dot product
auto norm_x = sqrt(norm[0]);
// Get sign of initial value
auto w1 = w[0];
auto sgn = -copysignf(1, w1);
// Compute u1
auto u1 = w1 - sgn * norm_x;
// Compute tau
tau[0] = -sgn * u1 / norm_x;
// invert u1
auto alpha = 1. / u1;
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
auto const idx = global_y * n + global_x;
if((global_x < n) && (global_y < m)) {
w[idx] *= alpha; // Scale householder
w_T[idx] *= alpha; // Scale householder
}
// Set first value to one
if ( idx == 0 ) {
w[0] = 1.;
w_T[0] = 1.;
}
}
/*
* ===============================================
* Matrix Multiplication - CUDA Kernel (global)
* -----------------------------------------------
* Evaluated matrix product:
* - C <- gamma*(alpha*A + AB)
* - C <- gamma*(beta*B + AB)
* CUDA device kernel (a.k.a., function). It runs on the GPU.
* The `__global__` keyword identifies it as a device kernel.
* Each thread will execute this function independently.
* Because it is a device kernel, the pointers passed as arguments
* must be allocated *on the device.* The input size, n, however,
* is passed by value, not by pointer, so a separate copy is
* created and it can reflect a host variable.
*
* Input:
* - <float>* A (m x p 1D-array)
* - <float>* B (p x n 1D-array)
* - <float>* result (m x n 1D-array)
* - Matrix dimensions: m, n, p
* - <float> alpha (constant in operation A <- alpha*A + AB
* - <float> beta (constant in operation B <- beta*B + AB
* - <float> gamma (constant in operation result <- gamma*(result)
* - <float>* zeta (pointer to constant in operation result <- gamma*(result)
* Output:
* - Result array (result) is overwritten with alpha*A + AB OR alpha*B + AB.
* ===============================================
*/
__global__
void static mm_kernel(float const *A, float const *B, float *result, size_t const m, size_t const n, size_t const p,
float const alpha, float const beta, float const gamma) {
// Shared memory to hold tiles
// tile_size is length (and width) of a thread submatrix
__shared__ float A_tile[tile_size][tile_size];
__shared__ float B_tile[tile_size][tile_size];
// tile row / column
auto const local_x = threadIdx.x;
auto const local_y = threadIdx.y;
// matrix row / column
auto const global_x = blockIdx.x * tile_size + local_x;
auto const global_y = blockIdx.y * tile_size + local_y;
// Initialise the accumulation register
float acc = 0.0f;
size_t const n_tiles = (tile_size + p - 1) / tile_size;
// Iterate over tiles
for ( auto t = 0u; t < n_tiles; t++ ) {
const int t_x = tile_size * t + local_x;
const int t_y = tile_size * t + local_y;
// Load data into shared memory tile
A_tile[local_y][local_x] = (t_x < p && global_y < m) ? A[global_y * p + t_x] : 0.0;
B_tile[local_y][local_x] = (t_y < p && global_x < n) ? B[t_y * n + global_x] : 0.0;
__syncthreads();
for (int k = 0; k < tile_size; ++k)
acc += A_tile[local_y][k] * B_tile[k][local_x];
__syncthreads();
}
// Copy element to result matrix
if( global_y < m && global_x < n ) {
// Compute index
auto idx = (blockIdx.y * blockDim.y + threadIdx.y) * n + (blockIdx.x * blockDim.x + threadIdx.x);
// A <- gamma*(A + alpha*Result)
if (alpha) {
result[idx] = gamma * (acc + alpha * A[idx] );
}
// A <- gamma*(B + beta*Result)
else if (beta) {
result[idx] = gamma * (acc + beta * B[idx]);
}
// A <- gamma*(Result)
else {
result[idx] = gamma * acc;
}
}
__syncthreads();
}
/*
* ===============================================
* Matrix Transpose - CUDA Kernel
* -----------------------------------------------
* Evaluated matrix product: A <- gamma(alpha*A + AB)
* Uses shared memory tiles to coalesce global reads
* and writes.
*
* Input:
* - <float>* A (m x n 1D-array)
* - <float>* A_T (n x m 1D-array)
* - Matrix dimensions: m, n
* Output:
* - A_T is overwritten with A' (transpose)
* ===============================================
*/
__global__
void static trans_kernel(float *A_T, float const *A, size_t const m, size_t const n )
{
__shared__ float block[tile_size][tile_size + 1];
// read the matrix tile into shared memory
// load one element per thread from device memory (idata) and store it
// in transposed order in block[][]
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
if((global_x < n) && (global_y < m))
{
auto const idx_in = global_y * n + global_x;
block[threadIdx.y][threadIdx.x] = A[idx_in];
}
// synchronise to ensure all writes to block[][] have completed
__syncthreads();
// write the transposed matrix tile to global memory (odata) in linear order
global_x = blockIdx.y * tile_size + threadIdx.x;
global_y = blockIdx.x * tile_size + threadIdx.y;
if((global_x < m) && (global_y < n))
{
auto const idx_out = global_y * m + global_x;
A_T[idx_out] = block[threadIdx.x][threadIdx.y];
}
__syncthreads();
}
/*
* ===============================================
* Matrix Addition/Substraction - CUDA Kernel
* -----------------------------------------------
* Evaluated matrix difference: result <- A - alpha * B
*
* Input:
* - <float>* A (m x n 1D-array)
* - <float>* B (m x n 1D-array)
* - <float>* result (m x n 1D-array)
* - Matrix dimensions: m, n
* - <float> alpha (scaling factor)
* Output:
* - results is overwritten with A - alpha * B
* ===============================================
*/
__global__
void static add_kernel(float const *A, float const *B, float *result,
size_t const m, size_t const n, float const alpha )
{
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
auto const idx = global_y * n + global_x;
if((global_x < n) && (global_y < m))
result[idx] = A[idx] + alpha * B[idx];
}
/*
* ===============================================
* Matrix Scale - CUDA Kernel
* -----------------------------------------------
* Evaluated matrix difference: result <- A - alpha * B
*
* Input:
* - <float>* A (m x n 1D-array)
* - Matrix dimensions: m, n
* - <float> alpha (scaling factor)
* Output:
* - results is overwritten with A <- alpha * A
* ===============================================
*/
__global__
void static scale_kernel(float *A, size_t const m, size_t const n, float const alpha )
{
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
auto const idx = global_y * n + global_x;
if((global_x < n) && (global_y < m))
A[idx] *= alpha;
}
__global__
void static scale_ptr_kernel(float *A, size_t const m, size_t const n, float* alpha )
{
auto global_x = blockIdx.x * tile_size + threadIdx.x;
auto global_y = blockIdx.y * tile_size + threadIdx.y;
auto const idx = global_y * n + global_x;
if((global_x < n) && (global_y < m))
A[idx] *= alpha[0];
}
/*
* ===============================================
* Matrix Copy (and variants) - Host Wrapper
* -----------------------------------------------
* Copy matrix data slice: tgt <- src
*
* Input:
* - MatrixCUDA src (source m x n 1D-array)
* - MatrixCUDA tgt (target m x n 1D-array)
* - <Slice> range: Range dimensions
* Output:
* - tgt is overwritten with src
* ===============================================
*/
// [OVERLOADED] Copy Device matrix to Device matrix [source -> target]
void copy( MatrixCUDA &src, MatrixCUDA &tgt, Slice const src_range, Slice const tgt_range ) {
assert( (src_range.i2 - src_range.i1) == (tgt_range.i2 - tgt_range.i1) && "Slice rows are out of range.");
assert( (src_range.j2 - src_range.j1) == (tgt_range.j2 - tgt_range.j1) && "Slice columns are out of range.");
init_grid( src_range.i2 - src_range.i1, src_range.j2 - src_range.j1 );
copy_kernel <<< dimGrid, dimBlock >>> ( src, tgt, src_range, tgt_range );
}
// [OVERLOADED] Copy Device matrix to Device matrix [full copy -> target]
void copy( MatrixCUDA &src, MatrixCUDA &tgt, Slice const tgt_range ) {
assert( src.nrows == (tgt_range.i2 - tgt_range.i1) && "Slice rows are out of range.");
assert( src.ncols == (tgt_range.j2 - tgt_range.j1) && "Slice columns are out of range.");
init_grid( tgt_range.i2 - tgt_range.i1, tgt_range.j2 - tgt_range.j1 );
copy_kernel <<< dimGrid, dimBlock >>> ( src, tgt, {0, src.nrows, 0, src.ncols}, tgt_range );
}
// [OVERLOADED] Copy Device matrix to Device matrix [full copy -> full copy]
void copy( MatrixCUDA &src, MatrixCUDA &tgt ) {
assert(src.nrows == tgt.nrows && src.ncols == tgt.ncols && "Source and target copy is out of range.");
cudaMemcpy(tgt.elements, src.elements, src.alloc(), cudaMemcpyDeviceToDevice);
}
// Returns slice copied from Device matrix to Device matrix
MatrixCUDA slice( MatrixCUDA &src, Slice const range, float*& buffer) {
assert(src.nrows >= (range.i2 - range.i1) && src.ncols >= (range.j2 - range.j1) && "Slice is out of range.");
MatrixCUDA tgt = create_matrix( range.i2 - range.i1, range.j2 - range.j1, buffer );
copy(src, tgt, range, {0, tgt.nrows, 0, tgt.ncols});
// return slice
return tgt;
}
// Reduces size of Device matrix
void reduce( MatrixCUDA &src, Slice const range, float*& buffer ) {
assert(src.nrows >= (range.i2 - range.i1) && src.ncols >= (range.j2 - range.j1) && "Slice is out of range.");
MatrixCUDA tgt = create_matrix( range.i2 - range.i1, range.j2 - range.j1, buffer );
copy(src, tgt, range, {0, tgt.nrows, 0, tgt.ncols});
// Reset dimensions of source matrix
src.set_dim( range.i2 - range.i1, range.j2 - range.j1 );
// Copy src <- tgt
copy(tgt, src);
// Reset buffer
buffer -= tgt.size();
}
// [OVERLOADED] Copy Host matrix to Device matrix
void copy( Matrix<float>& A_cpu, MatrixCUDA& A_gpu ) {
assert(A_cpu.nrows == A_gpu.nrows && A_cpu.ncols == A_gpu.ncols && "CPU matrix dimensions must match GPU dimensions.");
// load matrices
auto A_1d = A_cpu.flatten();
cudaMemcpy(A_gpu.elements, &A_1d[0][0], sizeof(float) * A_cpu.size(), cudaMemcpyHostToDevice);
A_cpu = A_1d.reshape(A_cpu.nrows, A_cpu.ncols);
}
// [OVERLOADED] Copy Device matrix to Host matrix
void copy( MatrixCUDA& A_gpu, Matrix<float>& A_cpu ) {
assert(A_cpu.nrows == A_gpu.nrows && A_cpu.ncols == A_gpu.ncols && "CPU matrix dimensions must match GPU dimensions.");
// load matrices
auto A_1d = A_cpu.flatten();
cudaMemcpy(&A_1d[0][0], A_gpu.elements, sizeof(float) * A_gpu.size(), cudaMemcpyDeviceToHost);
A_cpu = A_1d.reshape(A_cpu.nrows, A_cpu.ncols);
}
/*
* ===============================================
* Matrix Multiplication - Host Wrapper
* -----------------------------------------------
* Evaluated matrix product: C <- AB
* CPU host function that contains built-in CUDA
* functions to initialize the GPU kernel.
*
* Input:
* - MatrixCUDA A (m x p matrix)
* - MatrixCUDA B (p x n matrix)
* - MatrixCUDA C (m x n matrix)
* - <float> alpha (constant in operation: C <- alpha*A + AB
* - <float> beta (constant in operation: C <- beta*B + AB
* - <float> gamma (constant in operation: C <- zeta(AB)
* - <float> zeta (pointer to constant in operation: C <- zeta(AB)
* Output:
* - Returns matrix C <- alpha*A + AB OR beta*B + AB.
* ===============================================
*/
MatrixCUDA matmul( MatrixCUDA A, MatrixCUDA B, float*& buffer, float const alpha = 0.0,
float const beta = 0.0, float const gamma = 1.0 ) {
assert(A.ncols == B.nrows && "Matrix 1 col dim must match Matrix 2 row dim.");
assert( !(alpha > 0 && beta > 0) && "Matrix self-addition must be for matrix A or B, not both.");
// Parameters
auto m = A.nrows;
auto n = B.ncols;
auto p = A.ncols;
// Initialize Grid
init_grid( m, n );
// Define resultant matrix parameters
// Initialize transposed matrix
MatrixCUDA C = create_matrix( m, n, buffer );
// Matrix Multiplication kernel
mm_kernel <<< dimGrid, dimBlock >>> (A.elements, B.elements, C.elements, m, n, p, alpha, beta, gamma );
// return product
return C;
}
/*
* ===============================================
* Matrix Transpose - Host Wrapper
* -----------------------------------------------
* Evaluated matrix transpose: A' <- transpose(A)
* CPU host function that contains built-in CUDA
* functions to initialize the GPU kernel.
*
* Input:
* - MatrixCUDA A (m x n matrix)
* Output:
* - MatrixCUDA A' (n x m matrix)
* ===============================================
*/
MatrixCUDA transpose( MatrixCUDA &A, float*& buffer ) {
// Parameters
auto m = A.nrows;
auto n = A.ncols;
// Initialize transposed matrix
MatrixCUDA A_T = create_matrix( n, m, buffer );
// Initialize Grid
init_grid( m, n );
// Matrix transpose kernel
trans_kernel <<< dimGrid, dimBlock >>> ( A_T.elements, A.elements, m, n );
// return transposed matrix
return A_T;
}
/*
* ===============================================
* Matrix Addition/Substraction - Host Wrapper
* -----------------------------------------------
* Evaluated matrix addition: C <- A + alpha * B
* CPU host function that contains built-in CUDA
* functions to initialize the GPU kernel.
*
* Input:
* - MatrixCUDA A (m x n matrix)
* - MatrixCUDA B (m x n matrix)
* Output:
* - MatrixCUDA C (m x n matrix) = A + alpha * B
* ===============================================
*/
MatrixCUDA add( MatrixCUDA &A, MatrixCUDA &B, float*& buffer, float const alpha = 1.0 ) {
assert(A.nrows == B.nrows && A.ncols == B.ncols && "Matrix dimensions must match for addition.");
// Parameters
auto m = A.nrows;
auto n = A.ncols;
// Initialize resultant matrix
MatrixCUDA C = create_matrix( m, n, buffer );
// Initialize Grid
init_grid( m, n );
// Matrix Addition/Subtraction kernel
add_kernel <<< dimGrid, dimBlock >>> (A.elements, B.elements, C.elements, m, n, alpha );
// return sum
return C;
}
/*
* ===============================================
* Matrix Scale - Host Wrapper
* -----------------------------------------------
* Evaluated matrix addition: C <- A + alpha * B
* CPU host function that contains built-in CUDA
* functions to initialize the GPU kernel.
*
* Input:
* - MatrixCUDA A (m x n matrix)
* - MatrixCUDA B (m x n matrix)
* Output:
* - MatrixCUDA C (m x n matrix) = A + alpha * B
* ===============================================
*/
void scale( MatrixCUDA &A, float const alpha = 1.0 ) {
// Parameters
auto m = A.nrows;
auto n = A.ncols;
// Initialize Grid
init_grid( m, n );
// Matrix Addition/Subtraction kernel
scale_kernel <<< dimGrid, dimBlock >>> (A.elements, m, n, alpha );
}
void scale( MatrixCUDA &A, MatrixCUDA alpha ) {
assert(alpha.nrows == 1 && alpha.ncols == 1 && "Scaling matrix must be 1 x 1.");
// Parameters
auto m = A.nrows;
auto n = A.ncols;
// Initialize Grid
init_grid( m, n );
// Matrix Addition/Subtraction kernel
scale_ptr_kernel <<< dimGrid, dimBlock >>> (A.elements, m, n, alpha.elements );
}
/*
* ===============================================
* Matrix Set Element - Host Wrapper
* -----------------------------------------------
* Sets value of matrix element A[i][j]
* CPU host function that contains built-in CUDA
* functions to initialize the GPU kernel.
*
* Input:
* - MatrixCUDA A (m x n matrix)
* - <size_t> i : row index
* - <size_t> j : column index
* - <float> value : value to set
* Output:
* - A[i][j] is overwritten with value.
* ===============================================
*/
void set_elem( MatrixCUDA A, size_t const i, size_t const j, float const value ) {
assert(i < A.nrows && j < A.ncols && "Index is out of range for matrix.");
auto idx = A.nrows * i + j;
// Set matrix value kernel
set_val_kernel << < 1, 1 >> > (A.elements, idx, value );
}
void set_elem( MatrixCUDA A, size_t const i, size_t const j, MatrixCUDA value ) {
assert(i < A.nrows && j < A.ncols && "Index is out of range for matrix.");
auto idx = A.nrows * i + j;
// Set value to matrix value
cudaMemcpy(A.elements + idx, value.elements, sizeof(float), cudaMemcpyDeviceToDevice);
}
void get_elem( MatrixCUDA A, size_t const i, size_t const j, MatrixCUDA value ) {
assert(i < A.nrows && j < A.ncols && "Index is out of range for matrix.");
auto idx = A.nrows * i + j;
// Set value to matrix value
cudaMemcpy(value.elements, A.elements + idx, sizeof(float), cudaMemcpyDeviceToDevice);
}
/*
* ===============================================
* Householder Reflection - Host Wrapper
* -----------------------------------------------
* Input: Column vector w
* Output: x (projection vector); tau (scaling factor)
* ===============================================
*/
ReflectionCUDA hholder_cuda( MatrixCUDA w, float*& buffer ) {
auto m = w.nrows;
auto n = w.ncols;
assert( w.ncols == 1 && "Householder applied to column vectors only." );
// Calculate matrices
auto tau = create_matrix( 1, 1, buffer, true );
auto w_T = transpose( w, buffer );
auto norm = matmul( w_T, w, buffer );
// Compute Householder reflector parameters
init_grid( m, n );
hh_kernel <<< dimGrid, dimBlock >>> ( w.elements, w_T.elements, m, n, tau.elements, norm.elements );
return ReflectionCUDA{ w, w_T, tau };
}
/*
* ===============================================
* Compact YT represent. of Householder reflectors
* Hk...H3.H2.H1 = I - VSV'
* -----------------------------------------------
* See Schreiber and Van Loan (1989)
*
* Input:
* - <float>* tau : Householder scalar factor
* - MatrixCUDA S: k x k Triangular matrix T
* - MatrixCUDA V: n x k Householder vectors Y
* Output:
*
* - S_k+1 = [ S_k −tau_k+1.S_k.V_k'.v_k+1 ]
* [ 0 -tau_k+1 ]
* ===============================================
*/
void wy_compact_cuda( const size_t j, MatrixCUDA tau, MatrixCUDA S, MatrixCUDA V, float*& buffer ) {
// base case
if ( j == 0u ) {
//S[0][0] = -tau;
scale(tau, -1.0f);
set_elem( S, 0, 0, tau );
}
else {
scale(tau, -1.0f);
auto S_k = slice( S, {0, j, 0, j}, buffer );
auto v = slice( V, {0, V.nrows, j, j+1}, buffer );
auto V_k = slice( V, {0, V.nrows, 0, j}, buffer );
auto V_k_T = transpose( V_k, buffer );
auto z = matmul( V_k_T, v, buffer);
z = matmul( S_k, z, buffer);
scale( z, tau );
// copy T_01 = z
copy( z, S, {0, z.nrows, S_k.ncols, S_k.ncols + z.ncols});
// copy T_11 = -tau
set_elem( S, S_k.nrows, S_k.ncols, tau );
}
}
/*
* ===============================================
* Panel QR Decomposition
* -----------------------------------------------
* Subroutine performs a panel QR factorization
* of a matrix A of size m x n. This operation produces
* an upper triangular matrix R, a unit lower triangular
* matrix V that contains b Householder reflectors
* and an upper triangular matrix Y as defined by the
* compact WY technique.
*
* Input:
* - MatrixCUDA A: m x n panel matrix
* - MatrixCUDA S: m x m upper triangular matrix
* - MatrixCUDA V: m x n lower triangular matrix
* - <float>* buffer: CUDA buffer allocation
* ===============================================
*/
void qr_cuda( MatrixCUDA& A, MatrixCUDA& S, MatrixCUDA& V, float*& buffer_ptr ) {
// Input matrix panel dimensions
auto m = A.nrows;
auto n = A.ncols;
// Initialize buffer
auto buffer = buffer_ptr;
// Initialize container matrices
auto R = create_matrix( m, n, buffer );
auto Y = create_matrix( n, n, buffer, true );
// Copy panel matrix data -> R
copy(A, R);
// Create reset point for buffer
auto reset_buffer = buffer;
// Reduction of rectangular matrix to upper triangular form
for (auto j = 0u; j < std::min(n, m); ++j) {
// compute Householder H_j from column A_j
auto A_j = slice( R, {j, m, j, j + 1}, buffer );
auto H_j = hholder_cuda( A_j, buffer );
// Compute Y(i+1:n,i): y_i = tau * R'v
auto A_trail = slice(R, {j, m, j, n}, buffer);
A_trail = transpose( A_trail, buffer );
auto y = matmul( A_trail, H_j.w, buffer );
scale( y, H_j.tau );
auto y_T = transpose( y, buffer );
// Update matrices V, Y
copy(H_j.w, V, {j, m, j, j + 1});
copy(y_T, Y, {j, j + 1, j, n});
// Store Housholder reflectors in WY compact form
wy_compact_cuda( size_t(j), H_j.tau, S, V, buffer );
// R <- A - VY
auto VY = matmul( V, Y, buffer );
R = add(A, VY, R.elements, -1. );
// Reset buffer
buffer = reset_buffer;
}
// update matrix with A <- A - VY
copy( R, A );
// Reset buffer
buffer = buffer_ptr;
}
/*
* ===============================================
* Panel LQ Decomposition
* -----------------------------------------------
* Subroutine performs the panel LQ factorization
* of a matrix A of size m x n. This operation produces
* a lower triangular matrix R, a unit upper triangular
* matrix U that contains b Householder reflectors
* and a lower triangular matrix X as defined by the
* compact WY technique.
*
* Input:
* - MatrixCUDA A: m x n panel matrix
* - MatrixCUDA S: m x m upper triangular matrix
* - MatrixCUDA V: m x n lower triangular matrix
* - <float>* buffer: CUDA buffer allocation
* ===============================================
*/
void lq_cuda( MatrixCUDA& A, MatrixCUDA& S, MatrixCUDA& U, float*& buffer_ptr ) {
// Input matrix panel dimensions
auto m = A.nrows;
auto n = A.ncols;
// Initialize buffer
auto buffer = buffer_ptr;
// Initialize container matrices
auto L = create_matrix( m, n, buffer );
auto X = create_matrix( m, m, buffer, true );
// Copy trailing matrix data -> L
copy( A, L );
// Create reset point for buffer
auto reset_buffer = buffer;
// Reduction of rectangular matrix to lower triangular form
for (auto i = 0u; i < std::min(n, m); ++i) {
// Reduce row i of A = A - XU'
// compute Householder H_i from column A_i
auto A_i = slice( L, {i, i + 1, i, n}, buffer );
auto A_i_T = transpose( A_i, buffer );
auto H_i = hholder_cuda( A_i_T, buffer );
// Compute X(i+1:n,i): x_i = tau * L'v
auto A_trail = slice( L, {i, m, i, n}, buffer);
auto x = matmul( A_trail, H_i.w, buffer );
scale( x, H_i.tau );
// Update matrices X, U
copy(x, X, {i, m, i, i + 1});
copy(H_i.w_T, U, {i, i + 1, i, n});
auto U_T = transpose( U, buffer );
// Store Housholder reflectors in WY compact form
wy_compact_cuda( size_t(i), H_i.tau, S, U_T, buffer );
// L <- A - XU'