-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcuda_fcts.c
3178 lines (2891 loc) · 151 KB
/
cuda_fcts.c
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
/************************* CudaMat ******************************************
* Copyright (C) 2008-2009 by Rainer Heintzmann *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; Version 2 of the License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************
*
This file contains a number of functions to call to work with CudaMat
The Matlab and the Julia versions
Compile with:
Windows:
cc -o CudaMat.dll cuda_fcts.c cudaArith.obj -Ic:\\CUDA\include\ -Lc:\\CUDA\lib64\ -lcublas -lcufft -lcudart
Windows 64 bit:
No Cula:
% cc -o CudaMat.dll cuda_fcts.c cudaArith.obj -DNOCULA "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include" "-IC:\Program Files\CULA\R14\include" "-LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\lib\x64" -lcublas -lcufft -lcudart
cc -o CudaMat.dll cuda_fcts.c cudaArith.obj -DNOCULA "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\include" "-LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0\lib\x64" -lcublas -lcufft -lcudart
* Cula:
cc -o CudaMat.dll cuda_fcts.c cudaArith.obj "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include" "-IC:\Program Files\CULA\R14\include" "-LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\lib\x64" "-LC:\Program Files\CULA\R14\lib64" -lcublas -lcufft -lcudart -lcula_core -lcula_lapack
Linux:
cc -o CudaMat.dll cuda_fcts.c cudaArith.o -I/usr/local/cuda/include -L/usr/local/cuda/lib64 -lcublas -lcufft -lcudart -v
or Linux including CULA support:
cc -o CudaMat.dll cuda_fcts.c cudaArith.o -I/usr/local/cuda/include -I/usr/local/cula/include -L/usr/local/cuda/lib64 -L/usr/local/cula/lib64 -lcublas -lcufft -lcudart -lcula
*/
/*
This performs a number of operations using cuda on graphic cards.
* The sytax is always cuda_cuda('operation',arg1, arg2) whereas arg2 can be empty.
'alloc' convert a matlab single into a cuda object which is stored on the graphics card. Returns integer reference to cuda object.
*/
#ifdef MEX
#include "mex.h"
#end
#include "cufft.h"
#include "cuda_runtime.h"
#include "cublas.h"
#define externC
#include "cudaArith.h"
#include "matrix.h"
#include "stdio.h"
#include "string.h"
#include "cufft.h"
// #define DEBUG
#ifndef NOCULA
// #include "culadevice.h" // Only for old Cula releases
#include "cula.h" // Later releases such as R14
#include "cula_device.h" // Later releases such as R14
#endif
#define UseHeap // if defined the heap allocation and recycling is used. Otherwise normal allocation and free is used
#define AllocBlas // use the cublasAlloc and free functions instead of cudaMalloc and cudaFree
#define MAX_ARRAYS 65738 // maximum number of arrays simultaneously on card
#ifdef UseHeap
#define MAX_HEAP 25 // size of the heap of arrays to recycle
#endif
#define CHECK_CUDAREF(p) {if ((((double) (int) p) != p) || (p < 0) || (p >= MAX_ARRAYS)) \
myErrMsgTxt("cuda: Reference must be an integer between 0 and max_array\n");}
#define CHECK_CUDASIZES(ref1,ref2) {if (cuda_array_dim[ref1] != cuda_array_dim[ref2]) myErrMsgTxt("cuda: Arrays have different dimensionalities\n"); \
int d; for (d=0;d< cuda_array_dim[ref1]) if (cuda_array_size[ref1][d] != cuda_array_size[ref2][d])\
myErrMsgTxt("cuda: Array sizes must be equal in all dimensions\n");}
#define CHECK_CUDATotalSIZES(ref1,ref2) {if (getTotalSizeFromRefNum(ref1) != getTotalSizeFromRefNum(ref2)) myErrMsgTxt("cuda: Total array sizes are unequal. Bailing out\n");}
#ifdef DEBUG
#define Dbg_printf(arg) printf(arg)
#define Dbg_printf2(arg1,arg2) printf(arg1,arg2)
#define Dbg_printf3(arg1,arg2,arg3) printf(arg1,arg2,arg3)
#define Dbg_printf4(arg1,arg2,arg3,arg4) printf(arg1,arg2,arg3,arg4)
#define Dbg_printf5(arg1,arg2,arg3,arg4,arg5) printf(arg1,arg2,arg3,arg4,arg5)
#define Dbg_printf6(arg1,arg2,arg3,arg4,arg5,arg6) printf(arg1,arg2,arg3,arg4,arg5,arg6)
#define Dbg_printf7(arg1,arg2,arg3,arg4,arg5,arg6,arg7) printf(arg1,arg2,arg3,arg4,arg5,arg6,arg7)
#else
#define Dbg_printf(arg)
#define Dbg_printf2(arg1,arg2)
#define Dbg_printf3(arg1,arg2,arg3)
#define Dbg_printf4(arg1,arg2,arg3,arg4)
#define Dbg_printf5(arg1,arg2,arg3,arg4,arg5)
#define Dbg_printf6(arg1,arg2,arg3,arg4,arg5,arg6)
#define Dbg_printf7(arg1,arg2,arg3,arg4,arg5,arg6,arg7)
#endif
void myErrMsgTxt(char * s) {
#ifdef MEX
mexErrMsgTxt(s);
#else
fprintf(stderr,s);
#end
}
// is defined in stdlib.h
// #define min(a,b) ((a)<(b) ? (a):(b))
// Generates a new array (float * newarr) from a size vector
#define CUDA_NewArrayFromSize(IsComplex) \
int dims_sizes,nsizes[CUDA_MAXDIM],d,tsize=1; \
double * dsizes;float * newarr=0; \
if (nrhs < 2) myErrMsgTxt("cuda: newarr needs >= 2 arguments\n"); \
dims_sizes=(int)(myGetM(prhs[1]) * myGetN(prhs[1])); \
dsizes=myGetPr(prhs[1]); \
if (dims_sizes >= CUDA_MAXDIM) \
myErrMsgTxt("cuda: newarr to many dimensions (>CUDA_MAXDIM)\n"); \
for (d=0;d<dims_sizes;d++) {nsizes[d]=(int) dsizes[d];tsize *= nsizes[d];} \
Dbg_printf5("newarray with dimension %d, sizes %d %d %d\n",dims_sizes,nsizes[0],nsizes[1],nsizes[2]); \
\
if (IsComplex) { \
newarr=cudaAllocDetailed(dims_sizes,nsizes,scomplex); \
} else { \
newarr=cudaAllocDetailed(dims_sizes,nsizes,single); \
}
// ----------------- Macros of code snippets, defining common ways of calling Cuda ---------
#define CallCUDA_BinaryFkt(FktName,AllocFkt) \
const char *ret=0; int _ref1,_ref2; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
_ref1=getCudaRefNum(prhs[1]);_ref2=getCudaRefNum(prhs[2]); \
CHECK_CUDATotalSIZES(_ref1,_ref2); \
if (isComplexType(_ref1) && isComplexType(_ref2)) { \
Dbg_printf("cuda: complex array " #FktName " complex array\n"); \
ret=CUDAcarr_##FktName##_carr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(_ref1)) { \
Dbg_printf("cuda: complex array " #FktName " float array\n"); \
ret=CUDAcarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(_ref2)) { \
Dbg_printf("cuda: float array " #FktName " complex array\n"); \
ret=CUDAarr_##FktName##_carr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[2]),getTotalSizeFromRef(prhs[1])); }\
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
// ----------------- for calling with array and constant ---------
#define CallCUDA_UnaryFktConst(FktName,AllocFkt) \
const char *ret=0; \
int ref; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
ref=getCudaRefNum(prhs[1]); \
if (myIsComplex(prhs[2])) { \
double myreal = myGetScalar(prhs[2]); \
double myimag = * ((double *) (myGetPi(prhs[2]))); \
if (isComplexType(ref)) { \
Dbg_printf3("cuda: complex array " #FktName " complex-cons Real: %g Imag: %g\n",myreal,myimag); \
ret=CUDAcarr_##FktName##_const(getCudaRef(prhs[1]),(float) myreal,(float) myimag,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
float * narr=cudaAllocComplex(prhs[1]); \
Dbg_printf3("cuda: float array " #FktName " complex-const Real: %g Imag: %g\n",myreal,myimag); \
ret=CUDAarr_##FktName##_Cconst(getCudaRef(prhs[1]),(float) myreal,(float) myimag,narr,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
} else { \
double alpha = myGetScalar(prhs[2]); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " real-const\n"); \
ret=CUDAcarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,0.0,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// ----------------- for calling with array and constant but in Reverse order---------
#define CallCUDA_UnaryFktConstR(FktName,AllocFkt) \
const char *ret=0; \
int ref; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
ref=getCudaRefNum(prhs[1]); \
if (myIsComplex(prhs[2])) { \
double myreal = myGetScalar(prhs[2]); \
double myimag = * ((double *) (myGetPi(prhs[2]))); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " complex-const\n"); \
ret=CUDAconst_##FktName##_carr(getCudaRef(prhs[1]),(float) myreal,(float) myimag,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
float * narr=cudaAllocComplex(prhs[1]); \
Dbg_printf("cuda: float array " #FktName " complex-const\n"); \
ret=CUDACconst_##FktName##_arr(getCudaRef(prhs[1]),(float) myreal,(float) myimag,narr,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
} else { \
double alpha = myGetScalar(prhs[2]); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_carr(getCudaRef(prhs[1]),(float) alpha,0.0,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_arr(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// --------- The ones below are FOR REAL-VALUED Functions only --- (e.g. comparison operations) ----------
#define CallCUDA_BinaryHRealFkt(FktName,AllocFkt) \
const char *ret=0; int _ref1,_ref2; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
_ref1=getCudaRefNum(prhs[1]);_ref2=getCudaRefNum(prhs[2]); \
CHECK_CUDATotalSIZES(_ref1,_ref2); \
if (isComplexType(_ref1) && isComplexType(_ref2)) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real argument data.\n");} \
else if (isComplexType(_ref1)) { \
Dbg_printf("cuda: complex array " #FktName " float array\n"); \
ret=CUDAcarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(_ref2)) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real argument data.\n");} \
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
// --------- The ones below are FOR REAL-VALUED Functions only --- (e.g. comparison operations) ----------
#define CallCUDA_BinaryRealFkt(FktName,AllocFkt) \
const char *ret=0; int _ref1,_ref2; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
_ref1=getCudaRefNum(prhs[1]);_ref2=getCudaRefNum(prhs[2]); \
CHECK_CUDATotalSIZES(_ref1,_ref2); \
if (isComplexType(_ref1) || isComplexType(_ref2)) \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");}
// ----------------- for calling with array and constant ---------
#define CallCUDA_UnaryRealFktConst(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
if (myIsComplex(prhs[2])) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
double alpha = myGetScalar(prhs[2]); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
} \
} \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");}
// ----------------- for calling with array and constant but in Reverse order (e.g. for alpha / array) ---------
#define CallCUDA_UnaryRealFktConstR(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
if (myIsComplex(prhs[2])) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
double alpha = myGetScalar(prhs[2]); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
myErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_arr(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// ----------------- Unary function for real valued data only ------AllocCommand determines whether the result type is that same, complex or real ----------
#define CallCUDA_UnaryRealFkt(FktName,AllocCommand) \
const char *ret=0; \
if (nrhs != 2) myErrMsgTxt("cuda: " #FktName " needs one argument\n"); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
myErrMsgTxt("cuda error " #FktName ": Tried to apply to complex valued data."); \
ret="Error " #FktName ": Tried to apply to complex valued data."; \
} else { \
Dbg_printf("cuda: float array " #FktName "\n"); \
ret=CUDA##FktName##_arr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
}
// ----------------- Unary function ------AllocCommand determines whether the result type is that same, complex or real ----------
#define CallCUDA_UnaryFkt(FktName,AllocCommand) \
const char *ret=0; \
if (nrhs != 2) myErrMsgTxt("cuda: " #FktName " needs one argument\n"); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
Dbg_printf("cuda: complex array " #FktName "\n"); \
ret=CUDA##FktName##_carr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
} else { \
Dbg_printf("cuda: float array " #FktName "\n"); \
ret=CUDA##FktName##_arr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
}
// Snippet below expects a vector(CUDA_MAXDIM) and an array as input and generates an array as output. E.g. circshift
#define CallCUDA_ArrVecFkt(FktName,AllocCommand,SetToVal) \
int dims_sizes,nshifts[CUDA_MAXDIM], dsize[CUDA_MAXDIM],d,tsize=1,ref; \
double * dshifts;float * newarr=0; \
const char * ret; \
\
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
dims_sizes=(int)(myGetM(prhs[2]) * myGetN(prhs[2])); dshifts=myGetPr(prhs[2]); \
if (dims_sizes > CUDA_MAXDIM) \
myErrMsgTxt("cuda: " #FktName " to many dimensions (>CUDA_MAXDIM)\n"); \
\
ref=getCudaRefNum(prhs[1]); \
\
for (d=0;d<CUDA_MAXDIM;d++) { \
if (d<dims_sizes) \
nshifts[d]=(int) dshifts[d]; \
else \
nshifts[d]=SetToVal; \
if (d<cuda_array_dim[ref]) \
dsize[d]=cuda_array_size[ref][d]; \
else \
dsize[d]=1; \
} \
Dbg_printf5("" #FktName " with size %d, shifts %d %d %d\n",dims_sizes,nshifts[0],nshifts[1],nshifts[2]); \
if (nrhs != 3) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
\
if (isComplexType(ref)) { \
ret=CUDAcarr_##FktName##_vec(getCudaRef(prhs[1]),nshifts,AllocCommand(prhs[1]),dsize,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda complex " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
ret=CUDAarr_##FktName##_vec(getCudaRef(prhs[1]),nshifts,AllocCommand(prhs[1]),dsize,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
Dbg_printf("" #FktName "\n"); \
// Snippet below expects a vector(CUDA_MAXDIM) and two vectors as input and generates an array as output. E.g. xx,yy,zz,rr,phiphi
#define CallCUDA_GenArrFkt(FktName) \
{VecND vec1,vec2; \
SizeND sSize; \
if (nrhs != 4) myErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
else {CUDA_NewArrayFromSize(0) /* uses Matlab Ref 1 as a size vector, 0 for no complex number*/ \
vec1=VecNDFromRef(prhs[2]); \
vec2=VecNDFromRef(prhs[3]); \
sSize=SizeNDFromRef(prhs[1]); \
CUDAarr_##FktName##_2vec(newarr, vec1, vec2, sSize, getTotalSizeFromRefNum(free_array));\
if (! (cudaGetLastError() == cudaSuccess)) \
{ printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt(" " #FktName " Bailing out");} \
Dbg_printf("" #FktName "\n"); \
} }
static const char * ERROR_NAMES[]={
"SUCCESS",
"INVALID_PLAN",
"ALLOC_FAILED",
"INVALID_TYPE",
"INVALID_VALUE",
"INTERNAL_ERROR",
"EXEC_FAILED",
"SETUP_FAILED",
// "SHOWDOWN_FAILED",
"INVALID_SIZE",
"" // needed to stop the search
};
enum CUDA_TYPE {
single,
int16,
// fftSingle,
fftHalfSComplex,
scomplex
};
static const char * CUDA_TYPE_NAMES[]={
"single",
"int16",
// "fftSingle",
"fftHalfSComplex",
"scomplex",
"" // needed to stop the search
};
static int CUDA_TYPE_SIZE[]={
sizeof(float),
2,
// sizeof(float),
sizeof(cufftComplex),
sizeof(cufftComplex)
};
static int CUDA_MATLAB_CLASS[]={
mySINGLE_CLASS,
myINT16_CLASS,
// mySINGLE_CLASS,
mySINGLE_CLASS,
mySINGLE_CLASS
};
#define MAX_FFTPLANS 15
#define MaxCudaDevices 5
static cufftHandle cuda_FFTplans[MAX_FFTPLANS][3][3]; // stores a number of plans for each type of transform and dimension
static int cuda_FFTplan_sizes[MAX_FFTPLANS][3][3][3]; // Stores the associated sizes, to check if plan needs to be redone
static float * cuda_arrays[MAX_ARRAYS]; // static array of cuda arrays
static int cuda_array_dim[MAX_ARRAYS]; // type tags see CUDA_TYPE definitions above
static int * cuda_array_size[MAX_ARRAYS]; // dynamically allocated
//static int cuda_array_origFTsize[MAX_ARRAYS]; // for storing the original data size, when doing FFTs
static float cuda_array_FTscale[MAX_ARRAYS]; // to do the maginitude correction
static int cuda_array_type[MAX_ARRAYS]; // type tags see CUDA_TYPE definitions above
static int free_array=0; // next number of array to fill
static int cuda_curr_arrays=0;
static int cuda_initialized=0;
// static int sizes[100];
// static int dims=0,totalsize=0;
static float * pOne[MaxCudaDevices], * pZero[MaxCudaDevices], * pReturnVal[MaxCudaDevices];
static int NumZero[MaxCudaDevices],NumOne[MaxCudaDevices],NumReturnVal[MaxCudaDevices]; // = {-1,-1,-1,-1,-1}
static int currentCudaDevice=0;
static int ignoreDelete=0; // Needed to avoid delete (or copyiing the whole array) after subassign
static int ignoreRef=-2; // Needed to avoid delete (or copyiing the whole array) after subassign
static void * fastMem=0, * fastMemI=0;
static const int fastMemSize=1024; // number of byte for fast transfer
static int SumAllocated=0; // next number of array to fill
#ifdef UseHeap
static void * mem_heap[MAX_HEAP]; // memory which can be reused if size matches
static int memsize_heap[MAX_HEAP]; // sizes in bytes
static int mem_heap_pos=0; // position of the next entry to free from the heap
static int mem_heap_first_free=0; // position of the next entry to free from the heap
static int mem_heap_allocated=0; // filling of the heap
#endif
/**************************************************************************/
/* MATLAB stores complex numbers in separate arrays for the real and
imaginary parts. The following functions take the data in
this format and pack it into a complex work array, or
unpack it, respectively.
We are using cufftComplex defined in cufft.h to handle complex on Windows and Linux
*/
#ifndef NOCULA
void checkCULAStatus(char * text, culaStatus status)
{
if(!status)
return;
if(status == culaArgumentError)
printf("%s: Invalid value for parameter %d\n", text,culaGetErrorInfo());
else if(status == culaDataError)
printf("%s: Data error (%d)\n", text,culaGetErrorInfo());
else if(status == culaBlasError)
printf("%s: Blas error (%d)\n", text,culaGetErrorInfo());
else if(status == culaRuntimeError)
printf("%s: Runtime error (%d)\n", text,culaGetErrorInfo());
else
printf("%s: %s\n", text,culaGetStatusString(status));
myErrMsgTxt("CULA Error: Bailing out\n");
// culaShutdown();
}
#endif
void checkCudaError(char * text, cudaError_t err)
{
if(!err)
return;
printf("%s: %s\n", text, cudaGetErrorString(err));
myErrMsgTxt("CULA Error: Bailing out\n");
}
// returns array size in 3D coordinates (expanding with ones)
void get3DSize(int ref, int * mysize) {
int d;
for (d=0;d<3;d++)
if (d< cuda_array_dim[ref])
mysize[d]=cuda_array_size[ref][d];
else
mysize[d]=1;
}
// returns array size in 5D coordinates (expanding with ones)
void get5DSize(int ref, int * mysize) {
int d;
for (d=0;d<5;d++)
if (d< cuda_array_dim[ref])
mysize[d]=cuda_array_size[ref][d];
else
mysize[d]=1;
}
VecND VecNDFromRef(const myArray * MatlabRef) {
VecND ret;
int d,dim;
double * pVal=myGetPr(MatlabRef);
dim=(int)(myGetM(MatlabRef) * myGetN(MatlabRef));
for (d=0;d<CUDA_MAXDIM;d++)
if (d< dim)
ret.s[d]=(float) pVal[d];
else
ret.s[d]=0.0f;
return ret;
}
SizeND SizeNDFromRef(const myArray * MatlabRef) {
SizeND ret;
int d,dim;
double * pVal=myGetPr(MatlabRef);
dim=(int)(myGetM(MatlabRef) * myGetN(MatlabRef));
for (d=0;d<CUDA_MAXDIM;d++)
if (d< dim)
ret.s[d]=(int) pVal[d];
else
ret.s[d]=1;
return ret;
}
int getCudaRefNum(const myArray * arg) {
double cudaref;
if (! myIsDouble(arg))
myErrMsgTxt("cuda: Obtaining reference number. Number must be a double");
cudaref = myGetScalar(arg);
/* printf("cuda: get ref %g, next free array %d\n",cudaref,free_array); */
CHECK_CUDAREF(cudaref);
if (cuda_array_size[(int) cudaref] == 0)
myErrMsgTxt("cuda: Trying to access non-existing cuda reference.");
return (int) cudaref;
}
bool isComplexType(int ref) {
return (cuda_array_type[ref] >= fftHalfSComplex);
}
int getTotalSize(int dim,const int * sizevec) { // returns the total size in numbers (floats or complex), not accounting for complex size
int totalsize=1,d;
for (d=0;d<dim;d++) {
totalsize *= sizevec[d];
if (sizevec[d]==0)
{ myErrMsgTxt("cuda: detected a zero in the size of an array. (e.g. in allocation)\n"); return 0;}
}
// Dbg_printf2("Totalsize = %d\n",totalsize);
return totalsize;
}
int getTotalSizeFromRefNum(int pos) {
return getTotalSize(cuda_array_dim[pos],cuda_array_size[pos]);
}
int getTotalSizeFromRef(const myArray * arg) {
return getTotalSizeFromRefNum(getCudaRefNum(arg));
}
int getTotalFloatSizeFromRef(const myArray * arg) { // sizes in floating point numbers
int ref=getCudaRefNum(arg);
if (isComplexType(ref)) // this is a complex datatyp
return getTotalSizeFromRefNum(ref)*2;
else
return getTotalSizeFromRefNum(ref);
}
void CheckMemoryConsistency(); // Just declare, but no definition yet. See below
void PrintMemoryOverview() {
int p,d,plantypenum,n;
int sumMem=0;
int sumHeap=0;
printf("Overview of use Memory:\n");
printf("----------------------------------------------------------------------------------\n");
printf("Array # Type Size XYZ TotalSize Adress\n");
for (p=0;p<MAX_ARRAYS;p++)
if (cuda_arrays[p] !=0)
{
printf(" %4d %1d %4d %4d %4d %9d %9d\n",p,cuda_array_type[p],cuda_array_size[p][0],cuda_array_size[p][1],cuda_array_size[p][2],getTotalSizeFromRefNum(p),cuda_arrays[p]);
sumMem+=getTotalSizeFromRefNum(p);
}
printf("\n--------------------------------------------------------------------------------\n");
printf("Overview of Memory Heap (heapsize %d, allocated %d, first_free %d, tofree %d\n",MAX_HEAP,mem_heap_allocated, mem_heap_first_free,mem_heap_pos);
#ifndef UseHeap
printf("Memory Heap is not used\n");
#else
printf("HeapPos TotalSize Adress\n");
for (p=0;p<mem_heap_allocated;p++) // find the next free entry
if (mem_heap[p] !=0)
{
printf(" %4d %9d %9d\n",p,memsize_heap[p],mem_heap[p]);
sumHeap+=memsize_heap[p];
}
#endif
printf("----------------------------------------------------------------------------------\n");
printf("FFT-Plans (Maximum number is %d):\n",MAX_FFTPLANS);
for (d=0;d<3;d++)
for (plantypenum=0;plantypenum<3;plantypenum++)
for (n=0;n<MAX_FFTPLANS;n++)
if (cuda_FFTplans[n][d][plantypenum] != 0)
{
if (d==0)
printf("1D plan no. %d, Size: %d \n",n,cuda_FFTplan_sizes[n][0][plantypenum][0]);
else if (d==1)
printf("2D plan no. %d Size: %d x %d\n",n,cuda_FFTplan_sizes[n][1][plantypenum][0],cuda_FFTplan_sizes[n][1][plantypenum][1]);
else
printf("3D plan no. %d Size: %d x %d x %d\n",n,cuda_FFTplan_sizes[n][2][plantypenum][0],cuda_FFTplan_sizes[n][2][plantypenum][1],cuda_FFTplan_sizes[n][2][plantypenum][2]);
}
printf("----------------------------------------------------------------------------------\n");
printf("Summary: Memory used %9d, Heap %9d, Total used %9d, ?= Allocated %10d, Total: %10d, Free %10d \n",sumMem,sumHeap,sumMem+sumHeap,SumAllocated,GetDeviceProp().totalGlobalMem,GetDeviceProp().totalGlobalMem - SumAllocated);
printf("Current Reduce Array size %9d \n",GetCurrentRedSize());
}
void CheckMemoryConsistency() {
int sumMem=0;
int sumHeap=0;
int p;
for (p=0;p<MAX_ARRAYS;p++)
if (cuda_arrays[p] !=0)
sumMem+=getTotalSizeFromRefNum(p)*CUDA_TYPE_SIZE[cuda_array_type[p]];
for (p=0;p<mem_heap_allocated;p++) // find the next free entry
if (mem_heap[p] !=0)
sumHeap+=memsize_heap[p];
if (sumHeap+sumMem != SumAllocated)
{ printf("Memory Consitency Check failed for total allocation: %d, (Heap+Arrays): %d\n",SumAllocated,sumHeap+sumMem);
PrintMemoryOverview();
SumAllocated=sumHeap+sumMem;
myErrMsgTxt("Adjusting Total Size and ... Bailing out");
return;
}
}
int ClearHeap() // release all resources
{
int custatus;
#ifndef UseHeap
return; // do nothing
#endif
Dbg_printf2("Out of Memory. Clearing heap of size %d\n",mem_heap_allocated);
for (mem_heap_allocated--;mem_heap_allocated>=0;mem_heap_allocated--) // find the next free entry
if (mem_heap[mem_heap_allocated] != 0)
{
Dbg_printf3("Freeing array %d of size %d\n",mem_heap_allocated,mem_heap[mem_heap_allocated]);
#ifdef AllocBlas
custatus=cublasFree(mem_heap[mem_heap_allocated]);
#else
custatus=cudaFree(mem_heap[mem_heap_allocated]);
#endif
SumAllocated -= memsize_heap[mem_heap_allocated];
if (custatus!=cudaSuccess)
{ printf("ERROR cuda Free: %s\n",cudaGetErrorString(cudaGetLastError()));
myErrMsgTxt("Bailing out");
return custatus;
}
mem_heap[mem_heap_allocated]=0;
memsize_heap[mem_heap_allocated]=0;
}
mem_heap_first_free=0;
mem_heap_allocated=0;
return cudaSuccess;
}
float * MemAlloc(int mysize) { // returns an array from the heap or a fresh array, mysize given in bytes. DOES NOT REGISTER THE ARRAY!
float * p_cuda_data; float ** pp_cuda_data= & p_cuda_data;
int custatus;
#ifdef UseHeap
int p;
float * tmp=0;
for (p=mem_heap_allocated-1;p>=0;p--) // Look in the heap, whether there is something of the right size
{
Dbg_printf4("Scanning heap for memory %d, has size %d, looking for %d\n",p,memsize_heap[p],mysize);
if (mysize == memsize_heap[p]) // found the right size (in bytes) on the heap
{
memsize_heap[p]=0;
tmp=(float *) mem_heap[p];
mem_heap[p]=0;
if (p==mem_heap_allocated-1) // Decrease heapsize only, if the last entry was removed
mem_heap_allocated--; // heap is less full now
if (p< mem_heap_first_free) mem_heap_first_free=p; // lowest position free space needs to be updated
Dbg_printf3("Array allocated from heap %d, heap filling is %d\n",p,mem_heap_allocated);
return tmp; // found something
}
}
Dbg_printf2("No matching size in heap. To allocate: %d \n",mysize);
#endif
#ifdef AllocBlas
custatus = cublasAlloc((mysize+3)/sizeof(float), sizeof(float), (void**) pp_cuda_data);
if (custatus != CUBLAS_STATUS_SUCCESS) {
const char * dummy=cudaGetErrorString(cudaGetLastError()); // just to clear the error
custatus=cublasGetError(); // also to clear the error
custatus=ClearHeap(); // Clear heap and try again
custatus = cublasAlloc((mysize+3)/sizeof(float), sizeof(float), (void**) pp_cuda_data);
if (custatus != CUBLAS_STATUS_SUCCESS) {
printf("cuda Malloc: %s\n",cudaGetErrorString(cudaGetLastError()));
myErrMsgTxt("cuda: cublasAlloc Device memory allocation error (on card)\n");
return 0;
}
}
#else
custatus=cudaMalloc((void **) pp_cuda_data, mysize);
if (custatus!=cudaSuccess) {
const char * dummy=cudaGetErrorString(cudaGetLastError()); // just to clear the error
custatus=ClearHeap(); // Clear heap and try again
custatus=cudaMalloc((void **) pp_cuda_data, mysize);
if (custatus!=cudaSuccess) {
printf("cuda Malloc: %s\n",cudaGetErrorString(cudaGetLastError()));
myErrMsgTxt("cuda: cudaMallox Device memory allocation error (on card)\n");
return 0;
}
}
#endif
SumAllocated += mysize;
Dbg_printf2("Allocated %d bytes\n",mysize);
return p_cuda_data;
}
void MemFree(int ref) {
#ifdef UseHeap
int totalsize=getTotalSizeFromRefNum(ref) * CUDA_TYPE_SIZE[cuda_array_type[ref]]; // size in bytes
int similarCnt=0,p=0;
if (mem_heap_first_free<MAX_HEAP) // this is the free space. Deposite the array here
{
mem_heap[mem_heap_first_free]=(void *) cuda_arrays[ref];
memsize_heap[mem_heap_first_free]=totalsize;
cuda_arrays[ref]=0;
if (mem_heap_first_free==mem_heap_allocated) // Increase heapsize only, if the last entry was first_free
mem_heap_allocated++; // keeps track of the laset used entry on the heap
for (;mem_heap_first_free<MAX_HEAP;mem_heap_first_free++) // find the next free entry
if (memsize_heap[mem_heap_first_free]==0)
break; // found the next empty space
Dbg_printf4("Array reference %d stored to heap place %d, filling is %d\n",ref,mem_heap_first_free,mem_heap_allocated);
return;
//if (totalsize == memsize_heap[p])
// similarCnt++;
} // No empty space there. Will have to free this array or another one from the heap
// if (similarCnt > (int) sqrt(MAX_HEAP+1)) // enough of these there already
// printf("Warning: Cuda Heap is full, %d arrays on stack\n",mem_heap_allocated);
for (p=0;p<MAX_HEAP;p++)
if (memsize_heap[p]==totalsize) similarCnt++; // count the number of arrays of this type
if (similarCnt > (int)((MAX_HEAP+1)/2)) // enough of these there already, free this space
{
#endif
#ifdef AllocBlas
int custatus=cublasFree(cuda_arrays[ref]);
#else
int custatus=cudaFree(cuda_arrays[ref]);
#endif
SumAllocated -= totalsize;
if (custatus!=cudaSuccess) { printf("Error cuda Free: %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("Bailing out");}
cuda_arrays[ref]=0;
#ifdef UseHeap
Dbg_printf2("Array reference %d freed entirely as already in heap\n",ref);
// ClearHeap();
}
else // we need to free another one on the heap and keep this one as a replacement
{
int custatus;
//mem_heap_first_free=MAX_HEAP-1; // always take the last on the heap to free, as this is most recent one
#ifdef AllocBlas
custatus=cublasFree(mem_heap[mem_heap_pos]);
#else
custatus=cudaFree(mem_heap[mem_heap_pos]);
#endif
if (custatus!=cudaSuccess) { printf("cuda Free: %s\n",cudaGetErrorString(cudaGetLastError())); myErrMsgTxt("Bailing out");}
SumAllocated -= memsize_heap[mem_heap_pos];
mem_heap[mem_heap_pos]=(void *) cuda_arrays[ref];
memsize_heap[mem_heap_pos]=totalsize;
cuda_arrays[ref]=0;
Dbg_printf3("Array reference %d kept but a different array %d freed from heap\n",ref,mem_heap_first_free);
// mem_heap_first_free++; // which means no free one available again
mem_heap_pos = (mem_heap_pos+1) % MAX_HEAP; // next time free a different one
}
#endif
}
int MatlabTypeFromCuda(int ref) { /// returns the Matlab class for the specified datatype
return CUDA_MATLAB_CLASS[cuda_array_type[ref]];
}
int MatlabRealCpxFromCuda(int ref) { // returns a specifier to indicate whether this is real or complex valued data in Matlab
if (!isComplexType(ref))
return myREAL;
else
return myCOMPLEX;
}
int cudaTypeFromArg(const char * MatlabString) {
int i;
/* Copy the string data from prhs[0] into a C string */
Dbg_printf2("cuda: type to allocate is %s\n",MatlabString);
// printf("cuda: Number of CUDA_TYPENAMES is %d\n",sizeof(CUDA_TYPE_NAMES));
// return 0;
for (i=0;CUDA_TYPE_NAMES[i][0] != 0;i++)
if (strcmp(MatlabString,CUDA_TYPE_NAMES[i])==0)
{
return i;
}
myErrMsgTxt("cuda: Unknown type!\n");
return -1;
}
int updateFreeArray() { // looks for the next free position to store and array
int howmany=0;
int pos=free_array;
for(;cuda_array_size[pos] != 0;pos=(pos+1)%MAX_ARRAYS)
{ howmany++;
if (howmany > MAX_ARRAYS+1) {
printf("cuda: MAX_ARRAYS is %d\n",MAX_ARRAYS);
myErrMsgTxt("cuda: Maximum number of allocatable arrays reached!\n");
return -1;
}
}
free_array=pos;
return free_array;
}
float * getCudaRef(const myArray * arg) {
return cuda_arrays[getCudaRefNum(arg)];
}
// The idea below cannot be used, as otherwise all the functions need to copy the origFT sizes along
/* void ReduceToHalfComplex(int pos) {
int mydim=cuda_array_dim[pos];
if (mydim>3) mydim=3; // because maximally 3d ffts are allowed
cuda_array_origFTsize[pos] = cuda_array_size[pos][mydim-1]; // last dimension needs to be stored to recover it when doing inverse FTs
cuda_array_size[pos][mydim-1] = ((int) ((cuda_array_size[pos][mydim-1]) / 2)) +1; // reduce size accordingly for half complex values
}
void ExpandToFullReal(int pos) {
int mydim=cuda_array_dim[pos];
if (mydim>3) mydim=3; // because maximally 3d ffts are allowed
cuda_array_size[pos][mydim-1] = cuda_array_origFTsize[pos]; // restore size for real space
} */
void swapMatlabSize(int * mysize, int dims) {
int tmp=mysize[0];
if (dims>1)
{mysize[0]=mysize[1];mysize[1]=tmp;} // the bad matlab problem with x and y dimensions
}
void cudaCopySizeVec(int pos, const int * sizevec,int dims) { // copies a matlab sizevector to the array
double FTscale = 1.0;
int d;
cuda_array_size[pos]=calloc(dims,sizeof(cuda_array_size[0][0]));
for (d=0;d<dims;d++) {
cuda_array_size[pos][d]=sizevec[d]; // copy sizes
FTscale *= sizevec[d];
}
//swapMatlabSize(cuda_array_size[pos],dims);
cuda_array_FTscale[pos]=(float) (1.0/sqrt(FTscale));
cuda_array_dim[pos]=dims;
Dbg_printf2("CopySizeVec of %d dimensional vector\n",dims);
}
void cudaCopySizeVecD(int pos, const double * sizevec,int dims) { // copies a matlab sizevector to the array (by creating a new one using calloc)
double FTscale = 1.0;
int d;
cuda_array_size[pos]=calloc(dims,sizeof(cuda_array_size[0][0]));
for (d=0;d<dims;d++) {
cuda_array_size[pos][d]=(int) sizevec[d]; // copy sizes
FTscale *= sizevec[d];
}
//swapMatlabSize(cuda_array_size[pos],dims);
cuda_array_FTscale[pos]=(float) (1.0/sqrt(FTscale));
cuda_array_dim[pos]=dims;
Dbg_printf2("CopySizeVecD of %d dimensional vector\n",dims);
}
float * cudaAllocDetailed(int dims, const int * sizevec, int cuda_type) { // make a new array
float * p_cuda_data; // float ** pp_cuda_data=& p_cuda_data;
int pos=updateFreeArray(),ts;
cudaCopySizeVec(pos,sizevec,dims);
cuda_array_type[pos]=cuda_type;
ts=getTotalSize(dims,cuda_array_size[pos]);
if (ts>0) {
p_cuda_data=MemAlloc(ts*CUDA_TYPE_SIZE[cuda_type]);
}
else p_cuda_data=0;
cuda_arrays[pos]=p_cuda_data; // save it in the array
cuda_curr_arrays++;
Dbg_printf3("constructed cuda array nr %d of %d dimensions\n",pos,dims);
return p_cuda_data;
}
float * cudaReturnVal(const myArray * arg) { // sets the result value to zero and returns the pointer
cudaError_t err;
err=cudaMemset(pReturnVal[currentCudaDevice],0,2*sizeof(float));
checkCudaError("cudaReturnVal: ",err);
return pReturnVal[currentCudaDevice];
}
float * cudaAllocNum(const myArray * arg) { // make a new result float number
cudaError_t err;
int mysizes[3]={1,0,0};
float * ret=cudaAllocDetailed(1, mysizes, single);
err=cudaMemset(cuda_arrays[free_array],0,sizeof(float));checkCudaError("cudaAllocNum single: ",err);
cuda_array_FTscale[free_array]=1; // to do the maginitude correction
cuda_array_type[free_array]=single; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAllocCNum(const myArray * arg) { // make a new result complex number
cudaError_t err;
int mysizes[3]={1,0,0};
float * ret=cudaAllocDetailed(1, mysizes, scomplex);
err=cudaMemset(cuda_arrays[free_array],0,sizeof(cufftComplex));checkCudaError("cudaAllocNum complex: ",err);
cuda_array_FTscale[free_array]=1; // to do the maginitude correction
cuda_array_type[free_array]=1; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAlloc(const myArray * arg) { // make a new array with same properties as other array
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], cuda_array_type[ref]);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
//cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=cuda_array_type[ref]; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAllocReal(const myArray * arg) { // make a new array with same properties as other array, but ignores Complex and makes it Real
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], single);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
//cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=single; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAllocComplex(const myArray * arg) { // make a new array with same properties as other array, but ignores type and makes it Complex
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], scomplex);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
//cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=scomplex; // type tags see CUDA_TYPE definitions above
return ret;
}
float * getMatlabFloatArray(const myArray * arg, int * nd) {
(* nd) = myGetNumberOfDimensions(arg);
// int * sz = myGetDimensions(arg);
if (*nd > 0) {
/* Pointer for the real part of the input */
return (float *) myGetData(arg);
}
myErrMsgTxt("cuda: getMatlabFloatArray; data is zero dimensional\n");
return 0;
}
float * cudaPut(const myArray * arg) { // copies Matlab array into cuda
int dims = myGetNumberOfDimensions(arg);
const int * sizevec = myGetDimensions(arg);
unsigned long ts,maxarr;
int cuda_type = -1;