-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhingetree_sparse_gpu.cu
745 lines (533 loc) · 36.1 KB
/
hingetree_sparse_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
/*-
* Nathan Lay
* AI Resource at National Cancer Institute
* National Institutes of Health
* April 2024
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <type_traits>
#include "torch/extension.h"
#include "HingeTreeCommon.cuh"
#include <cuda.h>
typedef c10::IntArrayRef IntArrayRef;
// From: https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html
// And from: https://stackoverflow.com/questions/39274472/error-function-atomicadddouble-double-has-already-been-defined
#if !defined(__CUDA_ARCH__) || __CUDA_ARCH__ >= 600
//#if __CUDA_ARCH__ < 600
#else
static inline __device__ double atomicAdd(double* address, double val)
{
unsigned long long int* address_as_ull =
(unsigned long long int*)address;
unsigned long long int old = *address_as_ull, assumed;
do {
assumed = old;
old = atomicCAS(address_as_ull, assumed,
__double_as_longlong(val +
__longlong_as_double(assumed)));
// Note: uses integer comparison to avoid hang in case of NaN (since NaN != NaN)
} while (assumed != old);
return __longlong_as_double(old);
}
#endif
namespace {
template<typename RealType>
class IndexMap {
public:
using KeyType = int64_t;
using ValueType = RealType;
__host__ __device__ constexpr static KeyType UnoccupiedKey() { return KeyType((((uint64_t)1) << 63) - 1); }
// d_keys assumed to be initialized to UnoccupiedKey()
__host__ IndexMap(KeyType *d_keys, ValueType *d_values, size_t length, bool *d_fail)
: m_d_keys(d_keys), m_d_values(d_values), m_length(length), m_d_fail(d_fail) { }
__device__ ValueType & operator[](const KeyType &key) {
if (key == UnoccupiedKey()) {
*m_d_fail = true;
return m_d_values[0];
}
constexpr unsigned long long unoccupied = UnoccupiedKey();
const unsigned long long key_as_ull = (unsigned long long)key;
const size_t hash = (size_t)key_as_ull;
for (size_t i = 0; i < m_length; ++i) {
const size_t index = ((hash + i) % m_length);
unsigned long long * const d_address = ((unsigned long long *)m_d_keys) + index;
const unsigned long long old = atomicCAS(d_address, unoccupied, key_as_ull);
if (old == unoccupied || old == key_as_ull)
return m_d_values[index];
}
*m_d_fail = true;
return m_d_values[0];
}
private:
KeyType * const m_d_keys;
ValueType * const m_d_values;
const size_t m_length;
bool * const m_d_fail;
};
template class IndexMap<float>;
template class IndexMap<double>;
static_assert(std::is_trivially_copyable_v<IndexMap<float>>);
static_assert(std::is_trivially_copyable_v<IndexMap<double>>);
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void BackwardThresholdsKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inWeights,
const RealType *d_outDataGradient, IndexMap<RealType> inThresholdsGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
//RealType * const d_thresholdsGradient = d_inThresholdsGradient + j*i64ThresholdStride;
const int64_t thresholdsOffset = j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const KeyType thresholdIndex = keyMarginTuple.thresholdIndex;
const RealType sign = RealType((RealType(0) < signedMargin) - (signedMargin < RealType(0)));
const RealType * const d_leafWeights = d_inWeights + (j*i64WeightsStride + key)*i64InnerWeightsNum;
const RealType * const d_outGradient = d_outDataGradient + ((i*i64NumTrees + j)*i64InnerDataNum + k)*i64InnerWeightsNum;
RealType tmpSum = RealType(0);
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
tmpSum += d_leafWeights[l] * d_outGradient[l];
tmpSum *= -sign;
atomicAdd(&inThresholdsGradient[thresholdsOffset + thresholdIndex], tmpSum); // Do this just once
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void BackwardWeightsKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, /*const RealType *d_inWeights,*/
const RealType *d_outDataGradient, IndexMap<RealType> inWeightsGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const RealType margin = std::abs(signedMargin);
const RealType * const d_outGradient = d_outDataGradient + ((i*i64NumTrees + j)*i64InnerDataNum + k)*i64InnerWeightsNum;
const int64_t leafWeightsOffset = (j*i64WeightsStride + key)*i64InnerWeightsNum;
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
atomicAdd(&inWeightsGradient[leafWeightsOffset + l], margin * d_outGradient[l]); // Really bad!
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void BackwardDataKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inWeights,
const RealType *d_outDataGradient, IndexMap<RealType> inDataGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const KeyType thresholdIndex = keyMarginTuple.thresholdIndex;
const int64_t i64InputIndex = d_ordinals[thresholdIndex];
const RealType * const d_leafWeights = d_inWeights + (j*i64WeightsStride + key)*i64InnerWeightsNum;
const RealType * const d_outGradient = d_outDataGradient + ((i*i64NumTrees + j)*i64InnerDataNum + k)*i64InnerWeightsNum;
const RealType sign = RealType((RealType(0) < signedMargin) - (signedMargin < RealType(0)));
RealType tmpSum = RealType(0);
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
tmpSum += d_leafWeights[l] * d_outGradient[l];
tmpSum *= sign;
atomicAdd(&inDataGradient[((i*i64NumChannels + i64InputIndex)*i64InnerDataNum + k)], tmpSum); // Do this just once
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void FusedBackwardThresholdsKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inWeights, const RealType *d_inLinearWeights,
const RealType *d_outDataGradient, IndexMap<RealType> inThresholdsGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum, int64_t i64OutChannels) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
//RealType * const d_thresholdsGradient = d_inThresholdsGradient + j*i64ThresholdStride;
const int64_t thresholdsOffset = j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const KeyType thresholdIndex = keyMarginTuple.thresholdIndex;
const RealType sign = RealType((RealType(0) < signedMargin) - (signedMargin < RealType(0)));
const RealType * const d_leafWeights = d_inWeights + (j*i64WeightsStride + key)*i64InnerWeightsNum;
RealType tmpSum = RealType(0);
for (int64_t o = 0; o < i64OutChannels; ++o) {
const RealType * const d_outGradient = d_outDataGradient + ((i*i64OutChannels + o)*i64InnerDataNum + k)*i64InnerWeightsNum;
RealType tmpSum2 = RealType(0);
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
tmpSum2 += d_leafWeights[l] * d_outGradient[l];
tmpSum += tmpSum2 * d_inLinearWeights[o*i64NumTrees + j];
}
tmpSum *= -sign;
atomicAdd(&inThresholdsGradient[thresholdsOffset + thresholdIndex], tmpSum);
//atomicAdd(d_thresholdsGradient + thresholdIndex, tmpSum); // Do this just once
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void FusedBackwardWeightsKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inLinearWeights,
const RealType *d_outDataGradient, IndexMap<RealType> inWeightsGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum, int64_t i64OutChannels) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const RealType margin = std::abs(signedMargin);
//RealType * const d_leafWeightsGradient = d_inWeightsGradient + (j*i64WeightsStride + key)*i64InnerWeightsNum;
const int64_t leafWeightsOffset = (j*i64WeightsStride + key)*i64InnerWeightsNum;
for (int64_t l = 0; l < i64InnerWeightsNum; ++l) {
RealType tmpSum = RealType(0);
for (int64_t o = 0; o < i64OutChannels; ++o) {
const RealType * const d_outGradient = d_outDataGradient + ((i*i64OutChannels + o)*i64InnerDataNum + k)*i64InnerWeightsNum;
tmpSum += d_inLinearWeights[o*i64NumTrees + j] * d_outGradient[l];
}
tmpSum *= margin;
atomicAdd(&inWeightsGradient[leafWeightsOffset + l], tmpSum);
//atomicAdd(d_leafWeightsGradient + l, tmpSum); // Really bad!
}
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void FusedBackwardDataKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inWeights, const RealType *d_inLinearWeights,
const RealType *d_outDataGradient, IndexMap<RealType> inDataGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum, int64_t i64OutChannels) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType signedMargin = keyMarginTuple.signedMargin;
const KeyType thresholdIndex = keyMarginTuple.thresholdIndex;
const int64_t i64InputIndex = d_ordinals[thresholdIndex];
const RealType * const d_leafWeights = d_inWeights + (j*i64WeightsStride + key)*i64InnerWeightsNum;
const RealType sign = RealType((RealType(0) < signedMargin) - (signedMargin < RealType(0)));
RealType tmpSum = RealType(0);
for (int64_t o = 0; o < i64OutChannels; ++o) {
const RealType * const d_outGradient = d_outDataGradient + ((i*i64OutChannels + o)*i64InnerDataNum + k)*i64InnerWeightsNum;
RealType tmpSum2 = RealType(0);
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
tmpSum2 += d_leafWeights[l] * d_outGradient[l];
tmpSum += d_inLinearWeights[o*i64NumTrees + j] * tmpSum2;
}
tmpSum *= sign;
atomicAdd(&inDataGradient[(i*i64NumChannels + i64InputIndex)*i64InnerDataNum + k], tmpSum);
//atomicAdd(d_inDataGradient + ((i*i64NumChannels + i64InputIndex)*i64InnerDataNum + k), tmpSum); // Do this just once
}
}
template<typename TreeTraitsTypeGPU, typename RealType>
__global__ void FusedBackwardLinearWeightsKernel(const RealType *d_inData, const RealType *d_inThresholds, const int64_t *d_inOrdinals, const RealType *d_inWeights,
const RealType *d_outDataGradient, RealType *d_inLinearWeightsGradient, int64_t i64TreeDepth, int64_t i64ThresholdStride, int64_t i64WeightsStride, int64_t i64InnerWeightsNum, int64_t i64NumTrees,
int64_t i64OuterNum, int64_t i64NumChannels, int64_t i64InnerDataNum, int64_t i64OutChannels) {
typedef typename TreeTraitsTypeGPU::KeyType KeyType;
const int64_t i = (int64_t)blockIdx.y * blockDim.y + threadIdx.y;
const int64_t j = (int64_t)blockIdx.z * blockDim.z + threadIdx.z;
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64OuterNum && j < i64NumTrees && k < i64InnerDataNum) {
const RealType * const d_thresholds = d_inThresholds + j*i64ThresholdStride;
const int64_t * const d_ordinals = d_inOrdinals + j*i64ThresholdStride;
const RealType * const d_row = d_inData + ((i*i64NumChannels + 0)*i64InnerDataNum + k);
// leaf key, margin, ordinal index
const auto keyMarginTuple = TreeTraitsTypeGPU::ComputeKeyAndSignedMargin(d_row, d_thresholds, d_ordinals, i64TreeDepth, i64InnerDataNum);
const KeyType key = keyMarginTuple.leafKey;
const RealType margin = std::abs(keyMarginTuple.signedMargin);
const RealType * const d_leafWeights = d_inWeights + (j*i64WeightsStride + key)*i64InnerWeightsNum;
for (int64_t o = 0; o < i64OutChannels; ++o) {
const RealType * const d_outGradient = d_outDataGradient + ((i*i64OutChannels + o)*i64InnerDataNum + k)*i64InnerWeightsNum;
RealType tmpSum = RealType(0);
for (int64_t l = 0; l < i64InnerWeightsNum; ++l)
tmpSum += d_leafWeights[l] * d_outGradient[l];
tmpSum *= margin;
atomicAdd(d_inLinearWeightsGradient + (o*i64NumTrees + j), tmpSum); // This is bad!
}
}
}
__global__ void ConvertLinearToCoo(const int64_t *d_i64Linear, int64_t *d_i64Coo, const int64_t *d_i64Shape, int64_t i64Dimension, int64_t i64NumIndices) {
const int64_t i = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i < i64NumIndices) {
int64_t n = d_i64Linear[i];
for (int64_t d = i64Dimension-1; d > 0; --d) {
const int64_t q = n / d_i64Shape[d];
const int64_t r = n - q * d_i64Shape[d];
d_i64Coo[i64NumIndices*d + i] = r;
n = q;
}
d_i64Coo[i64NumIndices*0 + i] = n;
}
}
torch::Tensor make_sparse(torch::Tensor linearIndices, torch::Tensor values, IntArrayRef shape) {
if (linearIndices.scalar_type() != torch::kInt64 || linearIndices.dim() != 1 || linearIndices.device() != values.device() || linearIndices.sizes() != values.sizes())
return torch::Tensor();
const int64_t i64Dimension = shape.size();
{
auto mask = (linearIndices != IndexMap<float>::UnoccupiedKey());
values = values.masked_select(mask);
linearIndices = linearIndices.masked_select(mask);
}
const int64_t i64MaxIndex = std::accumulate(shape.begin(), shape.end(), (int64_t)1, std::multiplies<int64_t>());
if (linearIndices.min().to(torch::kCPU).item<int64_t>() < 0 || linearIndices.max().to(torch::kCPU).item<int64_t>() >= i64MaxIndex) {
std::cerr << "Error: Invalid linear index encountered during conversion to sparse." << std::endl;
return torch::Tensor();
}
const int64_t i64NumIndices = linearIndices.sizes()[0];
auto clOptions = torch::TensorOptions().dtype(torch::kInt64);
torch::Tensor shapeAsTensor = torch::empty({ i64Dimension }, clOptions);
std::copy(shape.begin(), shape.end(), shapeAsTensor.data_ptr<int64_t>());
shapeAsTensor = shapeAsTensor.to(linearIndices.device());
torch::Tensor cooIndices = torch::empty({ i64Dimension, i64NumIndices }, clOptions.device(linearIndices.device()));
constexpr unsigned int threadsPerBlock = 1024;
const unsigned int numBlocks = (unsigned int)((i64NumIndices + threadsPerBlock-1)/threadsPerBlock);
ConvertLinearToCoo<<<numBlocks, threadsPerBlock>>>(linearIndices.data_ptr<int64_t>(), cooIndices.data_ptr<int64_t>(), shapeAsTensor.data_ptr<int64_t>(), i64Dimension, i64NumIndices);
return torch::sparse_coo_tensor(cooIndices, values, shape).coalesce();
}
} // end anonymous namespace
template<typename RealType, typename TreeTraitsType>
std::vector<torch::Tensor> sparse_hingetree_gpu_backward(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor outDataGrad) {
typedef bleak::HingeTreeCommonGPU<TreeTraitsType> TreeTraitsTypeGPU;
if (bInOrdinalsGrad) // Not differentiable, ever!
return std::vector<torch::Tensor>();
if (inData.dim() < 2 || inThresholds.dim() != 2 || inOrdinals.dim() != 2 || inWeights.dim() < 2)
return std::vector<torch::Tensor>();
if (inThresholds.sizes() != inOrdinals.sizes() || inWeights.sizes()[0] != inThresholds.sizes()[0])
return std::vector<torch::Tensor>();
const int64_t i64NumTrees = inWeights.sizes()[0];
const int64_t i64NumLeavesPerTree = inWeights.sizes()[1];
const int64_t i64TreeDepth = TreeTraitsType::ComputeDepth(i64NumLeavesPerTree);
if (i64TreeDepth > TreeTraitsType::GetMaxDepth() || inThresholds.sizes()[1] != TreeTraitsType::GetThresholdCount(i64TreeDepth))
return std::vector<torch::Tensor>();
const int64_t i64BatchSize = inData.sizes()[0];
const int64_t i64NumChannels = inData.sizes()[1];
const int64_t i64NumDecisionsPerTree = inThresholds.sizes()[1];
if (inOrdinals.min().to(torch::kCPU).item<int64_t>() < 0 || inOrdinals.max().to(torch::kCPU).item<int64_t>() >= i64NumChannels)
return std::vector<torch::Tensor>();
std::vector<IntArrayRef::value_type> vSizes;
vSizes.resize(2);
vSizes[0] = inData.sizes()[0]; // batch size
vSizes[1] = inWeights.sizes()[0]; // Number of trees
int64_t i64InnerDataNum = 1;
{
auto inDataSlice = inData.sizes().slice(2);
i64InnerDataNum = std::accumulate(inDataSlice.begin(), inDataSlice.end(), (int64_t)1, std::multiplies<IntArrayRef::value_type>());
vSizes.insert(vSizes.end(), inDataSlice.begin(), inDataSlice.end());
}
int64_t i64InnerWeightsNum = 1;
{
auto inWeightsSlice = inWeights.sizes().slice(2);
i64InnerWeightsNum = std::accumulate(inWeightsSlice.begin(), inWeightsSlice.end(), (int64_t)1, std::multiplies<IntArrayRef::value_type>());
vSizes.insert(vSizes.end(), inWeightsSlice.begin(), inWeightsSlice.end());
}
// Sanity check on outDataGrad
if (outDataGrad.sizes() != IntArrayRef(vSizes.data(), vSizes.size()))
return std::vector<torch::Tensor>();
const int64_t i64DataSize = std::min((int64_t)inData.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum);
const int64_t i64WeightsSize = std::min((int64_t)inWeights.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum*i64InnerWeightsNum);
const int64_t i64ThresholdsSize = std::min((int64_t)inThresholds.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum);
const int64_t i64WorkSize = std::max(std::max(i64DataSize, i64WeightsSize), i64ThresholdsSize);
auto clOptions = torch::TensorOptions().device(inData.device());
torch::Tensor indices = torch::empty({ i64WorkSize }, clOptions.dtype(torch::kInt64));
torch::Tensor values = torch::empty({ i64WorkSize }, clOptions.dtype(inData.dtype()));
torch::Tensor fail = torch::scalar_tensor(false, clOptions.dtype(torch::kBool));
IndexMap<RealType> gradientMap(indices.data_ptr<int64_t>(), values.data_ptr<RealType>(), i64WorkSize, fail.data_ptr<bool>());
const RealType * const p_inData = inData.data_ptr<RealType>();
const RealType * const p_inThresholds = inThresholds.data_ptr<RealType>();
const int64_t * const p_inOrdinals = inOrdinals.data_ptr<int64_t>();
const RealType * const p_inWeights = inWeights.data_ptr<RealType>();
const RealType * const p_outDataGrad = outDataGrad.data_ptr<RealType>();
const dim3 threadsPerBlock(16,8,8);
const dim3 numBlocks((i64InnerDataNum + threadsPerBlock.x-1)/threadsPerBlock.x, (i64BatchSize + threadsPerBlock.y-1)/threadsPerBlock.y, (i64NumTrees + threadsPerBlock.z-1)/threadsPerBlock.z);
std::vector<torch::Tensor> vGradTensors(4);
if (bInDataGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
BackwardDataKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inWeights, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[0] = make_sparse(indices, values, inData.sizes());
}
if (bInThresholdsGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
BackwardThresholdsKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inWeights, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[1] = make_sparse(indices, values, inThresholds.sizes());
}
if (bInWeightsGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
BackwardWeightsKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[3] = make_sparse(indices, values, inWeights.sizes());
}
return vGradTensors;
}
template<typename RealType, typename TreeTraitsType>
std::vector<torch::Tensor> sparse_hingetree_fused_linear_gpu_backward(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor inLinearWeights, bool bInLinearWeightsGrad, torch::Tensor inLinearBias, bool bInLinearBiasGrad, torch::Tensor outDataGrad) {
typedef bleak::HingeTreeCommonGPU<TreeTraitsType> TreeTraitsTypeGPU;
if (bInOrdinalsGrad) // Not differentiable, ever!
return std::vector<torch::Tensor>();
if (inData.dim() < 2 || inThresholds.dim() != 2 || inOrdinals.dim() != 2 || inWeights.dim() < 2 || inLinearWeights.dim() != 2 || inLinearBias.dim() != 1 || outDataGrad.dim() < 2)
return std::vector<torch::Tensor>();
if (inThresholds.sizes() != inOrdinals.sizes() || inWeights.sizes()[0] != inThresholds.sizes()[0] || inWeights.sizes()[0] != inLinearWeights.sizes()[1] || inLinearWeights.sizes()[0] != inLinearBias.sizes()[0])
return std::vector<torch::Tensor>();
const int64_t i64NumTrees = inWeights.sizes()[0];
const int64_t i64NumLeavesPerTree = inWeights.sizes()[1];
const int64_t i64TreeDepth = TreeTraitsType::ComputeDepth(i64NumLeavesPerTree);
const int64_t i64OutChannels = inLinearWeights.sizes()[0];
if (i64TreeDepth > TreeTraitsType::GetMaxDepth() || inThresholds.sizes()[1] != TreeTraitsType::GetThresholdCount(i64TreeDepth))
return std::vector<torch::Tensor>();
const int64_t i64BatchSize = inData.sizes()[0];
const int64_t i64NumChannels = inData.sizes()[1];
const int64_t i64NumDecisionsPerTree = inThresholds.sizes()[1];
if (inOrdinals.min().to(torch::kCPU).item<int64_t>() < 0 || inOrdinals.max().to(torch::kCPU).item<int64_t>() >= i64NumChannels)
return std::vector<torch::Tensor>();
std::vector<IntArrayRef::value_type> vSizes;
vSizes.resize(2);
vSizes[0] = inData.sizes()[0]; // batch size
//vSizes[1] = inWeights.sizes()[0]; // Number of trees
vSizes[1] = inLinearWeights.sizes()[0]; // Number of linear outputs
int64_t i64InnerDataNum = 1;
{
auto inDataSlice = inData.sizes().slice(2);
i64InnerDataNum = std::accumulate(inDataSlice.begin(), inDataSlice.end(), (int64_t)1, std::multiplies<IntArrayRef::value_type>());
vSizes.insert(vSizes.end(), inDataSlice.begin(), inDataSlice.end());
}
int64_t i64InnerWeightsNum = 1;
{
auto inWeightsSlice = inWeights.sizes().slice(2);
i64InnerWeightsNum = std::accumulate(inWeightsSlice.begin(), inWeightsSlice.end(), (int64_t)1, std::multiplies<IntArrayRef::value_type>());
vSizes.insert(vSizes.end(), inWeightsSlice.begin(), inWeightsSlice.end());
}
// Sanity check on outDataGrad
if (outDataGrad.sizes() != IntArrayRef(vSizes.data(), vSizes.size()))
return std::vector<torch::Tensor>();
const int64_t i64DataSize = std::min((int64_t)inData.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum);
const int64_t i64WeightsSize = std::min((int64_t)inWeights.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum*i64InnerWeightsNum);
const int64_t i64ThresholdsSize = std::min((int64_t)inThresholds.numel(), i64BatchSize*i64NumTrees*i64InnerDataNum);
const int64_t i64WorkSize = std::max(std::max(i64DataSize, i64WeightsSize), i64ThresholdsSize);
auto clOptions = torch::TensorOptions().device(inData.device());
torch::Tensor indices = torch::empty({ i64WorkSize }, clOptions.dtype(torch::kInt64));
torch::Tensor values = torch::empty({ i64WorkSize }, clOptions.dtype(inData.dtype()));
torch::Tensor fail = torch::scalar_tensor(false, clOptions.dtype(torch::kBool));
IndexMap<RealType> gradientMap(indices.data_ptr<int64_t>(), values.data_ptr<RealType>(), i64WorkSize, fail.data_ptr<bool>());
const RealType * const p_inData = inData.data_ptr<RealType>();
const RealType * const p_inThresholds = inThresholds.data_ptr<RealType>();
const int64_t * const p_inOrdinals = inOrdinals.data_ptr<int64_t>();
const RealType * const p_inWeights = inWeights.data_ptr<RealType>();
const RealType * const p_inLinearWeights = inLinearWeights.data_ptr<RealType>();
const RealType * const p_outDataGrad = outDataGrad.data_ptr<RealType>();
const dim3 threadsPerBlock(16,8,8);
const dim3 numBlocks((i64InnerDataNum + threadsPerBlock.x-1)/threadsPerBlock.x, (i64BatchSize + threadsPerBlock.y-1)/threadsPerBlock.y, (i64NumTrees + threadsPerBlock.z-1)/threadsPerBlock.z);
std::vector<torch::Tensor> vGradTensors(6);
if (bInDataGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
FusedBackwardDataKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inWeights, p_inLinearWeights, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum, i64OutChannels);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[0] = make_sparse(indices, values, inData.sizes());
}
if (bInThresholdsGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
FusedBackwardThresholdsKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inWeights, p_inLinearWeights, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum, i64OutChannels);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[1] = make_sparse(indices, values, inThresholds.sizes());
}
if (bInWeightsGrad) {
values.zero_();
indices.fill_(gradientMap.UnoccupiedKey());
FusedBackwardWeightsKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inLinearWeights, p_outDataGrad, gradientMap,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum, i64OutChannels);
if (fail.to(torch::kCPU).item<bool>()) {
std::cerr << "Error: IndexMap overflowed!" << std::endl;
return std::vector<torch::Tensor>();
}
vGradTensors[3] = make_sparse(indices, values, inWeights.sizes());
}
if (bInLinearWeightsGrad) {
torch::Tensor inLinearWeightsGrad = torch::zeros_like(inLinearWeights);
RealType * const p_inLinearWeightsGrad = inLinearWeightsGrad.data_ptr<RealType>();
FusedBackwardLinearWeightsKernel<TreeTraitsTypeGPU><<<numBlocks, threadsPerBlock>>>(p_inData, p_inThresholds, p_inOrdinals, p_inWeights, p_outDataGrad, p_inLinearWeightsGrad,
i64TreeDepth, i64NumDecisionsPerTree, i64NumLeavesPerTree, i64InnerWeightsNum, i64NumTrees, i64BatchSize, i64NumChannels, i64InnerDataNum, i64OutChannels);
vGradTensors[4] = inLinearWeightsGrad;
}
if (bInLinearBiasGrad) {
std::vector<IntArrayRef::value_type> vSumOver(vSizes.size()-1);
vSumOver[0] = 0;
std::iota(vSumOver.begin()+1, vSumOver.end(), 2);
torch::Tensor inLinearBiasGrad = outDataGrad.sum(IntArrayRef(vSumOver.data(), vSumOver.size()));
vGradTensors[5] = inLinearBiasGrad;
}
return vGradTensors;
}
template std::vector<torch::Tensor> sparse_hingetree_gpu_backward<float, bleak::HingeTreeCommon<float>>(torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor);
template std::vector<torch::Tensor> sparse_hingetree_gpu_backward<double, bleak::HingeTreeCommon<double>>(torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor);
template std::vector<torch::Tensor> sparse_hingetree_gpu_backward<float, bleak::HingeFernCommon<float>>(torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor);
template std::vector<torch::Tensor> sparse_hingetree_gpu_backward<double, bleak::HingeFernCommon<double>>(torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor, bool, torch::Tensor);
template std::vector<torch::Tensor> sparse_hingetree_fused_linear_gpu_backward<float, bleak::HingeTreeCommon<float>>(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor inLinearWeights, bool bInLinearWeightsGrad, torch::Tensor inLinearBias, bool bInLinearBiasGrad, torch::Tensor outDataGrad);
template std::vector<torch::Tensor> sparse_hingetree_fused_linear_gpu_backward<double, bleak::HingeTreeCommon<double>>(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor inLinearWeights, bool bInLinearWeightsGrad, torch::Tensor inLinearBias, bool bInLinearBiasGrad, torch::Tensor outDataGrad);
template std::vector<torch::Tensor> sparse_hingetree_fused_linear_gpu_backward<float, bleak::HingeFernCommon<float>>(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor inLinearWeights, bool bInLinearWeightsGrad, torch::Tensor inLinearBias, bool bInLinearBiasGrad, torch::Tensor outDataGrad);
template std::vector<torch::Tensor> sparse_hingetree_fused_linear_gpu_backward<double, bleak::HingeFernCommon<double>>(torch::Tensor inData, bool bInDataGrad, torch::Tensor inThresholds, bool bInThresholdsGrad, torch::Tensor inOrdinals, bool bInOrdinalsGrad, torch::Tensor inWeights, bool bInWeightsGrad, torch::Tensor inLinearWeights, bool bInLinearWeightsGrad, torch::Tensor inLinearBias, bool bInLinearBiasGrad, torch::Tensor outDataGrad);