4#ifndef XGBOOST_C_API_C_API_UTILS_H_
5#define XGBOOST_C_API_C_API_UTILS_H_
17#include "xgboost/json.h"
21#include "xgboost/string_view.h"
37inline void CalcPredictShape(
bool strict_shape, PredictionType type,
size_t rows,
size_t cols,
38 size_t chunksize,
size_t groups,
size_t rounds,
39 std::vector<bst_ulong> *out_shape,
41 auto &shape = *out_shape;
42 if (type == PredictionType::kMargin && rows != 0) {
44 CHECK_EQ(chunksize, groups);
48 case PredictionType::kValue:
49 case PredictionType::kMargin: {
50 if (chunksize == 1 && !strict_shape) {
52 shape.resize(*out_dim);
56 shape.resize(*out_dim);
59 shape.back() = std::min(groups, chunksize);
63 case PredictionType::kApproxContribution:
64 case PredictionType::kContribution: {
65 if (groups == 1 && !strict_shape) {
67 shape.resize(*out_dim);
69 shape.back() = cols + 1;
72 shape.resize(*out_dim);
79 case PredictionType::kApproxInteraction:
80 case PredictionType::kInteraction: {
81 if (groups == 1 && !strict_shape) {
83 shape.resize(*out_dim);
89 shape.resize(*out_dim);
97 case PredictionType::kLeaf: {
103 auto forest = chunksize / (shape[1] * shape[2]);
104 forest = std::max(
static_cast<decltype(forest)
>(1), forest);
106 *out_dim = shape.size();
107 }
else if (chunksize == 1) {
109 shape.resize(*out_dim);
110 shape.front() = rows;
113 shape.resize(*out_dim);
114 shape.front() = rows;
115 shape.back() = chunksize;
120 LOG(FATAL) <<
"Unknown prediction type:" <<
static_cast<int>(type);
124 std::accumulate(shape.cbegin(), shape.cend(),
static_cast<bst_ulong
>(1), std::multiplies<>{}),
129inline uint32_t GetIterationFromTreeLimit(uint32_t ntree_limit, Learner *learner) {
132 if (ntree_limit != 0) {
133 learner->Configure();
134 uint32_t num_parallel_tree = 0;
136 Json config{Object()};
137 learner->SaveConfig(&config);
138 auto const &booster = get<String const>(config[
"learner"][
"gradient_booster"][
"name"]);
139 if (booster ==
"gblinear") {
140 num_parallel_tree = 0;
141 }
else if (booster ==
"dart") {
143 std::stoi(get<String const>(config[
"learner"][
"gradient_booster"][
"gbtree"]
144 [
"gbtree_model_param"][
"num_parallel_tree"]));
145 }
else if (booster ==
"gbtree") {
146 num_parallel_tree = std::stoi(get<String const>(
147 (config[
"learner"][
"gradient_booster"][
"gbtree_model_param"][
"num_parallel_tree"])));
149 LOG(FATAL) <<
"Unknown booster:" << booster;
151 ntree_limit /= std::max(num_parallel_tree, 1u);
156inline float GetMissing(Json
const &config) {
158 auto const &obj = get<Object const>(config);
159 auto it = obj.find(
"missing");
160 if (it == obj.cend()) {
161 LOG(FATAL) <<
"Argument `missing` is required.";
164 auto const &j_missing = it->second;
165 if (IsA<Number const>(j_missing)) {
166 missing = get<Number const>(j_missing);
167 }
else if (IsA<Integer const>(j_missing)) {
168 missing = get<Integer const>(j_missing);
171 TypeCheck<Number, Integer>(j_missing,
"missing");
178#if defined(XGBOOST_USE_CUDA)
179 int32_t device_id_ {0};
181 void SetGPUAttribute();
182 void RestoreGPUAttribute();
184 void SetGPUAttribute() {}
185 void RestoreGPUAttribute() {}
193 RestoreGPUAttribute();
197inline FeatureMap LoadFeatureMap(std::string
const& uri) {
199 if (uri.size() != 0) {
207inline void GenerateFeatureMap(Learner
const *learner,
208 std::vector<Json>
const &custom_feature_names,
209 size_t n_features, FeatureMap *out_feature_map) {
210 auto &feature_map = *out_feature_map;
211 auto maybe = [&](std::vector<std::string>
const &values,
size_t i,
212 std::string
const &dft) {
213 return values.empty() ? dft : values[i];
215 if (feature_map.Size() == 0) {
217 std::vector<std::string> feature_names;
223 if (!custom_feature_names.empty()) {
224 CHECK_EQ(custom_feature_names.size(), n_features)
225 <<
"Incorrect number of feature names.";
226 feature_names.resize(custom_feature_names.size());
227 std::transform(custom_feature_names.begin(), custom_feature_names.end(),
228 feature_names.begin(),
229 [](Json
const &name) { return get<String const>(name); });
231 learner->GetFeatureNames(&feature_names);
233 if (!feature_names.empty()) {
234 CHECK_EQ(feature_names.size(), n_features) <<
"Incorrect number of feature names.";
237 std::vector<std::string> feature_types;
238 learner->GetFeatureTypes(&feature_types);
239 if (!feature_types.empty()) {
240 CHECK_EQ(feature_types.size(), n_features) <<
"Incorrect number of feature types.";
243 for (
size_t i = 0; i < n_features; ++i) {
244 feature_map.PushBack(
246 maybe(feature_names, i,
"f" + std::to_string(i)).data(),
247 maybe(feature_types, i,
"q").data());
250 CHECK_EQ(feature_map.Size(), n_features);
253void XGBBuildInfoDevice(Json* p_info);
255template <
typename JT>
256auto const &RequiredArg(Json
const &in, StringView key, StringView func) {
257 auto const &obj = get<Object const>(in);
258 auto it = obj.find(key);
259 if (it == obj.cend() || IsA<Null>(it->second)) {
260 LOG(FATAL) <<
"Argument `" << key <<
"` is required for `" << func <<
"`.";
262 TypeCheck<JT>(it->second, StringView{key});
263 return get<std::remove_const_t<JT>
const>(it->second);
266template <
typename JT,
typename T>
267auto const &OptionalArg(Json
const &in, StringView key, T
const &dft) {
268 auto const &obj = get<Object const>(in);
269 auto it = obj.find(key);
270 if (it != obj.cend() && !IsA<Null>(it->second)) {
271 TypeCheck<JT>(it->second, key);
272 return get<std::remove_const_t<JT>
const>(it->second);
281 auto pp_m =
static_cast<std::shared_ptr<DMatrix> *
>(handle);
290template <
typename PtrT,
typename I,
typename T>
291void MakeSparseFromPtr(PtrT
const *p_indptr, I
const *p_indices, T
const *p_data,
292 std::size_t nindptr, std::string *indptr_str, std::string *indices_str,
293 std::string *data_str) {
294 auto ndata =
static_cast<Integer::Int
>(p_indptr[nindptr - 1]);
296 Json jindptr{Object{}};
297 Json jindices{Object{}};
298 Json jdata{Object{}};
301 Array{std::vector<Json>{Json{
reinterpret_cast<Integer::Int
>(p_indptr)}, Json{
true}}};
302 jindptr[
"shape"] = std::vector<Json>{Json{nindptr}};
303 jindptr[
"version"] = Integer{3};
307 Array{std::vector<Json>{Json{
reinterpret_cast<Integer::Int
>(p_indices)}, Json{
true}}};
308 jindices[
"shape"] = std::vector<Json>{Json{ndata}};
309 jindices[
"version"] = Integer{3};
313 Array{std::vector<Json>{Json{
reinterpret_cast<Integer::Int
>(p_data)}, Json{
true}}};
314 jdata[
"shape"] = std::vector<Json>{Json{ndata}};
315 jdata[
"version"] = Integer{3};
317 std::string pindptr_typestr =
318 linalg::detail::ArrayInterfaceHandler::TypeChar<PtrT>() + std::to_string(
sizeof(PtrT));
319 std::string ind_typestr =
320 linalg::detail::ArrayInterfaceHandler::TypeChar<I>() + std::to_string(
sizeof(I));
321 std::string data_typestr =
322 linalg::detail::ArrayInterfaceHandler::TypeChar<T>() + std::to_string(
sizeof(T));
323 if (DMLC_LITTLE_ENDIAN) {
324 jindptr[
"typestr"] = String{
"<" + pindptr_typestr};
325 jindices[
"typestr"] = String{
"<" + ind_typestr};
326 jdata[
"typestr"] = String{
"<" + data_typestr};
328 jindptr[
"typestr"] = String{
">" + pindptr_typestr};
329 jindices[
"typestr"] = String{
">" + ind_typestr};
330 jdata[
"typestr"] = String{
">" + data_typestr};
static Stream * Create(const char *uri, const char *const flag, bool allow_null=false)
generic factory function create an stream, the stream will close the underlying files upon deletion
Definition io.cc:132
a std::istream class that can can wrap Stream objects, can use istream with that output to underlying...
Definition io.h:385
Feature map data structure to help text model dump. TODO(tqchen) consider make it even more lightweig...
Definition feature_map.h:22
void LoadText(std::istream &is)
load feature map from input stream
Definition feature_map.h:36
static void Dump(Json json, std::string *out, std::ios::openmode mode=std::ios::out)
Encode the JSON object.
Definition json.cc:669
Definition c_api_utils.h:177
Feature map data structure to help visualization and model dump.
Copyright 2015-2023 by XGBoost Contributors.
defines console logging options for xgboost. Use to enforce unified print behavior.
Copyright 2015-2023 by XGBoost Contributors.
Copyright 2021-2023 by XGBoost Contributors.
detail namespace with internal helper functions
Definition json.hpp:249
namespace of xgboost
Definition base.h:90
uint64_t bst_ulong
unsigned long integers
Definition base.h:95
std::shared_ptr< DMatrix > CastDMatrixHandle(DMatrixHandle const handle)
Get shared ptr from DMatrix C handle with additional checks.
Definition c_api_utils.h:280
Definition string_view.h:15
Copyright 2015~2023 by XGBoost Contributors.