"src/vscode:/vscode.git/clone" did not exist on "6a367ac41cbb71db1efc92d9aa0588119a4c16ac"
feature_histogram.hpp 44.4 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
    if (meta_->bin_type == BinType::NumericalBin) {
63
      FuncForNumrical();
64
    } else {
65
      FuncForCategorical();
66
    }
Guolin Ke's avatar
Guolin Ke committed
67
68
  }

69
  hist_t* RawData() { return data_; }
70

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

81
82
83
84
  void FindBestThreshold(double sum_gradient, double sum_hessian,
                         data_size_t num_data,
                         const ConstraintEntry& constraints,
                         SplitInfo* output) {
Guolin Ke's avatar
Guolin Ke committed
85
    output->default_left = true;
Guolin Ke's avatar
Guolin Ke committed
86
    output->gain = kMinScore;
87
88
    find_best_threshold_fun_(sum_gradient, sum_hessian + 2 * kEpsilon, num_data,
                             constraints, output);
Guolin Ke's avatar
Guolin Ke committed
89
    output->gain *= meta_->penalty;
90
91
  }

92
93
94
  template <bool USE_RAND, bool USE_L1, bool USE_MAX_OUTPUT>
  double BeforeNumercal(double sum_gradient, double sum_hessian,
                        SplitInfo* output, int* rand_threshold) {
Guolin Ke's avatar
Guolin Ke committed
95
    is_splittable_ = false;
96
97
98
99
100
101
102
103
104
    output->monotone_type = meta_->monotone_type;
    double gain_shift = GetLeafGain<USE_L1, USE_MAX_OUTPUT>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1,
        meta_->config->lambda_l2, meta_->config->max_delta_step);
    *rand_threshold = 0;
    if (USE_RAND) {
      if (meta_->num_bin - 2 > 0) {
        *rand_threshold = meta_->rand.NextInt(0, meta_->num_bin - 2);
      }
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
    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() {
Guolin Ke's avatar
Guolin Ke committed
143
144
    if (meta_->num_bin > 2 && meta_->missing_type != MissingType::None) {
      if (meta_->missing_type == MissingType::Zero) {
145
146
147
148
149
150
151
        find_best_threshold_fun_ =
            [=](double sum_gradient, double sum_hessian, data_size_t num_data,
                const ConstraintEntry& constraints, SplitInfo* output) {
              int rand_threshold = 0;
              double min_gain_shift =
                  BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT>(
                      sum_gradient, sum_hessian, output, &rand_threshold);
guolinke's avatar
guolinke committed
152
153
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, true, true, false>(
154
155
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
guolinke's avatar
guolinke committed
156
157
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, false, true, false>(
158
159
160
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
            };
Guolin Ke's avatar
Guolin Ke committed
161
      } else {
162
163
164
165
166
167
168
        find_best_threshold_fun_ =
            [=](double sum_gradient, double sum_hessian, data_size_t num_data,
                const ConstraintEntry& constraints, SplitInfo* output) {
              int rand_threshold = 0;
              double min_gain_shift =
                  BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT>(
                      sum_gradient, sum_hessian, output, &rand_threshold);
guolinke's avatar
guolinke committed
169
170
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, true, false, true>(
171
172
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
guolinke's avatar
guolinke committed
173
174
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, false, false, true>(
175
176
177
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
            };
Guolin Ke's avatar
Guolin Ke committed
178
      }
179
    } else {
180
181
182
183
184
185
186
187
      if (meta_->missing_type != MissingType::NaN) {
        find_best_threshold_fun_ =
            [=](double sum_gradient, double sum_hessian, data_size_t num_data,
                const ConstraintEntry& constraints, SplitInfo* output) {
              int rand_threshold = 0;
              double min_gain_shift =
                  BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT>(
                      sum_gradient, sum_hessian, output, &rand_threshold);
guolinke's avatar
guolinke committed
188
189
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, true, false, false>(
190
191
192
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
            };
193
      } else {
194
195
196
197
198
199
200
        find_best_threshold_fun_ =
            [=](double sum_gradient, double sum_hessian, data_size_t num_data,
                const ConstraintEntry& constraints, SplitInfo* output) {
              int rand_threshold = 0;
              double min_gain_shift =
                  BeforeNumercal<USE_RAND, USE_L1, USE_MAX_OUTPUT>(
                      sum_gradient, sum_hessian, output, &rand_threshold);
guolinke's avatar
guolinke committed
201
202
              FindBestThresholdSequentially<USE_RAND, USE_MC, USE_L1,
                                            USE_MAX_OUTPUT, true, false, false>(
203
204
205
206
                  sum_gradient, sum_hessian, num_data, constraints,
                  min_gain_shift, output, rand_threshold);
              output->default_left = false;
            };
Guolin Ke's avatar
Guolin Ke committed
207
      }
Guolin Ke's avatar
Guolin Ke committed
208
209
    }
  }
210

211
  void FuncForCategorical() {
212
    if (meta_->config->extra_trees) {
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
      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>();
      }
    }
  }
  template <bool USE_RAND, bool USE_MC>
  void FuncForCategoricalL1() {
    if (meta_->config->lambda_l1 > 0) {
      if (meta_->config->max_delta_step > 0) {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
                          USE_RAND, USE_MC, true, true>,
                      this, std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4,
                      std::placeholders::_5);
      } else {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
                          USE_RAND, USE_MC, true, false>,
                      this, std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4,
                      std::placeholders::_5);
      }
244
    } else {
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
      if (meta_->config->max_delta_step > 0) {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
                          USE_RAND, USE_MC, false, true>,
                      this, std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4,
                      std::placeholders::_5);
      } else {
        find_best_threshold_fun_ =
            std::bind(&FeatureHistogram::FindBestThresholdCategoricalInner<
                          USE_RAND, USE_MC, false, false>,
                      this, std::placeholders::_1, std::placeholders::_2,
                      std::placeholders::_3, std::placeholders::_4,
                      std::placeholders::_5);
      }
260
261
262
    }
  }

263
264
265
266
267
268
269
  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT>
  void FindBestThresholdCategoricalInner(double sum_gradient,
                                         double sum_hessian,
                                         data_size_t num_data,
                                         const ConstraintEntry& constraints,
                                         SplitInfo* output) {
    is_splittable_ = false;
Guolin Ke's avatar
Guolin Ke committed
270
    output->default_left = false;
271
    double best_gain = kMinScore;
272
    data_size_t best_left_count = 0;
ChenZhiyong's avatar
ChenZhiyong committed
273
274
    double best_sum_left_gradient = 0;
    double best_sum_left_hessian = 0;
275
276
277
    double gain_shift = GetLeafGain<USE_L1, USE_MAX_OUTPUT>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1,
        meta_->config->lambda_l2, meta_->config->max_delta_step);
278

Guolin Ke's avatar
Guolin Ke committed
279
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
ChenZhiyong's avatar
ChenZhiyong committed
280
    bool is_full_categorical = meta_->missing_type == MissingType::None;
281
    int used_bin = meta_->num_bin - 1 + is_full_categorical;
ChenZhiyong's avatar
ChenZhiyong committed
282

Guolin Ke's avatar
Guolin Ke committed
283
    std::vector<int> sorted_idx;
Guolin Ke's avatar
Guolin Ke committed
284
285
    double l2 = meta_->config->lambda_l2;
    bool use_onehot = meta_->num_bin <= meta_->config->max_cat_to_onehot;
286
287
    int best_threshold = -1;
    int best_dir = 1;
288
    const double cnt_factor = num_data / sum_hessian;
289
    int rand_threshold = 0;
290
    if (use_onehot) {
291
      if (USE_RAND) {
292
        if (used_bin > 0) {
293
          rand_threshold = meta_->rand.NextInt(0, used_bin);
294
295
        }
      }
296
      for (int t = 0; t < used_bin; ++t) {
297
298
        const auto grad = GET_GRAD(data_, t);
        const auto hess = GET_HESS(data_, t);
299
300
        data_size_t cnt =
            static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
301
        // if data not enough, or sum hessian too small
302
        if (cnt < meta_->config->min_data_in_leaf ||
303
            hess < meta_->config->min_sum_hessian_in_leaf) {
304
          continue;
305
        }
306
        data_size_t other_count = num_data - cnt;
307
        // if data not enough
308
309
310
        if (other_count < meta_->config->min_data_in_leaf) {
          continue;
        }
ChenZhiyong's avatar
ChenZhiyong committed
311

312
        double sum_other_hessian = sum_hessian - hess - kEpsilon;
313
        // if sum hessian too small
314
        if (sum_other_hessian < meta_->config->min_sum_hessian_in_leaf) {
315
          continue;
316
        }
ChenZhiyong's avatar
ChenZhiyong committed
317

318
        double sum_other_gradient = sum_gradient - grad;
319
        if (USE_RAND) {
320
321
322
323
          if (t != rand_threshold) {
            continue;
          }
        }
324
        // current split gain
325
326
327
328
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT>(
            sum_other_gradient, sum_other_hessian, grad, hess + kEpsilon,
            meta_->config->lambda_l1, l2, meta_->config->max_delta_step,
            constraints, 0);
329
        // gain with split is worse than without split
330
331
332
        if (current_gain <= min_gain_shift) {
          continue;
        }
333
334

        // mark to is splittable
ChenZhiyong's avatar
ChenZhiyong committed
335
        is_splittable_ = true;
336
        // better split point
ChenZhiyong's avatar
ChenZhiyong committed
337
        if (current_gain > best_gain) {
338
          best_threshold = t;
339
340
341
          best_sum_left_gradient = grad;
          best_sum_left_hessian = hess + kEpsilon;
          best_left_count = cnt;
ChenZhiyong's avatar
ChenZhiyong committed
342
          best_gain = current_gain;
343
344
345
346
        }
      }
    } else {
      for (int i = 0; i < used_bin; ++i) {
347
348
        if (Common::RoundInt(GET_HESS(data_, i) * cnt_factor) >=
            meta_->config->cat_smooth) {
349
350
351
352
353
          sorted_idx.push_back(i);
        }
      }
      used_bin = static_cast<int>(sorted_idx.size());

Guolin Ke's avatar
Guolin Ke committed
354
      l2 += meta_->config->cat_l2;
355
356

      auto ctr_fun = [this](double sum_grad, double sum_hess) {
Guolin Ke's avatar
Guolin Ke committed
357
        return (sum_grad) / (sum_hess + meta_->config->cat_smooth);
358
359
      };
      std::sort(sorted_idx.begin(), sorted_idx.end(),
360
361
362
363
                [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));
                });
364
365
366
367
368

      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);
369
370
      const int max_num_cat =
          std::min(meta_->config->max_cat_threshold, (used_bin + 1) / 2);
371
      int max_threshold = std::max(std::min(max_num_cat, used_bin) - 1, 0);
372
      if (USE_RAND) {
373
        if (max_threshold > 0) {
374
          rand_threshold = meta_->rand.NextInt(0, max_threshold);
375
        }
376
      }
377

378
379
380
381
      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
382
        data_size_t min_data_per_group = meta_->config->min_data_per_group;
383
384
385
386
387
388
389
        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;
390
391
          const auto grad = GET_GRAD(data_, t);
          const auto hess = GET_HESS(data_, t);
392
393
          data_size_t cnt =
              static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
394

395
396
397
398
          sum_left_gradient += grad;
          sum_left_hessian += hess;
          left_count += cnt;
          cnt_cur_group += cnt;
399

400
          if (left_count < meta_->config->min_data_in_leaf ||
401
              sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
402
            continue;
403
          }
404
          data_size_t right_count = num_data - left_count;
405
          if (right_count < meta_->config->min_data_in_leaf ||
406
              right_count < min_data_per_group) {
407
            break;
408
          }
409
410

          double sum_right_hessian = sum_hessian - sum_left_hessian;
411
412
413
          if (sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
            break;
          }
414

415
416
417
          if (cnt_cur_group < min_data_per_group) {
            continue;
          }
418
419
420
421

          cnt_cur_group = 0;

          double sum_right_gradient = sum_gradient - sum_left_gradient;
422
          if (USE_RAND) {
423
424
            if (i != rand_threshold) {
              continue;
425
            }
426
          }
427
428
429
430
          double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              sum_left_gradient, sum_left_hessian, sum_right_gradient,
              sum_right_hessian, meta_->config->lambda_l1, l2,
              meta_->config->max_delta_step, constraints, 0);
431
432
433
          if (current_gain <= min_gain_shift) {
            continue;
          }
434
435
436
437
438
439
440
441
442
          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
443
        }
444
445
      }
    }
446

447
    if (is_splittable_) {
448
449
450
451
452
      output->left_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              best_sum_left_gradient, best_sum_left_hessian,
              meta_->config->lambda_l1, l2, meta_->config->max_delta_step,
              constraints);
453
454
455
      output->left_count = best_left_count;
      output->left_sum_gradient = best_sum_left_gradient;
      output->left_sum_hessian = best_sum_left_hessian - kEpsilon;
456
457
458
459
460
      output->right_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              sum_gradient - best_sum_left_gradient,
              sum_hessian - best_sum_left_hessian, meta_->config->lambda_l1, l2,
              meta_->config->max_delta_step, constraints);
461
462
      output->right_count = num_data - best_left_count;
      output->right_sum_gradient = sum_gradient - best_sum_left_gradient;
463
464
      output->right_sum_hessian =
          sum_hessian - best_sum_left_hessian - kEpsilon;
Guolin Ke's avatar
Guolin Ke committed
465
      output->gain = best_gain - min_gain_shift;
466
467
      if (use_onehot) {
        output->num_cat_threshold = 1;
468
469
        output->cat_threshold =
            std::vector<uint32_t>(1, static_cast<uint32_t>(best_threshold));
ChenZhiyong's avatar
ChenZhiyong committed
470
      } else {
471
        output->num_cat_threshold = best_threshold + 1;
472
473
        output->cat_threshold =
            std::vector<uint32_t>(output->num_cat_threshold);
474
475
476
477
478
479
480
481
482
483
        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
484
485
        }
      }
Guolin Ke's avatar
Guolin Ke committed
486
      output->monotone_type = 0;
487
    }
488
489
  }

490
  void GatherInfoForThreshold(double sum_gradient, double sum_hessian,
491
492
                              uint32_t threshold, data_size_t num_data,
                              SplitInfo* output) {
493
    if (meta_->bin_type == BinType::NumericalBin) {
494
495
      GatherInfoForThresholdNumerical(sum_gradient, sum_hessian, threshold,
                                      num_data, output);
496
    } else {
497
498
      GatherInfoForThresholdCategorical(sum_gradient, sum_hessian, threshold,
                                        num_data, output);
499
500
501
502
    }
  }

  void GatherInfoForThresholdNumerical(double sum_gradient, double sum_hessian,
503
504
505
506
507
                                       uint32_t threshold, data_size_t num_data,
                                       SplitInfo* output) {
    double gain_shift = GetLeafGain<true, true>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1,
        meta_->config->lambda_l2, meta_->config->max_delta_step);
Guolin Ke's avatar
Guolin Ke committed
508
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
509
510

    // do stuff here
511
    const int8_t offset = meta_->offset;
512
513
514
515
516
517

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

    // set values
518
519
    bool use_na_as_missing = false;
    bool skip_default_bin = false;
520
521
    if (meta_->missing_type == MissingType::Zero) {
      skip_default_bin = true;
522
    } else if (meta_->missing_type == MissingType::NaN) {
523
524
525
      use_na_as_missing = true;
    }

526
527
    int t = meta_->num_bin - 1 - offset - use_na_as_missing;
    const int t_end = 1 - offset;
528
    const double cnt_factor = num_data / sum_hessian;
529
530
    // from right to left, and we don't need data in bin0
    for (; t >= t_end; --t) {
531
532
533
      if (static_cast<uint32_t>(t + offset) < threshold) {
        break;
      }
534
535

      // need to skip default bin
536
537
538
539
      if (skip_default_bin &&
          (t + offset) == static_cast<int>(meta_->default_bin)) {
        continue;
      }
540
541
      const auto grad = GET_GRAD(data_, t);
      const auto hess = GET_HESS(data_, t);
542
543
      data_size_t cnt =
          static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
544
545
546
      sum_right_gradient += grad;
      sum_right_hessian += hess;
      right_count += cnt;
547
548
549
550
    }
    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;
551
552
553
554
555
556
557
    double current_gain =
        GetLeafGain<true, true>(
            sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1,
            meta_->config->lambda_l2, meta_->config->max_delta_step) +
        GetLeafGain<true, true>(
            sum_right_gradient, sum_right_hessian, meta_->config->lambda_l1,
            meta_->config->lambda_l2, meta_->config->max_delta_step);
558
559
560
561

    // gain with split is worse than without split
    if (std::isnan(current_gain) || current_gain <= min_gain_shift) {
      output->gain = kMinScore;
562
      Log::Warning(
563
          "'Forced Split' will be ignored since the gain getting worse.");
564
      return;
565
    }
566
567
568

    // update split information
    output->threshold = threshold;
569
570
571
    output->left_output = CalculateSplittedLeafOutput<true, true>(
        sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1,
        meta_->config->lambda_l2, meta_->config->max_delta_step);
572
573
574
    output->left_count = left_count;
    output->left_sum_gradient = sum_left_gradient;
    output->left_sum_hessian = sum_left_hessian - kEpsilon;
575
576
577
578
    output->right_output = CalculateSplittedLeafOutput<true, true>(
        sum_gradient - sum_left_gradient, sum_hessian - sum_left_hessian,
        meta_->config->lambda_l1, meta_->config->lambda_l2,
        meta_->config->max_delta_step);
579
580
581
    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;
582
    output->gain = current_gain - min_gain_shift;
583
584
585
    output->default_left = true;
  }

586
587
588
589
  void GatherInfoForThresholdCategorical(double sum_gradient,
                                         double sum_hessian, uint32_t threshold,
                                         data_size_t num_data,
                                         SplitInfo* output) {
590
591
    // get SplitInfo for a given one-hot categorical split.
    output->default_left = false;
592
593
594
    double gain_shift = GetLeafGain<true, true>(
        sum_gradient, sum_hessian, meta_->config->lambda_l1,
        meta_->config->lambda_l2, meta_->config->max_delta_step);
Guolin Ke's avatar
Guolin Ke committed
595
    double min_gain_shift = gain_shift + meta_->config->min_gain_to_split;
596
597
598
599
600
601
602
    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;
    }
603
604
605
    const double cnt_factor = num_data / sum_hessian;
    const auto grad = GET_GRAD(data_, threshold);
    const auto hess = GET_HESS(data_, threshold);
606
607
    data_size_t cnt =
        static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
608

Guolin Ke's avatar
Guolin Ke committed
609
    double l2 = meta_->config->lambda_l2;
610
    data_size_t left_count = cnt;
611
    data_size_t right_count = num_data - left_count;
612
    double sum_left_hessian = hess + kEpsilon;
613
    double sum_right_hessian = sum_hessian - sum_left_hessian;
614
    double sum_left_gradient = grad;
615
616
    double sum_right_gradient = sum_gradient - sum_left_gradient;
    // current split gain
617
618
619
620
621
622
623
    double current_gain =
        GetLeafGain<true, true>(sum_right_gradient, sum_right_hessian,
                                meta_->config->lambda_l1, l2,
                                meta_->config->max_delta_step) +
        GetLeafGain<true, true>(sum_left_gradient, sum_left_hessian,
                                meta_->config->lambda_l1, l2,
                                meta_->config->max_delta_step);
624
625
    if (std::isnan(current_gain) || current_gain <= min_gain_shift) {
      output->gain = kMinScore;
626
627
      Log::Warning(
          "'Forced Split' will be ignored since the gain getting worse.");
628
629
630
      return;
    }

631
632
633
    output->left_output = CalculateSplittedLeafOutput<true, true>(
        sum_left_gradient, sum_left_hessian, meta_->config->lambda_l1, l2,
        meta_->config->max_delta_step);
634
635
636
    output->left_count = left_count;
    output->left_sum_gradient = sum_left_gradient;
    output->left_sum_hessian = sum_left_hessian - kEpsilon;
637
638
639
    output->right_output = CalculateSplittedLeafOutput<true, true>(
        sum_right_gradient, sum_right_hessian, meta_->config->lambda_l1, l2,
        meta_->config->max_delta_step);
640
641
642
643
644
645
646
647
    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
648
  /*!
649
650
   * \brief Binary size of this histogram
   */
Guolin Ke's avatar
Guolin Ke committed
651
  int SizeOfHistgram() const {
652
    return (meta_->num_bin - meta_->offset) * kHistEntrySize;
Guolin Ke's avatar
Guolin Ke committed
653
654
655
  }

  /*!
656
657
   * \brief Restore histogram from memory
   */
Guolin Ke's avatar
Guolin Ke committed
658
  void FromMemory(char* memory_data) {
659
660
    std::memcpy(data_, memory_data,
                (meta_->num_bin - meta_->offset) * kHistEntrySize);
Guolin Ke's avatar
Guolin Ke committed
661
662
663
  }

  /*!
664
665
   * \brief True if this histogram can be splitted
   */
Guolin Ke's avatar
Guolin Ke committed
666
667
668
  bool is_splittable() { return is_splittable_; }

  /*!
669
670
   * \brief Set splittable to this histogram
   */
Guolin Ke's avatar
Guolin Ke committed
671
672
  void set_is_splittable(bool val) { is_splittable_ = val; }

673
674
675
676
677
  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;
  }

678
679
680
681
682
683
684
685
686
687
688
  template <bool USE_L1, bool USE_MAX_OUTPUT>
  static double CalculateSplittedLeafOutput(double sum_gradients,
                                            double sum_hessians, double l1,
                                            double l2, double max_delta_step) {
    if (USE_L1) {
      double ret = -ThresholdL1(sum_gradients, l1) / (sum_hessians + l2);
      if (USE_MAX_OUTPUT) {
        if (max_delta_step > 0 && std::fabs(ret) > max_delta_step) {
          return Common::Sign(ret) * max_delta_step;
        }
      }
689
690
      return ret;
    } else {
691
692
693
694
695
696
697
      double ret = -sum_gradients / (sum_hessians + l2);
      if (USE_MAX_OUTPUT) {
        if (max_delta_step > 0 && std::fabs(ret) > max_delta_step) {
          return Common::Sign(ret) * max_delta_step;
        }
      }
      return ret;
698
    }
Guolin Ke's avatar
Guolin Ke committed
699
700
  }

701
702
703
704
705
706
707
708
709
710
711
712
713
714
  template <bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT>
  static double CalculateSplittedLeafOutput(
      double sum_gradients, double sum_hessians, double l1, double l2,
      double max_delta_step, const ConstraintEntry& constraints) {
    double ret = CalculateSplittedLeafOutput<USE_L1, USE_MAX_OUTPUT>(
        sum_gradients, sum_hessians, l1, l2, max_delta_step);
    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
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
 private:
  template <bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT>
  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,
                              int8_t monotone_constraint) {
    if (!USE_MC) {
      return GetLeafGain<USE_L1, USE_MAX_OUTPUT>(sum_left_gradients,
                                                 sum_left_hessians, l1, l2,
                                                 max_delta_step) +
             GetLeafGain<USE_L1, USE_MAX_OUTPUT>(sum_right_gradients,
                                                 sum_right_hessians, l1, l2,
                                                 max_delta_step);
    } else {
      double left_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              sum_left_gradients, sum_left_hessians, l1, l2, max_delta_step,
              constraints);
      double right_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              sum_right_gradients, sum_right_hessians, l1, l2, max_delta_step,
              constraints);
      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
750
    }
Guolin Ke's avatar
Guolin Ke committed
751
  }
Guolin Ke's avatar
Guolin Ke committed
752

753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
  template <bool USE_L1, bool USE_MAX_OUTPUT>
  static double GetLeafGain(double sum_gradients, double sum_hessians,
                            double l1, double l2, double max_delta_step) {
    if (!USE_MAX_OUTPUT) {
      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 {
      double output = CalculateSplittedLeafOutput<USE_L1, USE_MAX_OUTPUT>(
          sum_gradients, sum_hessians, l1, l2, max_delta_step);
      return GetLeafGainGivenOutput<USE_L1>(sum_gradients, sum_hessians, l1, l2,
                                            output);
    }
Guolin Ke's avatar
Guolin Ke committed
769
770
  }

771
772
773
774
775
776
777
778
779
780
781
  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
782
  }
Guolin Ke's avatar
Guolin Ke committed
783

784
785
  template <bool USE_RAND, bool USE_MC, bool USE_L1, bool USE_MAX_OUTPUT,
            bool REVERSE, bool SKIP_DEFAULT_BIN, bool NA_AS_MISSING>
guolinke's avatar
guolinke committed
786
787
788
789
790
  void FindBestThresholdSequentially(double sum_gradient, double sum_hessian,
                                     data_size_t num_data,
                                     const ConstraintEntry& constraints,
                                     double min_gain_shift, SplitInfo* output,
                                     int rand_threshold) {
791
    const int8_t offset = meta_->offset;
Guolin Ke's avatar
Guolin Ke committed
792
793
794
795
796
    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);
797
    const double cnt_factor = num_data / sum_hessian;
798
    if (REVERSE) {
Guolin Ke's avatar
Guolin Ke committed
799
800
801
802
      double sum_right_gradient = 0.0f;
      double sum_right_hessian = kEpsilon;
      data_size_t right_count = 0;

803
      int t = meta_->num_bin - 1 - offset - NA_AS_MISSING;
804
      const int t_end = 1 - offset;
Guolin Ke's avatar
Guolin Ke committed
805
806
807
808

      // from right to left, and we don't need data in bin0
      for (; t >= t_end; --t) {
        // need to skip default bin
809
810
811
812
813
        if (SKIP_DEFAULT_BIN) {
          if ((t + offset) == static_cast<int>(meta_->default_bin)) {
            continue;
          }
        }
814
815
        const auto grad = GET_GRAD(data_, t);
        const auto hess = GET_HESS(data_, t);
816
817
        data_size_t cnt =
            static_cast<data_size_t>(Common::RoundInt(hess * cnt_factor));
818
819
820
        sum_right_gradient += grad;
        sum_right_hessian += hess;
        right_count += cnt;
Guolin Ke's avatar
Guolin Ke committed
821
        // if data not enough, or sum hessian too small
822
        if (right_count < meta_->config->min_data_in_leaf ||
823
            sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
824
          continue;
825
        }
Guolin Ke's avatar
Guolin Ke committed
826
827
        data_size_t left_count = num_data - right_count;
        // if data not enough
828
829
830
        if (left_count < meta_->config->min_data_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
831
832
833

        double sum_left_hessian = sum_hessian - sum_right_hessian;
        // if sum hessian too small
834
835
836
        if (sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
837
838

        double sum_left_gradient = sum_gradient - sum_right_gradient;
839
        if (USE_RAND) {
840
          if (t - 1 + offset != rand_threshold) {
Guolin Ke's avatar
Guolin Ke committed
841
            continue;
842
          }
Guolin Ke's avatar
Guolin Ke committed
843
        }
Guolin Ke's avatar
Guolin Ke committed
844
        // current split gain
845
846
847
848
849
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT>(
            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,
            constraints, meta_->monotone_type);
Guolin Ke's avatar
Guolin Ke committed
850
        // gain with split is worse than without split
851
852
853
        if (current_gain <= min_gain_shift) {
          continue;
        }
Guolin Ke's avatar
Guolin Ke committed
854
855
856
857
858
859
860
861
862
863
864
865

        // 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
866
      }
ChenZhiyong's avatar
ChenZhiyong committed
867
    } else {
Guolin Ke's avatar
Guolin Ke committed
868
869
870
871
872
      double sum_left_gradient = 0.0f;
      double sum_left_hessian = kEpsilon;
      data_size_t left_count = 0;

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

875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
      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
890
891
892
        }
      }

Guolin Ke's avatar
Guolin Ke committed
893
      for (; t <= t_end; ++t) {
894
895
896
897
898
        if (SKIP_DEFAULT_BIN) {
          if ((t + offset) == static_cast<int>(meta_->default_bin)) {
            continue;
          }
        }
Guolin Ke's avatar
Guolin Ke committed
899
        if (t >= 0) {
900
901
          sum_left_gradient += GET_GRAD(data_, t);
          sum_left_hessian += GET_HESS(data_, t);
902
903
          left_count += static_cast<data_size_t>(
              Common::RoundInt(GET_HESS(data_, t) * cnt_factor));
Guolin Ke's avatar
Guolin Ke committed
904
        }
Guolin Ke's avatar
Guolin Ke committed
905
        // if data not enough, or sum hessian too small
906
        if (left_count < meta_->config->min_data_in_leaf ||
907
            sum_left_hessian < meta_->config->min_sum_hessian_in_leaf) {
908
          continue;
909
        }
Guolin Ke's avatar
Guolin Ke committed
910
911
        data_size_t right_count = num_data - left_count;
        // if data not enough
912
913
914
        if (right_count < meta_->config->min_data_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
915
916
917

        double sum_right_hessian = sum_hessian - sum_left_hessian;
        // if sum hessian too small
918
919
920
        if (sum_right_hessian < meta_->config->min_sum_hessian_in_leaf) {
          break;
        }
Guolin Ke's avatar
Guolin Ke committed
921
922

        double sum_right_gradient = sum_gradient - sum_left_gradient;
923
        if (USE_RAND) {
Guolin Ke's avatar
Guolin Ke committed
924
925
          if (t + offset != rand_threshold) {
            continue;
926
          }
Guolin Ke's avatar
Guolin Ke committed
927
        }
Guolin Ke's avatar
Guolin Ke committed
928
        // current split gain
929
930
931
932
933
        double current_gain = GetSplitGains<USE_MC, USE_L1, USE_MAX_OUTPUT>(
            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,
            constraints, meta_->monotone_type);
Guolin Ke's avatar
Guolin Ke committed
934
        // gain with split is worse than without split
935
936
937
        if (current_gain <= min_gain_shift) {
          continue;
        }
Guolin Ke's avatar
Guolin Ke committed
938
939
940
941
942
943
944
945
946
947
948

        // 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
949
950
951
      }
    }

952
    if (is_splittable_ && best_gain > output->gain + min_gain_shift) {
Guolin Ke's avatar
Guolin Ke committed
953
954
      // update split information
      output->threshold = best_threshold;
955
956
957
958
959
      output->left_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              best_sum_left_gradient, best_sum_left_hessian,
              meta_->config->lambda_l1, meta_->config->lambda_l2,
              meta_->config->max_delta_step, constraints);
Guolin Ke's avatar
Guolin Ke committed
960
961
962
      output->left_count = best_left_count;
      output->left_sum_gradient = best_sum_left_gradient;
      output->left_sum_hessian = best_sum_left_hessian - kEpsilon;
963
964
965
966
967
968
      output->right_output =
          CalculateSplittedLeafOutput<USE_MC, USE_L1, USE_MAX_OUTPUT>(
              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,
              constraints);
Guolin Ke's avatar
Guolin Ke committed
969
970
      output->right_count = num_data - best_left_count;
      output->right_sum_gradient = sum_gradient - best_sum_left_gradient;
971
972
973
974
      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
975
976
977
    }
  }

Guolin Ke's avatar
Guolin Ke committed
978
  const FeatureMetainfo* meta_;
Guolin Ke's avatar
Guolin Ke committed
979
  /*! \brief sum of gradient of each bin */
980
  hist_t* data_;
Guolin Ke's avatar
Guolin Ke committed
981
  bool is_splittable_ = true;
982

983
984
985
  std::function<void(double, double, data_size_t, const ConstraintEntry&,
                     SplitInfo*)>
      find_best_threshold_fun_;
Guolin Ke's avatar
Guolin Ke committed
986
};
Nikita Titov's avatar
Nikita Titov committed
987

Guolin Ke's avatar
Guolin Ke committed
988
class HistogramPool {
989
 public:
Guolin Ke's avatar
Guolin Ke committed
990
  /*!
991
992
   * \brief Constructor
   */
Guolin Ke's avatar
Guolin Ke committed
993
  HistogramPool() {
Guolin Ke's avatar
Guolin Ke committed
994
995
    cache_size_ = 0;
    total_size_ = 0;
Guolin Ke's avatar
Guolin Ke committed
996
  }
997

Guolin Ke's avatar
Guolin Ke committed
998
  /*!
999
1000
1001
   * \brief Destructor
   */
  ~HistogramPool() {}
1002

Guolin Ke's avatar
Guolin Ke committed
1003
  /*!
1004
1005
1006
1007
   * \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
1008
  void Reset(int cache_size, int total_size) {
Guolin Ke's avatar
Guolin Ke committed
1009
1010
    cache_size_ = cache_size;
    // at least need 2 bucket to store smaller leaf and larger leaf
1011
    CHECK_GE(cache_size_, 2);
Guolin Ke's avatar
Guolin Ke committed
1012
1013
1014
1015
1016
1017
    total_size_ = total_size;
    if (cache_size_ > total_size_) {
      cache_size_ = total_size_;
    }
    is_enough_ = (cache_size_ == total_size_);
    if (!is_enough_) {
1018
1019
1020
      mapper_.resize(total_size_);
      inverse_mapper_.resize(cache_size_);
      last_used_time_.resize(cache_size_);
Guolin Ke's avatar
Guolin Ke committed
1021
1022
1023
      ResetMap();
    }
  }
1024

Guolin Ke's avatar
Guolin Ke committed
1025
  /*!
1026
1027
   * \brief Reset mapper
   */
Guolin Ke's avatar
Guolin Ke committed
1028
1029
1030
1031
1032
1033
1034
1035
  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);
    }
  }
1036
1037
1038
  template <bool USE_DATA, bool USE_CONFIG>
  static void SetFeatureInfo(const Dataset* train_data, const Config* config,
                             std::vector<FeatureMetainfo>* feature_meta) {
1039
1040
1041
    auto& ref_feature_meta = *feature_meta;
    const int num_feature = train_data->num_features();
    ref_feature_meta.resize(num_feature);
1042
#pragma omp parallel for schedule(static, 512) if (num_feature >= 1024)
1043
    for (int i = 0; i < num_feature; ++i) {
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
      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();
1057
      }
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
      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);
1072
1073
1074
1075
1076
      }
      ref_feature_meta[i].config = config;
    }
  }

1077
1078
  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
1079
    if (feature_metas_.empty()) {
1080
      SetFeatureInfo<true, true>(train_data, config, &feature_metas_);
1081
      uint64_t bin_cnt_over_features = 0;
1082
      for (int i = 0; i < train_data->num_features(); ++i) {
1083
1084
        bin_cnt_over_features +=
            static_cast<uint64_t>(feature_metas_[i].num_bin);
Guolin Ke's avatar
Guolin Ke committed
1085
      }
1086
      Log::Info("Total Bins %d", bin_cnt_over_features);
Guolin Ke's avatar
Guolin Ke committed
1087
    }
Guolin Ke's avatar
Guolin Ke committed
1088
    int old_cache_size = static_cast<int>(pool_.size());
Guolin Ke's avatar
Guolin Ke committed
1089
    Reset(cache_size, total_size);
Guolin Ke's avatar
Guolin Ke committed
1090
1091
1092
1093
1094

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

1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
    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;
        }
      }
    }
1119
    OMP_INIT_EX();
1120
#pragma omp parallel for schedule(static)
Guolin Ke's avatar
Guolin Ke committed
1121
    for (int i = old_cache_size; i < cache_size; ++i) {
1122
      OMP_LOOP_EX_BEGIN();
Guolin Ke's avatar
Guolin Ke committed
1123
      pool_[i].reset(new FeatureHistogram[train_data->num_features()]);
1124
      data_[i].resize(num_total_bin * 2);
Guolin Ke's avatar
Guolin Ke committed
1125
      for (int j = 0; j < train_data->num_features(); ++j) {
1126
        pool_[i][j].Init(data_[i].data() + offsets[j] * 2, &feature_metas_[j]);
Guolin Ke's avatar
Guolin Ke committed
1127
      }
1128
      OMP_LOOP_EX_END();
Guolin Ke's avatar
Guolin Ke committed
1129
    }
1130
    OMP_THROW_EX();
Guolin Ke's avatar
Guolin Ke committed
1131
1132
  }

1133
  void ResetConfig(const Dataset* train_data, const Config* config) {
1134
    SetFeatureInfo<false, true>(train_data, config, &feature_metas_);
Guolin Ke's avatar
Guolin Ke committed
1135
  }
1136

Guolin Ke's avatar
Guolin Ke committed
1137
  /*!
1138
1139
1140
1141
1142
1143
   * \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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
  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 {
1154
      // choose the least used slot
Guolin Ke's avatar
Guolin Ke committed
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
      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;
    }
  }

  /*!
1170
1171
1172
1173
   * \brief Move data from one index to another index
   * \param src_idx
   * \param dst_idx
   */
Guolin Ke's avatar
Guolin Ke committed
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
  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;
  }
1192

1193
 private:
Guolin Ke's avatar
Guolin Ke committed
1194
  std::vector<std::unique_ptr<FeatureHistogram[]>> pool_;
1195
1196
1197
  std::vector<
      std::vector<hist_t, Common::AlignmentAllocator<hist_t, kAlignedSize>>>
      data_;
Guolin Ke's avatar
Guolin Ke committed
1198
  std::vector<FeatureMetainfo> feature_metas_;
Guolin Ke's avatar
Guolin Ke committed
1199
1200
1201
1202
1203
1204
1205
1206
1207
  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
1208
}  // namespace LightGBM
1209
#endif  // LightGBM_TREELEARNER_FEATURE_HISTOGRAM_HPP_