| 1 | /** |
| 2 | * Copyright 2014-2025, XGBoost Contributors |
| 3 | * |
| 4 | * @brief interface of objective function used by xgboost. |
| 5 | * @author Tianqi Chen, Kailong Chen |
| 6 | */ |
| 7 | #ifndef XGBOOST_OBJECTIVE_H_ |
| 8 | #define XGBOOST_OBJECTIVE_H_ |
| 9 | |
| 10 | #include <dmlc/registry.h> |
| 11 | #include <xgboost/base.h> |
| 12 | #include <xgboost/data.h> |
| 13 | #include <xgboost/host_device_vector.h> |
| 14 | #include <xgboost/linalg.h> // for Vector |
| 15 | #include <xgboost/model.h> |
| 16 | #include <xgboost/task.h> |
| 17 | |
| 18 | #include <cstdint> // for int32_t |
| 19 | #include <functional> |
| 20 | #include <string> // for string |
| 21 | |
| 22 | namespace xgboost { |
| 23 | |
| 24 | class RegTree; |
| 25 | struct Context; |
| 26 | |
| 27 | /** @brief The interface of objective function */ |
| 28 | class ObjFunction : public Configurable { |
| 29 | protected: |
| 30 | Context const* ctx_{nullptr}; |
| 31 | |
| 32 | public: |
| 33 | static constexpr float DefaultBaseScore() { return 0.5f; } |
| 34 | |
| 35 | public: |
| 36 | ~ObjFunction() override = default; |
| 37 | /** |
| 38 | * @brief Configure the objective with the specified parameters. |
| 39 | * |
| 40 | * @param args arguments to the objective function. |
| 41 | */ |
| 42 | virtual void Configure(Args const& args) = 0; |
| 43 | /** |
| 44 | * @brief Get gradient over each of predictions, given existing information. |
| 45 | * |
| 46 | * @param preds Raw prediction (before applying the inverse link) of the current round. |
| 47 | * @param info information about labels, weights, groups in rank. |
| 48 | * @param iteration current iteration number. |
| 49 | * @param out_gpair output of get gradient, saves gradient and second order gradient in |
| 50 | */ |
| 51 | virtual void GetGradient(HostDeviceVector<float> const& preds, MetaInfo const& info, |
| 52 | std::int32_t iter, linalg::Matrix<GradientPair>* out_gpair) = 0; |
| 53 | |
| 54 | /** @return the default evaluation metric for the objective */ |
| 55 | [[nodiscard]] virtual const char* DefaultEvalMetric() const = 0; |
| 56 | /** |
| 57 | * @brief Return the configuration for the default metric. |
| 58 | */ |
| 59 | [[nodiscard]] virtual Json DefaultMetricConfig() const { return Json{Null{}}; } |
| 60 | /** |
| 61 | * @brief Apply inverse link (activation) function to prediction values. |
| 62 | * |
| 63 | * This is only called when Prediction is called |
| 64 | * |
| 65 | * @param [in,out] io_preds prediction values, saves to this vector as well. |
| 66 | */ |
| 67 | virtual void PredTransform(HostDeviceVector<float>*) const {} |
| 68 | /** |
| 69 | * @brief Apply inverse link (activation) function to prediction values |
| 70 | * |
| 71 | * This is only called when Eval is called, usually it redirect to PredTransform |
| 72 | * |
| 73 | * @param [in,out] io_preds prediction values, saves to this vector as well. |
| 74 | */ |
| 75 | virtual void EvalTransform(HostDeviceVector<float>* io_preds) { this->PredTransform(io_preds); } |
| 76 | /** |
| 77 | * @brief Apply the link function to the intercept. |
| 78 | * |
| 79 | * This is an inverse of `PredTransform` for most of the objectives (if there's a |
| 80 | * valid inverse). It's used to transform user-set base_score back to margin used by |
| 81 | * gradient boosting. The method converts objective-based valid outputs like |
| 82 | * probability back to raw model outputs. |
| 83 | * |
| 84 | * @param [in,out] base_score The intercept to transform. |
| 85 | */ |
| 86 | virtual void ProbToMargin(linalg::Vector<float>* /*base_score*/) const {} |
| 87 | /** |
| 88 | * @brief Obtain the initial estimation of prediction (intercept). |
| 89 | * |
| 90 | * The output in `base_score` represents prediction after apply the inverse link function |
| 91 | * (valid prediction instead of raw). |
| 92 | * |
| 93 | * @param info MetaInfo that contains label. |
| 94 | * @param base_score Output estimation. |
| 95 | */ |
| 96 | virtual void InitEstimation(MetaInfo const& info, linalg::Vector<float>* base_score) const; |
| 97 | /** |
| 98 | * @brief Return task of this objective. |
| 99 | */ |
| 100 | [[nodiscard]] virtual struct ObjInfo Task() const = 0; |
| 101 | /** |
| 102 | * @brief Return number of targets for input matrix. Right now XGBoost supports only |
| 103 | * multi-target regression. |
| 104 | */ |
| 105 | [[nodiscard]] virtual bst_target_t Targets(MetaInfo const& info) const { |
| 106 | if (info.labels.Shape(1) > 1) { |
| 107 | LOG(FATAL) << "multioutput is not supported by the current objective function"; |
| 108 | } |
| 109 | return 1; |
| 110 | } |
| 111 | /** @brief Getter of the context. */ |
| 112 | [[nodiscard]] Context const* Ctx() const { return this->ctx_; } |
| 113 | |
| 114 | /** |
| 115 | * @brief Update the leaf values after a tree is built. Needed for objectives with 0 |
| 116 | * hessian. |
| 117 | * |
| 118 | * Note that the leaf update is not well defined for distributed training as XGBoost |
| 119 | * computes only an average of quantile between workers. This breaks when some leaf |
| 120 | * have no sample assigned in a local worker. |
| 121 | * |
| 122 | * @param position The leaf index for each rows. |
| 123 | * @param info MetaInfo providing labels and weights. |
| 124 | * @param learning_rate The learning rate for current iteration. |
| 125 | * @param prediction Model prediction after transformation. |
| 126 | * @param group_idx The group index for this tree, 0 when it's not multi-target or multi-class. |
| 127 | * @param p_tree Tree that needs to be updated. |
| 128 | */ |
| 129 | virtual void UpdateTreeLeaf(HostDeviceVector<bst_node_t> const& /*position*/, |
| 130 | MetaInfo const& /*info*/, float /*learning_rate*/, |
| 131 | HostDeviceVector<float> const& /*prediction*/, |
| 132 | bst_target_t /*group_idx*/, RegTree* /*p_tree*/) const {} |
| 133 | /** |
| 134 | * @brief Create an objective function according to the name. |
| 135 | * |
| 136 | * @param name Name of the objective. |
| 137 | * @param ctx Pointer to the context. |
| 138 | */ |
| 139 | static ObjFunction* Create(const std::string& name, Context const* ctx); |
| 140 | }; |
| 141 | |
| 142 | /*! |
| 143 | * \brief Registry entry for objective factory functions. |
| 144 | */ |
| 145 | struct ObjFunctionReg |
| 146 | : public dmlc::FunctionRegEntryBase<ObjFunctionReg, |
| 147 | std::function<ObjFunction* ()> > { |
| 148 | }; |
| 149 | |
| 150 | /*! |
| 151 | * \brief Macro to register objective function. |
| 152 | * |
| 153 | * \code |
| 154 | * // example of registering a objective |
| 155 | * XGBOOST_REGISTER_OBJECTIVE(LinearRegression, "reg:squarederror") |
| 156 | * .describe("Linear regression objective") |
| 157 | * .set_body([]() { |
| 158 | * return new RegLossObj(LossType::kLinearSquare); |
| 159 | * }); |
| 160 | * \endcode |
| 161 | */ |
| 162 | #define XGBOOST_REGISTER_OBJECTIVE(UniqueId, Name) \ |
| 163 | static DMLC_ATTRIBUTE_UNUSED ::xgboost::ObjFunctionReg & \ |
| 164 | __make_ ## ObjFunctionReg ## _ ## UniqueId ## __ = \ |
| 165 | ::dmlc::Registry< ::xgboost::ObjFunctionReg>::Get()->__REGISTER__(Name) |
| 166 | } // namespace xgboost |
| 167 | #endif // XGBOOST_OBJECTIVE_H_ |