Debian Codegraph @

src/include/xgboost/predictor.h

raw symbols SCIP
1 /**
2 * Copyright 2017-2025, XGBoost Contributors
3 * \file predictor.h
4 * \brief Interface of predictor,
5 * performs predictions for a gradient booster.
6 */
7 #pragma once
8 #include <dmlc/registry.h> // for FunctionRegEntryBase
9 #include <xgboost/base.h> // for bst_tree_t
10 #include <xgboost/cache.h> // for DMatrixCache
11 #include <xgboost/context.h> // for Context
12 #include <xgboost/context.h>
13 #include <xgboost/data.h>
14 #include <xgboost/host_device_vector.h>
15
16 #include <functional> // for function
17 #include <memory> // for shared_ptr
18 #include <string>
19 #include <vector>
20
21 // Forward declarations
22 namespace xgboost::gbm {
23 struct GBTreeModel;
24 } // namespace xgboost::gbm
25
26 namespace xgboost {
27 /**
28 * \brief Contains pointer to input matrix and associated cached predictions.
29 */
30 struct PredictionCacheEntry {
31 // A storage for caching prediction values
32 HostDeviceVector<float> predictions;
33 // The version of current cache, corresponding number of layers of trees
34 std::uint32_t version{0};
35
36 PredictionCacheEntry() = default;
37 /**
38 * \brief Update the cache entry by number of versions.
39 *
40 * \param v Added versions.
41 */
42 void Update(std::uint32_t v) { version += v; }
43 void Reset() { version = 0; }
44 };
45
46 /**
47 * \brief A container for managed prediction caches.
48 */
49 class PredictionContainer : public DMatrixCache<PredictionCacheEntry> {
50 // We cache up to 64 DMatrix for all threads
51 std::size_t static constexpr DefaultSize() { return 64; }
52
53 public:
54 PredictionContainer() : DMatrixCache<PredictionCacheEntry>{DefaultSize()} {}
55 std::shared_ptr<PredictionCacheEntry> Cache(std::shared_ptr<DMatrix> m, DeviceOrd device) {
56 auto p_cache = this->CacheItem(m);
57 if (!device.IsCPU()) {
58 p_cache->predictions.SetDevice(device);
59 }
60 return p_cache;
61 }
62 };
63
64 /**
65 * \class Predictor
66 *
67 * \brief Performs prediction on individual training instances or batches of instances for
68 * GBTree. Prediction functions all take a GBTreeModel and a DMatrix as input and
69 * output a vector of predictions. The predictor does not modify any state of the
70 * model itself.
71 */
72 class Predictor {
73 protected:
74 Context const* ctx_;
75
76 public:
77 explicit Predictor(Context const* ctx) : ctx_{ctx} {}
78
79 virtual ~Predictor() = default;
80
81 /**
82 * \brief Configure and register input matrices in prediction cache.
83 *
84 * \param cfg The configuration.
85 */
86 virtual void Configure(Args const&);
87
88 /**
89 * \brief Initialize output prediction
90 *
91 * \param info Meta info for the DMatrix object used for prediction.
92 * \param out_predt Prediction vector to be initialized.
93 * \param model Tree model used for prediction.
94 */
95 virtual void InitOutPredictions(const MetaInfo& info, HostDeviceVector<float>* out_predt,
96 const gbm::GBTreeModel& model) const;
97
98 /**
99 * \brief Generate batch predictions for a given feature matrix. May use
100 * cached predictions if available instead of calculating from scratch.
101 *
102 * \param [in,out] dmat Feature matrix.
103 * \param [in,out] out_preds The output preds.
104 * \param model The model to predict from.
105 * \param tree_begin The tree begin index.
106 * \param tree_end The tree end index.
107 */
108 virtual void PredictBatch(DMatrix* dmat, PredictionCacheEntry* out_preds,
109 gbm::GBTreeModel const& model, bst_tree_t tree_begin,
110 bst_tree_t tree_end = 0) const = 0;
111
112 /**
113 * \brief Inplace prediction.
114 *
115 * \param p_fmat A proxy DMatrix that contains the data and related
116 * meta info.
117 * \param model The model to predict from.
118 * \param missing Missing value in the data.
119 * \param [in,out] out_preds The output preds.
120 * \param tree_begin (Optional) Beginning of boosted trees used for prediction.
121 * \param tree_end (Optional) End of booster trees. 0 means do not limit trees.
122 *
123 * \return True if the data can be handled by current predictor, false otherwise.
124 */
125 virtual bool InplacePredict(std::shared_ptr<DMatrix> p_fmat, const gbm::GBTreeModel& model,
126 float missing, PredictionCacheEntry* out_preds,
127 bst_tree_t tree_begin = 0, bst_tree_t tree_end = 0) const = 0;
128
129 /**
130 * \brief predict the leaf index of each tree, the output will be nsample *
131 * ntree vector this is only valid in gbtree predictor.
132 *
133 * \param [in,out] dmat The input feature matrix.
134 * \param [in,out] out_preds The output preds.
135 * \param model Model to make predictions from.
136 * \param tree_end (Optional) The tree end index.
137 */
138
139 virtual void PredictLeaf(DMatrix* dmat, HostDeviceVector<float>* out_preds,
140 gbm::GBTreeModel const& model, bst_tree_t tree_end = 0) const = 0;
141
142 /**
143 * \brief feature contributions to individual predictions; the output will be
144 * a vector of length (nfeats + 1) * num_output_group * nsample, arranged in
145 * that order.
146 *
147 * \param [in,out] dmat The input feature matrix.
148 * \param [in,out] out_contribs The output feature contribs.
149 * \param model Model to make predictions from.
150 * \param tree_end The tree end index.
151 * \param tree_weights (Optional) Weights to multiply each tree by.
152 * \param approximate Use fast approximate algorithm.
153 * \param condition Condition on the condition_feature (0=no, -1=cond off, 1=cond on).
154 * \param condition_feature Feature to condition on (i.e. fix) during calculations.
155 */
156
157 virtual void PredictContribution(DMatrix* dmat, HostDeviceVector<float>* out_contribs,
158 gbm::GBTreeModel const& model, bst_tree_t tree_end = 0,
159 std::vector<float> const* tree_weights = nullptr,
160 bool approximate = false, int condition = 0,
161 unsigned condition_feature = 0) const = 0;
162
163 virtual void PredictInteractionContributions(DMatrix* dmat, HostDeviceVector<float>* out_contribs,
164 gbm::GBTreeModel const& model,
165 bst_tree_t tree_end = 0,
166 std::vector<float> const* tree_weights = nullptr,
167 bool approximate = false) const = 0;
168
169 /**
170 * \brief Creates a new Predictor*.
171 *
172 * \param name Name of the predictor.
173 * \param ctx Pointer to runtime parameters.
174 */
175 static Predictor* Create(std::string const& name, Context const* ctx);
176 };
177
178 /*!
179 * \brief Registry entry for predictor.
180 */
181 struct PredictorReg
182 : public dmlc::FunctionRegEntryBase<PredictorReg, std::function<Predictor*(Context const*)>> {};
183
184 #define XGBOOST_REGISTER_PREDICTOR(UniqueId, Name) \
185 static DMLC_ATTRIBUTE_UNUSED ::xgboost::PredictorReg& \
186 __make_##PredictorReg##_##UniqueId##__ = \
187 ::dmlc::Registry<::xgboost::PredictorReg>::Get()->__REGISTER__(Name)
188 } // namespace xgboost