-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGpu.cu
1799 lines (1641 loc) · 67 KB
/
Gpu.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
/*
* This file is part of the continuous space language and translation model toolkit
* for statistical machine translation and large vocabulary speech recognition.
*
* Copyright 2015, Holger Schwenk, LIUM, University of Le Mans, France
*
* The CSLM toolkit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3 as
* published by the Free Software Foundation
*
* This library 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
using namespace std;
#include <algorithm>
#include <map>
#include <sstream>
#include <signal.h>
#define RAISE raise(SIGINT);
typedef float REAL;
#define NULL_WORD (-1) // from WordList.h
#define LOG_PROBA_NONE 999 // from ErrFact.h
#define LOCK_FNAME "/tmp/gpu_lock.pid%d.gpu%d"
#define LOCK_FNAME_LEN 256 // Hack ;-)
#include <npps.h>
#include <cublas.h>
#include <cuda_runtime_api.h>
#include <nppcore.h>
#include "nvml.h"
#include "Gpu.cuh"
#include "Tools.h" //For Error()
// global variables
curandGenerator_t cuda_gen;
string cuda_user_list; // user specified list of GPUs
static REAL *gpu_result;
#define GPU_BUF_DIM 65536
static REAL *gpu_buf;
size_t Gpu::curDevIndex = (size_t)-1; ///< current device index
size_t Gpu::curConfIndex = (size_t)-1; ///< current configuration index
cudaStream_t Gpu::curStream = NULL; ///< current stream
bool Gpu::useConcurrentStreams = false; ///< status of concurrent streams
#ifdef GPU_CUBLAS_V2
cublasHandle_t Gpu::curCbHandle = NULL; ///< current Cublas handle
#endif
cudaDeviceProp* Gpu::curDevProps = NULL; ///< device properties
vector<Gpu::Device> Gpu::vDevices; ///< vector of Gpu devices to be used
vector<Gpu::Config> Gpu::vConfigs; ///< vector of Gpu configurations
void HandlerSigTERM(int s)
{
printf("Catched signal: removing lock-files\n");
Gpu::Unlock();
exit(1);
}
/**
* initializes Cuda and creates lock files
* @note selects first device and stream
* @returns configuration index 0
*/
size_t Gpu::Init()
{
size_t stId = 0;
if (0 >= Gpu::vConfigs.size()) {
Gpu::vConfigs.resize(1);
cout << "Initializing Nvidia GPU card" << endl;
int dev_max = 0;
cudaGetDeviceCount(&dev_max);
bool bSelAuto = (':' != cuda_user_list[0]);
Gpu::Device dev;
if (0 < dev_max) {
if (1 == dev_max)
cout << " - found 1 card:" << endl;
else
cout << " - found " << dev_max << " cards:" << endl;
if (bSelAuto)
nvmlInit();
nvmlDevice_t nd;
nvmlUtilization_t nu;
multimap<uint,Gpu::Device> mSelDev;
for (dev.number = 0 ; dev.number < dev_max ; dev.number++) {
cudaGetDeviceProperties(&dev.props, dev.number);
int nb_cores_per_multiprocessor = -1;
if(dev.props.major == 1 && (dev.props.minor == 0||dev.props.minor == 1||dev.props.minor == 2||dev.props.minor == 3))
nb_cores_per_multiprocessor = 8;
else if(dev.props.major == 2 && dev.props.minor == 0)
nb_cores_per_multiprocessor = 32;
else if(dev.props.major == 2 && dev.props.minor == 1)
nb_cores_per_multiprocessor = 48;
else if(dev.props.major == 3 && (dev.props.minor == 0||dev.props.minor == 5))
nb_cores_per_multiprocessor = 192;
printf(" %d: %s with %d CPUs x %d threads running at %4.2f Ghz, %d MBytes of memory, use -arch=sm_%d%d",
dev.number, dev.props.name, dev.props.multiProcessorCount, nb_cores_per_multiprocessor,
dev.props.clockRate/1000000.0, (int) (dev.props.totalGlobalMem/1024/1024),
dev.props.major, dev.props.minor);
if (bSelAuto) {
if ( (nvmlDeviceGetHandleByIndex(dev.number, &nd) == NVML_SUCCESS)
&& (nvmlDeviceGetUtilizationRates( nd , &nu) == NVML_SUCCESS) )
printf(", utilization %d%%", nu.gpu);
mSelDev.insert(make_pair(nu.gpu, dev));
}
printf("\n");
}
if (bSelAuto) { // select devices automatically
nvmlShutdown();
int iMaxDev = std::min(std::max(atoi(cuda_user_list.c_str()), 0), dev_max);
for (multimap<uint,Gpu::Device>::const_iterator mmci = mSelDev.begin() ; 0 < iMaxDev-- ; mmci++)
Gpu::vDevices.push_back(mmci->second);
}
}
if (!bSelAuto) { // read devices specified by user
char c;
istringstream iss;
iss.str(cuda_user_list);
while (iss.good()) {
iss >> c >> dev.number;
Gpu::vDevices.push_back(dev);
cudaGetDeviceProperties(&Gpu::vDevices.back().props, dev.number);
}
if (iss.fail())
ErrorN("format error in the selection of CUDA devices \"%s\"", cuda_user_list.c_str() + 1);
}
size_t dev_sel = Gpu::vDevices.size();
switch (dev_sel) {
case 0: printf(" - no GPU device selected\n");
dev.number = 0;
Gpu::vDevices.push_back(dev);
dev_sel = 1;
cudaGetDeviceProperties(&Gpu::vDevices.back().props, dev.number);
case 1: printf(" - using device %d\n", Gpu::vDevices[0].number);
cudaSetDevice(Gpu::vDevices[0].number);
break;
default:
if (dev_sel > (size_t)dev_max) {
printf(" - requested more GPU devices than available, using %d first ones\n", dev_max);
dev_sel = dev_max;
Gpu::vDevices.resize(dev_sel);
}
printf(" - using %lu devices in parallel:", dev_sel);
for (size_t d = 0 ; d < dev_sel ; d++) {
int n = Gpu::vDevices[d].number;
printf(" %d", n);
if ((n < 0) || (n >= dev_max))
Error("illegal device identifier");
}
printf("\n");
cudaSetDevice(Gpu::vDevices[0].number);
}
// initialize cublas and random generator
cublasInit();
Gpu::CheckError("initialization of card\n");
curandCreateGenerator(&cuda_gen, CURAND_RNG_PSEUDO_DEFAULT);
// curandSetPseudoRandomGeneratorSeed(cuda_gen, CUDA_SEED);
Gpu::CheckError("initialization of random generator\n");
// allocate buffers
gpu_buf = Gpu::Alloc(GPU_BUF_DIM*sizeof(REAL),"internal buffer on GPU");
// locking devices
ofstream lfs;
char lfname[LOCK_FNAME_LEN] = LOCK_FNAME;
for (size_t d = 0 ; d < dev_sel ; d++) {
sprintf(lfname, LOCK_FNAME, getpid(), Gpu::vDevices[d].number);
lfs.open(lfname,ios::out);
CHECK_FILE(lfs, lfname);
lfs << "Runing job " << getpid() << " on GPU " << Gpu::vDevices[d].number << endl;
lfs.close();
}
// catch signals to clean up lock-files
signal(SIGINT , HandlerSigTERM);
signal(SIGHUP , HandlerSigTERM);
signal(SIGFPE , HandlerSigTERM);
signal(SIGSEGV, HandlerSigTERM);
signal(SIGTERM, HandlerSigTERM);
// create default configuration
Gpu::Config& newConfig = Gpu::vConfigs.back();
Gpu::curDevIndex = newConfig.devId = 0;
Gpu::curConfIndex = stId;
newConfig.stream = NULL;
#ifdef GPU_CUBLAS_V2
cublasCreate(&newConfig.cbHandle);
Gpu::curCbHandle = newConfig.cbHandle;
#endif
Gpu::curDevProps = &Gpu::vDevices[0].props;
}
return stId;
}
/**
* removes lock-files and deletes all configurations
*/
void Gpu::Unlock()
{
// remove lock-files
Gpu::curDevIndex = (size_t)-1;
char lfname[LOCK_FNAME_LEN] = LOCK_FNAME;
for (std::vector<Gpu::Device>::iterator id = Gpu::vDevices.begin() ; id != Gpu::vDevices.end() ; id++) {
sprintf(lfname, LOCK_FNAME, getpid(), id->number);
if (unlink(lfname))
cerr << " - ERROR: removing lock file " << lfname << endl;
}
// destroy streams
Gpu::curConfIndex = (size_t)-1;
Gpu::curStream = NULL;
Gpu::useConcurrentStreams = false;
#ifdef GPU_CUBLAS_V2
Gpu::curCbHandle = NULL;
#endif
Gpu::curDevProps = NULL;
Gpu::vDevices.clear();
for (std::vector<Gpu::Config>::iterator igc = Gpu::vConfigs.begin() ; igc != Gpu::vConfigs.end() ; igc++) {
if (NULL != igc->stream)
cudaStreamDestroy(igc->stream);
#ifdef GPU_CUBLAS_V2
if (NULL != igc->cbHandle)
cublasDestroy(igc->cbHandle);
#endif
}
Gpu::vConfigs.clear();
}
/**
* creates a new Gpu stream on next device
* @note selects the next device and the new stream
* @returns new configuration index
*/
size_t Gpu::NewConfig()
{
size_t stId = Gpu::vConfigs.size();
if (0 < stId) {
Gpu::useConcurrentStreams |= (Gpu::vDevices.size() <= (0.8 * (stId + 1)));
Gpu::vConfigs.resize(stId + 1);
Gpu::Config& newConfig = Gpu::vConfigs.back();
newConfig.devId = ((Gpu::curDevIndex + 1) % Gpu::vDevices.size());
newConfig.stream = NULL;
#ifdef GPU_CUBLAS_V2
newConfig.cbHandle = NULL;
#endif
Gpu::ChangeConfig(stId);
return stId;
}
else
return Gpu::Init();
}
/**
* changes current configuration
* @param stCfg index of configuration to use
*/
void Gpu::ChangeConfig(size_t stCfg)
{
Gpu::curConfIndex = stCfg;
Gpu::Config& config = Gpu::vConfigs[Gpu::curConfIndex];
if (Gpu::curDevIndex != config.devId) {
Gpu::curDevIndex = config.devId;
cudaSetDevice(Gpu::vDevices[Gpu::curDevIndex].number);
Gpu::curDevProps = &Gpu::vDevices[Gpu::curDevIndex].props;
}
#ifdef GPU_CUBLAS_V2
if (NULL == config.cbHandle)
cublasCreate(&config.cbHandle);
if (Gpu::useConcurrentStreams && (NULL == config.stream)) {
cudaStreamSynchronize(NULL);
cudaStreamCreate(&config.stream);
cublasSetStream(config.cbHandle, config.stream);
}
if (Gpu::curStream != config.stream) {
Gpu::curStream = config.stream;
nppSetStream(Gpu::curStream);
}
Gpu::curCbHandle = config.cbHandle;
debug4("Gpu::ChangeConfig cfg=%zu dev=%d str=%x cbh=%x\n", Gpu::curConfIndex, Gpu::vDevices[Gpu::curDevIndex].number, Gpu::curStream, Gpu::curCbHandle);
#endif
}
/**
* sets current device with default stream
* @param stDevId device index
*/
void Gpu::SetDevice(size_t stDevId)
{
Gpu::curConfIndex = (size_t)-1;
if (Gpu::curDevIndex != stDevId) {
Gpu::curDevIndex = (stDevId % Gpu::vDevices.size());
cudaSetDevice(Gpu::vDevices[Gpu::curDevIndex].number);
Gpu::curDevProps = &Gpu::vDevices[Gpu::curDevIndex].props;
}
#ifdef GPU_CUBLAS_V2
if (NULL != Gpu::curStream) {
Gpu::curStream = NULL;
nppSetStream(Gpu::curStream);
}
Gpu::curCbHandle = NULL;
#endif
}
/**
* allocates memory on Gpu and checks error
* @param msg message to print in case of error
*/
REAL* Gpu::Alloc(int dim, const char* msg) {
void* gpu_mem;
char err_msg[1024];
sprintf(err_msg, "CUDA: can't allocate memory for %s", msg);
sprintf(err_msg, "CUDA: can't allocate memory (%dMB) for %s", (int)(dim / 1024 / 1024 * sizeof(REAL)), msg);
if (dim > 0) {
cublasAlloc(dim, CUDA_SIZE, &gpu_mem);
#ifdef DEBUG
int dev = -1;
cudaGetDevice(&dev);
debug3("allocated %ld at %p on device %d\n", dim * CUDA_SIZE, gpu_mem, dev);
#endif
Gpu::CheckError(err_msg);
if (NULL == gpu_mem)
Error(err_msg);
return (CUDA*)gpu_mem;
}
else
return NULL;
}
/**
* checks error
* @param msg message to print in case of error
*/
void Gpu::CheckError(const char* msg) {
cudaError_t err = cudaGetLastError();
if (cudaSuccess != err)
ErrorN("CUDA: ERROR %d in %s: %s\n", cublasGetError(), msg, cudaGetErrorString(err));
}
// Corresponds to 2.0*numeric_limits<float>::min()
__device__ REAL GPU_LOG_LOWER_BOUND = 2.35099e-38;
__device__ REAL gpu_safelog(REAL x) { return (x<GPU_LOG_LOWER_BOUND) ? log(GPU_LOG_LOWER_BOUND) : log(x); };
//-----------------------------------------------
// forward pass for MachTab
//-----------------------------------------------
__global__
void KernelMachTabForw(const int bsize, const int odim, REAL *gpu_data_in, REAL *gpu_t, REAL *gpu_data_out)
{
for (int b=blockIdx.x ; b<bsize ; b+=gridDim.x) {
int idx= (int) gpu_data_in[b];
int offso=b*odim;
int offst=idx*odim;
for (int i=threadIdx.x ; i<odim ; i+=blockDim.x) {
if (idx==NULL_WORD) gpu_data_out[i+offso] = 0.0;
else gpu_data_out[i+offso] = gpu_t[i+offst];
}
}
}
void Gpu::MachTabForw(const int bsize, const int odim,
REAL *gpu_data_in, REAL *gpu_t, REAL *gpu_data_out)
{
int n_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], odim);
int n_blocks = std::min(Gpu::curDevProps->maxGridSize[0], bsize);
KernelMachTabForw<<<n_blocks, n_threads, 0, Gpu::curStream>>>(bsize, odim, gpu_data_in, gpu_t, gpu_data_out);
}
//-----------------------------------------------
// backward pass for MachTab
//-----------------------------------------------
__global__
void KernelMachTabBackw(const REAL lrate, const int bsize, const int odim,
REAL *gpu_data_in, REAL *gpu_t, REAL *gpu_grad_out)
{
for (int b=blockIdx.x; b<bsize; b+=gridDim.x) {
for (int i=threadIdx.x; i<odim; i+=blockDim.x) {
int idx = (int) gpu_data_in[b];
// Use atomicAdd instead of += to avoid race conditions between threads
if (idx != NULL_WORD)
atomicAdd(gpu_t+i+idx*odim, lrate * gpu_grad_out[i+b*odim]);
}
}
}
void Gpu::MachTabBackw(const REAL lrate, const int bsize, const int odim,
REAL *gpu_data_in, REAL *gpu_t, REAL *gpu_grad_out)
{
int n_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], odim);
int n_blocks = std::min(Gpu::curDevProps->maxGridSize[0], bsize);
KernelMachTabBackw<<<n_blocks, n_threads, 0, Gpu::curStream>>>(lrate, bsize, odim, gpu_data_in, gpu_t, gpu_grad_out);
}
//-----------------------------------------------
// Softmax normalization
//-----------------------------------------------
__global__ void KernelSoftmax(int M, int N,
const REAL * x, const int sx0, const int sx1,
REAL * sm, const int sm_s0, const int sm_s1)
{
extern __shared__ REAL buf[];
for (int blockIDX = blockIdx.x; blockIDX < M; blockIDX += gridDim.x) {
REAL sum = 0;
#pragma unroll 16
for (int i = threadIdx.x; i< N; i += blockDim.x){
sum += exp(x[blockIDX * sx0 + i * sx1]);
}
buf[threadIdx.x] = sum;
__syncthreads();
// This function trashes buf[1..warpsize], leaving the reduction result in buf[0].
if (threadIdx.x < warpSize){
#pragma unroll 8
for (int i = threadIdx.x + warpSize; i < blockDim.x; i += warpSize){
buf[threadIdx.x] += buf[i];
}
if (threadIdx.x < 16){
//reduce so that threadIdx.x 0 has the sum of everything
if(threadIdx.x + 16 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+16];
if(threadIdx.x + 8 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+8];
if(threadIdx.x + 4 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+4];
if(threadIdx.x + 2 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+2];
if(threadIdx.x + 1 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+1];
}
}
__syncthreads();
REAL row_sum = buf[0];
#pragma unroll 16
for (int i = threadIdx.x; i< N; i += blockDim.x){
sm[blockIDX * sm_s0 + i * sm_s1] = exp(x[blockIDX * sx0 + i * sx1]) / row_sum;
}
__syncthreads();
}
}
void Gpu::MachSoftmaxForw(const int bsize, const int odim, REAL *gpu_data_out)
{
if(0){
//This is the original code that is know to work correctly in all case,
//But is slower.
nppsExp_32f_I(gpu_data_out, bsize*odim);
REAL sum, *optr=gpu_data_out;
for (int b=0; b<bsize; b++,optr+=odim) {
sum=Gpu::CublasSasum(odim,optr,1); // exp(x) is always positive -> we can use the sum_i (ABS(x_i))
nppsMulC_32f_I(1.0/sum,optr,odim);
}
return;
}
//int warpSize = 32;
//The follwing check need to access the GPU properties to do it.
//To don't do this access each time, we have done it in MachSoftmax.cpp
// if(warpSize != 32){
// Error("Gpu::MachSoftmaxForw suppose the warpSize is 32. If run with a GPU with other warpSize"
// " like the current GPU, it will return wrong Results. You must update the reduction in KernelSoftmax");
// }
int n_blocks = std::min(bsize, 32 * 1024);
int n_threads = std::min(odim, 512);
int n_shared_bytes = n_threads * sizeof(REAL);
if (bsize > 0){
KernelSoftmax<<<n_blocks, n_threads, n_shared_bytes, Gpu::curStream>>>(
bsize,
odim,
gpu_data_out,
odim, //x.stride[0
1, //x.stride[1]
gpu_data_out,
odim, //sm.stride[0]
1//sm.stride[1]
);
cudaError_t err = cudaGetLastError();
if(cudaSuccess != err){
printf("KernelSoftmax: n_blockn=%d, n_threads=%d, n_shared_bytes=%d odim=%d\n",
n_blocks, n_threads, n_shared_bytes, odim);
Error(cudaGetErrorString(err));
}
}
}
//-----------------------------------------------
// Softmax stable normalization
//-----------------------------------------------
__global__ void KernelSoftmaxStable(int M, int N,
const REAL * x, const int sx0, const int sx1,
REAL * sm, const int sm_s0, const int sm_s1)
{
extern __shared__ REAL buf[];
for (int blockIDX = blockIdx.x; blockIDX < M; blockIDX += gridDim.x) {
REAL max_ = x[blockIDX * sx0 + threadIdx.x * sx1];
for (int i = threadIdx.x + blockDim.x; i< N; i += blockDim.x) {
max_ = max(max_, x[blockIDX * sx0 + i * sx1]);
};
buf[threadIdx.x] = max_;
__syncthreads();
// This function trashes buf[1..n_threads], leaving the reduction result in buf[0].
// Find the max to stabilize the softmax
if (threadIdx.x < warpSize)
{
for (int i = threadIdx.x + warpSize; i < blockDim.x; i += warpSize) {
buf[threadIdx.x] = max(buf[threadIdx.x], buf[i]);
}
if (threadIdx.x < 16) {
//reduce so that threadIdx.x 0 has the max of everything
if(threadIdx.x + 16 < N)
buf[threadIdx.x] = max(buf[threadIdx.x], buf[threadIdx.x+16]);
if(threadIdx.x + 8 < N)
buf[threadIdx.x] = max(buf[threadIdx.x], buf[threadIdx.x+8]);
if(threadIdx.x + 4 < N)
buf[threadIdx.x] = max(buf[threadIdx.x], buf[threadIdx.x+4]);
if(threadIdx.x + 2 < N)
buf[threadIdx.x] = max(buf[threadIdx.x], buf[threadIdx.x+2]);
if(threadIdx.x + 1 < N)
buf[threadIdx.x] = max(buf[threadIdx.x], buf[threadIdx.x+1]);
}
}
__syncthreads();
REAL row_max = buf[0];
__syncthreads();
REAL sum = 0;
for(int i=threadIdx.x; i<N; i+=blockDim.x){
sum += exp(x[blockIDX * sx0 + i * sx1] - row_max);
};
buf[threadIdx.x] = sum;
__syncthreads();
// This function trashes buf[1..N], leaving the reduction result in buf[0].
if (threadIdx.x < warpSize){
for (int i = threadIdx.x + warpSize; i < blockDim.x; i += warpSize){
buf[threadIdx.x] += buf[i];
}
if (threadIdx.x < 16){
//reduce so that threadIdx.x 0 has the sum of everything
if(threadIdx.x + 16 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+16];
if(threadIdx.x + 8 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+8];
if(threadIdx.x + 4 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+4];
if(threadIdx.x + 2 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+2];
if(threadIdx.x + 1 < N)
buf[threadIdx.x] = buf[threadIdx.x] + buf[threadIdx.x+1];
}
}
__syncthreads();
REAL row_sum = buf[0];
for (int i = threadIdx.x; i< N; i += blockDim.x){
sm[blockIDX * sm_s0 + i * sm_s1] = exp(x[blockIDX * sx0 + i * sx1] - row_max) / row_sum;
}
__syncthreads();
}
}
void Gpu::MachSoftmaxStableForw(const int bsize, const int odim, REAL *gpu_data_out)
{
if(0){
Error("Not implemented!");
//This is the original code that is know to work correctly in all case,
//But is slower.
nppsExp_32f_I(gpu_data_out, bsize*odim);
REAL sum, *optr=gpu_data_out;
for (int b=0; b<bsize; b++,optr+=odim) {
sum=Gpu::CublasSasum(odim,optr,1); // exp(x) is always positive -> we can use the sum_i (ABS(x_i))
nppsMulC_32f_I(1.0/sum,optr,odim);
}
return;
}
//int warpSize = 32;
//The follwing check need to access the GPU properties to do it.
//To don't do this access each time, we have done it in MachSoftmaxStable.cpp
// if(warpSize != 32){
// Error("Gpu::MachSoftmaxStableForw suppose the warpSize is 32. If run with a GPU with other warpSize"
// " like the current GPU, it will return wrong Results. You must update the reduction in KernelSoftmaxStable");
// }
int n_blocks = std::min(bsize, 32 * 1024);
int n_threads = std::min(odim, 512);
int n_shared_bytes = n_threads * sizeof(REAL);
if (bsize > 0){
KernelSoftmaxStable<<<n_blocks, n_threads, n_shared_bytes, Gpu::curStream>>>(
bsize,
odim,
gpu_data_out,
odim, //x.stride[0]
1, //x.stride[1]
gpu_data_out,
odim, //sm.stride[0]
1//sm.stride[1]
);
cudaError_t err = cudaGetLastError();
if(cudaSuccess != err){
printf("n_blocks=%d, n_threads=%d, n_shared_bytes=%d odim=%d\n",
n_blocks, n_threads, n_shared_bytes, odim);
Error(cudaGetErrorString(err));
}
}
}
//-----------------------------------------------
// Linear Rectifier units
//-----------------------------------------------
__global__
void KernelLinRectifForw(const int n, REAL *gpu_data_out)
{
int tx = threadIdx.x;
int bx = blockIdx.x;
int n_threads = blockDim.x * gridDim.x;
int id = tx * blockDim.x + bx * gridDim.x;
for(int i = id; i < n; i += n_threads){
if (gpu_data_out[i]<0) gpu_data_out[i]=0;
}
}
void Gpu::LinRectifForw(const int n, REAL *gpu_data_out)
{
int nb_thread = std::min(n, 256);
int nb_block = n / 256;
KernelLinRectifForw<<<nb_block, nb_thread, 0, Gpu::curStream>>>(n, gpu_data_out);
}
__global__
void KernelLinRectifBackw(const int n, REAL *gpu_data_out, REAL *gpu_grad_out)
{
int tx = threadIdx.x;
int bx = blockIdx.x;
int n_threads = blockDim.x * gridDim.x;
int id = tx * blockDim.x + bx * gridDim.x;
for(int i = id; i < n; i += n_threads){
if (gpu_data_out[i]<0) gpu_grad_out[i]=0; else gpu_grad_out[i]=1;
}
}
void Gpu::LinRectifBackw(const int n, REAL *gpu_data_out, REAL *gpu_grad_out)
{
int nb_thread = std::min(n, 256);
int nb_block = n / 256;
KernelLinRectifBackw<<<nb_block, nb_thread, 0, Gpu::curStream>>>(n, gpu_data_out, gpu_grad_out);
}
//-----------------------------------------------
// Helper functions for drop-out
//-----------------------------------------------
__global__
void KernelDropOut(const int n, REAL *gpu_vect, REAL *rand, REAL thresh)
{
int tx = threadIdx.x;
int bx = blockIdx.x;
int n_threads = blockDim.x * gridDim.x;
int id = tx * blockDim.x + bx * gridDim.x;
for (int i = id; i < n; i += n_threads) {
if (rand[i]<thresh) gpu_vect[i]=0.0;
}
}
void Gpu::DropOut(const int n, REAL *gpu_vect, REAL *rand, REAL thresh)
{
int nb_thread = std::min(n, 256);
int nb_block = n / 256;
KernelDropOut<<<nb_block, nb_thread, 0, Gpu::curStream>>>(n, gpu_vect, rand, thresh);
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcValue
//-----------------------------------------------
__global__
void KernelErrFctSoftmCrossEntNgramCalcValue(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target,
REAL *gpu_res)
{
extern __shared__ REAL buf[];
REAL err=0.0;
for (int b=threadIdx.x ; b<bsize ; b+=blockDim.x)
err += gpu_safelog(gpu_data_out[b*odim + (uint) gpu_target[b]]);
buf[threadIdx.x] = err;
__syncthreads();
if(threadIdx.x == 0) {
for(int i=1 ; i<blockDim.x ; i++)
err += buf[i];
atomicAdd(gpu_res, err);
}
}
REAL Gpu::ErrFctSoftmCrossEntNgramCalcValue(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target)
{
REAL res;
if (gpu_result==NULL) cudaMalloc(&gpu_result,sizeof(REAL));
cudaMemsetAsync(gpu_result, 0.0, sizeof(REAL), Gpu::curStream); //Each thread will atomicAdd into it.
int n_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], bsize);
KernelErrFctSoftmCrossEntNgramCalcValue<<<1, n_threads, n_threads*sizeof(REAL), Gpu::curStream>>>(bsize, odim, gpu_data_out, gpu_target, gpu_result);
cudaMemcpyAsync(&res, gpu_result, sizeof(REAL), cudaMemcpyDeviceToHost, Gpu::curStream);
cudaStreamSynchronize(Gpu::curStream);
return res;
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcValueNull
//-----------------------------------------------
__global__
void KernelErrFctSoftmCrossEntNgramCalcValueNull(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target,
REAL *gpu_res)
{
extern __shared__ REAL buf[];
REAL err=0.0;
for (int b=threadIdx.x ; b<bsize ; b+=blockDim.x) {
int tidx = gpu_target[b]; // do not cast to uint ! Otherwise, nvcc will transform the -1 to 0!
if (tidx != NULL_WORD) err += gpu_safelog(gpu_data_out[b*odim + tidx]);
}
buf[threadIdx.x] = err;
__syncthreads();
if(threadIdx.x == 0) {
for(int i=1 ; i<blockDim.x ; i++)
err += buf[i];
atomicAdd(gpu_res, err);
}
}
REAL Gpu::ErrFctSoftmCrossEntNgramCalcValueNull(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target)
{
REAL res;
if (gpu_result==NULL) cudaMalloc(&gpu_result,sizeof(REAL));
cudaMemsetAsync(gpu_result, 0.0, sizeof(REAL), Gpu::curStream); //Each thread will atomicAdd into it.
int n_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], bsize);
KernelErrFctSoftmCrossEntNgramCalcValueNull<<<1, n_threads, n_threads*sizeof(REAL), Gpu::curStream>>>(bsize, odim, gpu_data_out, gpu_target, gpu_result);
cudaMemcpyAsync(&res, gpu_result, sizeof(REAL), cudaMemcpyDeviceToHost, Gpu::curStream);
cudaStreamSynchronize(Gpu::curStream);
return res;
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcValueBatch
//-----------------------------------------------
__global__
void KernelErrFctSoftmCrossEntNgramCalcValueBatch(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target, REAL *tmp_buf)
{
//extern __shared__ REAL buf[];
for (int b=threadIdx.x ; b<bsize ; b+=blockDim.x) {
int tidx = gpu_target[b]; // do not cast to uint ! Otherwise, nvcc will transform the -1 to 0!
if (tidx== NULL_WORD)
tmp_buf[b] = LOG_PROBA_NONE; // handle NULL_WORD
else
tmp_buf[b] = gpu_safelog(gpu_data_out[b*odim + tidx]);
}
}
void Gpu::ErrFctSoftmCrossEntNgramCalcValueBatch(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_target, REAL *res_vect)
{
if (odim > GPU_BUF_DIM)
Error("Gpu::ErrFctSoftmCrossEntNgramCalcValueBatch(): odim (%d) is larger than internal buffer (%d)"); //,odim,GPU_BUF_DIM);
int n_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], bsize);
KernelErrFctSoftmCrossEntNgramCalcValueBatch<<<1, n_threads, 0, Gpu::curStream>>>(bsize, odim, gpu_data_out, gpu_target, gpu_buf);
cudaMemcpyAsync(res_vect, gpu_buf, bsize*sizeof(REAL), cudaMemcpyDeviceToHost, Gpu::curStream);
cudaStreamSynchronize(Gpu::curStream);
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcMax
//-----------------------------------------------
void Gpu::ErrFctSoftmCrossEntNgramCalcMax(const int eff_bsize, const int dim, REAL *output, REAL *target, REAL *res, int *pos)
{
Error("TODO: Gpu::ErrFctSoftmCrossEntNgramCalcMax()");
}
#if 0 // not used anymore, use CalcvalueBatch() instead
__global__
void KernelErrFctSoftmCrossEntNgramCalcValueNth(const int idx, const int odim, REAL *gpu_data_out, REAL *gpu_target, REAL *gpu_res)
{
int tidx = (int) gpu_target[idx]; // do not cast to uint ! Otherwise, nvcc will transform the -1 to 0!
if (tdx<0) // NULL_WORD
*gpu_res=-1;
else
*gpu_res = gpu_safelog(gpu_data_out[idx*odim + tidx]);
}
REAL Gpu::ErrFctSoftmCrossEntNgramCalcValueNth(const int idx, const int odim, REAL *gpu_data_out, REAL *gpu_target)
{
REAL res;
if (gpu_result==NULL) cudaMalloc(&gpu_result,sizeof(REAL));
KernelErrFctSoftmCrossEntNgramCalcValueNth<<<1, 1, 1*sizeof(REAL), Gpu::curStream>>>(idx, odim, gpu_data_out, gpu_target, gpu_result);
cudaMemcpyAsync(&res, gpu_result, sizeof(REAL), cudaMemcpyDeviceToHost, Gpu::curStream);
cudaStreamSynchronize(Gpu::curStream);
return res;
#endif
//-----------------------------------------------
// ErrFctSoftmClassCrossEntNgram::CalcWordClassError
//-----------------------------------------------
__global__
void KernelErrFctSoftmClassError(const int bsize, const int n_classes, REAL *gpu_class_out, REAL *gpu_class_target,
REAL *gpu_res)
{
int class_err=0;
REAL *ocptr=gpu_class_out;
REAL *tcptr=gpu_class_target;
for (int b=0; b<bsize; b++) {
REAL max_oclass = ocptr[0];
int argmax = 0;
for (int i=1; i<n_classes; i++) {
REAL oclass_i = ocptr[i];
if (oclass_i > max_oclass) {
argmax = i;
max_oclass = oclass_i;
}
}
if ((int) *tcptr != argmax)
class_err++;
ocptr += n_classes;
tcptr++;
}
*gpu_res = (REAL) class_err;
}
__global__ void KernelErrFctSoftmClassError2(const int bsize, const int n_classes,
REAL *gpu_class_out, REAL *gpu_class_target, REAL *gpu_res)
{
extern __shared__ REAL buf[];
buf[threadIdx.x] = 0;
for (int i = threadIdx.x; i < bsize; i += blockDim.x) {
int argmax = 0;
REAL max_oclass = gpu_class_out[i*n_classes];
for (int j = 1; j < n_classes; j++) {
REAL oclass_j = gpu_class_out[i*n_classes + j];
if (oclass_j > max_oclass) {
argmax = j;
max_oclass = oclass_j;
}
}
if ((int) gpu_class_target[i] != argmax)
buf[threadIdx.x] += 1;
}
__syncthreads();
// Reduce sum into buf[0]
if (threadIdx.x < warpSize) {
for (int i = threadIdx.x + warpSize; i < blockDim.x; i += warpSize) {
buf[threadIdx.x] += buf[i];
}
if (threadIdx.x < 16) {
if (threadIdx.x + 16 < n_classes)
buf[threadIdx.x] += buf[threadIdx.x + 16];
if (threadIdx.x + 8 < n_classes)
buf[threadIdx.x] += buf[threadIdx.x + 8];
if (threadIdx.x + 4 < n_classes)
buf[threadIdx.x] += buf[threadIdx.x + 4];
if (threadIdx.x + 2 < n_classes)
buf[threadIdx.x] += buf[threadIdx.x + 2];
if (threadIdx.x + 1 < n_classes)
buf[threadIdx.x] += buf[threadIdx.x + 1];
}
}
if (threadIdx.x == 0)
*gpu_res = buf[0];
}
REAL Gpu::ErrFctSoftmClassError(const int bsize, const int n_classes, REAL *gpu_class_out, REAL *gpu_class_target)
{
REAL res;
if (gpu_result==NULL) cudaMalloc(&gpu_result,sizeof(REAL));
int n_threads = std::min(bsize, 512);
int n_blocks = bsize / n_threads + ((bsize % n_threads) ? 1 : 0);
int n_shared_bytes = n_threads * sizeof(REAL);
KernelErrFctSoftmClassError2<<<n_blocks, n_threads, n_shared_bytes, Gpu::curStream>>>(
bsize, n_classes, gpu_class_out, gpu_class_target, gpu_result);
cudaMemcpyAsync(&res, gpu_result, sizeof(REAL), cudaMemcpyDeviceToHost, Gpu::curStream);
cudaStreamSynchronize(Gpu::curStream);
return res;
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcGrad
//-----------------------------------------------
/**
* @note This kernel need many block to compute the grad but also need to do a reduction.
* The first block will do the reduction and compute the grad associated with it
* and all the other will compute the grad for other words.
*/
__global__
void KernelErrFctSoftmCrossEntNgramCalcGrad(const int bsize, const int odim, REAL *gpu_data_out, REAL *gpu_grad, REAL *gpu_target,
REAL *gpu_res)
{
if (blockIdx.x == 0) {
// the first block computes the error and grad for used words
extern __shared__ REAL buf[];
REAL err=0.0;
for (int b=threadIdx.x; b<bsize; b+=blockDim.x) {
unsigned int tidx=(uint) gpu_target[b];
gpu_grad[b*odim + tidx] = (1.0f - gpu_grad[b*odim + tidx]);
err += gpu_safelog(gpu_data_out[b*odim + tidx]);
}
buf[threadIdx.x] = err;
__syncthreads();
if (threadIdx.x == 0) {
for (int i=1; i<blockDim.x; i++)
err += buf[i];
*gpu_res=err;
}
}
else
// the next blocks computes the grad for all other words
for (int b=blockIdx.x-1; b<bsize; b+=gridDim.x-1) {
unsigned int tidx=(uint) gpu_target[b];
for (int i=threadIdx.x; i<odim; i+=blockDim.x)
if (tidx != (uint)i)
gpu_grad[b*odim + i] *= -1.0f;
}
}
void Gpu::ErrFctSoftmCrossEntNgramCalcGrad(const int bsize, const int odim, REAL *gpu_data_out,
REAL *gpu_grad, REAL *gpu_target, REAL * gpu_res)
{
cudaMemcpyAsync(gpu_grad, gpu_data_out, bsize*odim*sizeof(REAL), cudaMemcpyDeviceToDevice, Gpu::curStream);
int nb_blocks = std::min(Gpu::curDevProps->maxGridSize[0], bsize + 1);
int nb_threads = std::min(Gpu::curDevProps->maxThreadsDim[0], bsize);
int n_shared_bytes = nb_threads * sizeof(REAL);
KernelErrFctSoftmCrossEntNgramCalcGrad<<<nb_blocks, nb_threads, n_shared_bytes, Gpu::curStream>>>(
bsize, odim, gpu_data_out, gpu_grad, gpu_target, gpu_res);
cudaError_t err = cudaGetLastError();
if(cudaSuccess != err){
ErrorN("Error in Gpu::ErrFctSoftmCrossEntNgramCalcGrad: %s", cudaGetErrorString(err));
}
}
//-----------------------------------------------
// ErrFctSoftmCrossEntNgram::CalcGradNull
//-----------------------------------------------
/**
* @note This kernel need many block to compute the grad but also need to do a reduction.
* The first block will do the reduction and compute the grad associated with it
* and all the other will compute the grad for other words.
*/
__global__
void KernelErrFctSoftmCrossEntNgramCalcGradNull(const int bsize, const int odim,
REAL *gpu_data_out, REAL *gpu_grad, REAL *gpu_target,
REAL *gpu_res)
{
if (blockIdx.x == 0) {
// the first block computes the error and grad for non NULL words
extern __shared__ REAL buf[];
REAL err=0.0;
for (int b=threadIdx.x; b<bsize; b+=blockDim.x) {
//Do not cast or use unsigned for tidx. Otherwise, nvcc will transform the -1 to 0!
//This is a difference compared to the GPU!
int tidx = gpu_target[b];
debug5(" -batch=%d target=%d -> output at %p is %f, update grad at %p\n", b, tidx, &(gpu_data_out[b*odim + tidx]), gpu_data_out[b*odim + tidx], &(gpu_grad[b*odim+tidx]));
if (tidx != NULL_WORD) {
gpu_grad[b*odim + tidx] = (1.0f - gpu_grad[b*odim + tidx]);
err += gpu_safelog(gpu_data_out[b*odim + tidx]);
}
}
buf[threadIdx.x] = err;
__syncthreads();
if (threadIdx.x == 0) {
for (int i=1; i<blockDim.x; i++)
err += buf[i];
*gpu_res=err;
}
}
else