Debian Codegraph @

src/include/xgboost/gbm.h

raw symbols SCIP
1 /**
2 * Copyright 2014-2025, XGBoost Contributors
3 * \file gbm.h
4 * \brief Interface of gradient booster,
5 * that learns through gradient statistics.
6 * \author Tianqi Chen
7 */
8 #ifndef XGBOOST_GBM_H_
9 #define XGBOOST_GBM_H_
10
11 #include <dmlc/registry.h>
12 #include <xgboost/base.h>
13 #include <xgboost/data.h>
14 #include <xgboost/gradient.h> // for GradientContainer
15 #include <xgboost/host_device_vector.h>
16 #include <xgboost/model.h>
17
18 #include <functional>
19 #include <memory>
20 #include <string>
21 #include <vector>
22
23 namespace xgboost {
24
25 class Json;
26 class FeatureMap;
27 class ObjFunction;
28 class CatContainer;
29
30 struct Context;
31 struct LearnerModelParam;
32 struct PredictionCacheEntry;
33
34 /*!
35 * \brief interface of gradient boosting model.
36 */
37 class GradientBooster : public Model, public Configurable {
38 protected:
39 Context const* ctx_;
40 explicit GradientBooster(Context const* ctx) : ctx_{ctx} {}
41
42 public:
43 /*! \brief virtual destructor */
44 ~GradientBooster() override = default;
45 /**
46 * @brief Set the configuration of gradient boosting.
47 * User must call configure once before InitModel and Training.
48 *
49 * @param cfg configurations on both training and model parameters.
50 */
51 virtual void Configure(Args const& cfg) = 0;
52
53 /**
54 * \brief Slice a model using boosting index. The slice m:n indicates taking all trees
55 * that were fit during the boosting rounds m, (m+1), (m+2), ..., (n-1).
56 * \param begin Beginning of boosted tree layer used for prediction.
57 * \param end End of booster layer. 0 means do not limit trees.
58 * \param out Output gradient booster
59 */
60 virtual void Slice(bst_layer_t /*begin*/, bst_layer_t /*end*/, bst_layer_t /*step*/,
61 GradientBooster* /*out*/, bool* /*out_of_bound*/) const {
62 LOG(FATAL) << "Slice is not supported by the current booster.";
63 }
64 /**
65 * @brief Return number of boosted rounds.
66 */
67 [[nodiscard]] virtual std::int32_t BoostedRounds() const = 0;
68 /**
69 * \brief Whether the model has already been trained. When tree booster is chosen, then
70 * returns true when there are existing trees.
71 */
72 [[nodiscard]] virtual bool ModelFitted() const = 0;
73 /**
74 * @brief perform update to the model(boosting)
75 *
76 * @param p_fmat feature matrix that provide access to features
77 * @param in_gpair address of the gradient pair statistics of the data
78 * @param prediction The output prediction cache entry that needs to be updated.
79 * the booster may change content of gpair
80 * @param obj The objective function used for boosting.
81 */
82 virtual void DoBoost(DMatrix* p_fmat, GradientContainer* in_gpair,
83 PredictionCacheEntry* prediction, ObjFunction const* obj) = 0;
84
85 /**
86 * \brief Generate predictions for given feature matrix
87 *
88 * \param dmat The feature matrix.
89 * \param out_preds output vector to hold the predictions
90 * \param training Whether the prediction value is used for training. For dart booster
91 * drop out is performed during training.
92 * \param begin Beginning of boosted tree layer used for prediction.
93 * \param end End of booster layer. 0 means do not limit trees.
94 */
95 virtual void PredictBatch(DMatrix* dmat, PredictionCacheEntry* out_preds, bool training,
96 bst_layer_t begin, bst_layer_t end) = 0;
97
98 /**
99 * \brief Inplace prediction.
100 *
101 * \param p_fmat A proxy DMatrix that contains the data and related.
102 * \param missing Missing value in the data.
103 * \param [in,out] out_preds The output preds.
104 * \param begin (Optional) Beginning of boosted tree layer used for prediction.
105 * \param end (Optional) End of booster layer. 0 means do not limit trees.
106 */
107 virtual void InplacePredict(std::shared_ptr<DMatrix>, float, PredictionCacheEntry*, bst_layer_t,
108 bst_layer_t) const {
109 LOG(FATAL) << "Inplace predict is not supported by the current booster.";
110 }
111 /*!
112 * \brief predict the leaf index of each tree, the output will be nsample * ntree vector
113 * this is only valid in gbtree predictor
114 * \param dmat feature matrix
115 * \param out_preds output vector to hold the predictions
116 * \param layer_begin Beginning of boosted tree layer used for prediction.
117 * \param layer_end End of booster layer. 0 means do not limit trees.
118 */
119 virtual void PredictLeaf(DMatrix *dmat,
120 HostDeviceVector<bst_float> *out_preds,
121 unsigned layer_begin, unsigned layer_end) = 0;
122
123 /*!
124 * \brief feature contributions to individual predictions; the output will be a vector
125 * of length (nfeats + 1) * num_output_group * nsample, arranged in that order
126 * \param dmat feature matrix
127 * \param out_contribs output vector to hold the contributions
128 * \param layer_begin Beginning of boosted tree layer used for prediction.
129 * \param layer_end End of booster layer. 0 means do not limit trees.
130 * \param approximate use a faster (inconsistent) approximation of SHAP values
131 */
132 virtual void PredictContribution(DMatrix* dmat, HostDeviceVector<float>* out_contribs,
133 bst_layer_t layer_begin, bst_layer_t layer_end,
134 bool approximate = false) = 0;
135
136 virtual void PredictInteractionContributions(DMatrix* dmat, HostDeviceVector<float>* out_contribs,
137 bst_layer_t layer_begin, bst_layer_t layer_end,
138 bool approximate) = 0;
139
140 /**
141 * @brief dump the model in the requested format
142 * @param fmap feature map that may help give interpretations of feature
143 * @param with_stats extra statistics while dumping model
144 * @param format the format to dump the model in
145 * @return a vector of dump for boosters.
146 */
147 [[nodiscard]] virtual std::vector<std::string> DumpModel(const FeatureMap& fmap, bool with_stats,
148 std::string format) const = 0;
149
150 virtual void FeatureScore(std::string const& importance_type,
151 common::Span<int32_t const> trees,
152 std::vector<bst_feature_t>* features,
153 std::vector<float>* scores) const = 0;
154 /**
155 * @brief Getter for categories.
156 */
157 [[nodiscard]] virtual CatContainer const* Cats() const {
158 LOG(FATAL) << "Retrieving categories is not supported by the current booster.";
159 return nullptr;
160 }
161 /**
162 * @brief create a gradient booster from given name
163 * @param name name of gradient booster
164 * @param generic_param Pointer to runtime parameters
165 * @param learner_model_param pointer to global model parameters
166 * @return The created booster.
167 */
168 static GradientBooster* Create(const std::string& name, Context const* ctx,
169 LearnerModelParam const* learner_model_param);
170 };
171
172 /*!
173 * \brief Registry entry for tree updater.
174 */
175 struct GradientBoosterReg
176 : public dmlc::FunctionRegEntryBase<
177 GradientBoosterReg,
178 std::function<GradientBooster*(LearnerModelParam const* learner_model_param,
179 Context const* ctx)> > {};
180
181 /*!
182 * \brief Macro to register gradient booster.
183 *
184 * \code
185 * // example of registering a objective ndcg@k
186 * XGBOOST_REGISTER_GBM(GBTree, "gbtree")
187 * .describe("Boosting tree ensembles.")
188 * .set_body([]() {
189 * return new GradientBooster<TStats>();
190 * });
191 * \endcode
192 */
193 #define XGBOOST_REGISTER_GBM(UniqueId, Name) \
194 static DMLC_ATTRIBUTE_UNUSED ::xgboost::GradientBoosterReg & \
195 __make_ ## GradientBoosterReg ## _ ## UniqueId ## __ = \
196 ::dmlc::Registry< ::xgboost::GradientBoosterReg>::Get()->__REGISTER__(Name)
197
198 } // namespace xgboost
199 #endif // XGBOOST_GBM_H_