-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtensorsvm-train.cu
2643 lines (2335 loc) · 77.1 KB
/
tensorsvm-train.cu
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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <mkl.h>
#include <time.h>
#include <algorithm> // std::min
#include <vector>
#include <chrono>
#include <utility> // std:swap
#ifdef CUDA
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <cusolverDn.h>
#include <thrust/transform_reduce.h>
#include <thrust/functional.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/inner_product.h>
#include <thrust/reduce.h>
#endif
//#define DEBUG 1
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
#ifdef DEBUG
# define DEBUG_PRINT(x) printf x
#else
# define DEBUG_PRINT(x) do {} while (0)
#endif
// convenient timer. just put these two states around a piece of code.
#define START_TIMER {\
struct timespec start, end; \
double diff; \
clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */ \
#define END_TIMER \
clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */\
diff = (end.tv_sec - start.tv_sec) + 1.0*(end.tv_nsec - start.tv_nsec)/BILLION;\
printf("elapsed time = %.4f seconds\n", diff);\
}
#define END_TIMER_PRINT_IF(exp) \
clock_gettime(CLOCK_MONOTONIC, &end); /* mark the end time */\
diff = (end.tv_sec - start.tv_sec) + 1.0*(end.tv_nsec - start.tv_nsec)/BILLION;\
if(exp) printf("elapsed time = %.4f seconds\n", diff);\
}
#define BILLION 1000000000L
#define MAX_MPC_ITER 100
/* Linear SVM training using interior point method;
Good when #features is less than 20k.
*/
int K = 50; // rank
double C = 1;
double g = 0;
int T = 0; // kernel type -- see help_msg
int CMDPARA_S = 0; // cmdline arg s -- see help_msg
char *trainfilepath = NULL;
char *modelfilepath = NULL;
char *testfilepath = NULL;
int POS, NEG; // mapping between datafile class and +1, -1 rquired by SVM.
// cublas state
cudaError_t cudaStat;
cublasStatus_t stat;
cusolverStatus_t statusH = CUSOLVER_STATUS_SUCCESS;
// libsvmread populates the next two main data structs.
float *LABELS = NULL;
float *INST = NULL;
long N = 0; // number of training instances
long NN = 0; // first #number of instances
long d = 0; // number of features
lapack_int *IPIV;
int flag_analysis = 0;
int flag_tensorcore = 0;
int flag_scale256 = 0;
void parsecmd(int, char *[]);
void help_msg();
void libsvmread(char *filepath, float **labels, float **inst, long *n, long *nf);
void setmat(double *mat, int n, double val);
void NewtonStep(double *Z, double *D, double *M, double C, double *a, double *X, double *S, double *Xi, double *r, double *work,
int d);
void SMWSolve(double *Z, double *D, double *M, double *b, double *work, int d);
void mpc(double *Z, double *a, double C, double *X, double *Xi, int n, int k);
void testKerMat(double *);
void rbf_kermatmul(float *Zd1, int ldz1, float *Zd2, int ldz2, float *Yd1, float *Yd2,
float *Ad, int lda, float *Bd, int ldb, int m, int n, int k,
cublasHandle_t handle);
float gaussrand();
template<typename FT>
__global__ void vecnorm(FT *Zd, int ldz, FT *ZI, int m, int k);
template<typename FT, typename FT2>
__global__ void rbf_kergen( int m, int n, FT *buf, int ldb, FT *XI, FT *XJ, FT *XIJ, int ldxij,
FT2 gamma, FT *YI, FT *YJ);
double LRA(float *Z, int ldz, double *U, int ldu, long n, long k);
void pgd(double *Z, double *Y, double C, double *X, long n, long d, double l1);
struct daxpy_functor
{
const double a;
daxpy_functor(double _a) : a{_a} {}
__host__ __device__
double operator()(const double& x, const double& y) const {
return a * x + y;
}
};
template<typename T, typename S>
void matcpy(int m, int n, const char *Amajor, T* A, int lda, const char *Bmajor, S* B, int ldb )
{
if (*Amajor == 'R' && *Bmajor == 'R') {
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
A[i*lda+j] = B[i*ldb+j];
} else if (*Amajor == 'R' && *Bmajor == 'C') {
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
A[i*lda+j] = B[i+j*ldb];
} else if (*Amajor == 'C' && *Bmajor == 'R') {
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
A[i+j*lda] = B[i*ldb+j];
} else if (*Amajor == 'C' && *Bmajor == 'C') {
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
A[i+j*lda] = B[i+j*ldb];
} else {
printf("unsupported major: Amajor=%c Bmajor=%c", *Amajor, *Bmajor);
}
}
// debuging devise
template<typename T>
void writematrix(char *filename, T *A, int m, int n, int lda)
{
FILE *f = fopen(filename, "w");
for( int i=0; i<m; i++ ) {
for( int j=0; j<n; j++ ) {
fprintf(f, "%.16e", A[i*lda+j] ); // row-major
if( j<n-1) fprintf(f, ",");
else fprintf(f, "\n");
}
}
}
void predict(double *X, double *testlabels, double *testinst, long testN, long testd)
{
int nSV = 0, nBSV = 0;
for( int i=0; i<N; i++ ){
if( X[i] > 1e-3 ) {
nSV++;
if( X[i] < C-1e-3 ) {
nBSV++;
}
}
}
int *iSV = (int*) malloc(sizeof(int)*nSV);
int *iBSV = (int*) malloc(sizeof(int)*nBSV);
int svi = 0, bsvi = 0;
for( int i=0; i<N; i++ ) {
if( X[i] > 1e-3 ) {
iSV[svi++] = i;
if( X[i] < C-1e-3 ) {
iBSV[bsvi++] = i;
}
}
}
// calculate w=sum alpha_i y_i x_i
double *w = (double*) calloc(d,sizeof(double));
for( int i=0; i<nSV; i++ ) {
int j = iSV[i]; // index
for( int k=0; k<testd; k++ ) {
w[k] += X[j]*LABELS[j]*INST[j*d+k];
//w[k] += X[j]*INST[j*d+k]; // INST unlabeled by main().
}
}
// calculate b
double b = 0;
if (T==0) { // linear SVM
if( nBSV > 0 ) {
for( int i=0; i<nBSV; i++ ) {
int j = iBSV[i];
b += LABELS[j];
for( int k=0; k<d; k++ ) {
b -= w[k]*INST[j*d+k];
}
}
b = b/nBSV;
} else {
printf("Empty boundary SV! Give up.\n");
b = 0;
}
printf("intercept b=%.3e\n", b);
long cntyes = 0;
for( int i=0; i<testN; i++ ) {
double f = cblas_ddot(testd, w, 1, &testinst[i*testd], 1) + b;
if( f * testlabels[i] > 0) cntyes++;
}
printf("prediction accuracy %.3f (%d/%d)\n", 1.0*cntyes/testN, cntyes, testN);
} else if (T==2) { //RBF kernel
double acc = 0;
std::vector<double> bs(std::min(nBSV,100), 0);
for (int j=0; j<std::min(nBSV,100); j++) {
int jj = iBSV[j];
double yj = LABELS[jj];
for (int i=0; i<nSV; i++) {
int ii = iSV[i];
double acc2 = 0;
for (int l=0; l<d; l++) {
double diff = INST[ii*d+l] - INST[jj*d+l];
acc2 += diff * diff;
}
yj -= X[ii]*LABELS[ii]*exp(-g*acc2);
}
acc += yj;
bs[j] = yj;
// printf("y[%d]=%.3e\n", jj, yj);
}
b = acc/std::min(nBSV,100);
double sumsq = 0;
for( int j=0; j<bs.size(); j++ )
sumsq += (bs[j]-b)*(bs[j]-b);
printf("mean b=%.6e std b=%.6e, #samples=%d\n ", b, sqrt(sumsq/bs.size()), bs.size());
long cntyes = 0;
for( int jj=0; jj<testN; jj++ ) {
// double f = cblas_ddot(testd, w, 1, &testinst[i*testd], 1) + b;
// int jj = iBSV[j];
double f = b;
for( int i=0; i<nSV; i++ ) {
int ii = iSV[i];
double acc2 = 0;
for (int l=0; l<d; l++) {
double diff = INST[ii*d+l] - testinst[jj*d+l];
acc2 += diff * diff;
}
acc += X[ii]*LABELS[ii]*exp(-g*acc2);
}
if( f * testlabels[jj] > 0) cntyes++;
}
printf("prediction accuracy %.3f (%d/%d)\n", 1.0*cntyes/testN, cntyes, testN);
}
}
// need U (Gram matrix approx U*U') for computing b
double writemodel(char *path, double *X, double C, double *U)
{
int nSV = 0, nBSV = 0;
for( int i=0; i<N; i++ ){
if( X[i] > 1e-6 ) {
nSV++;
if( X[i] < C-1e-6 ) {
nBSV++;
}
}
}
int *iSV = (int*) malloc(sizeof(int)*nSV);
int *iBSV = (int*) malloc(sizeof(int)*nBSV);
int svi = 0, bsvi = 0;
for( int i=0; i<N; i++ ) {
if( X[i] > 1e-6 ) {
iSV[svi++] = i;
if( X[i] < C-1e-6 ) {
iBSV[bsvi++] = i;
}
}
}
//writematrix("X.csv", X, N, 1, 1 );
printf("#BSV %d, #SV %d\n", nBSV, nSV);
// calculate w=sum alpha_i y_i x_i
double b = 0;
if (T==0) { // linear Kernel
double *w = (double*) calloc(d,sizeof(double));
for( int i=0; i<nSV; i++ ) {
int j = iSV[i]; // index
for( int k=0; k<d; k++ ) {
w[k] += X[j]*LABELS[j]*INST[j*d+k];
}
}
// calculate b
int nn = std::min(nBSV,5000);
std::vector<double> bs(nn, 0);
if( nBSV > 0 ) {
double sum = 0;
for( int i=0; i<nn; i++ ) {
int j = iBSV[i];
double tmp = LABELS[j];
for( int k=0; k<d; k++ ) {
tmp -= w[k]*INST[j*d+k];
}
bs[i] = tmp;
sum += tmp;
}
b = sum/nn;
double sumsq = 0;
for( int j=0; j<bs.size(); j++ )
sumsq += (bs[j]-b)*(bs[j]-b);
printf("approx mean b=%.6e std b=%.6e, #samples=%d\n ", b, sqrt(sumsq/bs.size()), bs.size());
} else {
printf("Empty boundary SV! Give up.\n");
b = 0;
}
{ // writing files in LIBSVM format
FILE *f = fopen(path, "w");
if (!f) {
fprintf(stderr,"Can't open %s\n",path);
exit(1);
}
fprintf(f,"solver_type L2R_L1LOSS_SVC_DUAL\n");
fprintf(f,"nr_class 2\n");
fprintf(f,"label %d %d\n", POS, NEG);
fprintf(f,"nr_feature %d\n", d);
fprintf(f,"bias %d\n", 1);
fprintf(f,"w\n");
for(int i=0; i<d; i++)
fprintf(f, "%.16f \n", w[i]);
fprintf(f,"%.16f\n",b);
fclose(f);
}
} else if (T==2) { // RBF Kernel
{
double acc = 0;
std::vector<double> bs(std::min(nBSV,50), 0);
for (long j=0; j<std::min(nBSV,50); j++) {
long jj = iBSV[j];
double yj = LABELS[jj];
for (long i=0; i<nSV; i++) {
long ii = iSV[i];
double sum = 0;
for (long k=0; k<K; k++) {
sum += U[ii*(long)K+k] * U[jj*(long)K+ k];
}
yj -= X[ii] * LABELS[jj] * sum;
}
acc += yj;
bs[j] = yj;
// printf("y[%d]=%.3e\n", jj, yj);
}
b = acc/std::min(nBSV,50);
double sumsq = 0;
for( int j=0; j<bs.size(); j++ )
sumsq += (bs[j]-b)*(bs[j]-b);
printf("approx mean b=%.6e std b=%.6e, #samples=%d\n ", b, sqrt(sumsq/bs.size()), bs.size());
}
{ // writing files in LIBSVM format
FILE *f = fopen(path, "w");
if (!f) {
fprintf(stderr,"Can't open %s\n",path);
exit(1);
}
fprintf(f,"svm_type c_svc\n");
if( T== 0 )
fprintf(f,"kernel_type linear\n");
else if( T == 2 ) {
fprintf(f,"kernel_type rbf\n");
fprintf(f,"gamma %.7f\n", g);
}
fprintf(f,"nr_class 2\n");
fprintf(f,"total_sv %d\n", nSV);
fprintf(f,"rho %f\n", -b);
fprintf(f,"label %d %d\n", POS, NEG);
fprintf(f,"nr_sv %d %d\n", nBSV, nSV-nBSV);
fprintf(f,"SV\n");
for( int i=0; i<nSV; i++ ) {
int j = iSV[i];
fprintf(f, "%7f ", LABELS[j]*X[j]);
for( int k=0; k<d; k++ ) {
if( INST[j*d+k]>0 || INST[j*d+k]<0) {
fprintf(f, "%d:%7f ", k+1, INST[j*d+k]);
}
}
fprintf(f, "\n");
}
fclose(f);
}
} else {
printf("unimplemeted -t %d", T);
exit(1);
}
free(iSV); free(iBSV);
return b;
}
void printmatrixd(char *filename, int m, int n, float* a, int lda)
{
FILE *f = fopen(filename, "w");
if (f == NULL) {
printf("fault!\n");
return;
}
for (int i = 0; i < m; i++) {
//printf("i = %d\n", i);
for (int j = 0; j < n; j++) {
fprintf(f, "%.6f", a[i + j*lda]);
if (j == n - 1) fprintf(f, "\n");
else fprintf(f, ",");
}
}
fclose(f);
}
void printmatrixdd(char *filename, int m, int n, float* a, int lda)
{
FILE *f = fopen(filename, "w");
if (f == NULL) {
printf("fault!\n");
return;
}
for (int i = 0; i < m; i++) {
//printf("i = %d\n", i);
for (int j = 0; j < n; j++) {
fprintf(f, "%.6f", a[i *lda + j]);
if (j == n - 1) fprintf(f, "\n");
else fprintf(f, ",");
}
}
fclose(f);
}
__global__
void getR(int m, int n, float *da, int lda, float *dr, int ldr)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int j = threadIdx.y + blockDim.y * blockIdx.y;
if (i < m&&j < n)
{
if (i <= j)
{
dr[i + j*ldr] = da[i + j*lda];
}
}
}
__global__
void myslacpyd(int m, int n, double *da, int lda, double *db, int ldb)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int j = threadIdx.y + blockDim.y * blockIdx.y;
if (i < m && j < n) {
db[i + j*ldb] = da[i + j*lda];
}
}
__global__
void clear_trid(char uplo, int m, int n, double *a, int lda)
{
int i = threadIdx.x + blockDim.x * blockIdx.x;
int j = threadIdx.y + blockDim.y * blockIdx.y;
if (i < m && j < n) {
if (uplo == 'l') {
if (i > j) {
a[i + j*lda] = 0;
}
}
else {
printf("clear_tri: option %c not implemented. \n", uplo);
assert(0);
}
}
}
void printmatrixDevice(char *filename, float *dA, int lda, int m, int n)
{
float ha[m*n];
cudaMemcpy(ha, dA, sizeof(float)*m*n, cudaMemcpyDeviceToHost);
printmatrixd(filename, m, n, ha, lda);
}
//transpose a Matrix
void transpose(float *dA, int lda, int m, int n, cublasHandle_t handle, cudaStream_t stream)
{
float *dC;
gpuErrchk(cudaMalloc(&dC, sizeof(float)*m*n));
float alpha = 1.0;
float beta = 0.0;
cublasSgeam(handle,
CUBLAS_OP_T, CUBLAS_OP_T,
m, n,
&alpha,
dA, lda,
&beta,
dA, lda,
dC, m);
cudaMemcpyAsync(dA, dC, m * n * sizeof(float), cudaMemcpyDeviceToDevice, stream);
cudaFree(dC);
}
void transpose(double *dA, int lda, int m, int n, cublasHandle_t handle, cudaStream_t stream)
{
double *dC;
gpuErrchk(cudaMalloc(&dC, sizeof(double)*m*n));
double alpha = 1.0;
double beta = 0.0;
cublasDgeam(handle,
CUBLAS_OP_T, CUBLAS_OP_T,
m, n,
&alpha,
dA, lda,
&beta,
dA, lda,
dC, m);
cudaMemcpyAsync(dA, dC, m * n * sizeof(double), cudaMemcpyDeviceToDevice, stream);
cudaFree(dC);
}
//dA is overwrite by Q, dR is overwrite by R
void QnR(float *dA, int lda, int m, int n, cusolverDnHandle_t cusolverH, cudaStream_t stream)
{
float *d_tau = NULL;
int *devInfo = NULL;
float *d_work = NULL;
int lwork_geqrf = 0;
int lwork_orgqr = 0;
int lwork = 0;
//int info_gpu = 0;
//const double h_one = 1;
//const double h_minus_one = -1;
cudaMalloc(&d_tau, sizeof(float)*n);
cudaMalloc((void**)&devInfo, sizeof(int));
cusolverDnSgeqrf_bufferSize(
cusolverH,
m,
n,
dA,
lda,
&lwork_geqrf);
cusolverDnSorgqr_bufferSize(
cusolverH,
m,
n,
n,
dA,
lda,
d_tau,
&lwork_orgqr);
lwork = (lwork_geqrf > lwork_orgqr) ? lwork_geqrf : lwork_orgqr;
cudaMalloc(&d_work, sizeof(int)*lwork);
cusolverDnSgeqrf(
cusolverH,
m,
n,
dA,
lda,
d_tau,
d_work,
lwork,
devInfo);
cusolverDnSorgqr(
cusolverH,
m,
n,
n,
dA,
lda,
d_tau,
d_work,
lwork,
devInfo);
return;
}
//dA is overwrite by Q, dR is overwrite by R
void QR(float *dA, int lda, int m, int n, float *dR, int ldr, cusolverDnHandle_t cusolverH, cudaStream_t stream, int flag)
{
/*
if(flag == 0)
printmatrixDevice("realA0.csv", dA, lda, m, n);*/
float *d_tau = NULL;
int *devInfo = NULL;
float *d_work = NULL;
int lwork_geqrf = 0;
int lwork_orgqr = 0;
int lwork = 0;
//int info_gpu = 0;
//const double h_one = 1;
//const double h_minus_one = -1;
cudaMalloc(&d_tau, sizeof(float)*n);
cudaMalloc((void**)&devInfo, sizeof(int));
cusolverDnSgeqrf_bufferSize(
cusolverH,
m,
n,
dA,
lda,
&lwork_geqrf);
cusolverDnSorgqr_bufferSize(
cusolverH,
m,
n,
n,
dA,
lda,
d_tau,
&lwork_orgqr);
lwork = (lwork_geqrf > lwork_orgqr) ? lwork_geqrf : lwork_orgqr;
cudaMalloc(&d_work, sizeof(int)*lwork);
cusolverDnSgeqrf(
cusolverH,
m,
n,
dA,
lda,
d_tau,
d_work,
lwork,
devInfo);
//copy R from A and clear tri
dim3 grid((n + 31) / 32, (n + 31) / 32);
dim3 block(32, 32);
/*
myslacpyd << <grid, block,0,stream >> > (n, n, dA, lda, dR, ldr);
clear_trid << <grid, block,0,stream >> > ('l', n, n, dR, ldr);*/
/*
if(flag == 0)
printmatrixDevice("realA.csv", dA, lda, m, n);*/
getR << <grid, block, 0, stream >> > (m, n, dA, lda, dR, ldr);
cudaStreamSynchronize(stream);
/*
printf("lda = %d ldr = %d\n", lda, ldr);
if(flag == 0)
printmatrixDevice("realR.csv", dR, ldr, ldr, n);*/
cusolverDnSorgqr(
cusolverH,
m,
n,
n,
dA,
lda,
d_tau,
d_work,
lwork,
devInfo);
cudaFree(d_tau);
cudaFree(d_work);
return;
}
void CAQR(float *Q, int m, int n, int lda, int em, int k)
{
struct timespec start, end;
float diff;
clock_gettime(CLOCK_MONOTONIC, &start);
int nb = m % em == 0 ? m / em : m / em + 1;//how many blocks
float *b0, *b1;
gpuErrchk(cudaMalloc(&b0, sizeof(float)*em*k));
gpuErrchk(cudaMalloc(&b1, sizeof(float)*em*k));
cusolverDnHandle_t csHandle;
cusolverDnCreate(&csHandle);
cublasHandle_t cbHandle;
cublasCreate(&cbHandle);
cudaStream_t stream;
cudaStreamCreate(&stream);
//cudaHostAlloc(&Q, m * n * sizeof(double), cudaHostAllocDefault);//fix the memory of Q on CPU
//printmatrixd("Q00.csv", m, n, Q, lda);
float *rr;//store the stack of R on GPU
gpuErrchk(cudaMalloc(&rr, sizeof(float)*nb*k*k));
//set stream to handle
cublasSetStream(cbHandle, stream);
cusolverDnSetStream(csHandle, stream);
int nr = 0;//nr-th R
for (long i = 0; i < (long)m*(long)n; i += em*k)
{
printf("%d-th block\n", i);
//need to be transpose
cudaMemcpyAsync(b0, Q + i, em * k * sizeof(float), cudaMemcpyHostToDevice, stream);
//printmatrixd("Q0.csv", m, n, Q, lda);
//if (i == 0)
// printmatrixDevice("b00.csv", b0, em, em, k);
//else
// printmatrixDevice("b11.csv", b0, em, em, k);
transpose(b0, k, em, k, cbHandle, stream);
//cudaStreamSynchronize(stream);
cudaStreamSynchronize(stream);
//if(i==0)
// printmatrixDevice("b0.csv", b0, em, em, k);
//else
// printmatrixDevice("b1.csv", b0, em, em, k);
cudaMemcpyAsync(b1, b0, em * k * sizeof(float), cudaMemcpyDeviceToDevice, stream);
QR(b1, em, em, k, rr + nr, k, csHandle, stream, i);
cudaStreamSynchronize(stream);
/*
if (i == 0)
{
printmatrixDevice("q11.csv", b1, em, em, k);
printmatrixDevice("r11.csv", rr+nr, k, k, k);
}
else
{
printmatrixDevice("q12.csv", b1, em, em, k);
printmatrixDevice("r12.csv", rr+nr, k, k, k);
}*/
transpose(rr + nr, k, k, k, cbHandle, stream);
nr += k*k;
cudaMemcpyAsync(Q + i, b1, em*k * sizeof(float), cudaMemcpyDeviceToHost, stream);
}
transpose(rr, k, nb*k, k, cbHandle, stream);
cudaStreamSynchronize(stream);
//printmatrixDevice("dRb.csv", rr, nb*k, nb*k, k);
//QnR(rr, nb*k, nb*k, k, csHandle, stream);
float *pr;
gpuErrchk(cudaMalloc(&pr, sizeof(float)*k*k));
QR(rr, nb*k, nb*k, k, pr, k, csHandle, stream, 1);
cudaStreamSynchronize(stream);
//printmatrixDevice("qr.csv", pr, k, k, k);
nr = 0;
transpose(rr, nb*k, k, nb*k, cbHandle, stream);
for (int i = 0; i < m*n; i += em*k)
{
printf("%d-th gemm\n", i);
cudaMemcpyAsync(b0, Q + i, em*k * sizeof(float), cudaMemcpyHostToDevice, stream);
cudaMemcpyAsync(b1, b0, em * k * sizeof(float), cudaMemcpyDeviceToDevice, stream);
float alpha = 1.0;
float beta = 0.0;
transpose(rr + nr, k, k, k, cbHandle, stream);
cudaStreamSynchronize(stream);
cublasSgemm(cbHandle,
CUBLAS_OP_N, CUBLAS_OP_N,
em, k, k,
&alpha,
b1, em,
rr + nr, k,
&beta,
b0, em);
nr += k*k;
/*if (i == 0)
{
printmatrixDevice("z11.csv", b0, em, em, k);
}
else
{
printmatrixDevice("z12.csv", b0, em, em, k);
}*/
transpose(b0, em, k, em, cbHandle, stream);
cudaMemcpyAsync(Q + i, b0, em*k * sizeof(float), cudaMemcpyDeviceToHost, stream);
}
cudaStreamSynchronize(stream);
//printmatrixdd("Q.csv", m, n, Q, n);
clock_gettime(CLOCK_MONOTONIC, &end);
diff = (end.tv_sec - start.tv_sec) + 1.0*(end.tv_nsec - start.tv_nsec) / BILLION;
//printf("MPC elapsed time = %.6f seconds\n", diff);
cudaFree(b0);
cudaFree(b1);
cudaFree(pr);
cudaFree(rr);
}
int getem(int m, int n)
{
if (1.0*m / 1000.0*n / 1000.0 * 4 / 1000.0 < 2)
return m;
for (int i = 2; i <= 100; i++)
{
if (m % i == 0)
{
m = m / i;
if (1.0*m / 1000.0*n / 1000.0 * 4 / 1000.0 < 2)
return m;
i--;
}
}
return m;
}
void ortho(float *W, int n, int k)
{
int em = getem(n, k);
printf("block size is %d\n", em);
//printmatrixdd("A.csv", n, k, W, k);
CAQR(W, n, k, k, em, k);
printf("-----------------------Ortho done!\n");
}
int main(int argc, char *argv[])
{
// stat = cublasCreate(&handle);
struct timespec start, end;
float diff;
// parse commandline
parsecmd(argc, argv);
// read LIBSVM format file
clock_t before = clock();
float *labels, *inst;
long n, nf;
libsvmread(trainfilepath, &labels, &inst, &n, &nf);
LABELS = labels; INST = inst; N = n; d = nf;
if (flag_tensorcore)
printf("\e[31mUsing TensorCore \e[39m\n");
if (NN!=0) {
printf("Truncating the input file to first %ld instances\n", NN);
N = NN; // only use the first NN instances; check -N options.
}
// PROCESSING the labes!! for COVTYPE
int pos=-42, neg=-42;
for( int i=0; i<N; i++ ) {
if( pos == -42) {
pos = LABELS[i];
} else if( neg==-42 && pos != LABELS[i] ){
neg = LABELS[i];
break;
}
}
POS = pos; NEG = neg;
for( int i=0; i<N; i++ ) {
if( LABELS[i] == POS ) LABELS[i] = 1;
else if( LABELS[i] == NEG ) LABELS[i] = -1;
else printf("Error: LABELS[%d] %.3f\n", i, LABELS[i]);
}
printf("found labels: %d(+1) %d(-1)\n", pos, neg);
clock_t difference = clock() - before;
printf("Reading files took %.3f seconds\n", 1.0*difference / CLOCKS_PER_SEC);
// primal-dual solution vectors X, Xi.
double *X, *Xi;
X = (double*) malloc(sizeof(double)*N);
Xi = (double*) malloc(sizeof(double)*N);
if( T == 0 ){ // Linear SVM.
printf("Linear SVM\n");
double *Z = new double[N*d];
double *Y = new double[N];
matcpy( N, d, "RowMajor", Z, d, "RowMajor", INST, d );
matcpy( N, 1, "RowMajor", Y, 1, "RowMajor", LABELS, 1 );
for( int i=0; i<N; i++ )
cblas_dscal(d, Y[i], &Z[i*d], 1);
//writematrix("/Users/pwu/ownCloud/Projects/2019June_TensorSVM/Z.csv", Z, N, d, d);
START_TIMER
printf("mpc ");
mpc(Z, Y, C, X, Xi, N, d);
END_TIMER
// unlabel the Z matrix; why?
for( int i=0; i<N; i++ )
cblas_dscal(d, Y[i], &Z[i*d], 1);
// write to the model
START_TIMER
printf("Writemodel ");
writemodel(modelfilepath, X, C, NULL); // No use of U
END_TIMER
// prediction if test file is supplied
if( testfilepath ) {
printf(" prediction unsupported \n");
//double *testlabels, *testinst;
//long testN, testd;
//libsvmread(testfilepath, &testlabels, &testinst, &testN, &testd);
//if( testd != d ) {
//printf("training #feature(%d) != testing feature (%d)\n",
//d, testd);
////return 0;
//}
//printf("\n\nPredicting on the test file %s...\n", testfilepath);
//printf("Number of test instances %ld, test features %ld\n", testN, testd);
//for( int i=0; i<testN; i++ ) {
//if( testlabels[i] == POS ) testlabels[i] = 1;
//else if( testlabels[i] == NEG ) testlabels[i] = -1;
//}
//predict(X, testlabels, testinst, testN, testd);
}
delete[] Z;
delete[] Y;
} else if ( T == 2 ) { // RBF kernel.
printf("\e[34mRBF kernel: gamma=%.3e, C=%.3e ", g, C);
printf("Approximation Rank K=%d\e[39m\n", K);
double *U = (double *) malloc( sizeof(double) * N*K );
int ldu = K;
clock_gettime( CLOCK_MONOTONIC, &start);
double l1 = LRA(INST, d, U, ldu, N, K);
clock_gettime( CLOCK_MONOTONIC, &end);
diff = (end.tv_sec - start.tv_sec) + 1.0*(end.tv_nsec - start.tv_nsec)/BILLION;
printf("\e[95mLRA elapsed time = %.0f seconds\e[39m\n", diff);
// FILE *f3 = fopen("U.csv","w");
// for( int i=0; i<N; i++ ){
// for( int j=0; j<K; j++ ){
// fprintf(f3, "%.6f", U[i*ldu+j]);
// if( j<K-1 ) fprintf(f3,",");
// else fprintf(f3, "\n");
// }
// }
// fclose(f3);
clock_gettime( CLOCK_MONOTONIC, &start);
if (CMDPARA_S == 0) { // approx IPM
double *a = (double*) malloc(sizeof(double) * N);
for(int i=0; i<N; i++) a[i] = LABELS[i];
mpc(U, a, C, X, Xi, N, K);
free(a);
} else if(CMDPARA_S == 1) { // projected gradient descent
printf("unimplemented pgd\n");
#if 0
pgd(INST, LABELS, C, X, N, d, l1);
#endif
}
clock_gettime( CLOCK_MONOTONIC, &end);
diff = (end.tv_sec - start.tv_sec) + 1.0*(end.tv_nsec - start.tv_nsec)/BILLION;
printf("\e[95mMPC elapsed time = %.0f seconds\e[39m\n", diff);
#ifdef DEBUG
printf("Calculating Primal/Dual Objective...");
using namespace std::chrono;
auto t1 = high_resolution_clock::now();
double *Zd, *Ld, *Xd, *Yd;
cudaMallocManaged( &Zd, sizeof(double)*N*d );
cudaMallocManaged( &Ld, sizeof(double)*N );
cudaMallocManaged( &Xd, sizeof(double)*N );
cudaMallocManaged( &Yd, sizeof(double)*N );
for( int i=0; i<N; i++ )
for( int j=0; j<d; j++ )