/
stats_ops.cc
1651 lines (1505 loc) · 71.7 KB
/
stats_ops.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
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <limits>
#include <vector>
#include "third_party/eigen3/Eigen/Core"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/kernels/boosted_trees/boosted_trees.pb.h"
#include "tensorflow/core/kernels/boosted_trees/tree_helper.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
using Matrix =
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
using ConstMatrixMap = Eigen::Map<const Matrix>;
using MatrixMap = Eigen::Map<Matrix>;
using ConstVectorMap = Eigen::Map<const Eigen::VectorXf>;
using VectorMap = Eigen::Map<Eigen::VectorXf>;
constexpr char kInequalitySplit[] = "inequality";
constexpr char kEqualitySplit[] = "equality";
// V1 Op. Deprecated. BoostedTreesCalculateBestFeatureSplitOpV2 is V2.
class BoostedTreesCalculateBestGainsPerFeatureOp : public OpKernel {
public:
explicit BoostedTreesCalculateBestGainsPerFeatureOp(
OpKernelConstruction* const context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("max_splits", &max_splits_));
OP_REQUIRES_OK(context, context->GetAttr("num_features", &num_features_));
}
void Compute(OpKernelContext* const context) override {
// node_id_range
const Tensor* node_id_range_t;
OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t));
const auto node_id_range = node_id_range_t->vec<int32>();
const int32 node_id_first = node_id_range(0); // inclusive
const int32 node_id_last = node_id_range(1); // exclusive
// stats_summary_list
OpInputList stats_summary_list;
OP_REQUIRES_OK(context, context->input_list("stats_summary_list",
&stats_summary_list));
const int64 num_buckets = stats_summary_list[0].dim_size(1);
// Check for single logit: 1 gradient + 1 hessian value.
DCHECK_EQ(stats_summary_list[0].dim_size(2), 2);
std::vector<TTypes<float, 3>::ConstTensor> stats_summary;
stats_summary.reserve(stats_summary_list.size());
for (const auto& tensor : stats_summary_list) {
stats_summary.emplace_back(tensor.tensor<float, 3>());
}
const Tensor* l1_t;
OP_REQUIRES_OK(context, context->input("l1", &l1_t));
const auto l1 = l1_t->scalar<float>()();
const Tensor* l2_t;
OP_REQUIRES_OK(context, context->input("l2", &l2_t));
const auto l2 = l2_t->scalar<float>()();
const Tensor* tree_complexity_t;
OP_REQUIRES_OK(context,
context->input("tree_complexity", &tree_complexity_t));
const auto tree_complexity = tree_complexity_t->scalar<float>()();
const Tensor* min_node_weight_t;
OP_REQUIRES_OK(context,
context->input("min_node_weight", &min_node_weight_t));
const auto min_node_weight = min_node_weight_t->scalar<float>()();
// Allocate output lists of tensors:
OpOutputList output_node_ids_list;
OP_REQUIRES_OK(
context, context->output_list("node_ids_list", &output_node_ids_list));
OpOutputList output_gains_list;
OP_REQUIRES_OK(context,
context->output_list("gains_list", &output_gains_list));
OpOutputList output_thresholds_list;
OP_REQUIRES_OK(context, context->output_list("thresholds_list",
&output_thresholds_list));
OpOutputList output_left_node_contribs_list;
OP_REQUIRES_OK(context,
context->output_list("left_node_contribs_list",
&output_left_node_contribs_list));
OpOutputList output_right_node_contribs_list;
OP_REQUIRES_OK(context,
context->output_list("right_node_contribs_list",
&output_right_node_contribs_list));
// Use identity later to convert float to Eigen::Matrix type for input to
// CalculateWeightsAndGains. This op only supports single dimension logits.
Eigen::MatrixXf identity;
identity.setIdentity(1, 1);
// Get the best split info per node for each feature.
for (int feature_idx = 0; feature_idx < num_features_; ++feature_idx) {
std::vector<float> cum_grad;
std::vector<float> cum_hess;
cum_grad.reserve(num_buckets);
cum_hess.reserve(num_buckets);
std::vector<int32> output_node_ids;
std::vector<float> output_gains;
std::vector<int32> output_thresholds;
std::vector<float> output_left_node_contribs;
std::vector<float> output_right_node_contribs;
for (int node_id = node_id_first; node_id < node_id_last; ++node_id) {
// Calculate gains.
cum_grad.clear();
cum_hess.clear();
float total_grad = 0.0;
float total_hess = 0.0;
for (int bucket = 0; bucket < num_buckets; ++bucket) {
// TODO(nponomareva): Consider multi-dimensional gradients/hessians.
total_grad += stats_summary[feature_idx](node_id, bucket, 0);
total_hess += stats_summary[feature_idx](node_id, bucket, 1);
cum_grad.push_back(total_grad);
cum_hess.push_back(total_hess);
}
// Check if node has enough of average hessian.
if (total_hess < min_node_weight) {
// Do not split the node because not enough avg hessian.
continue;
}
float best_gain = std::numeric_limits<float>::lowest();
float best_bucket = 0;
float best_contrib_for_left = 0.0;
float best_contrib_for_right = 0.0;
// Parent gain.
float parent_gain;
Eigen::VectorXf unused(1);
CalculateWeightsAndGains(total_grad * identity, total_hess * identity,
l1, l2, &unused, &parent_gain);
for (int bucket = 0; bucket < num_buckets; ++bucket) {
const float cum_grad_bucket = cum_grad[bucket];
const float cum_hess_bucket = cum_hess[bucket];
// Left child.
Eigen::VectorXf contrib_for_left(1);
float gain_for_left;
CalculateWeightsAndGains(cum_grad_bucket * identity,
cum_hess_bucket * identity, l1, l2,
&contrib_for_left, &gain_for_left);
// Right child.
// use contrib_for_right.
Eigen::VectorXf contrib_for_right(1);
float gain_for_right;
CalculateWeightsAndGains((total_grad - cum_grad_bucket) * identity,
(total_hess - cum_hess_bucket) * identity,
l1, l2, &contrib_for_right, &gain_for_right);
if (GainIsLarger(gain_for_left + gain_for_right, best_gain)) {
best_gain = gain_for_left + gain_for_right;
best_bucket = bucket;
best_contrib_for_left = contrib_for_left[0];
best_contrib_for_right = contrib_for_right[0];
}
} // for bucket
output_node_ids.push_back(node_id);
// Remove the parent gain for the parent node.
output_gains.push_back(best_gain - parent_gain);
output_thresholds.push_back(best_bucket);
output_left_node_contribs.push_back(best_contrib_for_left);
output_right_node_contribs.push_back(best_contrib_for_right);
} // for node_id
const int num_nodes = output_node_ids.size();
// output_node_ids
Tensor* output_node_ids_t;
OP_REQUIRES_OK(context,
output_node_ids_list.allocate(feature_idx, {num_nodes},
&output_node_ids_t));
auto output_node_ids_vec = output_node_ids_t->vec<int32>();
// output_gains
Tensor* output_gains_t;
OP_REQUIRES_OK(context, output_gains_list.allocate(
feature_idx, {num_nodes}, &output_gains_t));
auto output_gains_vec = output_gains_t->vec<float>();
// output_thresholds
Tensor* output_thresholds_t;
OP_REQUIRES_OK(context,
output_thresholds_list.allocate(feature_idx, {num_nodes},
&output_thresholds_t));
auto output_thresholds_vec = output_thresholds_t->vec<int32>();
// output_left_node_contribs
Tensor* output_left_node_contribs_t;
OP_REQUIRES_OK(context, output_left_node_contribs_list.allocate(
feature_idx, {num_nodes, 1},
&output_left_node_contribs_t));
auto output_left_node_contribs_matrix =
output_left_node_contribs_t->matrix<float>();
// output_right_node_contribs
Tensor* output_right_node_contribs_t;
OP_REQUIRES_OK(context, output_right_node_contribs_list.allocate(
feature_idx, {num_nodes, 1},
&output_right_node_contribs_t));
auto output_right_node_contribs_matrix =
output_right_node_contribs_t->matrix<float>();
// Sets output tensors from vectors.
for (int i = 0; i < num_nodes; ++i) {
output_node_ids_vec(i) = output_node_ids[i];
// Adjust the gains to penalize by tree complexity.
output_gains_vec(i) = output_gains[i] - tree_complexity;
output_thresholds_vec(i) = output_thresholds[i];
output_left_node_contribs_matrix(i, 0) = output_left_node_contribs[i];
// This op only supports 1-dimensional logits.
output_right_node_contribs_matrix(i, 0) = output_right_node_contribs[i];
}
} // for f
}
private:
int max_splits_;
int num_features_;
};
// V1 op that only supports single dimensional logit.
REGISTER_KERNEL_BUILDER(
Name("BoostedTreesCalculateBestGainsPerFeature").Device(DEVICE_CPU),
BoostedTreesCalculateBestGainsPerFeatureOp);
// Deprecated op. Use BoostedTreesCalculateBestFeatureSplitOpV2.
class BoostedTreesCalculateBestFeatureSplitOp : public OpKernel {
public:
explicit BoostedTreesCalculateBestFeatureSplitOp(
OpKernelConstruction* const context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("logits_dimension", &logits_dim_));
OP_REQUIRES_OK(context, context->GetAttr("split_type", &split_type_));
}
void Compute(OpKernelContext* const context) override {
// node_id_range
const Tensor* node_id_range_t;
OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t));
const auto node_id_range = node_id_range_t->vec<int32>();
const int32 node_id_first = node_id_range(0); // inclusive
const int32 node_id_last = node_id_range(1); // exclusive
const Tensor* stats_summary_t;
OP_REQUIRES_OK(context, context->input("stats_summary", &stats_summary_t));
TTypes<float, 4>::ConstTensor stats_summary =
stats_summary_t->tensor<float, 4>();
const int32 feature_dims = stats_summary_t->dim_size(1);
// The last bucket is for default/missing value.
const int32 num_buckets = stats_summary_t->dim_size(2) - 1;
const int32 logits_dim = logits_dim_;
const int32 hessian_dim = stats_summary_t->dim_size(3) - logits_dim;
DCHECK_GT(hessian_dim, 0);
DCHECK_LE(hessian_dim, logits_dim * logits_dim);
const Tensor* l1_t;
OP_REQUIRES_OK(context, context->input("l1", &l1_t));
const auto l1 = l1_t->scalar<float>()();
DCHECK_GE(l1, 0);
if (logits_dim_ > 1) {
// Multi-class L1 regularization not supported yet.
DCHECK_EQ(l1, 0);
}
const Tensor* l2_t;
OP_REQUIRES_OK(context, context->input("l2", &l2_t));
const auto l2 = l2_t->scalar<float>()();
DCHECK_GE(l2, 0);
const Tensor* tree_complexity_t;
OP_REQUIRES_OK(context,
context->input("tree_complexity", &tree_complexity_t));
const auto tree_complexity = tree_complexity_t->scalar<float>()();
const Tensor* min_node_weight_t;
OP_REQUIRES_OK(context,
context->input("min_node_weight", &min_node_weight_t));
const auto min_node_weight = min_node_weight_t->scalar<float>()();
std::vector<int32> output_node_ids;
std::vector<float> output_gains;
std::vector<int32> output_feature_dimensions;
std::vector<int32> output_thresholds;
std::vector<Eigen::VectorXf> output_left_node_contribs;
std::vector<Eigen::VectorXf> output_right_node_contribs;
std::vector<string> output_split_types;
// TODO(tanzheny) parallelize the computation.
// Iterate each node and find the best gain per node.
for (int32 node_id = node_id_first; node_id < node_id_last; ++node_id) {
float best_gain = std::numeric_limits<float>::lowest();
int32 best_bucket = 0;
int32 best_f_dim = 0;
string best_split_type;
Eigen::VectorXf best_contrib_for_left(logits_dim);
Eigen::VectorXf best_contrib_for_right(logits_dim);
float parent_gain;
// Including default bucket.
ConstMatrixMap stats_mat(&stats_summary(node_id, 0, 0, 0),
num_buckets + 1, logits_dim + hessian_dim);
const Eigen::VectorXf total_grad =
stats_mat.leftCols(logits_dim).colwise().sum();
const Eigen::VectorXf total_hess =
stats_mat.rightCols(hessian_dim).colwise().sum();
if (total_hess.norm() < min_node_weight) {
continue;
}
Eigen::VectorXf parent_weight(logits_dim);
CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &parent_weight,
&parent_gain);
if (split_type_ == "inequality") {
CalculateBestInequalitySplit(
stats_summary, node_id, feature_dims, logits_dim, hessian_dim,
num_buckets, min_node_weight, l1, l2, &best_gain, &best_bucket,
&best_f_dim, &best_split_type, &best_contrib_for_left,
&best_contrib_for_right);
} else {
CalculateBestEqualitySplit(
stats_summary, total_grad, total_hess, node_id, feature_dims,
logits_dim, hessian_dim, num_buckets, l1, l2, &best_gain,
&best_bucket, &best_f_dim, &best_split_type, &best_contrib_for_left,
&best_contrib_for_right);
}
if (best_gain == std::numeric_limits<float>::lowest()) {
// Do not add the node if not split if found.
continue;
}
output_node_ids.push_back(node_id);
// Remove the parent gain for the parent node.
output_gains.push_back(best_gain - parent_gain);
output_feature_dimensions.push_back(best_f_dim);
// default direction is fixed for dense splits.
// TODO(tanzheny) account for default values.
output_split_types.push_back(best_split_type);
output_thresholds.push_back(best_bucket);
output_left_node_contribs.push_back(best_contrib_for_left);
output_right_node_contribs.push_back(best_contrib_for_right);
} // for node id
const int num_nodes = output_node_ids.size();
// output_node_ids
Tensor* output_node_ids_t = nullptr;
OP_REQUIRES_OK(context, context->allocate_output("node_ids", {num_nodes},
&output_node_ids_t));
auto output_node_ids_vec = output_node_ids_t->vec<int32>();
// output_gains
Tensor* output_gains_t;
OP_REQUIRES_OK(context, context->allocate_output("gains", {num_nodes},
&output_gains_t));
auto output_gains_vec = output_gains_t->vec<float>();
// output_feature_dimensions
Tensor* output_feature_dimension_t;
OP_REQUIRES_OK(context,
context->allocate_output("feature_dimensions", {num_nodes},
&output_feature_dimension_t));
auto output_feature_dimensions_vec =
output_feature_dimension_t->vec<int32>();
// output_thresholds
Tensor* output_thresholds_t;
OP_REQUIRES_OK(context, context->allocate_output("thresholds", {num_nodes},
&output_thresholds_t));
auto output_thresholds_vec = output_thresholds_t->vec<int32>();
// output_left_node_contribs
Tensor* output_left_node_contribs_t;
OP_REQUIRES_OK(context, context->allocate_output(
"left_node_contribs", {num_nodes, logits_dim},
&output_left_node_contribs_t));
auto output_left_node_contribs_matrix =
output_left_node_contribs_t->matrix<float>();
// output_right_node_contribs
Tensor* output_right_node_contribs_t;
OP_REQUIRES_OK(context, context->allocate_output(
"right_node_contribs", {num_nodes, logits_dim},
&output_right_node_contribs_t));
auto output_right_node_contribs_matrix =
output_right_node_contribs_t->matrix<float>();
// split type
Tensor* output_split_types_t;
OP_REQUIRES_OK(
context, context->allocate_output("split_with_default_directions",
{num_nodes}, &output_split_types_t));
auto output_split_types_vec = output_split_types_t->vec<tstring>();
// Sets output tensors from vectors.
for (int i = 0; i < num_nodes; ++i) {
output_node_ids_vec(i) = output_node_ids[i];
// Adjust the gains to penalize by tree complexity.
output_gains_vec(i) = output_gains[i] - tree_complexity;
output_feature_dimensions_vec(i) = output_feature_dimensions[i];
output_thresholds_vec(i) = output_thresholds[i];
for (int j = 0; j < logits_dim; ++j) {
output_left_node_contribs_matrix(i, j) =
output_left_node_contribs[i][j];
output_right_node_contribs_matrix(i, j) =
output_right_node_contribs[i][j];
}
output_split_types_vec(i) = output_split_types[i];
}
}
private:
// TODO(crawles): Simplify inequality path just like equality b/138329196
// Currently this is not simplify-able due to numerical instability in math
// i.e. gain = -g.transpose() * hessian_and_reg.colPivHouseholderQr().solve(g)
// It caused gain to be Inf when g is approaching 0 but not exactly 0 while
// there is no regularization.
// Calculate the best inequality split per node.
void CalculateBestInequalitySplit(
TTypes<float, 4>::ConstTensor stats_summary, const int32 node_id,
const int32 feature_dims, const int32 logits_dim, const int32 hessian_dim,
const int32 num_buckets, const float min_node_weight, const float l1,
const float l2, float* best_gain, int32* best_bucket, int32* best_f_dim,
string* best_split_type, Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
std::vector<Eigen::VectorXf> cum_grad;
std::vector<Eigen::VectorXf> cum_hess;
// get all cumulative gradients including default bucket.
cum_grad.reserve(num_buckets);
cum_hess.reserve(num_buckets);
for (int f_dim = 0; f_dim < feature_dims; ++f_dim) {
ConstVectorMap default_stats_vec(
&stats_summary(node_id, f_dim, num_buckets, 0),
logits_dim + hessian_dim);
Eigen::VectorXf missing_bucket_grad = default_stats_vec.head(logits_dim);
Eigen::VectorXf missing_bucket_hess = default_stats_vec.tail(hessian_dim);
cum_grad.clear();
cum_hess.clear();
Eigen::VectorXf total_grad = Eigen::VectorXf::Zero(logits_dim);
Eigen::VectorXf total_hess = Eigen::VectorXf::Zero(hessian_dim);
// sum all the gradients including default bucket.
for (int bucket = 0; bucket <= num_buckets; ++bucket) {
for (int i = 0; i < logits_dim; ++i) {
total_grad[i] += stats_summary(node_id, f_dim, bucket, i);
}
for (int i = 0; i < hessian_dim; ++i) {
// Full hessian.
total_hess[i] +=
stats_summary(node_id, f_dim, bucket, logits_dim + i);
}
if (bucket < num_buckets) {
cum_grad.push_back(total_grad);
cum_hess.push_back(total_hess);
}
}
const string kInequalityDefaultLeft =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::INEQUALITY_DEFAULT_LEFT);
const string kInequalityDefaultRight =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::INEQUALITY_DEFAULT_RIGHT);
// Iterate from left to right, excluding default bucket.
for (int bucket = 0; bucket < num_buckets; ++bucket) {
// default value goes to left node.
const Eigen::VectorXf total_left_grad =
cum_grad[bucket] + missing_bucket_grad;
const Eigen::VectorXf total_left_hess =
cum_hess[bucket] + missing_bucket_hess;
MaybeUpdateBestSplit(
total_left_grad, total_grad - total_left_grad, total_left_hess,
total_hess - total_left_hess, logits_dim, bucket, f_dim, l1, l2,
kInequalityDefaultLeft, best_gain, best_bucket, best_f_dim,
best_split_type, best_contrib_for_left, best_contrib_for_right);
// default value goes to right node.
MaybeUpdateBestSplit(
cum_grad[bucket], total_grad - cum_grad[bucket], cum_hess[bucket],
total_hess - cum_hess[bucket], logits_dim, bucket, f_dim, l1, l2,
kInequalityDefaultRight, best_gain, best_bucket, best_f_dim,
best_split_type, best_contrib_for_left, best_contrib_for_right);
} // for bucket
}
}
// Calculate the best equality split per node.
void CalculateBestEqualitySplit(
TTypes<float, 4>::ConstTensor stats_summary,
const Eigen::VectorXf& total_grad, const Eigen::VectorXf& total_hess,
const int32 node_id, const int32 feature_dims, const int32 logits_dim,
const int32 hessian_dim, const int32 num_buckets, const float l1,
const float l2, float* best_gain, int32* best_bucket, int32* best_f_dim,
string* best_split_type, Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
const string kEqualityDefaultRight =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::EQUALITY_DEFAULT_RIGHT);
for (int f_dim = 0; f_dim < feature_dims; ++f_dim) {
for (int bucket = 0; bucket < num_buckets; ++bucket) {
ConstVectorMap stats_vec(&stats_summary(node_id, f_dim, bucket, 0),
logits_dim + hessian_dim);
Eigen::VectorXf curr_grad = stats_vec.head(logits_dim);
Eigen::VectorXf curr_hess = stats_vec.tail(hessian_dim);
MaybeUpdateBestSplit(curr_grad, total_grad - curr_grad, curr_hess,
total_hess - curr_hess, logits_dim, bucket, f_dim,
l1, l2, kEqualityDefaultRight, best_gain,
best_bucket, best_f_dim, best_split_type,
best_contrib_for_left, best_contrib_for_right);
}
}
}
void MaybeUpdateBestSplit(const Eigen::VectorXf& grad_for_left,
const Eigen::VectorXf& grad_for_right,
const Eigen::VectorXf& hess_for_left,
const Eigen::VectorXf& hess_for_right,
const int32 logits_dim, const int32 bucket,
const int32 f_dim, const float l1, const float l2,
const string split_type, float* best_gain,
int32* best_bucket, int32* best_f_dim,
string* best_split_type,
Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
// Left child.
Eigen::VectorXf contrib_for_left(logits_dim);
float gain_for_left;
CalculateWeightsAndGains(grad_for_left, hess_for_left, l1, l2,
&contrib_for_left, &gain_for_left);
Eigen::VectorXf contrib_for_right(logits_dim);
float gain_for_right;
CalculateWeightsAndGains(grad_for_right, hess_for_right, l1, l2,
&contrib_for_right, &gain_for_right);
if (GainIsLarger(gain_for_left + gain_for_right, *best_gain)) {
*best_gain = gain_for_left + gain_for_right;
*best_bucket = bucket;
*best_f_dim = f_dim;
*best_contrib_for_left = contrib_for_left;
*best_contrib_for_right = contrib_for_right;
*best_split_type = split_type;
}
}
int logits_dim_;
string split_type_;
};
// Deprecated op. Use BoostedTreesCalculateBestFeatureSplitOpV2.
REGISTER_KERNEL_BUILDER(
Name("BoostedTreesCalculateBestFeatureSplit").Device(DEVICE_CPU),
BoostedTreesCalculateBestFeatureSplitOp);
// V2 Op.
class BoostedTreesCalculateBestFeatureSplitV2 : public OpKernel {
public:
explicit BoostedTreesCalculateBestFeatureSplitV2(
OpKernelConstruction* const context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("logits_dimension", &logits_dim_));
OP_REQUIRES_OK(context, context->GetAttr("num_features", &num_features_));
}
void Compute(OpKernelContext* const context) override {
// node_id_range
const Tensor* node_id_range_t;
OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t));
const auto node_id_range = node_id_range_t->vec<int32>();
const int32 node_id_first = node_id_range(0); // Inclusive.
const int32 node_id_last = node_id_range(1); // Exclusive.
// Get stats_summaries_list.
OpInputList stats_summaries_list;
OP_REQUIRES_OK(context, context->input_list("stats_summaries_list",
&stats_summaries_list));
// Infer dimensions of a stats_summary.
DCHECK_GT(stats_summaries_list.size(), 0);
const int32 feature_dims = stats_summaries_list[0].dim_size(1);
// The last bucket is for default/missing value.
const int32 num_buckets = stats_summaries_list[0].dim_size(2) - 1;
const int32 logits_dim = logits_dim_;
const int32 hessian_dim = stats_summaries_list[0].dim_size(3) - logits_dim;
DCHECK_GT(hessian_dim, 0);
DCHECK_LE(hessian_dim, logits_dim * logits_dim);
// Vector of stats_summaries; each element is stats for feature of shape
// [max_splits, feature_dim, num_buckets, logits_dim + hessian_dim].
std::vector<TTypes<float, 4>::ConstTensor> stats_summaries;
DCHECK_EQ(stats_summaries_list.size(), num_features_);
stats_summaries.reserve(num_features_);
for (const auto& tensor : stats_summaries_list) {
stats_summaries.emplace_back(tensor.tensor<float, 4>());
}
// Split types.
const Tensor* split_types_t;
OP_REQUIRES_OK(context, context->input("split_types", &split_types_t));
const auto split_types = split_types_t->vec<tstring>();
DCHECK_EQ(split_types.size(), num_features_);
// Validate.
for (int i = 0; i < num_features_; ++i) {
if (!(split_types(i) == kInequalitySplit ||
split_types(i) == kEqualitySplit)) {
OP_REQUIRES_OK(
context,
errors::Aborted(
"Operation received an exception: Incorrect split type"));
}
}
// Feature ids.
const Tensor* candidate_feature_ids_t;
OP_REQUIRES_OK(context, context->input("candidate_feature_ids",
&candidate_feature_ids_t));
const auto candidate_feature_ids = candidate_feature_ids_t->vec<int32>();
DCHECK_EQ(candidate_feature_ids.size(), num_features_);
// L1, L2, tree_complexity, min_node_weight.
const Tensor* l1_t;
OP_REQUIRES_OK(context, context->input("l1", &l1_t));
const auto l1 = l1_t->scalar<float>()();
DCHECK_GE(l1, 0);
if (logits_dim_ > 1) {
// Multi-class L1 regularization not supported yet.
DCHECK_EQ(l1, 0);
}
const Tensor* l2_t;
OP_REQUIRES_OK(context, context->input("l2", &l2_t));
const auto l2 = l2_t->scalar<float>()();
DCHECK_GE(l2, 0);
const Tensor* tree_complexity_t;
OP_REQUIRES_OK(context,
context->input("tree_complexity", &tree_complexity_t));
const auto tree_complexity = tree_complexity_t->scalar<float>()();
const Tensor* min_node_weight_t;
OP_REQUIRES_OK(context,
context->input("min_node_weight", &min_node_weight_t));
const auto min_node_weight = min_node_weight_t->scalar<float>()();
std::vector<int32> output_node_ids;
std::vector<float> output_gains;
std::vector<int32> output_feature_ids;
std::vector<int32> output_feature_dimensions;
std::vector<int32> output_thresholds;
std::vector<Eigen::VectorXf> output_left_node_contribs;
std::vector<Eigen::VectorXf> output_right_node_contribs;
std::vector<string> output_split_types;
// TODO(tanzheny) parallelize the computation.
// Iterate each node and find the best gain per node.
float parent_gain;
for (int32 node_id = node_id_first; node_id < node_id_last; ++node_id) {
float best_gain = std::numeric_limits<float>::lowest();
int32 best_bucket;
int32 best_f_id;
int32 best_f_dim;
string best_split_type;
Eigen::VectorXf best_contrib_for_left(logits_dim);
Eigen::VectorXf best_contrib_for_right(logits_dim);
// Sum of gradient and hessian. Compute parent gain using first feature.
ConstMatrixMap stats_mat(&stats_summaries[0](node_id, 0, 0, 0),
num_buckets + 1, // Including default bucket.
logits_dim + hessian_dim);
const Eigen::VectorXf total_grad =
stats_mat.leftCols(logits_dim).colwise().sum();
const Eigen::VectorXf total_hess =
stats_mat.rightCols(hessian_dim).colwise().sum();
if (total_hess.norm() < min_node_weight) {
continue;
}
Eigen::VectorXf unused(logits_dim);
CalculateWeightsAndGains(total_grad, total_hess, l1, l2, &unused,
&parent_gain);
for (int f_idx = 0; f_idx < num_features_; ++f_idx) {
const string split_type = split_types(f_idx);
TTypes<float, 4>::ConstTensor stats_summary = stats_summaries[f_idx];
float f_best_gain = std::numeric_limits<float>::lowest();
int32 f_best_bucket;
int32 f_best_f_dim;
string f_best_split_type;
Eigen::VectorXf f_best_contrib_for_left(logits_dim);
Eigen::VectorXf f_best_contrib_for_right(logits_dim);
if (split_type == kInequalitySplit) {
CalculateBestInequalitySplit(
stats_summary, node_id, feature_dims, logits_dim, hessian_dim,
num_buckets, min_node_weight, l1, l2, &f_best_gain,
&f_best_bucket, &f_best_f_dim, &f_best_split_type,
&f_best_contrib_for_left, &f_best_contrib_for_right);
} else {
CalculateBestEqualitySplit(
stats_summary, total_grad, total_hess, node_id, feature_dims,
logits_dim, hessian_dim, num_buckets, l1, l2, &f_best_gain,
&f_best_bucket, &f_best_f_dim, &f_best_split_type,
&f_best_contrib_for_left, &f_best_contrib_for_right);
}
if (f_best_gain > best_gain) {
best_gain = f_best_gain;
best_f_id = candidate_feature_ids(f_idx);
best_f_dim = f_best_f_dim;
best_split_type = f_best_split_type;
best_bucket = f_best_bucket;
best_contrib_for_left = f_best_contrib_for_left;
best_contrib_for_right = f_best_contrib_for_right;
}
} // For feature id.
if (best_gain == std::numeric_limits<float>::lowest()) {
// Do not add the node if no split is found.
continue;
}
output_node_ids.push_back(node_id);
// Remove the parent gain for the parent node.
output_gains.push_back(best_gain - parent_gain);
output_feature_ids.push_back(best_f_id);
output_feature_dimensions.push_back(best_f_dim);
// Default direction is fixed for dense splits.
// TODO(tanzheny) account for default values.
output_split_types.push_back(best_split_type);
output_thresholds.push_back(best_bucket);
output_left_node_contribs.push_back(best_contrib_for_left);
output_right_node_contribs.push_back(best_contrib_for_right);
} // for node id.
const int num_nodes = output_node_ids.size();
// output_node_ids
Tensor* output_node_ids_t = nullptr;
OP_REQUIRES_OK(context, context->allocate_output("node_ids", {num_nodes},
&output_node_ids_t));
auto output_node_ids_vec = output_node_ids_t->vec<int32>();
// output_gains
Tensor* output_gains_t;
OP_REQUIRES_OK(context, context->allocate_output("gains", {num_nodes},
&output_gains_t));
auto output_gains_vec = output_gains_t->vec<float>();
// output_feature_ids
Tensor* output_features_ids_t;
OP_REQUIRES_OK(context, context->allocate_output("feature_ids", {num_nodes},
&output_features_ids_t));
auto output_features_vec = output_features_ids_t->vec<int32>();
// output_feature_dimensions
Tensor* output_feature_dimension_t;
OP_REQUIRES_OK(context,
context->allocate_output("feature_dimensions", {num_nodes},
&output_feature_dimension_t));
auto output_feature_dimensions_vec =
output_feature_dimension_t->vec<int32>();
// output_thresholds
Tensor* output_thresholds_t;
OP_REQUIRES_OK(context, context->allocate_output("thresholds", {num_nodes},
&output_thresholds_t));
auto output_thresholds_vec = output_thresholds_t->vec<int32>();
// output_left_node_contribs
Tensor* output_left_node_contribs_t;
OP_REQUIRES_OK(context, context->allocate_output(
"left_node_contribs", {num_nodes, logits_dim},
&output_left_node_contribs_t));
auto output_left_node_contribs_matrix =
output_left_node_contribs_t->matrix<float>();
// output_right_node_contribs
Tensor* output_right_node_contribs_t;
OP_REQUIRES_OK(context, context->allocate_output(
"right_node_contribs", {num_nodes, logits_dim},
&output_right_node_contribs_t));
auto output_right_node_contribs_matrix =
output_right_node_contribs_t->matrix<float>();
// split type
Tensor* output_split_types_t;
OP_REQUIRES_OK(
context, context->allocate_output("split_with_default_directions",
{num_nodes}, &output_split_types_t));
auto output_split_types_vec = output_split_types_t->vec<tstring>();
// Sets output tensors from vectors.
for (int i = 0; i < num_nodes; ++i) {
output_node_ids_vec(i) = output_node_ids[i];
output_features_vec(i) = output_feature_ids[i];
// Adjust the gains to penalize by tree complexity.
output_gains_vec(i) = output_gains[i] - tree_complexity;
output_feature_dimensions_vec(i) = output_feature_dimensions[i];
output_thresholds_vec(i) = output_thresholds[i];
for (int j = 0; j < logits_dim; ++j) {
output_left_node_contribs_matrix(i, j) =
output_left_node_contribs[i][j];
output_right_node_contribs_matrix(i, j) =
output_right_node_contribs[i][j];
}
output_split_types_vec(i) = output_split_types[i];
}
}
private:
// TODO(crawles): Simplify inequality path just like equality b/138329196
// Currently this is not simplify-able due to numerical instability in math
// i.e. gain = -g.transpose() * hessian_and_reg.colPivHouseholderQr().solve(g)
// It caused gain to be Inf when g is approaching 0 but not exactly 0 while
// there is no regularization.
// Calculate the best inequality split per node.
void CalculateBestInequalitySplit(
TTypes<float, 4>::ConstTensor stats_summary, const int32 node_id,
const int32 feature_dims, const int32 logits_dim, const int32 hessian_dim,
const int32 num_buckets, const float min_node_weight, const float l1,
const float l2, float* best_gain, int32* best_bucket, int32* best_f_dim,
string* best_split_type, Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
std::vector<Eigen::VectorXf> cum_grad;
std::vector<Eigen::VectorXf> cum_hess;
// get all cumulative gradients including default bucket.
cum_grad.reserve(num_buckets);
cum_hess.reserve(num_buckets);
for (int f_dim = 0; f_dim < feature_dims; ++f_dim) {
ConstVectorMap default_stats_vec(
&stats_summary(node_id, f_dim, num_buckets, 0),
logits_dim + hessian_dim);
Eigen::VectorXf missing_bucket_grad = default_stats_vec.head(logits_dim);
Eigen::VectorXf missing_bucket_hess = default_stats_vec.tail(hessian_dim);
cum_grad.clear();
cum_hess.clear();
Eigen::VectorXf total_grad = Eigen::VectorXf::Zero(logits_dim);
Eigen::VectorXf total_hess = Eigen::VectorXf::Zero(hessian_dim);
// sum all the gradients including default bucket.
for (int bucket = 0; bucket <= num_buckets; ++bucket) {
for (int i = 0; i < logits_dim; ++i) {
total_grad[i] += stats_summary(node_id, f_dim, bucket, i);
}
for (int i = 0; i < hessian_dim; ++i) {
// Full hessian.
total_hess[i] +=
stats_summary(node_id, f_dim, bucket, logits_dim + i);
}
if (bucket < num_buckets) {
cum_grad.push_back(total_grad);
cum_hess.push_back(total_hess);
}
}
const string kInequalityDefaultLeft =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::INEQUALITY_DEFAULT_LEFT);
const string kInequalityDefaultRight =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::INEQUALITY_DEFAULT_RIGHT);
// Iterate from left to right, excluding default bucket.
for (int bucket = 0; bucket < num_buckets; ++bucket) {
// default value goes to left node.
const Eigen::VectorXf total_left_grad =
cum_grad[bucket] + missing_bucket_grad;
const Eigen::VectorXf total_left_hess =
cum_hess[bucket] + missing_bucket_hess;
MaybeUpdateBestSplit(
total_left_grad, total_grad - total_left_grad, total_left_hess,
total_hess - total_left_hess, logits_dim, bucket, f_dim, l1, l2,
kInequalityDefaultLeft, best_gain, best_bucket, best_f_dim,
best_split_type, best_contrib_for_left, best_contrib_for_right);
// default value goes to right node.
MaybeUpdateBestSplit(
cum_grad[bucket], total_grad - cum_grad[bucket], cum_hess[bucket],
total_hess - cum_hess[bucket], logits_dim, bucket, f_dim, l1, l2,
kInequalityDefaultRight, best_gain, best_bucket, best_f_dim,
best_split_type, best_contrib_for_left, best_contrib_for_right);
} // for bucket
}
}
// Calculate the best equality split per node.
void CalculateBestEqualitySplit(
TTypes<float, 4>::ConstTensor stats_summary,
const Eigen::VectorXf& total_grad, const Eigen::VectorXf& total_hess,
const int32 node_id, const int32 feature_dims, const int32 logits_dim,
const int32 hessian_dim, const int32 num_buckets, const float l1,
const float l2, float* best_gain, int32* best_bucket, int32* best_f_dim,
string* best_split_type, Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
const string kEqualityDefaultRight =
boosted_trees::SplitTypeWithDefault_Name(
boosted_trees::EQUALITY_DEFAULT_RIGHT);
for (int f_dim = 0; f_dim < feature_dims; ++f_dim) {
for (int bucket = 0; bucket < num_buckets; ++bucket) {
ConstVectorMap stats_vec(&stats_summary(node_id, f_dim, bucket, 0),
logits_dim + hessian_dim);
Eigen::VectorXf curr_grad = stats_vec.head(logits_dim);
Eigen::VectorXf curr_hess = stats_vec.tail(hessian_dim);
MaybeUpdateBestSplit(curr_grad, total_grad - curr_grad, curr_hess,
total_hess - curr_hess, logits_dim, bucket, f_dim,
l1, l2, kEqualityDefaultRight, best_gain,
best_bucket, best_f_dim, best_split_type,
best_contrib_for_left, best_contrib_for_right);
}
}
}
void MaybeUpdateBestSplit(const Eigen::VectorXf& grad_for_left,
const Eigen::VectorXf& grad_for_right,
const Eigen::VectorXf& hess_for_left,
const Eigen::VectorXf& hess_for_right,
const int32 logits_dim, const int32 bucket,
const int32 f_dim, const float l1, const float l2,
const string split_type, float* best_gain,
int32* best_bucket, int32* best_f_dim,
string* best_split_type,
Eigen::VectorXf* best_contrib_for_left,
Eigen::VectorXf* best_contrib_for_right) {
// Left child.
Eigen::VectorXf contrib_for_left(logits_dim);
float gain_for_left;
CalculateWeightsAndGains(grad_for_left, hess_for_left, l1, l2,
&contrib_for_left, &gain_for_left);
Eigen::VectorXf contrib_for_right(logits_dim);
float gain_for_right;
CalculateWeightsAndGains(grad_for_right, hess_for_right, l1, l2,
&contrib_for_right, &gain_for_right);
if (GainIsLarger(gain_for_left + gain_for_right, *best_gain)) {
*best_gain = gain_for_left + gain_for_right;
*best_bucket = bucket;
*best_f_dim = f_dim;
*best_contrib_for_left = contrib_for_left;
*best_contrib_for_right = contrib_for_right;
*best_split_type = split_type;
}
}
int num_features_;
int logits_dim_;
};
// v2 op that supports multi-class.
REGISTER_KERNEL_BUILDER(
Name("BoostedTreesCalculateBestFeatureSplitV2").Device(DEVICE_CPU),
BoostedTreesCalculateBestFeatureSplitV2);
// Map from bucket id to vector of statistics.
typedef std::map<int32, std::vector<float>> BucketMap;
typedef BucketMap::iterator BucketMapIterator;
// Map from feature dimension to BucketMap.
typedef std::map<int32, BucketMap> FeatureMap;
typedef FeatureMap::iterator FeatureMapIterator;
class BoostedTreesSparseCalculateBestFeatureSplitOp : public OpKernel {
public:
explicit BoostedTreesSparseCalculateBestFeatureSplitOp(
OpKernelConstruction* const context)
: OpKernel(context) {
// TODO(crawles): Using logits_dim_ for multi-class split.
OP_REQUIRES_OK(context, context->GetAttr("logits_dimension", &logits_dim_));
// TODO(tanzheny): Using this for equality split.
OP_REQUIRES_OK(context, context->GetAttr("split_type", &split_type_));
}
void Compute(OpKernelContext* const context) override {
// node_id_range
const Tensor* node_id_range_t;
OP_REQUIRES_OK(context, context->input("node_id_range", &node_id_range_t));
const auto node_id_range = node_id_range_t->vec<int32>();
const int32 node_id_first = node_id_range(0); // inclusive
const int32 node_id_last = node_id_range(1); // exclusive
const Tensor* stats_summary_indices_t;
OP_REQUIRES_OK(context, context->input("stats_summary_indices",
&stats_summary_indices_t));
const auto stats_summary_indices = stats_summary_indices_t->matrix<int32>();
const int32 num_sparse_entries = stats_summary_indices_t->dim_size(0);
const Tensor* stats_summary_values_t;
OP_REQUIRES_OK(context, context->input("stats_summary_values",
&stats_summary_values_t));
const auto stats_summary_values = stats_summary_values_t->vec<float>();
const Tensor* stats_summary_shape_t;
OP_REQUIRES_OK(
context, context->input("stats_summary_shape", &stats_summary_shape_t));
const auto stats_summary_shape = stats_summary_shape_t->vec<int32>();
const int32 num_buckets = stats_summary_shape(2) - 1;
const int32 stats_dims = stats_summary_shape(3);
const Tensor* l1_t;
OP_REQUIRES_OK(context, context->input("l1", &l1_t));
const auto l1 = l1_t->scalar<float>()();
const Tensor* l2_t;
OP_REQUIRES_OK(context, context->input("l2", &l2_t));
const auto l2 = l2_t->scalar<float>()();
const Tensor* tree_complexity_t;
OP_REQUIRES_OK(context,
context->input("tree_complexity", &tree_complexity_t));
const auto tree_complexity = tree_complexity_t->scalar<float>()();
const Tensor* min_node_weight_t;
OP_REQUIRES_OK(context,
context->input("min_node_weight", &min_node_weight_t));
const auto min_node_weight = min_node_weight_t->scalar<float>()();