Blame view

src/cudamatrix/cu-packed-matrix.cc 11.4 KB
8dcb6dfcb   Yannick Estève   first commit
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
  // cudamatrix/cu-packed-matrix.cc
  
  // Copyright 2009-2013  Johns Hopkins University (author: Daniel Povey)
  //                      Karel Vesely
  
  // 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
  //
  //  http://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-packed-matrix.h"
  #include "cudamatrix/cublas-wrappers.h"
  
  namespace kaldi {
  
  template<typename Real>
  void CuPackedMatrix<Real>::Resize(MatrixIndexT rows,
                                    MatrixResizeType resize_type) {
    // This code does not currently support the other resize_type options.
    KALDI_ASSERT(resize_type == kSetZero || resize_type == kUndefined);
  
    if (this->num_rows_ == rows) {
      if (resize_type == kSetZero) this->SetZero();
      return;
    }
  
    if (this->num_rows_ != 0)
      this->Destroy();
    if (rows == 0) return;
  #if HAVE_CUDA == 1
    CuDevice &device = CuDevice::Instantiate();
    if (device.Enabled()) {
      CuTimer tim;
      this->num_rows_ = rows;
      size_t nr = static_cast<size_t>(num_rows_),
          num_bytes = ((nr * (nr+1)) / 2) * sizeof(Real);
      this->data_ = static_cast<Real*>(device.Malloc(num_bytes));
  
      if (resize_type == kSetZero) this->SetZero();
      device.AccuProfile("CuPackedMatrix::Resize", tim);
    } else
  #endif
    { // Let the initializer of SpMatrix<Real> handle the allocation,
      // and then just do Swap which will switch the pointers.
      // This wastes a few instructions but is simple to code.
      SpMatrix<Real> mat(rows, resize_type);
      this->Swap(&mat);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::SetRandn() {
    if (num_rows_ != 0) {
      MatrixIndexT size = num_rows_ * (num_rows_ + 1) / 2;
      CuSubVector<Real> tmp(data_, size);
      CuRand<Real> rand;
      rand.RandGaussian(&tmp);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::Destroy() {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (this->data_ != NULL) {
        CuDevice::Instantiate().Free(this->data_);
      }
    } else
  #endif
    {
      if (this->data_ != NULL) KALDI_MEMALIGN_FREE(this->data_);
    }
    this->data_ = NULL;
    this->num_rows_ = 0;
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::Swap(PackedMatrix<Real> *mat) {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (this->num_rows_ == 0) {
        if (mat->num_rows_ != 0) {
          // *this is empty, but mat is nonempty.
          Resize(mat->num_rows_, kUndefined);
          CopyFromPacked(*mat);
          mat->Resize(0);
        }
        // else both are empty.
      } else { // *this is nonempty.
        if (mat->num_rows_ != 0) {
          // Both *this and *mat are nonempty.  Recurse to simpler cases.
          // this could be done more efficiently in the case where
          // the size does not change.
          PackedMatrix<Real> temp;
          this->Swap(&temp); // now temp is full, *this is empty.
          mat->Swap(&temp); // now mat has data from *this, temp has
          // data from mat.
          this->Swap(&temp); // copy data in mat to *this, which is now empty.
        } else { // *this is full but *mat is empty.
          mat->Resize(this->num_rows_, kUndefined);
          this->CopyToPacked(mat);
          this->Destroy();
        }
      }
    } else
  #endif
    {
      std::swap(mat->data_, this->data_);
      std::swap(mat->num_rows_, this->num_rows_);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::CopyFromPacked(const CuPackedMatrix<Real> &src) {
    KALDI_ASSERT(src.NumRows() == num_rows_);
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return; // Nothing to do.
      CuTimer tim;
      size_t nr = static_cast<size_t>(num_rows_),
          num_bytes = ((nr * (nr+1)) / 2) * sizeof(Real);
  
      CU_SAFE_CALL(
        cudaMemcpyAsync(data_, src.data_, num_bytes, cudaMemcpyDeviceToDevice,
                        cudaStreamPerThread));
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::CopyFromPacked1",
                                          tim);
    } else
  #endif
    {
      Mat().CopyFromPacked(src.Mat());
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::CopyFromPacked(const PackedMatrix<Real> &src) {
    KALDI_ASSERT(src.NumRows() == num_rows_);
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return; // Nothing to do.
      CuTimer tim;
      CU_SAFE_CALL(cudaMemcpyAsync(data_, src.data_, src.SizeInBytes(),
                                   cudaMemcpyHostToDevice, cudaStreamPerThread));
      CU_SAFE_CALL(cudaStreamSynchronize(cudaStreamPerThread));
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::CopyFromPacked2", tim);
    } else
  #endif
    {
      Mat().CopyFromPacked(src);
      //memcpy(data_, src.Data(), SizeInBytes());
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::CopyToPacked(PackedMatrix<Real> *dst) const {
    KALDI_ASSERT(dst->NumRows() == NumRows());
  
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return; // Nothing to do.
      CuTimer tim;
      size_t nr = static_cast<size_t>(num_rows_),
        num_bytes = ((nr * (nr+1)) / 2) * sizeof(Real);
  
      CU_SAFE_CALL(cudaMemcpyAsync(dst->data_, data_, num_bytes,
                                   cudaMemcpyDeviceToHost, cudaStreamPerThread));
      CU_SAFE_CALL(cudaStreamSynchronize(cudaStreamPerThread));
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::CopyToPackedD2H", tim);
    } else
  #endif
    {
      //memcpy(data_, dst->Data(), SizeInBytes());
      dst->CopyFromPacked(Mat());
    }
  }
  
  /*
  template<typename Real>
  void CuPackedMatrix<Real>::CopyRowsFromPacked(int32 r, const CuPackedMatrix<Real> &src, int32 src_ro, int32 dst_ro) {
    KALDI_ASSERT(r+src_ro <= src.NumRows());
    KALDI_ASSERT(r+dst_ro <= NumRows());
    KALDI_ASSERT(NumCols() == src.NumCols());
  
    #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      CuTimer tim;
  
      MatrixIndexT dst_pitch = stride_*sizeof(Real);
      MatrixIndexT src_pitch = src.Stride()*sizeof(Real);
      MatrixIndexT width = src.NumCols()*sizeof(Real);
  
      const Real *p_src = src.Data() + src_ro*src.Stride();
      Real *p_dst = data_ + dst_ro*stride_;
  
      CU_SAFE_CALL(cudaMemcpy2D(p_dst, dst_pitch, p_src, src_pitch, width, r, cudaMemcpyDeviceToDevice));
  
      CuDevice::Instantiate().AccuProfile("CuMatrix::CopyRowsD2D", tim);
    } else
    #endif
    {
      memcpy(Data()+dst_ro*stride_, src.Data()+src_ro*src.Stride(), r*stride_*sizeof(Real));
    }
  } */
  
  
  
  template<typename Real>
  void CuPackedMatrix<Real>::Read(std::istream &is, bool binary) {
    PackedMatrix<Real> temp;
    temp.Read(is, binary);
    Destroy();
    Swap(&temp);
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::Write(std::ostream &os, bool binary) const {
    PackedMatrix<Real> temp(this->num_rows_, kUndefined);
    this->CopyToPacked(&temp);
    temp.Write(os, binary);
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::SetZero() {
    #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      CuTimer tim;
      size_t nr = static_cast<size_t>(num_rows_),
        num_bytes = ((nr * (nr+1)) / 2) * sizeof(Real);
  
      CU_SAFE_CALL(cudaMemsetAsync(reinterpret_cast<void*>(this->data_), 0, 
            num_bytes, cudaStreamPerThread));
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::SetZero", tim);
    } else
    #endif
    {
      Mat().SetZero();
    }
  }
  
  template<typename Real>
  Real CuPackedMatrix<Real>::Trace() const {
    Real result = 0.0;
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return 0.0;
      CuVector<Real> tmp(num_rows_, kUndefined);
      tmp.CopyDiagFromPacked(*this);
      return tmp.Sum();
    } else
  #endif
    {
      result = Mat().Trace();
    }
    return result;
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::SetDiag(Real alpha) {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return;
      CuTimer tim;
      int dimBlock(CU1DBLOCK);
      int dimGrid(n_blocks(NumRows(),CU1DBLOCK));
      cuda_set_diag_packed(dimGrid,dimBlock,data_,alpha,num_rows_);
      CU_SAFE_CALL(cudaGetLastError());
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::SetDiag", tim);
    } else
  #endif
    {
      Mat().SetDiag(alpha);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::Scale(Real alpha) {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      CuTimer tim;
      size_t nr = static_cast<size_t>(num_rows_),
          num_elements = ((nr * (nr+1)) / 2);
      CUBLAS_SAFE_CALL(cublas_scal(GetCublasHandle(), num_elements, alpha, data_, 1));
  
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::Scale", tim);
    } else
  #endif
    {
      Mat().Scale(alpha);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::ScaleDiag(Real alpha) {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      CuTimer tim;
      int dimBlock(CU1DBLOCK);
      int dimGrid(n_blocks(NumRows(),CU1DBLOCK));
      cuda_scale_diag_packed(dimGrid,dimBlock,data_,alpha,num_rows_);
      CU_SAFE_CALL(cudaGetLastError());
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::ScaleDiag", tim);
    } else
  #endif
    {
      Mat().ScaleDiag(alpha);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::AddPacked(const Real alpha, const CuPackedMatrix<Real> &M) {
    KALDI_ASSERT(num_rows_ == M.NumRows());
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return;
      CuTimer tim;
      size_t nr = num_rows_,
          sz = (nr * (nr + 1)) / 2;
      cublas_axpy(GetCublasHandle(), sz, alpha, M.Data(), 1, data_, 1);
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::AddPacked", tim);
    } else
  #endif
    {
      Mat().AddPacked(alpha, M.Mat());
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::AddToDiag(Real r) {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      if (num_rows_ == 0) return;
      CuTimer tim;
      int dimBlock(CU1DBLOCK);
      int dimGrid(n_blocks(NumRows(),CU1DBLOCK));
      cuda_add_diag_packed(dimGrid,dimBlock,data_,r,num_rows_);
      CU_SAFE_CALL(cudaGetLastError());
      CuDevice::Instantiate().AccuProfile("CuPackedMatrix::AddToDiag", tim);
    } else
  #endif
    {
      // TODO
      Mat().AddToDiag(r);
    }
  }
  
  template<typename Real>
  void CuPackedMatrix<Real>::SetUnit() {
  #if HAVE_CUDA == 1
    if (CuDevice::Instantiate().Enabled()) {
      this->SetZero();
      this->SetDiag(1.0);
    } else
  #endif
    {
      Mat().SetUnit();
    }
  }
  
  /**
   * Print the matrix to stream
   */
  template<typename Real>
  std::ostream &operator << (std::ostream &out, const CuPackedMatrix<Real> &mat) {
    PackedMatrix<Real> temp(mat.NumRows());
    mat.CopyToPacked(&temp);
    out << temp;
    return out;
  }
  
  // instantiate the template
  template
  std::ostream &operator << (std::ostream &out, const CuPackedMatrix<float> &mat);
  template
  std::ostream &operator << (std::ostream &out, const CuPackedMatrix<double> &mat);
  
  
  // Instantiate class CuPackedMatrix for float and double.
  template class CuPackedMatrix<float>;
  template class CuPackedMatrix<double>;
  
  
  } // namespace kaldi