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

8
9
10
11
12
13
14
#include <LightGBM/dataset.h>
#include <LightGBM/tree.h>
#include <LightGBM/tree_learner.h>
#include <LightGBM/utils/array_args.h>
#include <LightGBM/utils/json11.h>
#include <LightGBM/utils/random.h>

15
16
17
18
19
20
21
#include <string>
#include <cmath>
#include <cstdio>
#include <memory>
#include <random>
#include <vector>

22
#include "col_sampler.hpp"
Guolin Ke's avatar
Guolin Ke committed
23
#include "data_partition.hpp"
24
#include "feature_histogram.hpp"
Guolin Ke's avatar
Guolin Ke committed
25
#include "leaf_splits.hpp"
26
#include "monotone_constraints.hpp"
Nikita Titov's avatar
Nikita Titov committed
27
#include "split_info.hpp"
Guolin Ke's avatar
Guolin Ke committed
28

29
30
31
32
33
#ifdef USE_GPU
// Use 4KBytes aligned allocator for ordered gradients and ordered hessians when GPU is enabled.
// This is necessary to pin the two arrays in memory and make transferring faster.
#include <boost/align/aligned_allocator.hpp>
#endif
Guolin Ke's avatar
Guolin Ke committed
34
35

namespace LightGBM {
36
37
38

using json11::Json;

39
40
/*! \brief forward declaration */
class CostEfficientGradientBoosting;
Guolin Ke's avatar
Guolin Ke committed
41
42
43
44
/*!
* \brief Used for learning a tree by single machine
*/
class SerialTreeLearner: public TreeLearner {
Nikita Titov's avatar
Nikita Titov committed
45
 public:
46
  friend CostEfficientGradientBoosting;
Guolin Ke's avatar
Guolin Ke committed
47
  explicit SerialTreeLearner(const Config* config);
Guolin Ke's avatar
Guolin Ke committed
48
49
50

  ~SerialTreeLearner();

51
  void Init(const Dataset* train_data, bool is_constant_hessian) override;
Guolin Ke's avatar
Guolin Ke committed
52

53
54
55
56
57
58
59
60
61
62
63
64
  void ResetTrainingData(const Dataset* train_data,
                         bool is_constant_hessian) override {
    ResetTrainingDataInner(train_data, is_constant_hessian, true);
  }

  void ResetIsConstantHessian(bool is_constant_hessian) override {
    share_state_->is_constant_hessian = is_constant_hessian;
  }

  virtual void ResetTrainingDataInner(const Dataset* train_data,
                                      bool is_constant_hessian,
                                      bool reset_multi_val_bin);
Guolin Ke's avatar
Guolin Ke committed
65

Guolin Ke's avatar
Guolin Ke committed
66
  void ResetConfig(const Config* config) override;
Guolin Ke's avatar
Guolin Ke committed
67

68
69
70
71
72
73
74
75
76
  inline void SetForcedSplit(const Json* forced_split_json) override {
    if (forced_split_json != nullptr && !forced_split_json->is_null()) {
      forced_split_json_ = forced_split_json;
    } else {
      forced_split_json_ = nullptr;
    }
  }

  Tree* Train(const score_t* gradients, const score_t *hessians) override;
Guolin Ke's avatar
Guolin Ke committed
77

78
  Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override;
Guolin Ke's avatar
Guolin Ke committed
79

80
81
82
  Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred,
                          const score_t* gradients, const score_t* hessians) override;

83
84
85
86
87
88
89
90
91
92
93
  void SetBaggingData(const Dataset* subset, const data_size_t* used_indices, data_size_t num_data) override {
    if (subset == nullptr) {
      data_partition_->SetUsedDataIndices(used_indices, num_data);
      share_state_->is_use_subrow = false;
    } else {
      ResetTrainingDataInner(subset, share_state_->is_constant_hessian, false);
      share_state_->is_use_subrow = true;
      share_state_->is_subrow_copied = false;
      share_state_->bagging_use_indices = used_indices;
      share_state_->bagging_indices_cnt = num_data;
    }
Guolin Ke's avatar
Guolin Ke committed
94
95
  }

Guolin Ke's avatar
Guolin Ke committed
96
97
98
99
100
  void AddPredictionToScore(const Tree* tree,
                            double* out_score) const override {
    if (tree->num_leaves() <= 1) {
      return;
    }
Nikita Titov's avatar
Nikita Titov committed
101
    CHECK_LE(tree->num_leaves(), data_partition_->num_leaves());
Guolin Ke's avatar
Guolin Ke committed
102
#pragma omp parallel for schedule(static, 1)
103
    for (int i = 0; i < tree->num_leaves(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
104
      double output = static_cast<double>(tree->LeafOutput(i));
Guolin Ke's avatar
Guolin Ke committed
105
106
      data_size_t cnt_leaf_data = 0;
      auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data);
Guolin Ke's avatar
Guolin Ke committed
107
      for (data_size_t j = 0; j < cnt_leaf_data; ++j) {
108
        out_score[tmp_idx[j]] += output;
Guolin Ke's avatar
Guolin Ke committed
109
110
111
112
      }
    }
  }

113
  void RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter,
Guolin Ke's avatar
Guolin Ke committed
114
115
                       data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const override;

Nikita Titov's avatar
Nikita Titov committed
116
 protected:
117
118
119
120
121
122
  void ComputeBestSplitForFeature(FeatureHistogram* histogram_array_,
                                  int feature_index, int real_fidx,
                                  bool is_feature_used, int num_data,
                                  const LeafSplits* leaf_splits,
                                  SplitInfo* best_split);

123
  void GetShareStates(const Dataset* dataset, bool is_constant_hessian, bool is_first_time);
124

125
126
  void RecomputeBestSplitForLeaf(int leaf, SplitInfo* split);

Guolin Ke's avatar
Guolin Ke committed
127
128
129
130
131
132
133
134
  /*!
  * \brief Some initial works before training
  */
  virtual void BeforeTrain();

  /*!
  * \brief Some initial works before FindBestSplit
  */
Guolin Ke's avatar
Guolin Ke committed
135
  virtual bool BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf);
Guolin Ke's avatar
Guolin Ke committed
136

Guolin Ke's avatar
Guolin Ke committed
137
  virtual void FindBestSplits();
Guolin Ke's avatar
Guolin Ke committed
138

Guolin Ke's avatar
Guolin Ke committed
139
  virtual void ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract);
Guolin Ke's avatar
Guolin Ke committed
140

Guolin Ke's avatar
Guolin Ke committed
141
  virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract);
Guolin Ke's avatar
Guolin Ke committed
142
143
144
145
146
147
148
149

  /*!
  * \brief Partition tree and data according best split.
  * \param tree Current tree, will be splitted on this function.
  * \param best_leaf The index of leaf that will be splitted.
  * \param left_leaf The index of left leaf after splitted.
  * \param right_leaf The index of right leaf after splitted.
  */
150
151
152
153
154
  inline virtual void Split(Tree* tree, int best_leaf, int* left_leaf,
    int* right_leaf) {
    SplitInner(tree, best_leaf, left_leaf, right_leaf, true);
  }

155
156
  void SplitInner(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf,
                  bool update_cnt);
Guolin Ke's avatar
Guolin Ke committed
157

158
  /* Force splits with forced_split_json dict and then return num splits forced.*/
159
160
  int32_t ForceSplits(Tree* tree, int* left_leaf, int* right_leaf,
                      int* cur_depth);
161

Guolin Ke's avatar
Guolin Ke committed
162
163
164
165
166
167
  /*!
  * \brief Get the number of data in a leaf
  * \param leaf_idx The index of leaf
  * \return The number of data in the leaf_idx leaf
  */
  inline virtual data_size_t GetGlobalDataCountInLeaf(int leaf_idx) const;
168

Guolin Ke's avatar
Guolin Ke committed
169
170
171
172
173
174
175
  /*! \brief number of data */
  data_size_t num_data_;
  /*! \brief number of features */
  int num_features_;
  /*! \brief training data */
  const Dataset* train_data_;
  /*! \brief gradients of current iteration */
176
  const score_t* gradients_;
Guolin Ke's avatar
Guolin Ke committed
177
  /*! \brief hessians of current iteration */
178
  const score_t* hessians_;
Guolin Ke's avatar
Guolin Ke committed
179
  /*! \brief training data partition on leaves */
Guolin Ke's avatar
Guolin Ke committed
180
  std::unique_ptr<DataPartition> data_partition_;
181
182
  /*! \brief pointer to histograms array of parent of current leaves */
  FeatureHistogram* parent_leaf_histogram_array_;
Guolin Ke's avatar
Guolin Ke committed
183
184
185
186
187
188
189
  /*! \brief pointer to histograms array of smaller leaf */
  FeatureHistogram* smaller_leaf_histogram_array_;
  /*! \brief pointer to histograms array of larger leaf */
  FeatureHistogram* larger_leaf_histogram_array_;

  /*! \brief store best split points for all leaves */
  std::vector<SplitInfo> best_split_per_leaf_;
190
191
  /*! \brief store best split per feature for all leaves */
  std::vector<SplitInfo> splits_per_leaf_;
Nikita Titov's avatar
Nikita Titov committed
192
  /*! \brief stores minimum and maximum constraints for each leaf */
193
  std::unique_ptr<LeafConstraintsBase> constraints_;
Guolin Ke's avatar
Guolin Ke committed
194
195

  /*! \brief stores best thresholds for all feature for smaller leaf */
Guolin Ke's avatar
Guolin Ke committed
196
  std::unique_ptr<LeafSplits> smaller_leaf_splits_;
Guolin Ke's avatar
Guolin Ke committed
197
  /*! \brief stores best thresholds for all feature for larger leaf */
Guolin Ke's avatar
Guolin Ke committed
198
  std::unique_ptr<LeafSplits> larger_leaf_splits_;
Guolin Ke's avatar
Guolin Ke committed
199

200
201
#ifdef USE_GPU
  /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */
202
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_;
203
  /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */
204
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_;
205
#else
Guolin Ke's avatar
Guolin Ke committed
206
  /*! \brief gradients of current iteration, ordered for cache optimized */
207
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_;
Guolin Ke's avatar
Guolin Ke committed
208
  /*! \brief hessians of current iteration, ordered for cache optimized */
209
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_;
210
#endif
211
  /*! \brief used to cache historical histogram to speed up*/
Guolin Ke's avatar
Guolin Ke committed
212
  HistogramPool histogram_pool_;
Guolin Ke's avatar
Guolin Ke committed
213
  /*! \brief config of tree learner*/
Guolin Ke's avatar
Guolin Ke committed
214
  const Config* config_;
215
216
  ColSampler col_sampler_;
  const Json* forced_split_json_;
217
  std::unique_ptr<TrainingShareStates> share_state_;
218
  std::unique_ptr<CostEfficientGradientBoosting> cegb_;
Guolin Ke's avatar
Guolin Ke committed
219
220
};

Luke Gallagher's avatar
Luke Gallagher committed
221
222
223
inline data_size_t SerialTreeLearner::GetGlobalDataCountInLeaf(int leaf_idx) const {
  if (leaf_idx >= 0) {
    return data_partition_->leaf_count(leaf_idx);
Guolin Ke's avatar
Guolin Ke committed
224
225
226
227
228
229
  } else {
    return 0;
  }
}

}  // namespace LightGBM
Guolin Ke's avatar
Guolin Ke committed
230
#endif   // LightGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_