feature_histogram.hpp 49.3 KB
Newer Older
1
2
/*!
 * Copyright (c) 2016 Microsoft Corporation. All rights reserved.
3
4
 * Licensed under the MIT License. See LICENSE file in the project root for
 * license information.
5
 */
Guolin Ke's avatar
Guolin Ke committed
6
7
8
#ifndef LIGHTGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_
#define LIGHTGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_

9
#include <LightGBM/bin.h>
Guolin Ke's avatar
Guolin Ke committed
10
#include <LightGBM/dataset.h>
11
#include <LightGBM/utils/array_args.h>
Guolin Ke's avatar
Guolin Ke committed
12

13
#include <algorithm>
14
#include <cmath>
15
16
17
18
19
#include <cstring>
#include <memory>
#include <utility>
#include <vector>

20
#include "monotone_constraints.hpp"
Nikita Titov's avatar
Nikita Titov committed
21
#include "split_info.hpp"
Guolin Ke's avatar
Guolin Ke committed
22

23
namespace LightGBM {
Guolin Ke's avatar
Guolin Ke committed
24

Guolin Ke's avatar
Guolin Ke committed
25
class FeatureMetainfo {
26
 public:
Guolin Ke's avatar
Guolin Ke committed
27
  int num_bin;
Guolin Ke's avatar
Guolin Ke committed
28
  MissingType missing_type;
29
  int8_t offset = 0;
Guolin Ke's avatar
Guolin Ke committed
30
  uint32_t default_bin;
31
32
  int8_t monotone_type = 0;
  double penalty = 1.0;
Guolin Ke's avatar
Guolin Ke committed
33
  /*! \brief pointer of tree config */
Guolin Ke's avatar
Guolin Ke committed
34
  const Config* config;
35
  BinType bin_type;
36
37
  /*! \brief random number generator for extremely randomized trees */
  mutable Random rand;
Guolin Ke's avatar
Guolin Ke committed
38
};
Guolin Ke's avatar
Guolin Ke committed
39
/*!
40
41
42
 * \brief FeatureHistogram is used to construct and store a histogram for a
 * feature.
 */
Guolin Ke's avatar
Guolin Ke committed
43
class FeatureHistogram {
44
 public:
45
  FeatureHistogram() { data_ = nullptr; }
Guolin Ke's avatar
Guolin Ke committed
46

47
  ~FeatureHistogram() {}
Guolin Ke's avatar
Guolin Ke committed
48

Guolin Ke's avatar
Guolin Ke committed
49
50
51
52
53
  /*! \brief Disable copy */
  FeatureHistogram& operator=(const FeatureHistogram&) = delete;
  /*! \brief Disable copy */
  FeatureHistogram(const FeatureHistogram&) = delete;

Guolin Ke's avatar
Guolin Ke committed
54
  /*!
55
56
57
58
   * \brief Init the feature histogram
   * \param feature the feature data for this histogram
   * \param min_num_data_one_leaf minimal number of data in one leaf
   */
59
  void Init(hist_t* data, const FeatureMetainfo* meta) {
Guolin Ke's avatar
Guolin Ke committed
60
61
    meta_ = meta;
    data_ = data;
62
63
64
65
    ResetFunc();
  }

  void ResetFunc() {
66
    if (meta_->bin_type == BinType::NumericalBin) {
67
      FuncForNumrical();
68
    } else {
69
      FuncForCategorical();
70
    }
Guolin Ke's avatar
Guolin Ke committed
71
72
  }

73
  hist_t* RawData() { return data_; }
74

Guolin Ke's avatar
Guolin Ke committed
75
  /*!
76
77
78
   * \brief Subtract current histograms with other
   * \param other The histogram that want to subtract
   */
Guolin Ke's avatar
Guolin Ke committed
79
  void Subtract(const FeatureHistogram& other) {
80
81
    for (int i = 0; i < (meta_->num_bin - meta_->offset) * 2; ++i) {
      data_[i] -= other.data_[i];
Guolin Ke's avatar
Guolin Ke committed
82
83
    }
  }
84

85
86
87
  void FindBestThreshold(double sum_gradient, double sum_hessian,
                         data_size_t num_data,
                         const ConstraintEntry& constraints,
Belinda Trotta's avatar
Belinda Trotta committed
88
                         double parent_output,
89
                         SplitInfo* output) {
Guolin Ke's avatar
Guolin Ke committed
90
    output->default_left = true;
Guolin Ke's avatar
Guolin Ke committed
91
    output->gain = kMinScore;
92
    find_best_threshold_fun_(sum_gradient, sum_hessian + 2 * kEpsilon, num_data,
Belinda Trotta's avatar
Belinda Trotta committed
93
                             constraints, parent_output, output);
Guolin Ke's avatar
Guolin Ke committed
94
    output->gain *= meta_->penalty;
95
96
  }

Belinda Trotta's avatar
Belinda Trotta committed
97
98
  template <bool USE_RAND, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
  double BeforeNumercal(double sum_gradient, double sum_hessian, double parent_output, data_size_t num_data,
99
                        SplitInfo* output, int* rand_threshold) {
Guolin Ke's avatar
Guolin Ke committed
100
    is_splittable_ = false;
101
    output->monotone_type = meta_->monotone_type;
Belinda Trotta's avatar
Belinda Trotta committed
102
103
104
105

    double gain_shift = GetLeafGain<USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1, meta_->config->lambda_l2,
        meta_->config->max_delta_step, meta_->config->path_smooth, num_data, parent_output);
106
107
108
109
110
    *rand_threshold = 0;
    if (USE_RAND) {
      if (meta_->num_bin - 2 > 0) {
        *rand_threshold = meta_->rand.NextInt(0, meta_->num_bin - 2);
      }
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
    return gain_shift + meta_->config->min_gain_to_split;
  }

  void FuncForNumrical() {
    if (meta_->config->extra_trees) {
      if (meta_->config->monotone_constraints.empty()) {
        FuncForNumricalL1<true, false>();
      } else {
        FuncForNumricalL1<true, true>();
      }
    } else {
      if (meta_->config->monotone_constraints.empty()) {
        FuncForNumricalL1<false, false>();
      } else {
        FuncForNumricalL1<false, true>();
      }
    }
  }
  template <bool USE_RAND, bool USE_MC>
  void FuncForNumricalL1() {
    if (meta_->config->lambda_l1 > 0) {
      if (meta_->config->max_delta_step > 0) {
        FuncForNumricalL2<USE_RAND, USE_MC, true, true>();
      } else {
        FuncForNumricalL2<USE_RAND, USE_MC, true, false>();
      }
    } else {
      if (meta_->config->max_delta_step > 0) {
        FuncForNumricalL2<USE_RAND, USE_MC, false, true>();
      } else {
        FuncForNumricalL2<USE_RAND, USE_MC, false, false>();
      }
    }
  }

  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT>
  void FuncForNumricalL2() {
Belinda Trotta's avatar
Belinda Trotta committed
149
150
151
152
153
154
155
156
157
158
    if (meta_->config->path_smooth > kEpsilon) {
      FuncForNumricalL3<USE_RAND, USE_MC, USE_L1, USE_MAX_OUTPUT, true>();
    } else {
      FuncForNumricalL3<USE_RAND, USE_MC, USE_L1, USE_MAX_OUTPUT, false>();
    }
  }

  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
  void FuncForNumricalL3() {
#define TEMPLATE_PREFIX USE_RAND, USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING
159
160
#define LAMBDA_ARGUMENTS                                         \
  double sum_gradient, double sum_hessian, data_size_t num_data, \
Belinda Trotta's avatar
Belinda Trotta committed
161
162
      const ConstraintEntry &constraints, double parent_output, SplitInfo *output
#define BEFORE_ARGUMENTS sum_gradient, sum_hessian, parent_output, num_data, output, &rand_threshold
163
#define FUNC_ARGUMENTS                                                      \
Belinda Trotta's avatar
Belinda Trotta committed
164
165
  sum_gradient, sum_hessian, num_data, constraints, min_gain_shift, \
      output, rand_threshold, parent_output
166

Guolin Ke's avatar
Guolin Ke committed
167
168
    if (meta_->num_bin > 2 && meta_->missing_type != MissingType::None) {
      if (meta_->missing_type == MissingType::Zero) {
169
170
171
        find_best_threshold_fun_ = [=](LAMBDA_ARGUMENTS) {
          int rand_threshold = 0;
          double min_gain_shift =
Belinda Trotta's avatar
Belinda Trotta committed
172
              BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
173
174
175
176
177
178
                  BEFORE_ARGUMENTS);
          FindBestThresholdSequentially<TEMPLATE_PREFIX, true, true, false>(
              FUNC_ARGUMENTS);
          FindBestThresholdSequentially<TEMPLATE_PREFIX, false, true, false>(
              FUNC_ARGUMENTS);
        };
Guolin Ke's avatar
Guolin Ke committed
179
      } else {
180
181
182
        find_best_threshold_fun_ = [=](LAMBDA_ARGUMENTS) {
          int rand_threshold = 0;
          double min_gain_shift =
Belinda Trotta's avatar
Belinda Trotta committed
183
              BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
184
185
186
187
188
189
                  BEFORE_ARGUMENTS);
          FindBestThresholdSequentially<TEMPLATE_PREFIX, true, false, true>(
              FUNC_ARGUMENTS);
          FindBestThresholdSequentially<TEMPLATE_PREFIX, false, false, true>(
              FUNC_ARGUMENTS);
        };
Guolin Ke's avatar
Guolin Ke committed
190
      }
191
    } else {
192
      if (meta_->missing_type != MissingType::NaN) {
193
194
195
        find_best_threshold_fun_ = [=](LAMBDA_ARGUMENTS) {
          int rand_threshold = 0;
          double min_gain_shift =
Belinda Trotta's avatar
Belinda Trotta committed
196
              BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
197
198
199
200
                  BEFORE_ARGUMENTS);
          FindBestThresholdSequentially<TEMPLATE_PREFIX, true, false, false>(
              FUNC_ARGUMENTS);
        };
201
      } else {
202
203
204
        find_best_threshold_fun_ = [=](LAMBDA_ARGUMENTS) {
          int rand_threshold = 0;
          double min_gain_shift =
Belinda Trotta's avatar
Belinda Trotta committed
205
              BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
206
                  BEFORE_ARGUMENTS);
Belinda Trotta's avatar
Belinda Trotta committed
207
          FindBestThresholdSequentially<TEMPLATE_PREFIX, true, false, false>(
208
209
210
              FUNC_ARGUMENTS);
          output->default_left = false;
        };
Guolin Ke's avatar
Guolin Ke committed
211
      }
Guolin Ke's avatar
Guolin Ke committed
212
    }
213
214
215
216
#undef TEMPLATE_PREFIX
#undef LAMBDA_ARGUMENTS
#undef BEFORE_ARGUMENTS
#undef FUNC_ARGURMENTS
Guolin Ke's avatar
Guolin Ke committed
217
  }
218

219
  void FuncForCategorical() {
220
    if (meta_->config->extra_trees) {
221
222
223
224
225
226
227
228
229
230
231
232
233
      if (meta_->config->monotone_constraints.empty()) {
        FuncForCategoricalL1<true, false>();
      } else {
        FuncForCategoricalL1<true, true>();
      }
    } else {
      if (meta_->config->monotone_constraints.empty()) {
        FuncForCategoricalL1<false, false>();
      } else {
        FuncForCategoricalL1<false, true>();
      }
    }
  }
234

235
236
  template <bool USE_RAND, bool USE_MC>
  void FuncForCategoricalL1() {
Belinda Trotta's avatar
Belinda Trotta committed
237
238
239
240
241
242
243
244
245
    if (meta_->config->path_smooth > kEpsilon) {
      FuncForCategoricalL2<USE_RAND, USE_MC, true>();
    } else {
      FuncForCategoricalL2<USE_RAND, USE_MC, false>();
    }
  }

  template <bool USE_RAND, bool USE_MC, bool USE_SMOOTHING>
  void FuncForCategoricalL2() {
246
247
#define ARGUMENTS                                                      \
  std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, \
Belinda Trotta's avatar
Belinda Trotta committed
248
      std::placeholders::_4, std::placeholders::_5, std::placeholders::_6
249
250
251
252
    if (meta_->config->lambda_l1 > 0) {
      if (meta_->config->max_delta_step > 0) {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
Belinda Trotta's avatar
Belinda Trotta committed
253
                          USE_RAND, USE_MC, true, true, USE_SMOOTHING>,
254
                      this, ARGUMENTS);
255
256
257
      } else {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
Belinda Trotta's avatar
Belinda Trotta committed
258
                          USE_RAND, USE_MC, true, false, USE_SMOOTHING>,
259
                      this, ARGUMENTS);
260
      }
261
    } else {
262
263
264
      if (meta_->config->max_delta_step > 0) {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
Belinda Trotta's avatar
Belinda Trotta committed
265
                          USE_RAND, USE_MC, false, true, USE_SMOOTHING>,
266
                      this, ARGUMENTS);
267
268
269
      } else {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
Belinda Trotta's avatar
Belinda Trotta committed
270
                          USE_RAND, USE_MC, false, false, USE_SMOOTHING>,
271
                      this, ARGUMENTS);
272
      }
273
    }
274
#undef ARGUMENTS
275
276
  }

Belinda Trotta's avatar
Belinda Trotta committed
277
  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
278
279
280
281
  void FindBestThresholdCategoricalInner(double sum_gradient,
                                         double sum_hessian,
                                         data_size_t num_data,
                                         const ConstraintEntry& constraints,
Belinda Trotta's avatar
Belinda Trotta committed
282
                                         double parent_output,
283
284
                                         SplitInfo* output) {
    is_splittable_ = false;
Guolin Ke's avatar
Guolin Ke committed
285
    output->default_left = false;
286
    double best_gain = kMinScore;
287
    data_size_t best_left_count = 0;
ChenZhiyong's avatar
ChenZhiyong committed
288
289
    double best_sum_left_gradient = 0;
    double best_sum_left_hessian = 0;
Belinda Trotta's avatar
Belinda Trotta committed
290
291
292
293
294
295
296
297
298
299
300
    double gain_shift;
    if (USE_SMOOTHING) {
      gain_shift = GetLeafGainGivenOutput<USE_L1>(
          sum_gradient, sum_hessian, meta_->config->lambda_l1, meta_->config->lambda_l2, parent_output);
    } else {
      // Need special case for no smoothing to preserve existing behaviour. If no smoothing, the parent output is calculated
      // with the larger categorical l2, whereas min_split_gain uses the original l2.
      gain_shift = GetLeafGain<USE_L1, USE_MAX_OUTPUT, false>(sum_gradient, sum_hessian,
          meta_->config->lambda_l1, meta_->config->lambda_l2, meta_->config->max_delta_step, 0,
          num_data, 0);
    }
301

Guolin Ke's avatar
Guolin Ke committed
302
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
ChenZhiyong's avatar
ChenZhiyong committed
303
    bool is_full_categorical = meta_->missing_type == MissingType::None;
304
    int used_bin = meta_->num_bin - 1 + is_full_categorical;
ChenZhiyong's avatar
ChenZhiyong committed
305

Guolin Ke's avatar
Guolin Ke committed
306
    std::vector<int> sorted_idx;
Guolin Ke's avatar
Guolin Ke committed
307
308
    double l2 = meta_->config->lambda_l2;
    bool use_onehot = meta_->num_bin <= meta_->config->max_cat_to_onehot;
309
310
    int best_threshold = -1;
    int best_dir = 1;
311
    const double cnt_factor = num_data / sum_hessian;
312
    int rand_threshold = 0;
313
    if (use_onehot) {
314
      if (USE_RAND) {
315
        if (used_bin > 0) {
316
          rand_threshold = meta_->rand.NextInt(0, used_bin);
317
318
        }
      }
319
      for (int t = 0; t < used_bin; ++t) {
320
321
        const auto grad = GET_GRAD(data_, t);
        const auto hess = GET_HESS(data_, t);
322
323
        data_size_t cnt =
            static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
324
        // if data not enough, or sum hessian too small
325
        if (cnt < meta_->config->min_data_in_leaf ||
326
            hess < meta_->config->min_sum_hessian_in_leaf) {
327
          continue;
328
        }
329
        data_size_t other_count = num_data - cnt;
330
        // if data not enough
331
332
333
        if (other_count < meta_->config->min_data_in_leaf) {
          continue;
        }
ChenZhiyong's avatar
ChenZhiyong committed
334

335
        double sum_other_hessian = sum_hessian - hess - kEpsilon;
336
        // if sum hessian too small
337
        if (sum_other_hessian < meta_->config->min_sum_hessian_in_leaf) {
338
          continue;
339
        }
ChenZhiyong's avatar
ChenZhiyong committed
340

341
        double sum_other_gradient = sum_gradient - grad;
342
        if (USE_RAND) {
343
344
345
346
          if (t != rand_threshold) {
            continue;
          }
        }
347
        // current split gain
Belinda Trotta's avatar
Belinda Trotta committed
348
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
349
350
            sum_other_gradient, sum_other_hessian, grad, hess + kEpsilon,
            meta_->config->lambda_l1, l2, meta_->config->max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
351
            constraints, 0, meta_->config->path_smooth, other_count, cnt, parent_output);
352
        // gain with split is worse than without split
353
354
355
        if (current_gain <= min_gain_shift) {
          continue;
        }
356
357

        // mark to is splittable
ChenZhiyong's avatar
ChenZhiyong committed
358
        is_splittable_ = true;
359
        // better split point
ChenZhiyong's avatar
ChenZhiyong committed
360
        if (current_gain > best_gain) {
361
          best_threshold = t;
362
363
364
          best_sum_left_gradient = grad;
          best_sum_left_hessian = hess + kEpsilon;
          best_left_count = cnt;
ChenZhiyong's avatar
ChenZhiyong committed
365
          best_gain = current_gain;
366
367
368
369
        }
      }
    } else {
      for (int i = 0; i < used_bin; ++i) {
370
371
        if (Common::RoundInt(GET_HESS(data_, i) * cnt_factor) >=
            meta_->config->cat_smooth) {
372
373
374
375
376
          sorted_idx.push_back(i);
        }
      }
      used_bin = static_cast<int>(sorted_idx.size());

Guolin Ke's avatar
Guolin Ke committed
377
      l2 += meta_->config->cat_l2;
378
379

      auto ctr_fun = [this](double sum_grad, double sum_hess) {
Guolin Ke's avatar
Guolin Ke committed
380
        return (sum_grad) / (sum_hess + meta_->config->cat_smooth);
381
382
      };
      std::sort(sorted_idx.begin(), sorted_idx.end(),
383
384
385
386
                [this, &ctr_fun](int i, int j) {
                  return ctr_fun(GET_GRAD(data_, i), GET_HESS(data_, i)) <
                         ctr_fun(GET_GRAD(data_, j), GET_HESS(data_, j));
                });
387
388
389
390
391

      std::vector<int> find_direction(1, 1);
      std::vector<int> start_position(1, 0);
      find_direction.push_back(-1);
      start_position.push_back(used_bin - 1);
392
393
      const int max_num_cat =
          std::min(meta_->config->max_cat_threshold, (used_bin + 1) / 2);
394
      int max_threshold = std::max(std::min(max_num_cat, used_bin) - 1, 0);
395
      if (USE_RAND) {
396
        if (max_threshold > 0) {
397
          rand_threshold = meta_->rand.NextInt(0, max_threshold);
398
        }
399
      }
400

401
402
403
404
      is_splittable_ = false;
      for (size_t out_i = 0; out_i < find_direction.size(); ++out_i) {
        auto dir = find_direction[out_i];
        auto start_pos = start_position[out_i];
Guolin Ke's avatar
Guolin Ke committed
405
        data_size_t min_data_per_group = meta_->config->min_data_per_group;
406
407
408
409
410
411
412
        data_size_t cnt_cur_group = 0;
        double sum_left_gradient = 0.0f;
        double sum_left_hessian = kEpsilon;
        data_size_t left_count = 0;
        for (int i = 0; i < used_bin && i < max_num_cat; ++i) {
          auto t = sorted_idx[start_pos];
          start_pos += dir;
413
414
          const auto grad = GET_GRAD(data_, t);
          const auto hess = GET_HESS(data_, t);
415
416
          data_size_t cnt =
              static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
417

418
419
420
421
          sum_left_gradient += grad;
          sum_left_hessian += hess;
          left_count += cnt;
          cnt_cur_group += cnt;
422

423
          if (left_count < meta_->config->min_data_in_leaf ||
424
              sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
425
            continue;
426
          }
427
          data_size_t right_count = num_data - left_count;
428
          if (right_count < meta_->config->min_data_in_leaf ||
429
              right_count < min_data_per_group) {
430
            break;
431
          }
432
433

          double sum_right_hessian = sum_hessian - sum_left_hessian;
434
435
436
          if (sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
            break;
          }
437

438
439
440
          if (cnt_cur_group < min_data_per_group) {
            continue;
          }
441
442
443
444

          cnt_cur_group = 0;

          double sum_right_gradient = sum_gradient - sum_left_gradient;
445
          if (USE_RAND) {
446
447
            if (i != rand_threshold) {
              continue;
448
            }
449
          }
Belinda Trotta's avatar
Belinda Trotta committed
450
          double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
451
452
              sum_left_gradient, sum_left_hessian, sum_right_gradient,
              sum_right_hessian, meta_->config->lambda_l1, l2,
Belinda Trotta's avatar
Belinda Trotta committed
453
454
              meta_->config->max_delta_step, constraints, 0, meta_->config->path_smooth,
              left_count, right_count, parent_output);
455
456
457
          if (current_gain <= min_gain_shift) {
            continue;
          }
458
459
460
461
462
463
464
465
466
          is_splittable_ = true;
          if (current_gain > best_gain) {
            best_left_count = left_count;
            best_sum_left_gradient = sum_left_gradient;
            best_sum_left_hessian = sum_left_hessian;
            best_threshold = i;
            best_gain = current_gain;
            best_dir = dir;
          }
ChenZhiyong's avatar
ChenZhiyong committed
467
        }
468
469
      }
    }
470

471
    if (is_splittable_) {
Belinda Trotta's avatar
Belinda Trotta committed
472
473
474
475
      output->left_output = CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
          best_sum_left_gradient, best_sum_left_hessian,
          meta_->config->lambda_l1, l2, meta_->config->max_delta_step,
          constraints, meta_->config->path_smooth, best_left_count, parent_output);
476
477
478
      output->left_count = best_left_count;
      output->left_sum_gradient = best_sum_left_gradient;
      output->left_sum_hessian = best_sum_left_hessian - kEpsilon;
Belinda Trotta's avatar
Belinda Trotta committed
479
480
481
482
483
      output->right_output = CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
          sum_gradient - best_sum_left_gradient,
          sum_hessian - best_sum_left_hessian, meta_->config->lambda_l1, l2,
          meta_->config->max_delta_step, constraints, meta_->config->path_smooth,
          num_data - best_left_count, parent_output);
484
485
      output->right_count = num_data - best_left_count;
      output->right_sum_gradient = sum_gradient - best_sum_left_gradient;
486
487
      output->right_sum_hessian =
          sum_hessian - best_sum_left_hessian - kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
488
      output->gain = best_gain - min_gain_shift;
489
490
      if (use_onehot) {
        output->num_cat_threshold = 1;
491
492
        output->cat_threshold =
            std::vector<uint32_t>(1, static_cast<uint32_t>(best_threshold));
ChenZhiyong's avatar
ChenZhiyong committed
493
      } else {
494
        output->num_cat_threshold = best_threshold + 1;
495
496
        output->cat_threshold =
            std::vector<uint32_t>(output->num_cat_threshold);
497
498
499
500
501
502
503
504
505
506
        if (best_dir == 1) {
          for (int i = 0; i < output->num_cat_threshold; ++i) {
            auto t = sorted_idx[i];
            output->cat_threshold[i] = t;
          }
        } else {
          for (int i = 0; i < output->num_cat_threshold; ++i) {
            auto t = sorted_idx[used_bin - 1 - i];
            output->cat_threshold[i] = t;
          }
ChenZhiyong's avatar
ChenZhiyong committed
507
508
        }
      }
Guolin Ke's avatar
Guolin Ke committed
509
      output->monotone_type = 0;
510
    }
511
512
  }

513
  void GatherInfoForThreshold(double sum_gradient, double sum_hessian,
514
                              uint32_t threshold, data_size_t num_data,
Belinda Trotta's avatar
Belinda Trotta committed
515
                              double parent_output, SplitInfo* output) {
516
    if (meta_->bin_type == BinType::NumericalBin) {
517
      GatherInfoForThresholdNumerical(sum_gradient, sum_hessian, threshold,
Belinda Trotta's avatar
Belinda Trotta committed
518
                                      num_data, parent_output, output);
519
    } else {
520
      GatherInfoForThresholdCategorical(sum_gradient, sum_hessian, threshold,
Belinda Trotta's avatar
Belinda Trotta committed
521
                                        num_data, parent_output, output);
522
523
524
525
    }
  }

  void GatherInfoForThresholdNumerical(double sum_gradient, double sum_hessian,
526
                                       uint32_t threshold, data_size_t num_data,
Belinda Trotta's avatar
Belinda Trotta committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
                                       double parent_output, SplitInfo* output) {
    bool use_smoothing = meta_->config->path_smooth > kEpsilon;
    if (use_smoothing) {
      GatherInfoForThresholdNumericalInner<true>(sum_gradient, sum_hessian,
                                                 threshold, num_data,
                                                 parent_output, output);
    } else {
      GatherInfoForThresholdNumericalInner<false>(sum_gradient, sum_hessian,
                                                  threshold, num_data,
                                                  parent_output, output);
    }
  }

  template<bool USE_SMOOTHING>
  void GatherInfoForThresholdNumericalInner(double sum_gradient, double sum_hessian,
                                            uint32_t threshold, data_size_t num_data,
                                            double parent_output, SplitInfo* output) {
    double gain_shift = GetLeafGainGivenOutput<true>(
545
        sum_gradient, sum_hessian, meta_->config->lambda_l1,
Belinda Trotta's avatar
Belinda Trotta committed
546
        meta_->config->lambda_l2, parent_output);
Guolin Ke's avatar
Guolin Ke committed
547
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
548
549

    // do stuff here
550
    const int8_t offset = meta_->offset;
551
552
553
554
555
556

    double sum_right_gradient = 0.0f;
    double sum_right_hessian = kEpsilon;
    data_size_t right_count = 0;

    // set values
557
558
    bool use_na_as_missing = false;
    bool skip_default_bin = false;
559
560
    if (meta_->missing_type == MissingType::Zero) {
      skip_default_bin = true;
561
    } else if (meta_->missing_type == MissingType::NaN) {
562
563
564
      use_na_as_missing = true;
    }

565
566
    int t = meta_->num_bin - 1 - offset - use_na_as_missing;
    const int t_end = 1 - offset;
567
    const double cnt_factor = num_data / sum_hessian;
568
569
    // from right to left, and we don't need data in bin0
    for (; t >= t_end; --t) {
570
571
572
      if (static_cast<uint32_t>(t + offset) < threshold) {
        break;
      }
573
574

      // need to skip default bin
575
576
577
578
      if (skip_default_bin &&
          (t + offset) == static_cast<int>(meta_->default_bin)) {
        continue;
      }
579
580
      const auto grad = GET_GRAD(data_, t);
      const auto hess = GET_HESS(data_, t);
581
582
      data_size_t cnt =
          static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
583
584
585
      sum_right_gradient += grad;
      sum_right_hessian += hess;
      right_count += cnt;
586
587
588
589
    }
    double sum_left_gradient = sum_gradient - sum_right_gradient;
    double sum_left_hessian = sum_hessian - sum_right_hessian;
    data_size_t left_count = num_data - right_count;
590
    double current_gain =
Belinda Trotta's avatar
Belinda Trotta committed
591
        GetLeafGain<true, true, USE_SMOOTHING>(
592
            sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1,
Belinda Trotta's avatar
Belinda Trotta committed
593
594
595
            meta_->config->lambda_l2, meta_->config->max_delta_step,
            meta_->config->path_smooth, left_count, parent_output) +
        GetLeafGain<true, true, USE_SMOOTHING>(
596
            sum_right_gradient, sum_right_hessian, meta_->config->lambda_l1,
Belinda Trotta's avatar
Belinda Trotta committed
597
598
            meta_->config->lambda_l2, meta_->config->max_delta_step,
            meta_->config->path_smooth, right_count, parent_output);
599
600
601
602

    // gain with split is worse than without split
    if (std::isnan(current_gain) || current_gain <= min_gain_shift) {
      output->gain = kMinScore;
603
      Log::Warning(
604
          "'Forced Split' will be ignored since the gain getting worse.");
605
      return;
606
    }
607
608
609

    // update split information
    output->threshold = threshold;
Belinda Trotta's avatar
Belinda Trotta committed
610
    output->left_output = CalculateSplittedLeafOutput<true, true, USE_SMOOTHING>(
611
        sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1,
Belinda Trotta's avatar
Belinda Trotta committed
612
613
        meta_->config->lambda_l2, meta_->config->max_delta_step,
        meta_->config->path_smooth, left_count, parent_output);
614
615
616
    output->left_count = left_count;
    output->left_sum_gradient = sum_left_gradient;
    output->left_sum_hessian = sum_left_hessian - kEpsilon;
Belinda Trotta's avatar
Belinda Trotta committed
617
    output->right_output = CalculateSplittedLeafOutput<true, true, USE_SMOOTHING>(
618
619
        sum_gradient - sum_left_gradient, sum_hessian - sum_left_hessian,
        meta_->config->lambda_l1, meta_->config->lambda_l2,
Belinda Trotta's avatar
Belinda Trotta committed
620
621
        meta_->config->max_delta_step, meta_->config->path_smooth,
        right_count, parent_output);
622
623
624
    output->right_count = num_data - left_count;
    output->right_sum_gradient = sum_gradient - sum_left_gradient;
    output->right_sum_hessian = sum_hessian - sum_left_hessian - kEpsilon;
625
    output->gain = current_gain - min_gain_shift;
626
627
628
    output->default_left = true;
  }

Belinda Trotta's avatar
Belinda Trotta committed
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
  void GatherInfoForThresholdCategorical(double sum_gradient,  double sum_hessian,
                                         uint32_t threshold, data_size_t num_data,
                                         double parent_output, SplitInfo* output) {
    bool use_smoothing = meta_->config->path_smooth > kEpsilon;
    if (use_smoothing) {
      GatherInfoForThresholdCategoricalInner<true>(sum_gradient, sum_hessian, threshold,
                                                   num_data, parent_output, output);
    } else {
      GatherInfoForThresholdCategoricalInner<false>(sum_gradient, sum_hessian, threshold,
                                                    num_data, parent_output, output);
    }
  }

  template<bool USE_SMOOTHING>
  void GatherInfoForThresholdCategoricalInner(double sum_gradient,
                                              double sum_hessian, uint32_t threshold,
                                              data_size_t num_data, double parent_output,
                                              SplitInfo* output) {
647
648
    // get SplitInfo for a given one-hot categorical split.
    output->default_left = false;
Belinda Trotta's avatar
Belinda Trotta committed
649
650
    double gain_shift = GetLeafGainGivenOutput<true>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1, meta_->config->lambda_l2, parent_output);
Guolin Ke's avatar
Guolin Ke committed
651
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
652
653
654
655
656
657
658
    bool is_full_categorical = meta_->missing_type == MissingType::None;
    int used_bin = meta_->num_bin - 1 + is_full_categorical;
    if (threshold >= static_cast<uint32_t>(used_bin)) {
      output->gain = kMinScore;
      Log::Warning("Invalid categorical threshold split");
      return;
    }
659
660
661
    const double cnt_factor = num_data / sum_hessian;
    const auto grad = GET_GRAD(data_, threshold);
    const auto hess = GET_HESS(data_, threshold);
662
663
    data_size_t cnt =
        static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
664

Guolin Ke's avatar
Guolin Ke committed
665
    double l2 = meta_->config->lambda_l2;
666
    data_size_t left_count = cnt;
667
    data_size_t right_count = num_data - left_count;
668
    double sum_left_hessian = hess + kEpsilon;
669
    double sum_right_hessian = sum_hessian - sum_left_hessian;
670
    double sum_left_gradient = grad;
671
672
    double sum_right_gradient = sum_gradient - sum_left_gradient;
    // current split gain
673
    double current_gain =
Belinda Trotta's avatar
Belinda Trotta committed
674
675
676
677
678
679
680
681
682
683
        GetLeafGain<true, true, USE_SMOOTHING>(sum_right_gradient, sum_right_hessian,
                                      meta_->config->lambda_l1, l2,
                                      meta_->config->max_delta_step,
                                      meta_->config->path_smooth, right_count,
                                      parent_output) +
        GetLeafGain<true, true, USE_SMOOTHING>(sum_left_gradient, sum_left_hessian,
                                      meta_->config->lambda_l1, l2,
                                      meta_->config->max_delta_step,
                                      meta_->config->path_smooth, left_count,
                                      parent_output);
684
685
    if (std::isnan(current_gain) || current_gain <= min_gain_shift) {
      output->gain = kMinScore;
686
687
      Log::Warning(
          "'Forced Split' will be ignored since the gain getting worse.");
688
689
      return;
    }
Belinda Trotta's avatar
Belinda Trotta committed
690
    output->left_output = CalculateSplittedLeafOutput<true, true, USE_SMOOTHING>(
691
        sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1, l2,
Belinda Trotta's avatar
Belinda Trotta committed
692
693
        meta_->config->max_delta_step, meta_->config->path_smooth, left_count,
        parent_output);
694
695
696
    output->left_count = left_count;
    output->left_sum_gradient = sum_left_gradient;
    output->left_sum_hessian = sum_left_hessian - kEpsilon;
Belinda Trotta's avatar
Belinda Trotta committed
697
    output->right_output = CalculateSplittedLeafOutput<true, true, USE_SMOOTHING>(
698
        sum_right_gradient, sum_right_hessian, meta_->config->lambda_l1, l2,
Belinda Trotta's avatar
Belinda Trotta committed
699
700
        meta_->config->max_delta_step, meta_->config->path_smooth, right_count,
        parent_output);
701
702
703
704
705
706
707
708
    output->right_count = right_count;
    output->right_sum_gradient = sum_gradient - sum_left_gradient;
    output->right_sum_hessian = sum_right_hessian - kEpsilon;
    output->gain = current_gain - min_gain_shift;
    output->num_cat_threshold = 1;
    output->cat_threshold = std::vector<uint32_t>(1, threshold);
  }

Guolin Ke's avatar
Guolin Ke committed
709
  /*!
710
711
   * \brief Binary size of this histogram
   */
Guolin Ke's avatar
Guolin Ke committed
712
  int SizeOfHistgram() const {
713
    return (meta_->num_bin - meta_->offset) * kHistEntrySize;
Guolin Ke's avatar
Guolin Ke committed
714
715
716
  }

  /*!
717
718
   * \brief Restore histogram from memory
   */
Guolin Ke's avatar
Guolin Ke committed
719
  void FromMemory(char* memory_data) {
720
721
    std::memcpy(data_, memory_data,
                (meta_->num_bin - meta_->offset) * kHistEntrySize);
Guolin Ke's avatar
Guolin Ke committed
722
723
724
  }

  /*!
725
726
   * \brief True if this histogram can be splitted
   */
Guolin Ke's avatar
Guolin Ke committed
727
728
729
  bool is_splittable() { return is_splittable_; }

  /*!
730
731
   * \brief Set splittable to this histogram
   */
Guolin Ke's avatar
Guolin Ke committed
732
733
  void set_is_splittable(bool val) { is_splittable_ = val; }

734
735
736
737
738
  static double ThresholdL1(double s, double l1) {
    const double reg_s = std::max(0.0, std::fabs(s) - l1);
    return Common::Sign(s) * reg_s;
  }

Belinda Trotta's avatar
Belinda Trotta committed
739
  template <bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
740
741
  static double CalculateSplittedLeafOutput(double sum_gradients,
                                            double sum_hessians, double l1,
Belinda Trotta's avatar
Belinda Trotta committed
742
743
744
745
                                            double l2, double max_delta_step,
                                            double smoothing, data_size_t num_data,
                                            double parent_output) {
    double ret;
746
    if (USE_L1) {
Belinda Trotta's avatar
Belinda Trotta committed
747
      ret = -ThresholdL1(sum_gradients, l1) / (sum_hessians + l2);
748
    } else {
Belinda Trotta's avatar
Belinda Trotta committed
749
750
751
752
753
      ret = -sum_gradients / (sum_hessians + l2);
    }
    if (USE_MAX_OUTPUT) {
      if (max_delta_step > 0 && std::fabs(ret) > max_delta_step) {
        ret = Common::Sign(ret) * max_delta_step;
754
      }
755
    }
Belinda Trotta's avatar
Belinda Trotta committed
756
757
758
759
760
    if (USE_SMOOTHING) {
      ret = ret * (num_data / smoothing) / (num_data / smoothing + 1) \
          + parent_output / (num_data / smoothing + 1);
    }
    return ret;
Guolin Ke's avatar
Guolin Ke committed
761
762
  }

Belinda Trotta's avatar
Belinda Trotta committed
763
  template <bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
764
765
  static double CalculateSplittedLeafOutput(
      double sum_gradients, double sum_hessians, double l1, double l2,
Belinda Trotta's avatar
Belinda Trotta committed
766
767
768
769
      double max_delta_step, const ConstraintEntry& constraints,
      double smoothing, data_size_t num_data, double parent_output) {
    double ret = CalculateSplittedLeafOutput<USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
        sum_gradients, sum_hessians, l1, l2, max_delta_step, smoothing, num_data, parent_output);
770
771
772
773
774
775
776
777
    if (USE_MC) {
      if (ret < constraints.min) {
        ret = constraints.min;
      } else if (ret > constraints.max) {
        ret = constraints.max;
      }
    }
    return ret;
Guolin Ke's avatar
Guolin Ke committed
778
779
  }

780
 private:
Belinda Trotta's avatar
Belinda Trotta committed
781
  template <bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
782
783
784
785
786
787
  static double GetSplitGains(double sum_left_gradients,
                              double sum_left_hessians,
                              double sum_right_gradients,
                              double sum_right_hessians, double l1, double l2,
                              double max_delta_step,
                              const ConstraintEntry& constraints,
Belinda Trotta's avatar
Belinda Trotta committed
788
789
790
791
792
                              int8_t monotone_constraint,
                              double smoothing,
                              data_size_t left_count,
                              data_size_t right_count,
                              double parent_output) {
793
    if (!USE_MC) {
Belinda Trotta's avatar
Belinda Trotta committed
794
795
796
797
798
799
800
801
      return GetLeafGain<USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(sum_left_gradients,
                                                                sum_left_hessians, l1, l2,
                                                                max_delta_step, smoothing,
                                                                left_count, parent_output) +
             GetLeafGain<USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(sum_right_gradients,
                                                                sum_right_hessians, l1, l2,
                                                                max_delta_step, smoothing,
                                                                right_count, parent_output);
802
803
    } else {
      double left_output =
Belinda Trotta's avatar
Belinda Trotta committed
804
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
805
              sum_left_gradients, sum_left_hessians, l1, l2, max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
806
              constraints, smoothing, left_count, parent_output);
807
      double right_output =
Belinda Trotta's avatar
Belinda Trotta committed
808
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
809
              sum_right_gradients, sum_right_hessians, l1, l2, max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
810
              constraints, smoothing, right_count, parent_output);
811
812
813
814
815
816
817
818
      if (((monotone_constraint > 0) && (left_output > right_output)) ||
          ((monotone_constraint < 0) && (left_output < right_output))) {
        return 0;
      }
      return GetLeafGainGivenOutput<USE_L1>(
                 sum_left_gradients, sum_left_hessians, l1, l2, left_output) +
             GetLeafGainGivenOutput<USE_L1>(
                 sum_right_gradients, sum_right_hessians, l1, l2, right_output);
Guolin Ke's avatar
Guolin Ke committed
819
    }
Guolin Ke's avatar
Guolin Ke committed
820
  }
Guolin Ke's avatar
Guolin Ke committed
821

Belinda Trotta's avatar
Belinda Trotta committed
822
  template <bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING>
823
  static double GetLeafGain(double sum_gradients, double sum_hessians,
Belinda Trotta's avatar
Belinda Trotta committed
824
825
826
                            double l1, double l2, double max_delta_step,
                            double smoothing, data_size_t num_data, double parent_output) {
    if (!USE_MAX_OUTPUT && !USE_SMOOTHING) {
827
828
829
830
831
832
833
      if (USE_L1) {
        const double sg_l1 = ThresholdL1(sum_gradients, l1);
        return (sg_l1 * sg_l1) / (sum_hessians + l2);
      } else {
        return (sum_gradients * sum_gradients) / (sum_hessians + l2);
      }
    } else {
Belinda Trotta's avatar
Belinda Trotta committed
834
835
836
      double output = CalculateSplittedLeafOutput<USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
          sum_gradients, sum_hessians, l1, l2, max_delta_step, smoothing, num_data, parent_output);
      return GetLeafGainGivenOutput<USE_L1>(sum_gradients, sum_hessians, l1, l2, output);
837
    }
Guolin Ke's avatar
Guolin Ke committed
838
839
  }

840
841
842
843
844
845
846
847
848
849
850
  template <bool USE_L1>
  static double GetLeafGainGivenOutput(double sum_gradients,
                                       double sum_hessians, double l1,
                                       double l2, double output) {
    if (USE_L1) {
      const double sg_l1 = ThresholdL1(sum_gradients, l1);
      return -(2.0 * sg_l1 * output + (sum_hessians + l2) * output * output);
    } else {
      return -(2.0 * sum_gradients * output +
               (sum_hessians + l2) * output * output);
    }
Guolin Ke's avatar
Guolin Ke committed
851
  }
Guolin Ke's avatar
Guolin Ke committed
852

Belinda Trotta's avatar
Belinda Trotta committed
853
  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT, bool USE_SMOOTHING,
854
            bool REVERSE, bool SKIP_DEFAULT_BIN, bool NA_AS_MISSING>
guolinke's avatar
guolinke committed
855
856
857
858
  void FindBestThresholdSequentially(double sum_gradient, double sum_hessian,
                                     data_size_t num_data,
                                     const ConstraintEntry& constraints,
                                     double min_gain_shift, SplitInfo* output,
Belinda Trotta's avatar
Belinda Trotta committed
859
                                     int rand_threshold, double parent_output) {
860
    const int8_t offset = meta_->offset;
Guolin Ke's avatar
Guolin Ke committed
861
862
863
864
865
    double best_sum_left_gradient = NAN;
    double best_sum_left_hessian = NAN;
    double best_gain = kMinScore;
    data_size_t best_left_count = 0;
    uint32_t best_threshold = static_cast<uint32_t>(meta_->num_bin);
866
    const double cnt_factor = num_data / sum_hessian;
867
    if (REVERSE) {
Guolin Ke's avatar
Guolin Ke committed
868
869
870
871
      double sum_right_gradient = 0.0f;
      double sum_right_hessian = kEpsilon;
      data_size_t right_count = 0;

872
      int t = meta_->num_bin - 1 - offset - NA_AS_MISSING;
873
      const int t_end = 1 - offset;
Guolin Ke's avatar
Guolin Ke committed
874
875
876
877

      // from right to left, and we don't need data in bin0
      for (; t >= t_end; --t) {
        // need to skip default bin
878
879
880
881
882
        if (SKIP_DEFAULT_BIN) {
          if ((t + offset) == static_cast<int>(meta_->default_bin)) {
            continue;
          }
        }
883
884
        const auto grad = GET_GRAD(data_, t);
        const auto hess = GET_HESS(data_, t);
885
886
        data_size_t cnt =
            static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
887
888
889
        sum_right_gradient += grad;
        sum_right_hessian += hess;
        right_count += cnt;
Guolin Ke's avatar
Guolin Ke committed
890
        // if data not enough, or sum hessian too small
891
        if (right_count < meta_->config->min_data_in_leaf ||
892
            sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
893
          continue;
894
        }
Guolin Ke's avatar
Guolin Ke committed
895
896
        data_size_t left_count = num_data - right_count;
        // if data not enough
897
898
899
        if (left_count < meta_->config->min_data_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
900
901
902

        double sum_left_hessian = sum_hessian - sum_right_hessian;
        // if sum hessian too small
903
904
905
        if (sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
906
907

        double sum_left_gradient = sum_gradient - sum_right_gradient;
908
        if (USE_RAND) {
909
          if (t - 1 + offset != rand_threshold) {
Guolin Ke's avatar
Guolin Ke committed
910
            continue;
911
          }
Guolin Ke's avatar
Guolin Ke committed
912
        }
Guolin Ke's avatar
Guolin Ke committed
913
        // current split gain
Belinda Trotta's avatar
Belinda Trotta committed
914
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
915
916
917
            sum_left_gradient, sum_left_hessian, sum_right_gradient,
            sum_right_hessian, meta_->config->lambda_l1,
            meta_->config->lambda_l2, meta_->config->max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
918
919
            constraints, meta_->monotone_type, meta_->config->path_smooth,
            left_count, right_count, parent_output);
Guolin Ke's avatar
Guolin Ke committed
920
        // gain with split is worse than without split
921
922
923
        if (current_gain <= min_gain_shift) {
          continue;
        }
Guolin Ke's avatar
Guolin Ke committed
924
925
926
927
928
929
930
931
932
933
934
935

        // mark to is splittable
        is_splittable_ = true;
        // better split point
        if (current_gain > best_gain) {
          best_left_count = left_count;
          best_sum_left_gradient = sum_left_gradient;
          best_sum_left_hessian = sum_left_hessian;
          // left is <= threshold, right is > threshold.  so this is t-1
          best_threshold = static_cast<uint32_t>(t - 1 + offset);
          best_gain = current_gain;
        }
Guolin Ke's avatar
Guolin Ke committed
936
      }
ChenZhiyong's avatar
ChenZhiyong committed
937
    } else {
Guolin Ke's avatar
Guolin Ke committed
938
939
940
941
942
      double sum_left_gradient = 0.0f;
      double sum_left_hessian = kEpsilon;
      data_size_t left_count = 0;

      int t = 0;
943
      const int t_end = meta_->num_bin - 2 - offset;
Guolin Ke's avatar
Guolin Ke committed
944

945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
      if (NA_AS_MISSING) {
        if (offset == 1) {
          sum_left_gradient = sum_gradient;
          sum_left_hessian = sum_hessian - kEpsilon;
          left_count = num_data;
          for (int i = 0; i < meta_->num_bin - offset; ++i) {
            const auto grad = GET_GRAD(data_, i);
            const auto hess = GET_HESS(data_, i);
            data_size_t cnt =
                static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
            sum_left_gradient -= grad;
            sum_left_hessian -= hess;
            left_count -= cnt;
          }
          t = -1;
Guolin Ke's avatar
Guolin Ke committed
960
961
962
        }
      }

Guolin Ke's avatar
Guolin Ke committed
963
      for (; t <= t_end; ++t) {
964
965
966
967
968
        if (SKIP_DEFAULT_BIN) {
          if ((t + offset) == static_cast<int>(meta_->default_bin)) {
            continue;
          }
        }
Guolin Ke's avatar
Guolin Ke committed
969
        if (t >= 0) {
970
971
          sum_left_gradient += GET_GRAD(data_, t);
          sum_left_hessian += GET_HESS(data_, t);
972
973
          left_count += static_cast<data_size_t>(
              Common::RoundInt(GET_HESS(data_, t) * cnt_factor));
Guolin Ke's avatar
Guolin Ke committed
974
        }
Guolin Ke's avatar
Guolin Ke committed
975
        // if data not enough, or sum hessian too small
976
        if (left_count < meta_->config->min_data_in_leaf ||
977
            sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
978
          continue;
979
        }
Guolin Ke's avatar
Guolin Ke committed
980
981
        data_size_t right_count = num_data - left_count;
        // if data not enough
982
983
984
        if (right_count < meta_->config->min_data_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
985
986
987

        double sum_right_hessian = sum_hessian - sum_left_hessian;
        // if sum hessian too small
988
989
990
        if (sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
991
992

        double sum_right_gradient = sum_gradient - sum_left_gradient;
993
        if (USE_RAND) {
Guolin Ke's avatar
Guolin Ke committed
994
995
          if (t + offset != rand_threshold) {
            continue;
996
          }
Guolin Ke's avatar
Guolin Ke committed
997
        }
Guolin Ke's avatar
Guolin Ke committed
998
        // current split gain
Belinda Trotta's avatar
Belinda Trotta committed
999
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
1000
1001
1002
            sum_left_gradient, sum_left_hessian, sum_right_gradient,
            sum_right_hessian, meta_->config->lambda_l1,
            meta_->config->lambda_l2, meta_->config->max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
1003
1004
            constraints, meta_->monotone_type, meta_->config->path_smooth, left_count,
            right_count, parent_output);
Guolin Ke's avatar
Guolin Ke committed
1005
        // gain with split is worse than without split
1006
1007
1008
        if (current_gain <= min_gain_shift) {
          continue;
        }
Guolin Ke's avatar
Guolin Ke committed
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019

        // mark to is splittable
        is_splittable_ = true;
        // better split point
        if (current_gain > best_gain) {
          best_left_count = left_count;
          best_sum_left_gradient = sum_left_gradient;
          best_sum_left_hessian = sum_left_hessian;
          best_threshold = static_cast<uint32_t>(t + offset);
          best_gain = current_gain;
        }
Guolin Ke's avatar
Guolin Ke committed
1020
1021
1022
      }
    }

1023
    if (is_splittable_ && best_gain > output->gain + min_gain_shift) {
Guolin Ke's avatar
Guolin Ke committed
1024
1025
      // update split information
      output->threshold = best_threshold;
1026
      output->left_output =
Belinda Trotta's avatar
Belinda Trotta committed
1027
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
1028
1029
              best_sum_left_gradient, best_sum_left_hessian,
              meta_->config->lambda_l1, meta_->config->lambda_l2,
Belinda Trotta's avatar
Belinda Trotta committed
1030
1031
              meta_->config->max_delta_step, constraints, meta_->config->path_smooth,
              best_left_count, parent_output);
Guolin Ke's avatar
Guolin Ke committed
1032
1033
1034
      output->left_count = best_left_count;
      output->left_sum_gradient = best_sum_left_gradient;
      output->left_sum_hessian = best_sum_left_hessian - kEpsilon;
1035
      output->right_output =
Belinda Trotta's avatar
Belinda Trotta committed
1036
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT, USE_SMOOTHING>(
1037
1038
1039
              sum_gradient - best_sum_left_gradient,
              sum_hessian - best_sum_left_hessian, meta_->config->lambda_l1,
              meta_->config->lambda_l2, meta_->config->max_delta_step,
Belinda Trotta's avatar
Belinda Trotta committed
1040
1041
              constraints, meta_->config->path_smooth, num_data - best_left_count,
              parent_output);
Guolin Ke's avatar
Guolin Ke committed
1042
1043
      output->right_count = num_data - best_left_count;
      output->right_sum_gradient = sum_gradient - best_sum_left_gradient;
1044
1045
1046
1047
      output->right_sum_hessian =
          sum_hessian - best_sum_left_hessian - kEpsilon;
      output->gain = best_gain - min_gain_shift;
      output->default_left = REVERSE;
Guolin Ke's avatar
Guolin Ke committed
1048
1049
1050
    }
  }

Guolin Ke's avatar
Guolin Ke committed
1051
  const FeatureMetainfo* meta_;
Guolin Ke's avatar
Guolin Ke committed
1052
  /*! \brief sum of gradient of each bin */
1053
  hist_t* data_;
Guolin Ke's avatar
Guolin Ke committed
1054
  bool is_splittable_ = true;
1055

1056
  std::function<void(double, double, data_size_t, const ConstraintEntry&,
Belinda Trotta's avatar
Belinda Trotta committed
1057
                     double, SplitInfo*)>
1058
      find_best_threshold_fun_;
Guolin Ke's avatar
Guolin Ke committed
1059
};
Nikita Titov's avatar
Nikita Titov committed
1060

Guolin Ke's avatar
Guolin Ke committed
1061
class HistogramPool {
1062
 public:
Guolin Ke's avatar
Guolin Ke committed
1063
  /*!
1064
1065
   * \brief Constructor
   */
Guolin Ke's avatar
Guolin Ke committed
1066
  HistogramPool() {
Guolin Ke's avatar
Guolin Ke committed
1067
1068
    cache_size_ = 0;
    total_size_ = 0;
Guolin Ke's avatar
Guolin Ke committed
1069
  }
1070

Guolin Ke's avatar
Guolin Ke committed
1071
  /*!
1072
1073
1074
   * \brief Destructor
   */
  ~HistogramPool() {}
1075

Guolin Ke's avatar
Guolin Ke committed
1076
  /*!
1077
1078
1079
1080
   * \brief Reset pool size
   * \param cache_size Max cache size
   * \param total_size Total size will be used
   */
Guolin Ke's avatar
Guolin Ke committed
1081
  void Reset(int cache_size, int total_size) {
Guolin Ke's avatar
Guolin Ke committed
1082
1083
    cache_size_ = cache_size;
    // at least need 2 bucket to store smaller leaf and larger leaf
1084
    CHECK_GE(cache_size_, 2);
Guolin Ke's avatar
Guolin Ke committed
1085
1086
1087
1088
1089
1090
    total_size_ = total_size;
    if (cache_size_ > total_size_) {
      cache_size_ = total_size_;
    }
    is_enough_ = (cache_size_ == total_size_);
    if (!is_enough_) {
1091
1092
1093
      mapper_.resize(total_size_);
      inverse_mapper_.resize(cache_size_);
      last_used_time_.resize(cache_size_);
Guolin Ke's avatar
Guolin Ke committed
1094
1095
1096
      ResetMap();
    }
  }
1097

Guolin Ke's avatar
Guolin Ke committed
1098
  /*!
1099
1100
   * \brief Reset mapper
   */
Guolin Ke's avatar
Guolin Ke committed
1101
1102
1103
1104
1105
1106
1107
1108
  void ResetMap() {
    if (!is_enough_) {
      cur_time_ = 0;
      std::fill(mapper_.begin(), mapper_.end(), -1);
      std::fill(inverse_mapper_.begin(), inverse_mapper_.end(), -1);
      std::fill(last_used_time_.begin(), last_used_time_.end(), 0);
    }
  }
1109
1110
1111
  template <bool USE_DATA, bool USE_CONFIG>
  static void SetFeatureInfo(const Dataset* train_data, const Config* config,
                             std::vector<FeatureMetainfo>* feature_meta) {
1112
1113
1114
    auto& ref_feature_meta = *feature_meta;
    const int num_feature = train_data->num_features();
    ref_feature_meta.resize(num_feature);
1115
#pragma omp parallel for schedule(static, 512) if (num_feature >= 1024)
1116
    for (int i = 0; i < num_feature; ++i) {
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
      if (USE_DATA) {
        ref_feature_meta[i].num_bin = train_data->FeatureNumBin(i);
        ref_feature_meta[i].default_bin =
            train_data->FeatureBinMapper(i)->GetDefaultBin();
        ref_feature_meta[i].missing_type =
            train_data->FeatureBinMapper(i)->missing_type();
        if (train_data->FeatureBinMapper(i)->GetMostFreqBin() == 0) {
          ref_feature_meta[i].offset = 1;
        } else {
          ref_feature_meta[i].offset = 0;
        }
        ref_feature_meta[i].bin_type =
            train_data->FeatureBinMapper(i)->bin_type();
1130
      }
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
      if (USE_CONFIG) {
        const int real_fidx = train_data->RealFeatureIndex(i);
        if (!config->monotone_constraints.empty()) {
          ref_feature_meta[i].monotone_type =
              config->monotone_constraints[real_fidx];
        } else {
          ref_feature_meta[i].monotone_type = 0;
        }
        if (!config->feature_contri.empty()) {
          ref_feature_meta[i].penalty = config->feature_contri[real_fidx];
        } else {
          ref_feature_meta[i].penalty = 1.0;
        }
        ref_feature_meta[i].rand = Random(config->extra_seed + i);
1145
1146
1147
1148
1149
      }
      ref_feature_meta[i].config = config;
    }
  }

1150
1151
  void DynamicChangeSize(const Dataset* train_data, bool is_hist_colwise,
                         const Config* config, int cache_size, int total_size) {
Guolin Ke's avatar
Guolin Ke committed
1152
    if (feature_metas_.empty()) {
1153
      SetFeatureInfo<true, true>(train_data, config, &feature_metas_);
1154
      uint64_t bin_cnt_over_features = 0;
1155
      for (int i = 0; i < train_data->num_features(); ++i) {
1156
1157
        bin_cnt_over_features +=
            static_cast<uint64_t>(feature_metas_[i].num_bin);
Guolin Ke's avatar
Guolin Ke committed
1158
      }
1159
      Log::Info("Total Bins %d", bin_cnt_over_features);
Guolin Ke's avatar
Guolin Ke committed
1160
    }
Guolin Ke's avatar
Guolin Ke committed
1161
    int old_cache_size = static_cast<int>(pool_.size());
Guolin Ke's avatar
Guolin Ke committed
1162
    Reset(cache_size, total_size);
Guolin Ke's avatar
Guolin Ke committed
1163
1164
1165
1166
1167

    if (cache_size > old_cache_size) {
      pool_.resize(cache_size);
      data_.resize(cache_size);
    }
1168
    int num_total_bin = static_cast<int>(train_data->NumTotalBin());
Guolin Ke's avatar
Guolin Ke committed
1169

1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    std::vector<int> offsets;
    if (is_hist_colwise) {
      int offset = 0;
      for (int j = 0; j < train_data->num_features(); ++j) {
        offset += train_data->SubFeatureBinOffset(j);
        offsets.push_back(offset);
        auto num_bin = train_data->FeatureNumBin(j);
        if (train_data->FeatureBinMapper(j)->GetMostFreqBin() == 0) {
          num_bin -= 1;
        }
        offset += num_bin;
      }
    } else {
      num_total_bin = 1;
      for (int j = 0; j < train_data->num_features(); ++j) {
        offsets.push_back(num_total_bin);
        num_total_bin += train_data->FeatureBinMapper(j)->num_bin();
        if (train_data->FeatureBinMapper(j)->GetMostFreqBin() == 0) {
          num_total_bin -= 1;
        }
      }
    }
1192
    OMP_INIT_EX();
1193
#pragma omp parallel for schedule(static)
Guolin Ke's avatar
Guolin Ke committed
1194
    for (int i = old_cache_size; i < cache_size; ++i) {
1195
      OMP_LOOP_EX_BEGIN();
Guolin Ke's avatar
Guolin Ke committed
1196
      pool_[i].reset(new FeatureHistogram[train_data->num_features()]);
1197
      data_[i].resize(num_total_bin * 2);
Guolin Ke's avatar
Guolin Ke committed
1198
      for (int j = 0; j < train_data->num_features(); ++j) {
1199
        pool_[i][j].Init(data_[i].data() + offsets[j] * 2, &feature_metas_[j]);
Guolin Ke's avatar
Guolin Ke committed
1200
      }
1201
      OMP_LOOP_EX_END();
Guolin Ke's avatar
Guolin Ke committed
1202
    }
1203
    OMP_THROW_EX();
Guolin Ke's avatar
Guolin Ke committed
1204
1205
  }

1206
  void ResetConfig(const Dataset* train_data, const Config* config) {
1207
1208
    CHECK_GT(train_data->num_features(), 0);
    const Config* old_config = feature_metas_[0].config;
1209
    SetFeatureInfo<false, true>(train_data, config, &feature_metas_);
1210
1211
1212
1213
    // if need to reset the function pointers
    if (old_config->lambda_l1 != config->lambda_l1 ||
        old_config->monotone_constraints != config->monotone_constraints ||
        old_config->extra_trees != config->extra_trees ||
Belinda Trotta's avatar
Belinda Trotta committed
1214
1215
        old_config->max_delta_step != config->max_delta_step ||
        old_config->path_smooth != config->path_smooth) {
1216
1217
1218
1219
1220
1221
1222
#pragma omp parallel for schedule(static)
      for (int i = 0; i < cache_size_; ++i) {
        for (int j = 0; j < train_data->num_features(); ++j) {
          pool_[i][j].ResetFunc();
        }
      }
    }
Guolin Ke's avatar
Guolin Ke committed
1223
  }
1224

Guolin Ke's avatar
Guolin Ke committed
1225
  /*!
1226
1227
1228
1229
1230
1231
   * \brief Get data for the specific index
   * \param idx which index want to get
   * \param out output data will store into this
   * \return True if this index is in the pool, False if this index is not in
   * the pool
   */
Guolin Ke's avatar
Guolin Ke committed
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
  bool Get(int idx, FeatureHistogram** out) {
    if (is_enough_) {
      *out = pool_[idx].get();
      return true;
    } else if (mapper_[idx] >= 0) {
      int slot = mapper_[idx];
      *out = pool_[slot].get();
      last_used_time_[slot] = ++cur_time_;
      return true;
    } else {
1242
      // choose the least used slot
Guolin Ke's avatar
Guolin Ke committed
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
      int slot = static_cast<int>(ArrayArgs<int>::ArgMin(last_used_time_));
      *out = pool_[slot].get();
      last_used_time_[slot] = ++cur_time_;

      // reset previous mapper
      if (inverse_mapper_[slot] >= 0) mapper_[inverse_mapper_[slot]] = -1;

      // update current mapper
      mapper_[idx] = slot;
      inverse_mapper_[slot] = idx;
      return false;
    }
  }

  /*!
1258
1259
1260
1261
   * \brief Move data from one index to another index
   * \param src_idx
   * \param dst_idx
   */
Guolin Ke's avatar
Guolin Ke committed
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
  void Move(int src_idx, int dst_idx) {
    if (is_enough_) {
      std::swap(pool_[src_idx], pool_[dst_idx]);
      return;
    }
    if (mapper_[src_idx] < 0) {
      return;
    }
    // get slot of src idx
    int slot = mapper_[src_idx];
    // reset src_idx
    mapper_[src_idx] = -1;

    // move to dst idx
    mapper_[dst_idx] = slot;
    last_used_time_[slot] = ++cur_time_;
    inverse_mapper_[slot] = dst_idx;
  }
1280

1281
 private:
Guolin Ke's avatar
Guolin Ke committed
1282
  std::vector<std::unique_ptr<FeatureHistogram[]>> pool_;
1283
1284
1285
  std::vector<
      std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>>
      data_;
Guolin Ke's avatar
Guolin Ke committed
1286
  std::vector<FeatureMetainfo> feature_metas_;
Guolin Ke's avatar
Guolin Ke committed
1287
1288
1289
1290
1291
1292
1293
1294
1295
  int cache_size_;
  int total_size_;
  bool is_enough_ = false;
  std::vector<int> mapper_;
  std::vector<int> inverse_mapper_;
  std::vector<int> last_used_time_;
  int cur_time_ = 0;
};

Guolin Ke's avatar
Guolin Ke committed
1296
}  // namespace LightGBM
1297
#endif  // LightGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_