forked from microsoft/CNTK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCPUSparseMatrix.cpp
1828 lines (1553 loc) · 68.6 KB
/
CPUSparseMatrix.cpp
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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
// Math.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "Basics.h"
#include "File.h"
#include <assert.h>
#include <stdexcept>
#include <omp.h>
#include <math.h>
#include "CPUMatrix.h"
#include "CPUSparseMatrix.h"
#include <random>
#include <chrono>
#include <iostream>
#ifdef LEAKDETECT
#include <vld.h>
#endif
#pragma warning(disable : 4127) // conditional expression is constant; "if (sizeof(ElemType)==sizeof(float))" triggers this
#ifdef USE_MKL
// requires MKL 10.0 and above
#include <mkl.h>
#else
#ifdef _MSC_VER
// Visual Studio doesn't define standard complex types properly
#define HAVE_LAPACK_CONFIG_H
#define LAPACK_COMPLEX_STRUCTURE
#endif
#include <cblas.h>
#include <lapacke.h>
#endif
// This is an example of an exported variable
//MATH_API int nMath=0;
// This is an example of an exported function.
//MATH_API int fnMath(void)
//{
// return 42;
//}
// TODO: Move to CommonMatrix.h
#define IDX2C(i, j, ld) (((j) * (ld)) + (i)) // 0 based indexing
namespace Microsoft { namespace MSR { namespace CNTK {
#pragma region Helpful Enum Definitions
enum class MatrixOrder
{
RowMajor = 101, // row-major arrays
ColMajor = 102 // column-major arrays
};
enum class MatrixTranspose : char
{
NoTrans = 'N', // trans='N'
Trans = 'T', // trans='T'
ConjTrans = 'C' // trans='C'
};
enum class SymMatrixType : char
{
Up = 'U', // symmetric matrix is stored in the upper part
Low = 'L', // symmetric matrix is stored in thelower part
Full = 'F', // full populated
NotSymmetric = 'N' // not a symmetric matrix
};
enum class MatrixOpSide : char
{
Left = 'L', // left multiply
Right = 'R', // right multiply
};
#pragma endregion Helpful Enum Definitions
#pragma region Constructors and Destructor
//-------------------------------------------------------------------------
// construction and conversion
//-------------------------------------------------------------------------
// should only be used by constructors.
template <class ElemType>
/*private*/ void CPUSparseMatrix<ElemType>::ZeroInit()
{
Base::ZeroInit();
SetComputeDeviceId(CPUDEVICE);
SetCompIndexSize(0);
SetColIdx(-1);
SetBuffer(nullptr, 0, false);
SetUnCompIndex(nullptr);
SetCompIndex(nullptr);
SetBlockSize(0);
SetBlockIdShift(0);
SetBlockIds(nullptr);
}
//should only be used by constructors.
template <class ElemType>
void CPUSparseMatrix<ElemType>::CheckInit(const MatrixFormat format)
{
if (format != MatrixFormat::matrixFormatSparseCSC && format != MatrixFormat::matrixFormatSparseCSR && format != MatrixFormat::matrixFormatSparseBlockCol && format != MatrixFormat::matrixFormatSparseBlockRow)
{
LogicError("CPUSparseMatrix: unsupported sparse matrix format");
}
SetFormat(format);
ZeroInit();
}
template <class ElemType>
CPUSparseMatrix<ElemType>::CPUSparseMatrix(const MatrixFormat format)
{
CheckInit(format);
}
template <class ElemType>
CPUSparseMatrix<ElemType>::CPUSparseMatrix(const MatrixFormat format, const size_t numRows, const size_t numCols, const size_t size)
{
CheckInit(format);
RequireSizeAndAllocate(numRows, numCols, size, true, false);
}
// copy constructor, deep copy
template <class ElemType>
CPUSparseMatrix<ElemType>::CPUSparseMatrix(const CPUSparseMatrix<ElemType>& deepCopyFrom)
{
ZeroInit();
if (!deepCopyFrom.IsEmpty())
SetValue(deepCopyFrom);
}
// assignment operator, deep copy
template <class ElemType>
CPUSparseMatrix<ElemType>& CPUSparseMatrix<ElemType>::operator=(const CPUSparseMatrix<ElemType>& deepCopyFrom)
{
if (!deepCopyFrom.IsEmpty())
SetValue(deepCopyFrom);
return *this;
}
// move constructor, shallow copy
template <class ElemType>
CPUSparseMatrix<ElemType>::CPUSparseMatrix(CPUSparseMatrix<ElemType>&& moveFrom)
{
Base::ShallowCopyFrom(moveFrom);
// release the pointer from the source object so that the destructor won't release it twice
moveFrom.ZeroValues();
}
//move assignment operator, shallow copy
template <class ElemType>
CPUSparseMatrix<ElemType>& CPUSparseMatrix<ElemType>::operator=(CPUSparseMatrix<ElemType>&& moveFrom)
{
if (this != &moveFrom)
{
Base::ShallowCopyFrom(moveFrom);
// release the pointer from the source object so that the destructor won't release it twice
moveFrom.ZeroValues();
}
return *this;
}
template <class ElemType>
CPUSparseMatrix<ElemType>::~CPUSparseMatrix()
{
ZeroValues();
}
template <class ElemType>
CPUSparseMatrix<ElemType>& CPUSparseMatrix<ElemType>::AssignOneHot(const CPUMatrix<ElemType>& a, vector<size_t>& shape, size_t axis)
{
if (a.IsEmpty())
LogicError("AssignOneHot: Matrix a is empty.");
if (GetFormat() != matrixFormatSparseCSC)
LogicError("AssignOneHot: Matrix format is not supported.");
if (axis >= shape.size())
LogicError("AssignOneHot: axis is not correct");
int item_size = 1;
for (size_t i = 0; i < shape.size() && i < axis; i++)
item_size *= (int)shape[i];
int num_class = (int)shape[axis];
auto nRows = item_size * num_class;
auto nCols = a.GetNumElements() / item_size;
if (((GetNumRows() != 0) && (GetNumRows() != nRows)) || ((GetNumCols() != 0) && (GetNumCols() != nCols)))
LogicError("AssignOneHot: Target matrix size is not correct");
RequireSizeAndAllocate(nRows, nCols, a.GetNumElements());
CPUSPARSE_INDEX_TYPE* secondaryIndices = SecondaryIndexLocation();
CPUSPARSE_INDEX_TYPE* majorIndices = MajorIndexLocation();
ElemType* data = NzValues();
ElemType* indices = a.Data();
#pragma omp parallel for
for (long i = 0; i < a.GetNumElements(); i++)
{
int block_id = i / item_size;
int item_id = i % item_size;
// for invalid indices, theorically they should not belong to nz elements.
// but if we scan the indices to count the valid indices number,
// it will be difficult for parallel calculation, especially on GPU.
// here we chose to keep those elements in nz element list, but with value 0 an at row 0
if (indices[i] >= 0 && indices[i] < num_class)
{
data[i] = 1;
majorIndices[i] = ((int)indices[i] * item_size) + item_id;
}
else
{
data[i] = 0;
majorIndices[i] = item_id;
}
if (item_id == 0)
secondaryIndices[block_id + 1] = item_size * (block_id + 1);
}
secondaryIndices[0] = 0;
return *this;
}
#pragma endregion Constructors and Destructor
#pragma region Basic Operators
// make sure call order in column wise for CSC and row wise for CSR
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetValue(const size_t row, const size_t col, const ElemType v)
{
if (!OwnBuffer())
LogicError("Cannot modify since the buffer is managed externally.");
if (GetFormat() != MatrixFormat::matrixFormatSparseCSC && GetFormat() != MatrixFormat::matrixFormatSparseCSR)
{
LogicError("CPUSparseMatrix: unsupported SetValue() call.");
}
if ((GetFormat() == MatrixFormat::matrixFormatSparseCSC) && ((*this)(row, col) == v))
return;
let nz = NzCount();
if (GetSizeAllocated() < nz + 1) // automatic resize
{
Allocate(m_numRows, m_numCols, nz + 100, true, true); // allocate 100 more elelemnts and keep existing values
}
if (row < 0 || row >= m_numRows)
{
LogicError("CPUSparseMatrix: SetValue() invalid row id");
}
if (col < 0 || col >= m_numCols)
{
LogicError("CPUSparseMatrix: SetValue() invalid column id");
}
size_t r = (GetFormat() == matrixFormatSparseCSC) ? row : col;
size_t c = (GetFormat() == matrixFormatSparseCSC) ? col : row;
Data()[nz] = v;
MajorIndexLocation()[nz] = (CPUSPARSE_INDEX_TYPE) r;
// consistency check
if (nz > 0)
{
if (c == GetColIdx() && r <= MajorIndexLocation()[nz - 1])
{
LogicError("CPUSparseMatrix: SetValue is not called properly");
}
}
if (c != GetColIdx())
{
SecondaryIndexLocation()[c] = CPUSPARSE_INDEX_TYPE(nz);
SetColIdx((int) c);
}
// Note we don't have m_nz anymore. In order for the change from m_nz to
// NzCount to make sense, we need to propogate nz+1 to all col slices.
for (size_t max = c + 1; max < m_numCols + 1; max++)
{
SecondaryIndexLocation()[max] = CPUSPARSE_INDEX_TYPE(nz + 1);
}
}
// make sure call order in colume wise for CSC and row wise for CSR
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetValue(const CPUSparseMatrix<ElemType>& v)
{
SetFormat(v.GetFormat());
RequireSizeAndAllocate(v.GetNumRows(), v.GetNumCols(), v.NzCount() ); // TODO: rename to *Bytes/*Count instead of vague *Size if possible
let nz = v.NzCount();
auto matrixFormat = v.GetFormat();
if (((matrixFormat == matrixFormatSparseBlockCol) || (matrixFormat == matrixFormatSparseBlockRow)) && (v.GetBlockIdShift() > 0))
NOT_IMPLEMENTED;
if (nz > 0)
{
memcpy(NzValues(), v.NzValues(), v.NzSize());
if ((matrixFormat == matrixFormatSparseCSC) || (matrixFormat == matrixFormatSparseCSR))
{
memcpy(RowLocation(), v.RowLocation(), v.RowSize());
memcpy(ColLocation(), v.ColLocation(), v.ColSize());
}
else
{
memcpy(GetBlockIds(), v.GetBlockIds(), v.GetBlockSize() * sizeof(size_t)); // TODO: change block id from size_t to CPUSPARSE_INDEX_TYPE, and rename BlockSize to BlockCount
SetBlockSize(v.GetBlockSize());
}
}
if (v.m_sliceViewOffset > 0)
{
CPUSPARSE_INDEX_TYPE* loc = (GetFormat() == matrixFormatSparseCSC) ? ColLocation() : RowLocation();
size_t len = (GetFormat() == matrixFormatSparseCSC) ? ColSize() : RowSize();
CPUSPARSE_INDEX_TYPE offset = loc[0];
for (size_t c = 0; c < len; c++)
loc[c] -= offset;
}
}
#if 0
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetValue(const CPUMatrix<ElemType>& /*v*/)
{
NOT_IMPLEMENTED;
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetValue(const GPUMatrix<ElemType>& /*v*/)
{
NOT_IMPLEMENTED;
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetValue(const GPUSparseMatrix<ElemType>& /*v*/)
{
NOT_IMPLEMENTED;
}
#endif
template <class ElemType>
void CPUSparseMatrix<ElemType>::MaskColumnsValue(const CPUMatrix<char>& columnsMask, ElemType val, size_t numColsPerMaskEntry)
{
VerifyWritable(__func__);
if (GetNumCols() != (columnsMask.GetNumCols() * numColsPerMaskEntry))
RuntimeError("Matrix number of columns must equal 'number of columns in column mask * numColsPerMaskEntry'.");
if (val != 0)
LogicError("MaskColumnsValue is not implmented for a non-zero mask for sparse matrices.");
#ifdef _DEBUG
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC)
{
// Get the binary columns mask
char* maskedCols = columnsMask.Data();
// If we're CSC, we only need to verify that the columns to be zeroed are empty.
GPUSPARSE_INDEX_TYPE* colVector = SecondaryIndexLocation();
auto n = columnsMask.GetNumCols();
#pragma omp parallel for
for (long j = 0; j < n; j++)
for (long k = 0; k < numColsPerMaskEntry; ++k)
if (maskedCols[j] == 0 && colVector[(j * numColsPerMaskEntry) + k + 1] != colVector[(j * numColsPerMaskEntry) + k])
LogicError("CPUSparseMatrix attempted to mask column %d, but it has %d elements in it.", (int)((j * numColsPerMaskEntry) + k), (int)(colVector[(j * numColsPerMaskEntry) + k + 1] - colVector[(j * numColsPerMaskEntry) + k]));
}
else
NOT_IMPLEMENTED;
#endif
}
template <class ElemType>
CPUSparseMatrix<ElemType>& CPUSparseMatrix<ElemType>::DoGatherColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUSparseMatrix<ElemType>& a, ElemType alpha)
{
VerifyWritable(__func__);
if ((a.GetFormat() != matrixFormatSparseCSC) || (GetFormat() != matrixFormatSparseCSC))
NOT_IMPLEMENTED;
if (idx.GetNumRows() != 1) // index is 1-dimensional only
InvalidArgument("DoGatherColumnsOf: Map must be a row vector.");
if (beta != 0)
NOT_IMPLEMENTED;
// Determine the number of non-zero elements
size_t numCols = idx.GetNumCols();
size_t numNonZeroElements = 0;
// TODO: Does it make sense to parallelize this?
for (long j = 0; j < numCols; j++)
{
auto jInF = idx(0, j); // this is the column we need to get
if (std::isnan(jInF) || (jInF < 0)) // negative index means gap
continue;
size_t jIn = (size_t)jInF;
auto start = a.SecondaryIndexLocation()[jIn];
auto end = a.SecondaryIndexLocation()[jIn + 1];
numNonZeroElements += (end - start);
}
if (beta == 0)
RequireSizeAndAllocate(a.GetNumRows(), idx.GetNumCols(), numNonZeroElements); // output has same column format as a, but number of columns comes from idx
size_t offset = SecondaryIndexLocation()[0];
// TODO: Does it make sense to parallelize this?
for (long j = 0; j < numCols; j++)
{
auto jInF = idx(0, j); // this is the column we need to get
if (jInF >= 0) // negative or nan index means gap, but we still need to update the CompIndex
{
size_t jIn = (size_t)jInF;
auto start = a.SecondaryIndexLocation()[jIn];
auto end = a.SecondaryIndexLocation()[jIn + 1];
for (auto p = start; p < end; p++, offset++)
{
GetUnCompIndex()[offset] = a.GetUnCompIndex()[p];
Buffer()[offset] = a.Buffer()[p] * alpha;
}
}
SecondaryIndexLocation()[j + 1] = CPUSPARSE_INDEX_TYPE(offset);
}
return *this;
}
// *this[:,idx[j]] = a[:,j] * alpha + *this[:,idx[j]] * beta
template <class ElemType>
CPUSparseMatrix<ElemType>& CPUSparseMatrix<ElemType>::DoScatterColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUSparseMatrix<ElemType>& a, ElemType alpha)
{
VerifyWritable(__func__);
if ((a.GetFormat() != matrixFormatSparseCSC) || (GetFormat() != matrixFormatSparseCSC))
NOT_IMPLEMENTED;
if (idx.GetNumRows() != 1) // index is 1-dimensional only
InvalidArgument("DoScatterColumnsOf: Map must be a row vector.");
if (beta != 0)
NOT_IMPLEMENTED;
if (NzCount() != 0)
InvalidArgument("CPUSparseMatrix::DoScatterColumnsOf: The target matrix cannot have pre-existing non-zero values when being scattered into");
size_t numNonZeroElements = a.NzCount();
if (beta == 0)
RequireSizeAndAllocate(GetNumRows(), GetNumCols(), numNonZeroElements);
// Setup the Secondary index
std::vector<int> columnElementCounts(GetNumCols(), 0);
size_t numColsToWrite = idx.GetNumCols();
for (long j = 0; j < numColsToWrite; j++)
{
auto jOutF = idx(0, j); // this is the column we need to write to
if (std::isnan(jOutF) || (jOutF < 0)) // negative index means gap
continue;
size_t jOut = (size_t)jOutF;
columnElementCounts[jOut] = a.SecondaryIndexLocation()[j + 1] - a.SecondaryIndexLocation()[j];
}
// TODO: Replace with std::exclusive_scan when we switch to C++17
for (size_t i = 1; i <= GetNumCols(); ++i)
SecondaryIndexLocation()[i] = SecondaryIndexLocation()[i - 1] + columnElementCounts[i - 1];
size_t offset = a.SecondaryIndexLocation()[0];
// TODO: Does it make sense to parallelize this?
for (long j = 0; j < numColsToWrite; j++)
{
auto jOutF = idx(0, j); // this is the column we need to write to
if (std::isnan(jOutF) || (jOutF < 0)) // negative index means gap
continue;
size_t jOut = (size_t)jOutF;
auto start = SecondaryIndexLocation()[jOut];
auto end = SecondaryIndexLocation()[jOut + 1];
for (auto p = start; p < end; p++, offset++)
{
GetUnCompIndex()[p] = a.GetUnCompIndex()[offset];
Buffer()[p] = a.Buffer()[offset] * alpha;
}
}
return *this;
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::Print(const char* matrixName) const
{
Print(matrixName, 0, 0, 0, 0);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::Print(const char* matrixName, ptrdiff_t /*rowStart*/, ptrdiff_t /*rowEnd*/, ptrdiff_t /*colStart*/, ptrdiff_t /*colEnd*/) const
{
if (this->GetFormat() != matrixFormatSparseCSC && this->GetFormat() != matrixFormatSparseCSR)
{
return;
// NOT_IMPLEMENTED;
}
fprintf(stderr, "%s\n", matrixName);
const ElemType* dataBuffer = NzValues();
const size_t nz = MajorIndexCount();
CPUSPARSE_INDEX_TYPE* unCompressedIndex = MajorIndexLocation();
CPUSPARSE_INDEX_TYPE* compressedIndex = SecondaryIndexLocation();
for (size_t i = 0, j = 0; i < nz; ++i)
{
if (i >= compressedIndex[j])
{
fprintf(stderr, "\n");
j++;
}
fprintf(stderr, "%d:%.f ", unCompressedIndex[i], dataBuffer[i]);
}
fprintf(stderr, "\n");
}
template <class ElemType>
CPUSparseMatrix<ElemType> CPUSparseMatrix<ElemType>::ColumnSlice(size_t startColumn, size_t numCols) const
{
if (startColumn + numCols > m_numCols)
InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) m_numCols);
if (GetFormat() != MatrixFormat::matrixFormatSparseCSC && GetFormat() != MatrixFormat::matrixFormatSparseBlockCol)
NOT_IMPLEMENTED;
CPUSparseMatrix<ElemType> slice(GetFormat());
slice.ShallowCopyFrom(*this);
if ((startColumn != 0) || (slice.m_numCols != numCols))
{
slice.m_numCols = numCols;
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC)
{
slice.m_sliceViewOffset = m_sliceViewOffset + startColumn;
}
else if (GetFormat() == MatrixFormat::matrixFormatSparseBlockCol)
{
long long startColBlock = 0, endColBlock = 0;
bool foundStart = false, foundEnd = false;
for (size_t j = 0; j < GetBlockSize(); j++)
{
if (j > 0)
{
assert(GetBlockIds()[j] > GetBlockIds()[j - 1]); // assume ids are increasing.Is this valid?
}
if (!foundStart && (long long)GetBlockIds()[j] - (long long)GetBlockIdShift() >= (long long)startColumn) // start column with values
{
startColBlock = j;
foundStart = true;
}
else if ((long long)GetBlockIds()[j] - (long long)GetBlockIdShift() >= (long long)(startColumn + numCols)) // end column with values
{
endColBlock = j;
foundEnd = true;
break;
}
}
if (!foundStart)
{
startColBlock = (long long)GetBlockSize();
}
if (!foundEnd)
{
endColBlock = (long long)GetBlockSize();
}
slice.m_sliceViewOffset = startColBlock;
slice.SetBlockIds((size_t*)GetBlockIds() + startColBlock); // the value stored in the block id is based on the original column numbers
slice.SetBlockSize((size_t)max((long long)0, endColBlock - startColBlock));
slice.SetBlockIdShift(GetBlockIdShift() + startColumn);
}
}
return slice;
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::AssignColumnSliceToDense(CPUMatrix<ElemType>& slice, size_t startColumn, size_t numCols) const
{
if (startColumn + numCols > m_numCols)
InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) m_numCols);
if ((GetFormat() != MatrixFormat::matrixFormatSparseCSC) && (GetFormat() != MatrixFormat::matrixFormatSparseBlockCol))
NOT_IMPLEMENTED;
// We can either error out or RequireSize. Because RequireSize will error out if it's not allowed, I think this makes more sense.
slice.RequireSize(m_numRows, numCols);
memset(slice.Data(), 0, sizeof(ElemType) * slice.GetNumElements());
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC)
{
#pragma omp parallel for
for (long j = 0; j < numCols; j++)
{
long start = (long)SecondaryIndexLocation()[startColumn + j];
long end = (long)SecondaryIndexLocation()[startColumn + j + 1];
for (long p = start; p < end; p++)
{
size_t i = GetUnCompIndex()[p];
ElemType value = Buffer()[(size_t)p];
slice(i, (size_t)j) = value;
}
}
}
else
{
CPUSparseMatrix<ElemType> sparseSlice = ColumnSlice(startColumn, numCols);
size_t numColumnsWithNonZeroValues = sparseSlice.GetBlockSize();
#pragma omp parallel for
for (long j = 0; j < numColumnsWithNonZeroValues; j++)
{
size_t i = sparseSlice.GetBlockIds()[j] - sparseSlice.GetBlockIdShift();
size_t len = sparseSlice.GetNumRows();
size_t start = j * len;
for (size_t p = start; p < start + len; p++)
{
ElemType val = sparseSlice.Buffer()[p];
slice(p - start, i) = val;
}
}
}
}
template <class ElemType>
CPUMatrix<ElemType> CPUSparseMatrix<ElemType>::CopyColumnSliceToDense(size_t startColumn, size_t numCols) const
{
CPUMatrix<ElemType> slice(m_numRows, numCols);
AssignColumnSliceToDense(slice, startColumn, numCols);
return slice;
}
template <class ElemType>
CPUMatrix<ElemType> CPUSparseMatrix<ElemType>::DiagonalToDense() const
{
if (m_numRows != m_numCols)
LogicError("DiagonalToDense can be called only for square matrix.");
if (GetFormat() != MatrixFormat::matrixFormatSparseCSC)
NOT_IMPLEMENTED;
CPUMatrix<ElemType> diag(1, m_numCols);
#pragma omp parallel for
for (long j = 0; j < m_numCols; j++)
{
long start = (long) SecondaryIndexLocation()[j];
long end = (long) SecondaryIndexLocation()[j + 1];
for (long p = start; p < end; p++)
{
size_t i = MajorIndexLocation()[p];
if (i == (size_t) j)
{
diag(0, i) = Data()[(size_t) p];
}
}
}
return diag;
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetMatrixFromCSCFormat(const CPUSPARSE_INDEX_TYPE* h_CSCCol, const CPUSPARSE_INDEX_TYPE* h_Row, const ElemType* h_Val,
const size_t nz, const size_t numRows, const size_t numCols)
{
if (!OwnBuffer())
LogicError("Cannot modify since the buffer is managed externally.");
SetFormat(matrixFormatSparseCSC);
RequireSizeAndAllocate(numRows, numCols, nz, true, false);
// Note: This is a casualty of the switch away from m_nz. RowSize and NzSize depend on ColLocation being correct for format SparseCSC. Thus we must
// copy ColLocation before RowLocation and NzValues. That's ugly and error prone.
memcpy(ColLocation(), h_CSCCol, sizeof(CPUSPARSE_INDEX_TYPE)*(numCols + 1));
memcpy(RowLocation(), h_Row, sizeof(CPUSPARSE_INDEX_TYPE)*nz);
memcpy(NzValues(), h_Val, sizeof(ElemType)*nz);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::SetMatrixFromSBCFormat(const size_t* blockIds, const ElemType* val, const size_t numBlocks, const size_t numRows, const size_t numCols)
{
if (!OwnBuffer())
LogicError("Cannot modify since the buffer is managed externally.");
SetFormat(matrixFormatSparseBlockCol);
Resize(numRows, numCols, numBlocks * numRows);
SetBlockSize(numBlocks);
memcpy(GetBlockIds(), blockIds, sizeof(size_t)*(numBlocks));
memcpy(Data(), val, sizeof(ElemType)*numBlocks*numRows);
}
template <class ElemType>
ElemType* CPUSparseMatrix<ElemType>::Data() const
{
return (Buffer() +
((GetFormat() == matrixFormatSparseCSC || GetFormat() == matrixFormatSparseCSR) ? GetCompIndex()[m_sliceViewOffset] : 0));
}
// WARNING: When memory is reallocated, existing information will be lost.
// TODO: add keepExistingValues (default to true) argument so that the existing values are kept even after reallocation
template <class ElemType>
void CPUSparseMatrix<ElemType>::Allocate(const size_t numRows, const size_t numCols, const size_t numNZElemRequested, const bool growOnly /*= true*/, bool keepExistingValues /*= true*/)
{
if (m_numRows != numRows || m_numCols != numCols)
LogicError("Error, calling allocate with dimensions (%d, %d), but the matrix has dimension (%d, %d).", (int)numRows, (int)numCols, (int)GetNumRows(), (int)GetNumCols());
size_t numNZElemToReserve = max(numNZElemRequested, (size_t) 1);
size_t newCompIndexSize;
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC)
newCompIndexSize = numCols + 1;
else if (GetFormat() == MatrixFormat::matrixFormatSparseCSR)
newCompIndexSize = numRows + 1;
else
newCompIndexSize = (numCols > numRows ? numCols : numRows) + 1;
bool reallocate = (GetSizeAllocated() < numNZElemToReserve || (GetSizeAllocated() > numNZElemToReserve && !growOnly) || GetCompIndexSize() < newCompIndexSize);
if (reallocate)
{
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC || GetFormat() == MatrixFormat::matrixFormatSparseCSR)
{
// The initialization of the following buffer is done by new []().
auto* pArray = new ElemType[numNZElemToReserve]();
auto* unCompIndex = new CPUSPARSE_INDEX_TYPE[numNZElemToReserve]();
auto* compIndex = new CPUSPARSE_INDEX_TYPE[newCompIndexSize]();
if (keepExistingValues && (NzCount() > numNZElemToReserve || GetCompIndexSize() > newCompIndexSize))
LogicError("Allocate: To keep values m_nz should <= numNZElemToReserve and m_compIndexSize <= newCompIndexSize");
if (keepExistingValues && NzCount() > 0)
{
assert(GetCompIndexSize() > 0 && NzCount() < numNZElemToReserve);
memcpy(pArray, Data(), NzSize());
memcpy(unCompIndex, GetUnCompIndex(), MajorIndexSize());
memcpy(compIndex, GetCompIndex(), SecondaryIndexSize());
}
// TODO: This is super ugly. The internals of the storage object should be a shared_ptr.
delete[] Buffer();
delete[] GetUnCompIndex();
delete[] GetCompIndex();
SetBuffer(pArray, numNZElemToReserve, false);
SetUnCompIndex(unCompIndex);
SetCompIndex(compIndex);
}
else if (GetFormat() == MatrixFormat::matrixFormatSparseBlockCol || GetFormat() == MatrixFormat::matrixFormatSparseBlockRow)
{
ElemType* blockVal = new ElemType[numNZElemToReserve];
size_t* blockIds = new size_t[newCompIndexSize];
if (keepExistingValues && (NzCount() > numNZElemToReserve || GetCompIndexSize() > newCompIndexSize))
LogicError("Resize: To keep values m_nz should <= numNZElemToReserve and m_compIndexSize <= newCompIndexSize");
if (keepExistingValues && GetSizeAllocated() > 0)
{
assert(GetCompIndexSize() > 0 && GetSizeAllocated() < numNZElemToReserve);
memcpy(blockVal, Data(), NzSize());
memcpy(blockIds, GetBlockIds(), sizeof(size_t) * GetCompIndexSize());
}
delete[] Buffer();
delete[] GetBlockIds();
SetBuffer(blockVal, numNZElemToReserve, false);
SetBlockIds(blockIds);
}
SetSizeAllocated(numNZElemToReserve);
SetCompIndexSize(newCompIndexSize);
}
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::RequireSizeAndAllocate(const size_t numRows, const size_t numCols, const size_t numNZElemToReserve /*= 10000*/, const bool growOnly /*= true*/, bool keepExistingValues /*= false*/)
{
RequireSizeAndAllocate(numRows, numCols, numNZElemToReserve, GetFormat(), growOnly, keepExistingValues);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::RequireSizeAndAllocate(const size_t numRows, const size_t numCols, const size_t numNZElemToReserve, const MatrixFormat matrixFormat, const bool growOnly /*= true*/, bool keepExistingValues /*= true*/)
{
RequireSize(numRows, numCols, numNZElemToReserve, matrixFormat, growOnly);
size_t newCompIndexSize = (numCols > numRows ? numCols : numRows) + 1;
bool reallocate = (GetSizeAllocated() < numNZElemToReserve || (GetSizeAllocated() > numNZElemToReserve && !growOnly) || GetCompIndexSize() < newCompIndexSize);
if (reallocate)
Allocate(numRows, numCols, numNZElemToReserve, growOnly, keepExistingValues);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::RequireSize(const size_t numRows, const size_t numCols, const bool growOnly /*= true*/)
{
RequireSize(numRows, numCols, GetFormat(), growOnly);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::RequireSize(const size_t numRows, const size_t numCols, const size_t numNZElemToReserve, const MatrixFormat matrixFormat, const bool growOnly /*= true*/)
{
if (GetFormat() != matrixFormat || GetNumRows() != numRows || GetNumCols() != numCols)
Resize(numRows, numCols, numNZElemToReserve, matrixFormat, growOnly);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::Resize(const size_t numRows, const size_t numCols, const size_t numNZElemToReserve /*= 10000*/, const bool growOnly /*= true*/)
{
Resize(numRows, numCols, numNZElemToReserve, GetFormat(), growOnly);
}
template <class ElemType>
void CPUSparseMatrix<ElemType>::Resize(const size_t numRows, const size_t numCols, const size_t numNZElemToReserve, const MatrixFormat matrixFormat, const bool growOnly /*= true*/)
{
VerifyResizable(__func__);
m_sliceViewOffset = 0;
m_numRows = numRows;
m_numCols = numCols;
SetNumStorageRows(numRows);
SetNumStorageCols(numCols);
SetFormat(matrixFormat);
size_t newCompIndexSize = (numCols > numRows ? numCols : numRows) + 1;
bool reallocate = (GetCompIndexSize() < newCompIndexSize);
if (reallocate)
Allocate(numRows, numCols, numNZElemToReserve, growOnly, false);
else
Reset();
}
// Reset matrix to 0.
template <class ElemType>
void CPUSparseMatrix<ElemType>::Reset()
{
// This is equivalent to setting m_nz = 0; Note we can only do this for sparse CSC/CSR because CompIndexSize is overloaded.
if (GetFormat() == MatrixFormat::matrixFormatSparseCSC || GetFormat() == MatrixFormat::matrixFormatSparseCSR)
memset(GetCompIndex(), 0, sizeof(CPUSPARSE_INDEX_TYPE) * GetCompIndexSize());
SetColIdx(-1);
SetBlockSize(0);
SetBlockIdShift(0);
}
// Implements product of one sparse and one dense matrix updating a third dense matrix. Input matrices are optionally transposed.
// NOTE: The only for using a class template instead of a function template was that I couldn't make the function template compile.
template <class ElemType, bool denseTimesSparse /* false means SparseTimesDense */, bool transposeA, bool transposeB>
class MultiplyDenseAndSparse{
public:
// Note: Below the ordering of the matrix parameters 'sparse' and 'dense' does not imply the order of the matrices in the product which is instead controlled
// by the value of the boolean template parameter 'denseTimesSparse'.
static void MultiplyAndWeightedAdd(ElemType alpha, const CPUSparseMatrix<ElemType>& sparse, const CPUMatrix<ElemType>& dense, ElemType beta, CPUMatrix<ElemType>& c)
{
const BaseMatrix<ElemType>* lhs = denseTimesSparse ? (const BaseMatrix<ElemType>*) &dense : (const BaseMatrix<ElemType>*) &sparse;
const BaseMatrix<ElemType>* rhs = denseTimesSparse ? (const BaseMatrix<ElemType>*) &sparse : (const BaseMatrix<ElemType>*) &dense;
// C(m:n) is the product of matrices X * Y where we have the shapes X(m:k) and Y(l:n)
size_t m = transposeA ? lhs->GetNumCols() : lhs->GetNumRows();
size_t k = transposeA ? lhs->GetNumRows() : lhs->GetNumCols();
size_t l = transposeB ? rhs->GetNumCols() : rhs->GetNumRows();
size_t n = transposeB ? rhs->GetNumRows() : rhs->GetNumCols();
if (k != l)
InvalidArgument("CPUSparseMatrix::MultiplyAndWeightedAdd: The inner dimensions of a (= %lu) and b (= %lu) don't match.", k, l);
// Determine the dimension of the outer index of the dense matrix.
size_t outerDimensionDense;
if ( denseTimesSparse && !transposeA) outerDimensionDense = dense.GetNumRows();
else if ( denseTimesSparse && transposeA) outerDimensionDense = dense.GetNumCols();
else if (!denseTimesSparse && !transposeB) outerDimensionDense = dense.GetNumCols();
else if (!denseTimesSparse && transposeB) outerDimensionDense = dense.GetNumRows();
if (beta == 0)
c.RequireSize(m, n);
else
c.VerifySize(m, n); // Can't resize if beta != 0
if (beta == 0)
memset(c.Data(), 0, sizeof(ElemType)* c.GetNumElements());
else if (beta != 1)
{
#pragma omp parallel for
foreach_coord(i, j, c)
{
c(i, j) = beta * c(i, j);
}
}
else /* beta == 1*/
; // We keep the previous value of c before adding the matrix product.
// In case one factor in the matrix product is empty there is nothing to add to the output c so we can exit here.
if (sparse.IsEmpty() || dense.IsEmpty())
return;
// TODO: Implement CSR as a transposition of b, like we do for GPU.
if (sparse.GetFormat() != matrixFormatSparseCSC)
NOT_IMPLEMENTED;
// Up to here we have:
// * checked that the matrices are compatible in size
// * Initialized the output matrix c
// Now do the actual multiplication.
ElemType* valueBuffer = sparse.Buffer() + *sparse.SecondaryIndexLocation(); // Points to the value buffer of the current view (i.e. buffer containing values of non-zero elements).
int* rowIndexBuffer = sparse.MajorIndexLocation(); // Points to the index buffer of the current view (i.e. buffer containing indices of non-zero elements).
size_t iNonzero = 0; // Number of nonzero elements handled so far for curent slice view.
int numPreviosNonzero = sparse.SecondaryIndexLocation()[0]; // Total number of nonzero values handled in previous slices.
// Loop over columns of the sparse matrix
for (size_t colSparse = 0; colSparse < sparse.GetNumCols(); colSparse++)
{
size_t numNonzeroInSparseCol = sparse.SecondaryIndexLocation()[colSparse + 1] - numPreviosNonzero;
// Loop over the nonzero rows of the current column of the sparse matrix
for (; iNonzero < numNonzeroInSparseCol; iNonzero++)
{
size_t rowSparse = rowIndexBuffer[iNonzero]; // RowLocation
ElemType sparseVal = valueBuffer[iNonzero];
// Determine the index of the 'outer' dimension of the sparse matrix and the common inner index.
size_t outerIndexSparse;
size_t innerIndex;
// Below if-statements are evaluated at compile time.
if ( denseTimesSparse && !transposeB) { outerIndexSparse = colSparse; innerIndex = rowSparse; }
else if ( denseTimesSparse && transposeB) { outerIndexSparse = rowSparse; innerIndex = colSparse; }
else if (!denseTimesSparse && !transposeA) { outerIndexSparse = rowSparse; innerIndex = colSparse; }
else if (!denseTimesSparse && transposeA) { outerIndexSparse = colSparse; innerIndex = rowSparse; }
// Loop over the outer index of the dense matrix
for (size_t outerIndexDense = 0; outerIndexDense < outerDimensionDense; outerIndexDense++)
{
// Determine the row index of the dense input matrix.
// Below if-statements are evaluated at compile time.
ElemType denseVal;
if ( denseTimesSparse && !transposeA) denseVal = dense(outerIndexDense, innerIndex);
else if ( denseTimesSparse && transposeA) denseVal = dense( innerIndex, outerIndexDense);
else if (!denseTimesSparse && !transposeB) denseVal = dense( innerIndex, outerIndexDense);
else if (!denseTimesSparse && transposeB) denseVal = dense(outerIndexDense, innerIndex);
// Update matrix c.
if (denseTimesSparse)
c(outerIndexDense, outerIndexSparse) += alpha * denseVal * sparseVal;
else /*Sparse times dense */
c(outerIndexSparse, outerIndexDense) += alpha * denseVal * sparseVal;
}
}
}
}
};
// c = alpha * lhs * rhs + beta * c
// dense * sparse -> dense
template <class ElemType>
void CPUSparseMatrix<ElemType>::MultiplyAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const bool transposeA,
const CPUSparseMatrix<ElemType>& b, const bool transposeB, ElemType beta, CPUMatrix<ElemType>& c)
{
// Mapping variables to compile time template parameters for efficiency
if ( transposeA && transposeB)
MultiplyDenseAndSparse<ElemType, true /* dense times sparse */, true /* transposeA */, true /*transposeB*/>::MultiplyAndWeightedAdd(alpha, b /*sparse*/, a /* dense */, beta, c /* matrix beeing updated */);
else if ( transposeA && !transposeB)
MultiplyDenseAndSparse<ElemType, true /* dense times sparse */, true /* transposeA */, false /*transposeB*/>::MultiplyAndWeightedAdd(alpha, b /*sparse*/, a /* dense */, beta, c /* matrix beeing updated */);
else if (!transposeA && transposeB)
MultiplyDenseAndSparse<ElemType, true /* dense times sparse */, false /* transposeA */, true /*transposeB*/>::MultiplyAndWeightedAdd(alpha, b /*sparse*/, a /* dense */, beta, c /* matrix beeing updated */);
else if (!transposeA && !transposeB)
MultiplyDenseAndSparse<ElemType, true /* dense times sparse */, false /* transposeA */, false /*transposeB*/>::MultiplyAndWeightedAdd(alpha, b /*sparse*/, a /* dense */, beta, c /* matrix beeing updated */);
}
// c = alpha * lhs * rhs + beta * c
// sparse * dense -> dense
template <class ElemType>
void CPUSparseMatrix<ElemType>::MultiplyAndWeightedAdd(ElemType alpha, const CPUSparseMatrix<ElemType>& a, const bool transposeA,
const CPUMatrix<ElemType>& b, const bool transposeB, ElemType beta, CPUMatrix<ElemType>& c)