serial_tree_learner.h 9.05 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
#include <LightGBM/dataset.h>
#include <LightGBM/tree.h>
#include <LightGBM/tree_learner.h>
11
#include <LightGBM/cuda/vector_cudahost.h>
12
13
14
15
#include <LightGBM/utils/array_args.h>
#include <LightGBM/utils/json11.h>
#include <LightGBM/utils/random.h>

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

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

30
31
32
33
34
#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
35
36

namespace LightGBM {
37
38
39

using json11::Json;

40
41
/*! \brief forward declaration */
class CostEfficientGradientBoosting;
42

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

  ~SerialTreeLearner();

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

55
56
57
58
59
60
61
62
63
64
65
66
  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
67

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

70
71
72
73
74
75
76
77
  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;
    }
  }

78
  Tree* Train(const score_t* gradients, const score_t *hessians, bool is_first_tree) override;
Guolin Ke's avatar
Guolin Ke committed
79

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

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

85
86
87
  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);
88
      share_state_->SetUseSubrow(false);
89
90
    } else {
      ResetTrainingDataInner(subset, share_state_->is_constant_hessian, false);
91
92
      share_state_->SetUseSubrow(true);
      share_state_->SetSubrowCopied(false);
93
94
95
      share_state_->bagging_use_indices = used_indices;
      share_state_->bagging_indices_cnt = num_data;
    }
Guolin Ke's avatar
Guolin Ke committed
96
97
  }

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

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

118
119
120
  /*! \brief Get output of parent node, used for path smoothing */
  double GetParentOutput(const Tree* tree, const LeafSplits* leaf_splits) const;

Nikita Titov's avatar
Nikita Titov committed
121
 protected:
122
123
  void ComputeBestSplitForFeature(FeatureHistogram* histogram_array_,
                                  int feature_index, int real_fidx,
Guolin Ke's avatar
Guolin Ke committed
124
                                  int8_t is_feature_used, int num_data,
125
                                  const LeafSplits* leaf_splits,
126
127
                                  SplitInfo* best_split, double parent_output);

128

129
  void GetShareStates(const Dataset* dataset, bool is_constant_hessian, bool is_first_time);
130

131
  void RecomputeBestSplitForLeaf(Tree* tree, int leaf, SplitInfo* split);
132

Guolin Ke's avatar
Guolin Ke committed
133
134
135
136
137
138
139
140
  /*!
  * \brief Some initial works before training
  */
  virtual void BeforeTrain();

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

143
  virtual void FindBestSplits(const Tree* tree);
Guolin Ke's avatar
Guolin Ke committed
144

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

147
  virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract, const Tree*);
Guolin Ke's avatar
Guolin Ke committed
148
149
150
151
152
153
154
155

  /*!
  * \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.
  */
156
157
158
159
160
  inline virtual void Split(Tree* tree, int best_leaf, int* left_leaf,
    int* right_leaf) {
    SplitInner(tree, best_leaf, left_leaf, right_leaf, true);
  }

161
162
  void SplitInner(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf,
                  bool update_cnt);
Guolin Ke's avatar
Guolin Ke committed
163

164
  /* Force splits with forced_split_json dict and then return num splits forced.*/
165
166
  int32_t ForceSplits(Tree* tree, int* left_leaf, int* right_leaf,
                      int* cur_depth);
167

Guolin Ke's avatar
Guolin Ke committed
168
169
170
171
172
173
  /*!
  * \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;
174

Guolin Ke's avatar
Guolin Ke committed
175
176
177
178
179
180
181
  /*! \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 */
182
  const score_t* gradients_;
Guolin Ke's avatar
Guolin Ke committed
183
  /*! \brief hessians of current iteration */
184
  const score_t* hessians_;
Guolin Ke's avatar
Guolin Ke committed
185
  /*! \brief training data partition on leaves */
Guolin Ke's avatar
Guolin Ke committed
186
  std::unique_ptr<DataPartition> data_partition_;
187
188
  /*! \brief pointer to histograms array of parent of current leaves */
  FeatureHistogram* parent_leaf_histogram_array_;
Guolin Ke's avatar
Guolin Ke committed
189
190
191
192
193
194
  /*! \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_;
195
196
  /*! \brief store best split per feature for all leaves */
  std::vector<SplitInfo> splits_per_leaf_;
Nikita Titov's avatar
Nikita Titov committed
197
  /*! \brief stores minimum and maximum constraints for each leaf */
198
  std::unique_ptr<LeafConstraintsBase> constraints_;
Guolin Ke's avatar
Guolin Ke committed
199
200

  /*! \brief stores best thresholds for all feature for smaller leaf */
Guolin Ke's avatar
Guolin Ke committed
201
  std::unique_ptr<LeafSplits> smaller_leaf_splits_;
Guolin Ke's avatar
Guolin Ke committed
202
  /*! \brief stores best thresholds for all feature for larger leaf */
Guolin Ke's avatar
Guolin Ke committed
203
  std::unique_ptr<LeafSplits> larger_leaf_splits_;
204
205
#ifdef USE_GPU
  /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */
206
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_;
207
  /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */
208
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_;
209
210
211
212
213
#elif USE_CUDA
  /*! \brief gradients of current iteration, ordered for cache optimized */
  std::vector<score_t, CHAllocator<score_t>> ordered_gradients_;
  /*! \brief hessians of current iteration, ordered for cache optimized */
  std::vector<score_t, CHAllocator<score_t>> ordered_hessians_;
214
#else
Guolin Ke's avatar
Guolin Ke committed
215
  /*! \brief gradients of current iteration, ordered for cache optimized */
216
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_;
Guolin Ke's avatar
Guolin Ke committed
217
  /*! \brief hessians of current iteration, ordered for cache optimized */
218
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_;
219
#endif
220
  /*! \brief used to cache historical histogram to speed up*/
Guolin Ke's avatar
Guolin Ke committed
221
  HistogramPool histogram_pool_;
Guolin Ke's avatar
Guolin Ke committed
222
  /*! \brief config of tree learner*/
Guolin Ke's avatar
Guolin Ke committed
223
  const Config* config_;
224
225
  ColSampler col_sampler_;
  const Json* forced_split_json_;
226
  std::unique_ptr<TrainingShareStates> share_state_;
227
  std::unique_ptr<CostEfficientGradientBoosting> cegb_;
Guolin Ke's avatar
Guolin Ke committed
228
229
};

Luke Gallagher's avatar
Luke Gallagher committed
230
231
232
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
233
234
235
236
237
238
  } else {
    return 0;
  }
}

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