serial_tree_learner.h 7.93 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
8
9
#ifndef LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_
#define LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_

#include <LightGBM/dataset.h>
#include <LightGBM/tree.h>
10
11
12
13
14
15
16
17
18
19
#include <LightGBM/tree_learner.h>
#include <LightGBM/utils/array_args.h>
#include <LightGBM/utils/random.h>

#include <string>
#include <cmath>
#include <cstdio>
#include <memory>
#include <random>
#include <vector>
Guolin Ke's avatar
Guolin Ke committed
20
21

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

27
28
29
30
31
#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
32
33

namespace LightGBM {
34
35
36

using json11::Json;

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

  ~SerialTreeLearner();

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

Guolin Ke's avatar
Guolin Ke committed
51
52
  void ResetTrainingData(const Dataset* train_data) override;

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

55
  Tree* Train(const score_t* gradients, const score_t *hessians, bool is_constant_hessian,
Guolin Ke's avatar
Guolin Ke committed
56
              const Json& forced_split_json) override;
Guolin Ke's avatar
Guolin Ke committed
57

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

60
61
62
  Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred,
                          const score_t* gradients, const score_t* hessians) override;

Guolin Ke's avatar
Guolin Ke committed
63
64
65
66
  void SetBaggingData(const data_size_t* used_indices, data_size_t num_data) override {
    data_partition_->SetUsedDataIndices(used_indices, num_data);
  }

Guolin Ke's avatar
Guolin Ke committed
67
68
69
70
71
  void AddPredictionToScore(const Tree* tree,
                            double* out_score) const override {
    if (tree->num_leaves() <= 1) {
      return;
    }
Guolin Ke's avatar
Guolin Ke committed
72
    CHECK(tree->num_leaves() <= data_partition_->num_leaves());
Guolin Ke's avatar
Guolin Ke committed
73
#pragma omp parallel for schedule(static, 1)
74
    for (int i = 0; i < tree->num_leaves(); ++i) {
Guolin Ke's avatar
Guolin Ke committed
75
      double output = static_cast<double>(tree->LeafOutput(i));
Guolin Ke's avatar
Guolin Ke committed
76
77
      data_size_t cnt_leaf_data = 0;
      auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data);
Guolin Ke's avatar
Guolin Ke committed
78
      for (data_size_t j = 0; j < cnt_leaf_data; ++j) {
79
        out_score[tmp_idx[j]] += output;
Guolin Ke's avatar
Guolin Ke committed
80
81
82
83
      }
    }
  }

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

87
88
  bool IsHistColWise() const override { return is_hist_colwise_; }

Nikita Titov's avatar
Nikita Titov committed
89
 protected:
90
91
92
93
94
95
  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);

96
97
  void GetMultiValBin(const Dataset* dataset, bool is_first_time);

98
  virtual std::vector<int8_t> GetUsedFeatures(bool is_tree_level);
Guolin Ke's avatar
Guolin Ke committed
99
100
101
102
103
104
105
106
  /*!
  * \brief Some initial works before training
  */
  virtual void BeforeTrain();

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

Guolin Ke's avatar
Guolin Ke committed
109
  virtual void FindBestSplits();
Guolin Ke's avatar
Guolin Ke committed
110

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

Guolin Ke's avatar
Guolin Ke committed
113
  virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract);
Guolin Ke's avatar
Guolin Ke committed
114
115
116
117
118
119
120
121
122
123

  /*!
  * \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.
  */
  virtual void Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf);

124
  /* Force splits with forced_split_json dict and then return num splits forced.*/
Guolin Ke's avatar
Guolin Ke committed
125
  virtual int32_t ForceSplits(Tree* tree, const Json& forced_split_json, int* left_leaf,
126
                              int* right_leaf, int* cur_depth,
127
128
                              bool *aborted_last_force_split);

Guolin Ke's avatar
Guolin Ke committed
129
130
131
132
133
134
  /*!
  * \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;
135

Guolin Ke's avatar
Guolin Ke committed
136
137
138
139
140
141
142
  /*! \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 */
143
  const score_t* gradients_;
Guolin Ke's avatar
Guolin Ke committed
144
  /*! \brief hessians of current iteration */
145
  const score_t* hessians_;
Guolin Ke's avatar
Guolin Ke committed
146
  /*! \brief training data partition on leaves */
Guolin Ke's avatar
Guolin Ke committed
147
  std::unique_ptr<DataPartition> data_partition_;
Guolin Ke's avatar
Guolin Ke committed
148
149
  /*! \brief used for generate used features */
  Random random_;
Hui Xue's avatar
Hui Xue committed
150
  /*! \brief used for sub feature training, is_feature_used_[i] = false means don't used feature i */
Guolin Ke's avatar
Guolin Ke committed
151
  std::vector<int8_t> is_feature_used_;
152
153
  /*! \brief used feature indices in current tree */
  std::vector<int> used_feature_indices_;
154
155
  /*! \brief pointer to histograms array of parent of current leaves */
  FeatureHistogram* parent_leaf_histogram_array_;
Guolin Ke's avatar
Guolin Ke committed
156
157
158
159
160
161
162
  /*! \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_;
163
164
  /*! \brief store best split per feature for all leaves */
  std::vector<SplitInfo> splits_per_leaf_;
Nikita Titov's avatar
Nikita Titov committed
165
  /*! \brief stores minimum and maximum constraints for each leaf */
166
  std::unique_ptr<LeafConstraints<ConstraintEntry>> constraints_;
Guolin Ke's avatar
Guolin Ke committed
167
168

  /*! \brief stores best thresholds for all feature for smaller leaf */
Guolin Ke's avatar
Guolin Ke committed
169
  std::unique_ptr<LeafSplits> smaller_leaf_splits_;
Guolin Ke's avatar
Guolin Ke committed
170
  /*! \brief stores best thresholds for all feature for larger leaf */
Guolin Ke's avatar
Guolin Ke committed
171
  std::unique_ptr<LeafSplits> larger_leaf_splits_;
172
  std::vector<int> valid_feature_indices_;
Guolin Ke's avatar
Guolin Ke committed
173

174
175
#ifdef USE_GPU
  /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */
176
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_;
177
  /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */
178
  std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_;
179
#else
Guolin Ke's avatar
Guolin Ke committed
180
  /*! \brief gradients of current iteration, ordered for cache optimized */
181
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_;
Guolin Ke's avatar
Guolin Ke committed
182
  /*! \brief hessians of current iteration, ordered for cache optimized */
183
  std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_;
184
#endif
Guolin Ke's avatar
Guolin Ke committed
185
186

  /*! \brief  is_data_in_leaf_[i] != 0 means i-th data is marked */
187
  std::vector<char, Common::AlignmentAllocator<char, kAlignedSize>> is_data_in_leaf_;
188
  /*! \brief used to cache historical histogram to speed up*/
Guolin Ke's avatar
Guolin Ke committed
189
  HistogramPool histogram_pool_;
Guolin Ke's avatar
Guolin Ke committed
190
  /*! \brief config of tree learner*/
Guolin Ke's avatar
Guolin Ke committed
191
  const Config* config_;
Guolin Ke's avatar
Guolin Ke committed
192
  std::vector<int> ordered_bin_indices_;
193
  bool is_constant_hessian_;
194
  std::unique_ptr<TrainingTempState> temp_state_;
195
  bool is_hist_colwise_;
196
  std::unique_ptr<CostEfficientGradientBoosting> cegb_;
Guolin Ke's avatar
Guolin Ke committed
197
198
};

Luke Gallagher's avatar
Luke Gallagher committed
199
200
201
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
202
203
204
205
206
207
  } else {
    return 0;
  }
}

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