forked from kaldi-asr/kaldi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cu-vector.cc
1355 lines (1217 loc) · 40.4 KB
/
cu-vector.cc
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
// cudamatrix/cu-vector.cc
// Copyright 2012-2013 Karel Vesely
// 2012-2014 Johns Hopkins University (author: Daniel Povey)
// 2017 Daniel Galvez
// 2016-2018 Shiyin Kang
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#if HAVE_CUDA == 1
#include <cuda_runtime_api.h>
#include <cublas_v2.h>
#endif
#include "base/timer.h"
#include "cudamatrix/cu-common.h"
#include "cudamatrix/cu-vector.h"
#include "cudamatrix/cu-device.h"
#include "cudamatrix/cu-kernels.h"
#include "cudamatrix/cu-math.h"
#include "cudamatrix/cu-vector.h"
#include "cudamatrix/cu-matrix.h"
#include "cudamatrix/cu-rand.h"
#include "cudamatrix/cu-tp-matrix.h"
#include "cudamatrix/cu-sp-matrix.h"
#include "cudamatrix/cu-sparse-matrix.h"
#include "cudamatrix/cublas-wrappers.h"
namespace kaldi {
template<typename Real>
Real VecVec(const CuVectorBase<Real> &a,
const CuVectorBase<Real> &b) {
//MatrixIndexT a_dim = a.Dim();
KALDI_ASSERT(a.Dim() == b.Dim());
Real result = 0;
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
CUBLAS_SAFE_CALL(cublas_dot(GetCublasHandle(), a.Dim(), a.Data(), 1, b.Data(),
1, &result));
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
result = VecVec(a.Vec(), b.Vec());
}
return result;
}
// instantiate the template above
template float VecVec(const CuVectorBase<float> &a, const CuVectorBase<float> &b);
template double VecVec(const CuVectorBase<double> &a, const CuVectorBase<double> &b);
// The version of VecVec that can do type conversion. For now we give this a
// stupid implementation that converts one of the vectors. If it ever becomes
// an efficiency bottleneck, we can revisit this.
template<typename Real, typename OtherReal>
Real VecVec(const CuVectorBase<Real> &A, const CuVectorBase<OtherReal> &B) {
CuVector<Real> B2(B);
return VecVec(A, B2); // This will call the single-parameter template.
}
// instantiate the template above
template float VecVec(const CuVectorBase<float> &A, const CuVectorBase<double> &B);
template double VecVec(const CuVectorBase<double> &A, const CuVectorBase<float> &B);
template<typename Real>
Real VecMatVec(const CuVectorBase<Real> &v1, const CuMatrixBase<Real> &M,
const CuVectorBase<Real> &v2) {
KALDI_ASSERT(v1.Dim() == M.NumRows() && M.NumCols() == v2.Dim());
if (v1.Dim() > v2.Dim()) { // do v2*M first
CuVector<Real> v2M(v1.Dim());
v2M.AddMatVec(1.0, M, kNoTrans, v2, 0.0);
return VecVec(v2M, v1);
} else { // do v1*M first
CuVector<Real> v1M(v2.Dim());
v1M.AddMatVec(1.0, M, kTrans, v1, 0.0);
return VecVec(v1M, v2);
}
}
// instantiate the template above
template float VecMatVec(const CuVectorBase<float> &v1, const CuMatrixBase<float> &M,
const CuVectorBase<float> &v2);
template double VecMatVec(const CuVectorBase<double> &v1, const CuMatrixBase<double> &M,
const CuVectorBase<double> &v2);
template<typename Real>
void CuVectorBase<Real>::CopyColFromMat(const CuMatrixBase<Real> &mat, MatrixIndexT col) {
KALDI_ASSERT(col < mat.NumCols());
KALDI_ASSERT(dim_ == mat.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
cublas_copy(GetCublasHandle(),
this->dim_, mat.Data() + col, mat.Stride(), this->data_, 1);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::CopyColFromMat", tim);
} else
#endif
{
Vec().CopyColFromMat(mat.Mat(),col);
}
}
template<>
template<>
void CuVectorBase<double>::CopyColFromMat(const CuMatrixBase<float> &mat, MatrixIndexT col) {
KALDI_ASSERT(col < mat.NumCols());
KALDI_ASSERT(dim_ == mat.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
cuda_copy_col_from_mat_df(dimGrid, dimBlock, data_, col, mat.Data(), mat.Dim(), dim_);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::CopyColFromMat", tim);
} else
#endif
{
Vec().CopyColFromMat(mat.Mat(), col);
}
}
template<>
template<>
void CuVectorBase<float>::CopyColFromMat(const CuMatrixBase<double> &mat, MatrixIndexT col) {
KALDI_ASSERT(col < mat.NumCols());
KALDI_ASSERT(dim_ == mat.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
cuda_copy_col_from_mat_fd(dimGrid, dimBlock, data_, col, mat.Data(), mat.Dim(), dim_);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::CopyColFromMat", tim);
} else
#endif
{
Vec().CopyColFromMat(mat.Mat(), col);
}
}
template<typename Real>
void CuVectorBase<Real>::CopyRowsFromMat(const CuMatrixBase<Real> &mat) {
KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
if (mat.Stride() == mat.NumCols() && mat.NumRows() != 0) {
CU_SAFE_CALL(
cudaMemcpyAsync(data_, mat.Data(), sizeof(Real)*dim_,
cudaMemcpyDeviceToDevice, cudaStreamPerThread));
} else {
Real* vec_data = data_;
for (MatrixIndexT r = 0; r < mat.NumRows(); r++) {
CU_SAFE_CALL(cudaMemcpyAsync(vec_data, mat.RowData(r),
sizeof(Real) * mat.NumCols(),
cudaMemcpyDeviceToDevice,
cudaStreamPerThread));
vec_data += mat.NumCols();
}
}
CuDevice::Instantiate().AccuProfile("CuVectorBase::CopyRowsFromMat", tim);
} else
#endif
{
Vec().CopyRowsFromMat(mat.Mat());
}
}
template<typename Real>
Real CuVectorBase<Real>::Norm(Real p) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
Real ans;
KALDI_ASSERT(p == 1.0 || p == 2.0);
if (dim_ == 0) return 0.0;
if (p == 1.0) {
cublas_asum(GetCublasHandle(), dim_, data_, 1, &ans);
} else {
cublas_nrm2(GetCublasHandle(), dim_, data_, 1, &ans);
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
if (ans != ans) {
KALDI_ERR << "NaN in norm " << *this;
}
return ans;
} else
#endif
{
return Vec().Norm(p);
}
}
template<typename Real>
void CuVectorBase<Real>::CopyRowsFromMat(const MatrixBase<Real> &mat) {
KALDI_ASSERT(dim_ == mat.NumCols() * mat.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
if (mat.Stride() == mat.NumCols()) {
CU_SAFE_CALL(cudaMemcpy(data_, mat.Data(), sizeof(Real)*dim_,
cudaMemcpyHostToDevice));
} else {
Real* vec_data = data_;
for (MatrixIndexT r = 0; r < mat.NumRows(); r++) {
CU_SAFE_CALL(cudaMemcpy(vec_data, mat.RowData(r),
sizeof(Real) * mat.NumCols(),
cudaMemcpyHostToDevice));
vec_data += mat.NumCols();
}
}
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().CopyRowsFromMat(mat);
}
}
template<typename Real>
void MatrixBase<Real>::CopyRowsFromVec(const CuVectorBase<Real> &v) {
KALDI_ASSERT(v.Dim() == NumCols() * NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (num_rows_ == 0) return;
CuTimer tim;
if (Stride() == NumCols()) {
CU_SAFE_CALL(cudaMemcpy(data_, v.Data(),
sizeof(Real)*v.Dim(),
cudaMemcpyDeviceToHost));
} else {
const Real* vec_data = v.Data();
for (MatrixIndexT r = 0; r < NumRows(); r++) {
CU_SAFE_CALL(cudaMemcpy(RowData(r), vec_data,
sizeof(Real) * NumCols(),
cudaMemcpyDeviceToHost));
vec_data += NumCols();
}
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
CopyRowsFromVec(v.Vec());
}
}
// instantiate the template above.
template void MatrixBase<float>::CopyRowsFromVec(const CuVectorBase<float> &v);
template void MatrixBase<double>::CopyRowsFromVec(const CuVectorBase<double> &v);
template<typename Real>
void CuVectorBase<Real>::SetRandn() {
if (dim_ == 0) return;
CuRand<Real> tmp;
tmp.RandGaussian(this);
}
template<typename Real>
void CuVectorBase<Real>::SetRandUniform() {
if (dim_ == 0) return;
CuRand<Real> tmp;
tmp.RandUniform(this);
}
template<typename Real>
Real CuVectorBase<Real>::Sum() const {
if (dim_ == 0)
return 0.0;
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
Real result;
CuTimer tim;
// Small vectors are copied to RAM and reduced on CPU.
// The length is chosen by cu-vector-speed-test
if (dim_ < 4096) {
Vector<Real> ans_cpu(*this);
result = ans_cpu.Sum();
} else {
// Use no more than 256 blocks (still too many?)
int dimBlock = CU1DBLOCK;
int dimGrid = n_blocks(dim_, dimBlock);
if (dimGrid > 256) {
dimGrid = 256;
}
CuVector<Real> ans(dimGrid, kUndefined);
cuda_vec_sum(dimGrid, dimBlock, data_, ans.Data(), dim_, 1);
CU_SAFE_CALL(cudaGetLastError());
Vector<Real> ans_cpu(ans);
result = ans_cpu.Sum();
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
return result;
} else
#endif
{
return Vec().Sum();
}
}
template<typename Real>
void CuVectorBase<Real>::ApplySoftMax() {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
size_t dimBlock = CU1DBLOCK;
size_t dimGrid = 1; // dimGrid value represent the number of rows
::MatrixDim dim = { 1, this->dim_, this->dim_};
cuda_softmax_reduce(dimGrid, dimBlock, data_, data_, dim, this->dim_);//actually dim is not stride...
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().ApplySoftMax();
}
}
template<typename Real>
void CuVectorBase<Real>::ApplyFloor(Real floor_val, MatrixIndexT *floored_count) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
if (floored_count == nullptr) {
if (dim_ == 0) return;
CuTimer tim;
// We are calling a function meant for matrices, by viewing the
// vector as a matrix with a single row.
::MatrixDim dim = {1, Dim(), 1};
cuda_apply_floor(dimGrid, dimBlock, data_, floor_val, dim);
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyFloorNoCount", tim);
} else {
if (dim_ == 0) { *floored_count = 0; return; }
CuTimer tim;
CuVector<float> count_vec(dim_, kUndefined);
cuda_vec_apply_floor(dimGrid, dimBlock, data_, floor_val, count_vec.Data(), dim_);
CU_SAFE_CALL(cudaGetLastError());
*floored_count = count_vec.Sum();
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyFloor", tim);
}
} else
#endif
{
Vec().ApplyFloor(floor_val, floored_count);
}
}
template<typename Real>
void CuVectorBase<Real>::ApplyCeiling(Real ceiling_val, MatrixIndexT *ceiled_count) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
if (ceiled_count == nullptr) {
if (dim_ == 0) return;
CuTimer tim;
// We are calling a function meant for matrices, by viewing the
// vector as a matrix with a single row.
::MatrixDim dim = {1, Dim(), 1};
cuda_apply_ceiling(dimGrid, dimBlock, data_, ceiling_val, dim);
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyCeilingNoCount", tim);
} else {
if (dim_ == 0) { *ceiled_count = 0; return; }
CuTimer tim;
CuVector<float> count_vec(dim_, kUndefined);
cuda_vec_apply_ceiling(dimGrid, dimBlock, data_, ceiling_val, count_vec.Data(), dim_);
CU_SAFE_CALL(cudaGetLastError());
*ceiled_count = count_vec.Sum();
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyCeiling", tim);
}
} else
#endif
{
Vec().ApplyCeiling(ceiling_val, ceiled_count);
}
}
template<typename Real>
void CuVectorBase<Real>::ApplyPow(Real power) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
// for this particular kernel, x is #rows, y is #cols. so
// fake matrix with 1 row, Dim() cols.
dim3 dimBlock(CU1DBLOCK, 1);
dim3 dimGrid(n_blocks(Dim(), CU1DBLOCK), 1);
::MatrixDim fake_matrix_dim = { 1, Dim(), 1 };
// num_cols is Dim(), num_rows is 1, stride is 1 (it's a don't-care).
cuda_apply_pow(dimGrid, dimBlock, data_, power, fake_matrix_dim);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyPow", tim);
} else
#endif
{
Vec().ApplyPow(power);
}
}
template<typename Real>
void CuVectorBase<Real>::ApplyExp() {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
cuda_vec_apply_exp(dimGrid, dimBlock, data_, dim_);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyExp", tim);
} else
#endif
{
Vec().ApplyExp();
}
}
template<typename Real>
void CuVectorBase<Real>::ApplyLog() {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
CuVector<Real> flag(1);
cuda_vec_apply_log(dimGrid, dimBlock, data_, flag.Data(), dim_);
CU_SAFE_CALL(cudaGetLastError());
if (flag(0) > 0)
KALDI_ERR << "Trying to take log of a negative number.";
CuDevice::Instantiate().AccuProfile("CuVectorBase::ApplyLog", tim);
} else
#endif
{
Vec().ApplyLog();
}
}
template<typename Real>
void CuVectorBase<Real>::AddMatVec(const Real alpha,
const CuMatrixBase<Real> &M,
MatrixTransposeType trans,
const CuVectorBase<Real> &v,
const Real beta) {
KALDI_ASSERT((trans == kNoTrans && M.NumCols() == v.dim_ && M.NumRows() == dim_) ||
(trans == kTrans && M.NumRows() == v.dim_ && M.NumCols() == dim_));
KALDI_ASSERT(&v != this);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
// Everything is backwards in CuBlas. We need to reverse rows, columns,
// transpose-ness.
CUBLAS_SAFE_CALL(cublas_gemv(GetCublasHandle(),
(trans==kTrans? CUBLAS_OP_N:CUBLAS_OP_T),
M.NumCols(), M.NumRows(), alpha, M.Data(),
M.Stride(), v.Data(), 1, beta, data_, 1));
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().AddMatVec(alpha,M.Mat(),trans,v.Vec(),beta);
}
}
template<typename Real>
void CuVectorBase<Real>::AddSpVec(const Real alpha,
const CuSpMatrix<Real> &M,
const CuVectorBase<Real> &v,
const Real beta) {
KALDI_ASSERT(M.NumCols() == v.dim_ && M.NumRows() == dim_);
KALDI_ASSERT(&v != this);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
// Note: in our opinion the CuSpMatrix represents a lower-triangular matrix, but
// in CUBLAS, for some stupid reason, everything is reversed.
CUBLAS_SAFE_CALL(cublas_spmv(GetCublasHandle(), CUBLAS_FILL_MODE_UPPER, Dim(),
alpha, M.Data(), v.Data(), 1, beta, data_, 1));
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().AddSpVec(alpha,M.Mat(),v.Vec(),beta);
}
}
template<typename Real>
void CuVectorBase<Real>::AddVecVec(Real alpha, const CuVectorBase<Real> &v,
const CuVectorBase<Real> &r, Real beta) {
KALDI_ASSERT((dim_ == v.dim_ && dim_ == r.dim_));
KALDI_ASSERT(this != &v && this != &r);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_,CU1DBLOCK));
cuda_add_vec_vec(dimGrid, dimBlock, alpha, data_, v.Data(), r.Data(), beta, dim_);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::AddVecVec", tim);
} else
#endif
{
Vec().AddVecVec(alpha, v.Vec(), r.Vec(), beta);
}
}
template<typename Real>
bool CuVectorBase<Real>::ApproxEqual(const CuVectorBase<Real> &other, float tol) const {
if (dim_ != other.dim_) KALDI_ERR << "ApproxEqual: size mismatch "
<< dim_ << " vs. " << other.dim_;
KALDI_ASSERT(tol >= 0.0);
CuVector<Real> tmp(*this);
tmp.AddVec(-1.0, other);
BaseFloat tmp_norm = sqrt(VecVec(tmp, tmp)), this_norm = sqrt(VecVec(*this, *this));
return tmp_norm <= static_cast<Real>(tol) * this_norm;
}
template<typename Real>
void CuVectorBase<Real>::AddDiagMat2(Real alpha, const CuMatrixBase<Real> &M,
MatrixTransposeType trans, Real beta) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
MatrixTransposeType other_trans = (trans == kTrans ? kNoTrans : kTrans);
KALDI_ASSERT(dim_ == (trans == kNoTrans ? M.NumRows() : M.NumCols()));
this->AddDiagMatMat(alpha, M, trans, M, other_trans, beta);
} else
#endif
{
Vec().AddDiagMat2(alpha, M.Mat(), trans, beta);
}
}
template<typename Real>
void CuVectorBase<Real>::AddDiagMatMat(Real alpha, const CuMatrixBase<Real> &M,
MatrixTransposeType transM,
const CuMatrixBase<Real> &N,
MatrixTransposeType transN, Real beta) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
if (transM != transN) {
KALDI_ASSERT(M.NumCols() == N.NumCols());
KALDI_ASSERT(M.NumRows() == N.NumRows());
if (transM == kNoTrans) {
// Case 1: diag(M*N') == sum(M.*N, 2)
// 1D grid and 1D block. One block per row of N.
// 1D grid expands along the column of N.
int dimBlock(CU1DBLOCK);
int dimGrid(M.NumRows());
cuda_add_diag_mat_mat_MNT(dimGrid, dimBlock, alpha, M.Data(), M.Dim(),
N.Data(), N.Stride(), beta, data_);
} else {
// Case 2: diag(M'*N) == sum(M.*N, 1)
// 16x16 or 8x32 2D block for coalesced memory access.
// Grid shape is designed as follows,
// 1. for small matrices, use 1D grid with only 1 row of 16x16 block,
// to avoid multiple kernel launch;
// 2. for large enough matrices (no matter thin or fat),
// use 1- or 2-D grid so that the grid contains
// at least and not much larger than 'kOptNumBlocks' blocks
// to fully utilize the GPU;
const int32 warpSize = 32;
const int32 kOptNumBlocks = 512;
const int32 tile_dim =
(N.NumRows() < 4096 && N.NumCols() < kOptNumBlocks * warpSize) ?
16 : 32;
dim3 dimBlock(tile_dim, CU1DBLOCK / tile_dim);
dim3 dimGrid(n_blocks(N.NumCols(), dimBlock.x),
n_blocks(N.NumRows(), dimBlock.y));
dimGrid.y = std::min(dimGrid.y, (kOptNumBlocks - 1) / dimGrid.x + 1);
dimGrid.y = tile_dim == 16 ? 1 : dimGrid.y;
if (dimGrid.y > 1) {
CuMatrix<Real> buf(dimGrid.y, N.NumCols());
cuda_add_diag_mat_mat_MTN(dimGrid, dimBlock, Real(1), M.Data(),
M.Stride(), N.Data(), N.Dim(), Real(0),
buf.Data(), buf.Stride());
this->AddRowSumMat(alpha, buf, beta);
} else {
cuda_add_diag_mat_mat_MTN(dimGrid, dimBlock, alpha, M.Data(),
M.Stride(), N.Data(), N.Dim(), beta, data_,
dim_);
}
}
} else {
KALDI_ASSERT(M.NumCols() == N.NumRows());
KALDI_ASSERT(N.NumCols() == M.NumRows());
if (transM == kNoTrans) {
// Case 3: diag(M*N) == sum(M'.*N, 1)
// 16x16 or 8x32 2D block for matrix transpose and coalesced memory access.
// One block per 'tile_dim' columns of N.
// 1D grid expands along the row of N.
int tile_dim =
sizeof(Real) == sizeof(float) && N.NumCols() >= 2048 ? 32 : 16;
dim3 dimBlock(tile_dim, CU1DBLOCK / tile_dim);
dim3 dimGrid(n_blocks(N.NumCols(), tile_dim));
cuda_add_diag_mat_mat_MN(dimGrid, dimBlock, alpha, M.Data(), M.Stride(),
N.Data(), N.Dim(), beta, data_);
} else {
// Case 4: diag(M'*N') == sum(N'.*M, 1)
// Same kernel and config as case 3 except M and N are swapped.
int tile_dim =
sizeof(Real) == sizeof(float) && N.NumCols() >= 2048 ? 32 : 16;
dim3 dimBlock(tile_dim, CU1DBLOCK / tile_dim);
dim3 dimGrid(n_blocks(M.NumCols(), tile_dim));
cuda_add_diag_mat_mat_MN(dimGrid, dimBlock, alpha, N.Data(), N.Stride(),
M.Data(), M.Dim(), beta, data_);
}
}
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().AddDiagMatMat(alpha, M.Mat(), transM, N.Mat(), transN, beta);
}
}
template<typename Real>
void CuVectorBase<Real>::AddTpVec(const Real alpha, const CuTpMatrix<Real> &M,
const MatrixTransposeType trans,
const CuVectorBase<Real> &v,
const Real beta) {
KALDI_ASSERT(dim_ == v.dim_ && dim_ == M.NumRows());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
if (beta == 0.0) {
if (&v != this) CopyFromVec(v);
MulTp(M, trans);
if (alpha != 1.0) Scale(alpha);
} else {
CuVector<Real> tmp(v);
tmp.MulTp(M, trans);
if (beta != 1.0) Scale(beta); // *this <-- beta * *this
AddVec(alpha, tmp, 1.0); // *this += alpha * M * v
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().AddTpVec(alpha, M.Mat(), trans, v.Vec(), beta);
}
}
template<typename Real>
void CuVectorBase<Real>::MulTp(const CuTpMatrix<Real> &M, const MatrixTransposeType trans) {
KALDI_ASSERT(M.NumRows() == dim_);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
cublas_tpmv(GetCublasHandle(), (trans==kTrans? CUBLAS_OP_N:CUBLAS_OP_T),
M.NumRows(), M.Data(), data_, 1);
CuDevice::Instantiate().AccuProfile("CuVectorBase::MulTp", tim);
} else
#endif
{
Vec().MulTp(M.Mat(), trans);
}
}
template<typename Real>
Real CuVectorBase<Real>::Min() const {
Real result = 0.0;
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) { // min of an empty set is infinity.
return std::numeric_limits<Real>::infinity();
}
CuTimer tim;
// Small vectors are copied to RAM and reduced on CPU.
// The length is chosen by cu-vector-speed-test
if (dim_ < 4096) {
Vector<Real> ans_cpu(*this);
result = ans_cpu.Min();
} else {
// Use no more than 256 blocks (still too many?)
int dimBlock = CU1DBLOCK;
int dimGrid = n_blocks(dim_, dimBlock);
if (dimGrid > 256) {
dimGrid = 256;
}
CuVector<Real> ans(dimGrid, kUndefined);
cuda_vec_min(dimGrid, dimBlock, data_, ans.Data(), dim_, 1);
CU_SAFE_CALL(cudaGetLastError());
Vector<Real> ans_cpu(ans);
result = ans_cpu.Min();
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
result = (this->Vec()).Min();
}
return result;
}
template<typename Real>
Real CuVectorBase<Real>::Max() const {
Real result = 0.0;
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) { // max of an empty set is -infinity.
return -std::numeric_limits<Real>::infinity();
}
CuTimer tim;
// Small vectors are copied to RAM and reduced on CPU.
// The length is chosen by cu-vector-speed-test
if (dim_ < 4096) {
Vector<Real> ans_cpu(*this);
result = ans_cpu.Max();
} else {
// Use no more than 256 blocks (still too many?)
int dimBlock = CU1DBLOCK;
int dimGrid = n_blocks(dim_, dimBlock);
if (dimGrid > 256) {
dimGrid = 256;
}
CuVector<Real> ans(dimGrid, kUndefined);
cuda_vec_max(dimGrid, dimBlock, data_, ans.Data(), dim_, 1);
CU_SAFE_CALL(cudaGetLastError());
Vector<Real> ans_cpu(ans);
result = ans_cpu.Max();
}
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
result = (this->Vec()).Max();
}
return result;
}
template<typename Real>
void CuVectorBase<Real>::ReplaceValue(Real orig, Real changed) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_, CU1DBLOCK));
cuda_replace_value(dimGrid, dimBlock, data_, dim_, orig, changed);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().ReplaceValue(orig, changed);
}
}
template<typename Real>
void CuVectorBase<Real>::MulElements(const CuVectorBase<Real> &v) {
KALDI_ASSERT(dim_ == v.dim_);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
int dimBlock(CU1DBLOCK);
int dimGrid(n_blocks(dim_, CU1DBLOCK));
cuda_vec_mul_elements(dimGrid, dimBlock, data_, v.Data(), dim_);
CU_SAFE_CALL(cudaGetLastError());
CuDevice::Instantiate().AccuProfile("CuVectorBase::MulElements", tim);
} else
#endif
{
Vec().MulElements(v.Vec());
}
}
template<typename Real>
void CuVectorBase<Real>::DivElements(const CuVectorBase<Real> &v) {
// this just creates a matrix and calls the matrix version.
KALDI_ASSERT(dim_ == v.dim_);
CuSubMatrix<Real> this_mat(this->Data(), 1, dim_, dim_),
v_mat(v.Data(), 1, dim_, dim_);
this_mat.DivElements(v_mat);
}
template<>
template<>
void CuVectorBase<double>::CopyFromVec(const CuVectorBase<float> &src) {
KALDI_ASSERT(src.Dim() == dim_);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
CUBLAS_SAFE_CALL(cublas_copy(GetCublasHandle(), dim_, src.Data(), 1, data_, 1));
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().CopyFromVec(src.Vec());
}
}
template<>
template<>
void CuVectorBase<float>::CopyFromVec(const CuVectorBase<double> &src) {
KALDI_ASSERT(src.Dim() == dim_);
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (dim_ == 0) return;
CuTimer tim;
CUBLAS_SAFE_CALL(cublas_copy(GetCublasHandle(), dim_, src.Data(), 1, data_, 1));
CuDevice::Instantiate().AccuProfile(__func__, tim);
} else
#endif
{
Vec().CopyFromVec(src.Vec());
}
}
template<typename Real>
template<typename OtherReal>
void CuVectorBase<Real>::CopyFromVec(const VectorBase<OtherReal> &src) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (sizeof(Real) != sizeof(OtherReal)) {
CuVector<OtherReal> temp(dim_, kUndefined);
temp.CopyFromVec(src);
this->CopyFromVec(temp);
} else {
KALDI_ASSERT(src.Dim() == dim_);
if (dim_ == 0) return;
CuTimer tim;
CU_SAFE_CALL(cudaMemcpy(data_, src.Data(), src.Dim()*sizeof(Real), cudaMemcpyHostToDevice));
CuDevice::Instantiate().AccuProfile("CuVector::CopyFromVecH2D", tim);
}
} else
#endif
{
Vec().CopyFromVec(src);
}
}
// Instantiate the template above.
template
void CuVectorBase<float>::CopyFromVec(const VectorBase<float> &src);
template
void CuVectorBase<double>::CopyFromVec(const VectorBase<float> &src);
template
void CuVectorBase<float>::CopyFromVec(const VectorBase<double> &src);
template
void CuVectorBase<double>::CopyFromVec(const VectorBase<double> &src);
template<typename Real>
template<typename OtherReal>
void CuVectorBase<Real>::CopyToVec(VectorBase<OtherReal> *dst) const {
KALDI_ASSERT(dim_ == dst->Dim());
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (sizeof(Real) != sizeof(OtherReal)) {
CuVector<OtherReal> temp(*this);
temp.CopyToVec(dst);
} else {
if (dim_ == 0) return;
CuTimer tim;
CU_SAFE_CALL(cudaMemcpy(dst->Data(), this->data_,
sizeof(Real) * dim_, cudaMemcpyDeviceToHost));
CuDevice::Instantiate().AccuProfile(__func__, tim);
}
} else
#endif
{
dst->CopyFromVec(this->Vec());
}
}
template<typename Real>
void CuVector<Real>::Read(std::istream &is, bool binary) {
Vector<Real> temp;
temp.Read(is, binary);
Destroy();
Swap(&temp);
}
template<typename Real>
void CuVector<Real>::Write(std::ostream &os, bool binary) const {
Vector<BaseFloat> temp(this->dim_, kUndefined);
this->CopyToVec(&temp);
temp.Write(os, binary);
}
template<typename Real>
CuVector<Real>::CuVector(const CuVectorBase<Real> &v) {
this->Resize(v.Dim());
this->CopyFromVec(v);
}
template<typename Real>
CuVector<Real>::CuVector(const VectorBase<Real> &v) {
this->Resize(v.dim_);
this->CopyFromVec(v);
}
template<typename Real>
void CuVector<Real>::Resize(MatrixIndexT dim, MatrixResizeType t) {
KALDI_ASSERT(t == kSetZero || t == kUndefined); // Others not implemented
// yet.
if (this->dim_ == dim) {
this->SetZero();
return;
}
if (this->dim_ != 0)
this->Destroy();
if (dim == 0) return;
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
CuTimer tim;
this->data_ = static_cast<Real*>(CuDevice::Instantiate().Malloc(dim * sizeof(Real)));
this->dim_ = dim;
if (t == kSetZero) this->SetZero();
CuDevice::Instantiate().AccuProfile("CuVector::Resize", tim);
} else
#endif
{
Vector<Real> vec(dim);
this->Swap(&vec);
}
}
template<typename Real>
void CuVector<Real>::Swap(CuVector<Real> *vec) {
std::swap(this->data_, vec->data_);
std::swap(this->dim_, vec->dim_);
}
template<typename Real>
void CuVector<Real>::Swap(Vector<Real> *vec) {
#if HAVE_CUDA == 1
if (CuDevice::Instantiate().Enabled()) {
if (this->dim_ == 0) {
if (vec->dim_ != 0) {