Debian Codegraph @

src/include/xgboost/c_api.h

raw symbols SCIP
1 /**
2 * Copyright 2015-2025, XGBoost Contributors
3 *
4 * @brief C API of XGBoost, used to interface with other high-level languages.
5 */
6 #ifndef XGBOOST_C_API_H_
7 #define XGBOOST_C_API_H_
8
9 #ifdef __cplusplus
10 #define XGB_EXTERN_C extern "C"
11 #include <cstddef>
12 #include <cstdint>
13 #include <cstdio>
14 #else
15 #define XGB_EXTERN_C
16 #include <stddef.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #endif // __cplusplus
20
21 #if defined(_MSC_VER) || defined(_WIN32)
22 #define XGB_DLL XGB_EXTERN_C __declspec(dllexport)
23 #else
24 #define XGB_DLL XGB_EXTERN_C __attribute__((visibility("default")))
25 #endif // defined(_MSC_VER) || defined(_WIN32)
26
27 // manually define unsigned long
28 typedef uint64_t bst_ulong; // NOLINT(*)
29
30 /**
31 * @mainpage
32 *
33 * @brief XGBoost C API reference.
34 *
35 * For the official document page see:
36 * <a href="https://xgboost.readthedocs.io/en/stable/c.html">XGBoost C Package</a>.
37 */
38
39 /**
40 * @defgroup Library Library
41 *
42 * These functions are used to obtain general information about XGBoost including version,
43 * build info and current global configuration.
44 *
45 * @{
46 */
47
48 /** @brief Handle to the DMatrix */
49 typedef void *DMatrixHandle; // NOLINT(*)
50 /** @brief Handle to the Booster */
51 typedef void *BoosterHandle; // NOLINT(*)
52 /**
53 * @brief Handle to the categories container.
54 *
55 * @since 3.2.0
56 */
57 typedef void *CategoriesHandle; // NOLINT(*)
58
59 /**
60 * @brief Return the version of the XGBoost library.
61 *
62 * The output variable is only written if it's not NULL.
63 *
64 * @param major Store the major version number.
65 * @param minor Store the minor version number.
66 * @param patch Store the patch (revision) number.
67 */
68 XGB_DLL void XGBoostVersion(int *major, int *minor, int *patch);
69
70 /**
71 * @brief Get compile information of the shared XGBoost library.
72 *
73 * @param out string encoded JSON object containing build flags and dependency versions.
74 *
75 * @return 0 when success, -1 when failure happens
76 */
77 XGB_DLL int XGBuildInfo(char const **out);
78
79 /**
80 * @brief Get the string message of the last error.
81 *
82 * Most functions in XGBoost returns 0 when success and non-zero when an error
83 * occurred. In the case of error, @ref XGBGetLastError can be used to retrieve the
84 * error message
85 *
86 * This function is thread safe.
87 *
88 * @return The error message from the last error.
89 */
90 XGB_DLL const char *XGBGetLastError();
91
92 /**
93 * @brief register callback function for LOG(INFO) messages -- helpful messages
94 * that are not errors.
95 *
96 * @note This function can be called by multiple threads. The callback function
97 * will run on the thread that registered it.
98 *
99 * @return 0 when success, -1 when failure happens
100 */
101 XGB_DLL int XGBRegisterLogCallback(void (*callback)(const char *));
102
103 /**
104 * @brief Set global configuration (collection of parameters that apply globally). This function
105 * accepts the list of key-value pairs representing the global-scope parameters to be
106 * configured. The list of key-value pairs are passed in as a JSON string.
107 * @param config a JSON string representing the list of key-value pairs. The JSON object shall
108 * be flat: no value can be a JSON object or an array.
109 * @return 0 when success, -1 when failure happens
110 */
111 XGB_DLL int XGBSetGlobalConfig(char const *config);
112
113 /**
114 * @brief Get current global configuration (collection of parameters that apply globally).
115 * @param out_config pointer to received returned global configuration, represented as a JSON string.
116 * @return 0 when success, -1 when failure happens
117 */
118 XGB_DLL int XGBGetGlobalConfig(char const **out_config);
119
120 /**@}*/
121
122 /**
123 * @defgroup DMatrix DMatrix
124 *
125 * @brief DMatrix is the basic data storage for XGBoost used by all XGBoost algorithms
126 * including both training, prediction and explanation. There are a few variants of
127 * `DMatrix` including normal `DMatrix`, which is a CSR matrix, `QuantileDMatrix`,
128 * which is used by histogram-based tree methods for saving memory, and lastly the
129 * experimental external-memory-based DMatrix, which reads data in batches during
130 * training. For the last two variants, see the @ref Streaming group.
131 *
132 * @{
133 */
134
135 /**
136 * @brief load a data matrix
137 *
138 * @deprecated since 2.0.0
139 * @see XGDMatrixCreateFromURI()
140 * @param fname the name of the file
141 * @param silent whether print messages during loading
142 * @param out a loaded data matrix
143 *
144 * @return 0 when success, -1 when failure happens
145 */
146 XGB_DLL int XGDMatrixCreateFromFile(const char *fname, int silent, DMatrixHandle *out);
147
148 /**
149 * @brief load a data matrix
150 *
151 * @param config JSON encoded parameters for DMatrix construction. Accepted fields are:
152 * - uri: The URI of the input file. The URI parameter `format` is required when loading text data.
153 * @verbatim embed:rst:leading-asterisk
154 * See :doc:`/tutorials/input_format` for more info.
155 * @endverbatim
156 * - silent (optional): Whether to print message during loading. Default to true.
157 * - data_split_mode (optional): Whether the file was split by row or column beforehand for distributed computing. Default to row.
158 * @param out a loaded data matrix
159 * @return 0 when success, -1 when failure happens
160 */
161 XGB_DLL int XGDMatrixCreateFromURI(char const *config, DMatrixHandle *out);
162
163 /**
164 * @brief Create a DMatrix from columnar data. (table)
165 *
166 * A special type of input to the `DMatrix` is the columnar format, which refers to
167 * column-based dataframes. XGBoost can accept both numeric data types like integers and
168 * floats, along with the categorical type, called dictionary in arrow's term. The
169 * addition of categorical type is introduced in 3.1.0. The dataframe is represented by a
170 * list array interfaces with one object for each column.
171 *
172 * A categorical type is represented by 3 buffers, the validity mask, the names of the
173 * categories (called index for most of the dataframe implementation), and the codes used
174 * to represent the categories in the rows. XGBoost consumes a categorical column by
175 * accepting two JSON-encoded arrow arrays in a list. The first item in the list is a JSON
176 * object with `{"offsets": IntegerArray, "values": StringArray }` representing the string
177 * names defined by the arrow columnar format. The second buffer is an masked integer
178 * array that stores the categorical codes along with the validity mask:
179 *
180 * @code{javascript}
181 * [
182 * // categorical column, represented as an array (list)
183 * [
184 * {
185 * 'offsets':
186 * {
187 * 'data': (129412626415808, True),
188 * 'typestr': '<i4', 'version': 3, 'strides': None, 'shape': (3,), 'mask': None
189 * },
190 * 'values':
191 * {
192 * 'data': (129412626416000, True),
193 * 'typestr': '<i1', 'version': 3, 'strides': None, 'shape': (7,), 'mask': None
194 * }
195 * },
196 * {
197 * 'data': (106200854378448, True),
198 * 'typestr': '<i1', 'version': 3, 'strides': None, 'shape': (2,), 'mask': None
199 * }
200 * ],
201 * // numeric column, represented as an object, same number of rows as the previous column (2)
202 * {
203 * 'data': (106200854378448, True),
204 * 'typestr': '<f4', 'version': 3, 'strides': None, 'shape': (2,), 'mask': None
205 * }
206 * ]
207 * @endcode
208 *
209 * As for numeric inputs, it's the same as dense array.
210 *
211 * @param data A list of JSON-encoded array interfaces.
212 * @param config See @ref XGDMatrixCreateFromDense for details.
213 * @param out The created DMatrix.
214 *
215 * @return 0 when success, -1 when failure happens
216 */
217 XGB_DLL int XGDMatrixCreateFromColumnar(char const *data, char const *config, DMatrixHandle *out);
218
219 /**
220 * @example c-api-demo.c
221 */
222 /**
223 * @brief Create a DMatrix from CSR matrix.
224 * @param indptr JSON encoded __array_interface__ to row pointers in CSR.
225 * @param indices JSON encoded __array_interface__ to column indices in CSR.
226 * @param data JSON encoded __array_interface__ to values in CSR.
227 * @param ncol The number of columns.
228 * @param config See @ref XGDMatrixCreateFromDense for details.
229 * @param out The created dmatrix
230 *
231 * @return 0 when success, -1 when failure happens
232 */
233 XGB_DLL int XGDMatrixCreateFromCSR(char const *indptr, char const *indices, char const *data,
234 bst_ulong ncol, char const *config, DMatrixHandle *out);
235
236 /**
237 * @brief Create a DMatrix from dense array.
238 *
239 * The array interface is defined in https://numpy.org/doc/2.1/reference/arrays.interface.html
240 * We encode the interface as a JSON object.
241 *
242 * @param data JSON encoded __array_interface__ to array values.
243 * @param config JSON encoded configuration. Required values are:
244 * - missing: Which value to represent missing value.
245 * - nthread (optional): Number of threads used for initializing DMatrix.
246 * - data_split_mode (optional): Whether the data was split by row or column beforehand. Default to row.
247 * @param out The created DMatrix
248 *
249 * @return 0 when success, -1 when failure happens
250 */
251 XGB_DLL int XGDMatrixCreateFromDense(char const *data, char const *config, DMatrixHandle *out);
252
253 /**
254 * @brief Create a DMatrix from a CSC matrix.
255 *
256 * @param indptr JSON encoded __array_interface__ to column pointers in CSC.
257 * @param indices JSON encoded __array_interface__ to row indices in CSC.
258 * @param data JSON encoded __array_interface__ to values in CSC.
259 * @param nrow The number of rows in the matrix.
260 * @param config See @ref XGDMatrixCreateFromDense for details.
261 * @param out The created dmatrix.
262 *
263 * @return 0 when success, -1 when failure happens
264 */
265 XGB_DLL int XGDMatrixCreateFromCSC(char const *indptr, char const *indices, char const *data,
266 bst_ulong nrow, char const *config, DMatrixHandle *out);
267
268 /**
269 * @brief create matrix content from dense matrix
270 * @param data pointer to the data space
271 * @param nrow number of rows
272 * @param ncol number columns
273 * @param missing which value to represent missing value
274 * @param out created dmatrix
275 * @return 0 when success, -1 when failure happens
276 */
277 XGB_DLL int XGDMatrixCreateFromMat(const float *data, bst_ulong nrow, bst_ulong ncol, float missing,
278 DMatrixHandle *out);
279 /**
280 * @brief create matrix content from dense matrix
281 * @param data pointer to the data space
282 * @param nrow number of rows
283 * @param ncol number columns
284 * @param missing which value to represent missing value
285 * @param out created dmatrix
286 * @param nthread number of threads (up to maximum cores available, if <=0 use all cores)
287 * @return 0 when success, -1 when failure happens
288 */
289 XGB_DLL int XGDMatrixCreateFromMat_omp(const float *data, // NOLINT
290 bst_ulong nrow, bst_ulong ncol, float missing,
291 DMatrixHandle *out, int nthread);
292
293 /**
294 * @brief Create DMatrix from CUDA columnar format. (cuDF)
295 *
296 * See @ref XGDMatrixCreateFromColumnar for a brief description of the columnar format.
297 *
298 * @param data A list of JSON-encoded array interfaces.
299 * @param config See @ref XGDMatrixCreateFromDense for details.
300 * @param out Created dmatrix
301 *
302 * @return 0 when success, -1 when failure happens
303 */
304 XGB_DLL int XGDMatrixCreateFromCudaColumnar(char const *data, char const *config,
305 DMatrixHandle *out);
306
307 /**
308 * @brief Create DMatrix from CUDA array.
309 * @param data JSON encoded __cuda_array_interface__ for array data.
310 * @param config JSON encoded configuration. Required values are:
311 * - missing: Which value to represent missing value.
312 * - nthread (optional): Number of threads used for initializing DMatrix.
313 * - data_split_mode (optional): Whether the data was split by row or column beforehand. Default to row.
314 * @param out created dmatrix
315 * @return 0 when success, -1 when failure happens
316 */
317 XGB_DLL int XGDMatrixCreateFromCudaArrayInterface(char const *data, char const *config,
318 DMatrixHandle *out);
319
320 /**
321 * @defgroup Streaming Streaming
322 * @ingroup DMatrix
323 *
324 * @brief Quantile DMatrix and external memory DMatrix can be created from batches of
325 * data.
326 *
327 * There are 2 sets of data callbacks for DMatrix. The first one is currently exclusively
328 * used by JVM packages. It uses `XGBoostBatchCSR` to accept batches for CSR formated
329 * input, and concatenate them into 1 final big CSR. The related functions are:
330 *
331 * - @ref XGBCallbackSetData
332 * - @ref XGBCallbackDataIterNext
333 * - @ref XGDMatrixCreateFromDataIter
334 *
335 * Another set is used by external data iterator. It accepts foreign data iterators as
336 * callbacks. There are 2 different senarios where users might want to pass in callbacks
337 * instead of raw data. First it's the Quantile DMatrix used by the hist and GPU-based
338 * hist tree method. For this case, the data is first compressed by quantile sketching
339 * then merged. This is particular useful for distributed setting as it eliminates 2
340 * copies of data. First one by a `concat` from external library to make the data into a
341 * blob for normal DMatrix initialization, another one by the internal CSR copy of
342 * DMatrix.
343 *
344 * The second use case is external memory support where users can pass a custom data
345 * iterator into XGBoost for loading data in batches. For both cases, the iterator is only
346 * used during the construction of the DMatrix and can be safely freed after construction
347 * finishes. There are short notes on each of the use cases in respected DMatrix factory
348 * function.
349 *
350 * Related functions are:
351 *
352 * # Factory functions
353 * - @ref XGDMatrixCreateFromCallback for external memory
354 * - @ref XGQuantileDMatrixCreateFromCallback for quantile DMatrix
355 * - @ref XGExtMemQuantileDMatrixCreateFromCallback for External memory Quantile DMatrix
356 *
357 * # Proxy that callers can use to pass data to XGBoost
358 * - @ref XGProxyDMatrixCreate
359 * - @ref XGDMatrixCallbackNext
360 * - @ref DataIterResetCallback
361 * - @ref XGProxyDMatrixSetDataCudaArrayInterface
362 * - @ref XGProxyDMatrixSetDataColumnar
363 * - @ref XGProxyDMatrixSetDataCudaColumnar
364 * - @ref XGProxyDMatrixSetDataDense
365 * - @ref XGProxyDMatrixSetDataCSR
366 * - ... (data setters)
367 *
368 * @{
369 */
370
371 /* ==== First set of callback functions, used exclusively by JVM packages. ==== */
372
373 /** @brief handle to a external data iterator */
374 typedef void *DataIterHandle; // NOLINT(*)
375 /** @brief handle to an internal data holder. */
376 typedef void *DataHolderHandle; // NOLINT(*)
377
378 /** @brief Mini batch used in XGBoost Data Iteration */
379 typedef struct { // NOLINT(*)
380 /** @brief number of rows in the minibatch */
381 size_t size;
382 /** @brief number of columns in the minibatch. */
383 size_t columns;
384 /** @brief row pointer to the rows in the data */
385 #ifdef __APPLE__
386 /* Necessary as Java on MacOS defines jlong as long int
387 * and gcc defines int64_t as long long int. */
388 long *offset; // NOLINT(*)
389 #else
390 int64_t *offset; // NOLINT(*)
391 #endif // __APPLE__
392 /** @brief labels of each instance */
393 float *label;
394 /** @brief weight of each instance, can be NULL */
395 float *weight;
396 /** @brief feature index */
397 int *index;
398 /** @brief feature values */
399 float *value;
400 } XGBoostBatchCSR;
401
402 /**
403 * @brief Callback to set the data to handle,
404 * @param handle The handle to the callback.
405 * @param batch The data content to be set.
406 */
407 XGB_EXTERN_C typedef int XGBCallbackSetData( // NOLINT(*)
408 DataHolderHandle handle, XGBoostBatchCSR batch);
409
410 /**
411 * @brief The data reading callback function.
412 * The iterator will be able to give subset of batch in the data.
413 *
414 * If there is data, the function will call set_function to set the data.
415 *
416 * @param data_handle The handle to the callback.
417 * @param set_function The batch returned by the iterator
418 * @param set_function_handle The handle to be passed to set function.
419 * @return 0 if we are reaching the end and batch is not returned.
420 */
421 XGB_EXTERN_C typedef int XGBCallbackDataIterNext( // NOLINT(*)
422 DataIterHandle data_handle, XGBCallbackSetData *set_function,
423 DataHolderHandle set_function_handle);
424
425 /**
426 * @brief Create a DMatrix from a data iterator.
427 * @param data_handle The handle to the data.
428 * @param callback The callback to get the data.
429 * @param cache_info Additional information about cache file, can be null.
430 * @param missing Which value to represent missing value.
431 * @param out The created DMatrix
432 * @return 0 when success, -1 when failure happens.
433 */
434 XGB_DLL int XGDMatrixCreateFromDataIter(DataIterHandle data_handle,
435 XGBCallbackDataIterNext *callback, const char *cache_info,
436 float missing, DMatrixHandle *out);
437
438 /**
439 * Second set of callback functions, used by constructing Quantile DMatrix or external
440 * memory DMatrix using a custom iterator.
441 */
442
443 /**
444 * @brief Create a DMatrix proxy for setting data, can be freed by @ref XGDMatrixFree.
445 *
446 * The DMatrix proxy is only a temporary reference (wrapper) to the actual user data. For
447 * instance, if a dense matrix (like a numpy array) is passed into the proxy DMatrix via
448 * the @ref XGProxyDMatrixSetDataDense method, then the proxy DMatrix holds only a
449 * reference and the input array cannot be freed until the next iteration starts, signaled
450 * by a call to the @ref XGDMatrixCallbackNext by XGBoost. It's called `ProxyDMatrix`
451 * because it reuses the interface of the DMatrix class in XGBoost, but it's just a mid
452 * interface for the @ref XGDMatrixCreateFromCallback and related constructors to consume
453 * various user input types.
454 *
455 * @code{.unparsed}
456 * User inputs -> Proxy DMatrix (wrapper) -> Actual DMatrix
457 * @endcode
458 *
459 * @param out The created Proxy DMatrix.
460 *
461 * @return 0 when success, -1 when failure happens.
462 */
463 XGB_DLL int XGProxyDMatrixCreate(DMatrixHandle *out);
464
465 /**
466 * @brief Callback function prototype for getting next batch of data.
467 *
468 * @param iter A handler to the user defined iterator.
469 *
470 * @return 0 when success, -1 when failure happens.
471 */
472 XGB_EXTERN_C typedef int XGDMatrixCallbackNext(DataIterHandle iter); // NOLINT(*)
473
474 /**
475 * @brief Callback function prototype for resetting the external iterator.
476 */
477 XGB_EXTERN_C typedef void DataIterResetCallback(DataIterHandle handle); // NOLINT(*)
478
479 /**
480 * @brief Create an external memory DMatrix with data iterator.
481 *
482 * Short note for how to use second set of callback for external memory data support:
483 *
484 * - Step 0: Define a data iterator with 2 methods `reset`, and `next`.
485 * - Step 1: Create a DMatrix proxy by \ref XGProxyDMatrixCreate and hold the handle.
486 * - Step 2: Pass the iterator handle, proxy handle and 2 methods into
487 * \ref XGDMatrixCreateFromCallback, along with other parameters encoded as a JSON object.
488 * - Step 3: Call appropriate data setters in `next` functions.
489 *
490 * @param iter A handle to external data iterator.
491 * @param proxy A DMatrix proxy handle created by \ref XGProxyDMatrixCreate.
492 * @param reset Callback function resetting the iterator state.
493 * @param next Callback function yielding the next batch of data.
494 * @param config JSON encoded parameters for DMatrix construction. Accepted fields are:
495 * - missing: Which value to represent missing value
496 * - cache_prefix: The path of cache file, caller must initialize all the directories in this path.
497 * - nthread (optional): Number of threads used for initializing DMatrix.
498 * @param[out] out The created external memory DMatrix
499 *
500 * @return 0 when success, -1 when failure happens
501 */
502 XGB_DLL int XGDMatrixCreateFromCallback(DataIterHandle iter, DMatrixHandle proxy,
503 DataIterResetCallback *reset, XGDMatrixCallbackNext *next,
504 char const *config, DMatrixHandle *out);
505 /**
506 * @example external_memory.c
507 */
508
509 /**
510 * @brief Create a Quantile DMatrix with a data iterator.
511 *
512 * Short note for how to use the second set of callback for (GPU)Hist tree method:
513 *
514 * - Step 0: Define a data iterator with 2 methods `reset`, and `next`.
515 * - Step 1: Create a DMatrix proxy by @ref XGProxyDMatrixCreate and hold the handle.
516 * - Step 2: Pass the iterator handle, proxy handle and 2 methods into
517 * @ref XGQuantileDMatrixCreateFromCallback.
518 * - Step 3: Call appropriate data setters in `next` functions.
519 *
520 * See test_iterative_dmatrix.cu or Python interface for examples.
521 *
522 * @param iter A handle to external data iterator.
523 * @param proxy A DMatrix proxy handle created by @ref XGProxyDMatrixCreate.
524 * @param ref Reference DMatrix for providing quantile information.
525 * @param reset Callback function resetting the iterator state.
526 * @param next Callback function yielding the next batch of data.
527 * @param config JSON encoded parameters for DMatrix construction. Accepted fields are:
528 * - missing: Which value to represent missing value
529 * - nthread (optional): Number of threads used for initializing DMatrix.
530 * - max_bin (optional): Maximum number of bins for building histogram. Must be consistent with
531 * the corresponding booster training parameter.
532 * - max_quantile_blocks (optional): For GPU-based inputs, XGBoost handles incoming
533 * batches with multiple growing substreams. This parameter sets the maximum number
534 * of batches before XGBoost can cut the sub-stream and create a new one. This can
535 * help bound the memory usage. By default, XGBoost grows new sub-streams
536 * exponentially until batches are exhausted. Only used for the training dataset and
537 * the default is None (unbounded).
538 * @param out The created Quantile DMatrix.
539 *
540 * @return 0 when success, -1 when failure happens
541 */
542 XGB_DLL int XGQuantileDMatrixCreateFromCallback(DataIterHandle iter, DMatrixHandle proxy,
543 DataIterHandle ref, DataIterResetCallback *reset,
544 XGDMatrixCallbackNext *next, char const *config,
545 DMatrixHandle *out);
546
547 /**
548 * @brief Create a Quantile DMatrix backed by external memory.
549 *
550 * @since 3.0.0
551 *
552 * @note This is experimental and subject to change.
553 *
554 * @verbatim embed:rst:leading-asterisk
555 * See :doc:`/tutorials/external_memory` for more info.
556 * @endverbatim
557 *
558 * @param iter A handle to external data iterator.
559 * @param proxy A DMatrix proxy handle created by @ref XGProxyDMatrixCreate.
560 * @param ref Reference DMatrix for providing quantile information.
561 * @param reset Callback function resetting the iterator state.
562 * @param next Callback function yielding the next batch of data.
563 * @param config JSON encoded parameters for DMatrix construction. Accepted fields are:
564 * - missing: Which value to represent missing value
565 * - cache_prefix: The path of cache file, caller must initialize all the directories in this path.
566 * - nthread (optional): Number of threads used for initializing DMatrix.
567 * - max_bin (optional): Maximum number of bins for building histogram. Must be consistent with
568 * the corresponding booster training parameter.
569 * - on_host (optional): Whether the data should be placed on host memory. Used by GPU inputs.
570 * - min_cache_page_bytes (optional): The minimum number of bytes for each internal GPU
571 * page. Set to 0 to disable page concatenation. Automatic configuration if the
572 * parameter is not provided or set to None.
573 * - max_quantile_blocks (optional): For GPU-based inputs, XGBoost handles incoming
574 * batches with multiple growing substreams. This parameter sets the maximum number
575 * of batches before XGBoost can cut the sub-stream and create a new one. This can
576 * help bound the memory usage. By default, XGBoost grows new sub-streams
577 * exponentially until batches are exhausted. Only used for the training dataset and
578 * the default is None (unbounded).
579 * - cache_host_ratio (optioinal): For GPU-based inputs, XGBoost can split the cache into
580 * host and device portitions to reduce the data transfer overhead. This parameter
581 * specifies the size of host cache compared to the size of the entire cache:
582 * `host / (host + device)`.
583 * @param out The created Quantile DMatrix.
584 *
585 * @return 0 when success, -1 when failure happens
586 */
587 XGB_DLL int XGExtMemQuantileDMatrixCreateFromCallback(DataIterHandle iter, DMatrixHandle proxy,
588 DataIterHandle ref,
589 DataIterResetCallback *reset,
590 XGDMatrixCallbackNext *next,
591 char const *config, DMatrixHandle *out);
592
593 /**
594 * @brief Set data on a DMatrix proxy.
595 *
596 * @param handle A DMatrix proxy created by @ref XGProxyDMatrixCreate
597 * @param data Null terminated JSON document string representation of CUDA
598 * array interface.
599 *
600 * @return 0 when success, -1 when failure happens
601 */
602 XGB_DLL int XGProxyDMatrixSetDataCudaArrayInterface(DMatrixHandle handle, const char *data);
603
604 /**
605 * @brief Set columnar (table) data on a DMatrix proxy.
606 *
607 * @param handle A DMatrix proxy created by @ref XGProxyDMatrixCreate
608 * @param data See @ref XGDMatrixCreateFromColumnar for details.
609 *
610 * @return 0 when success, -1 when failure happens
611 */
612 XGB_DLL int XGProxyDMatrixSetDataColumnar(DMatrixHandle handle, char const *data);
613
614 /**
615 * @brief Set CUDA-based columnar (table) data on a DMatrix proxy.
616 *
617 * @param handle A DMatrix proxy created by @ref XGProxyDMatrixCreate
618 * @param data See @ref XGDMatrixCreateFromColumnar for details.
619 *
620 * @return 0 when success, -1 when failure happens
621 */
622 XGB_DLL int XGProxyDMatrixSetDataCudaColumnar(DMatrixHandle handle, const char *data);
623
624 /**
625 * @brief Set data on a DMatrix proxy.
626 *
627 * @param handle A DMatrix proxy created by @ref XGProxyDMatrixCreate
628 * @param data Null terminated JSON document string representation of array
629 * interface.
630 *
631 * @return 0 when success, -1 when failure happens
632 */
633 XGB_DLL int XGProxyDMatrixSetDataDense(DMatrixHandle handle, char const *data);
634
635 /**
636 * @brief Set data on a DMatrix proxy.
637 *
638 * @param handle A DMatrix proxy created by \ref XGProxyDMatrixCreate
639 * @param indptr JSON encoded __array_interface__ to row pointer in CSR.
640 * @param indices JSON encoded __array_interface__ to column indices in CSR.
641 * @param data JSON encoded __array_interface__ to values in CSR..
642 * @param ncol The number of columns of input CSR matrix.
643 *
644 * @return 0 when success, -1 when failure happens
645 */
646 XGB_DLL int XGProxyDMatrixSetDataCSR(DMatrixHandle handle, char const *indptr, char const *indices,
647 char const *data, bst_ulong ncol);
648
649 /** @} */ // End of Streaming
650
651 /**
652 * @brief create a new dmatrix from sliced content of existing matrix
653 * @param handle instance of data matrix to be sliced
654 * @param idxset index set
655 * @param len length of index set
656 * @param out a sliced new matrix
657 * @return 0 when success, -1 when failure happens
658 */
659 XGB_DLL int XGDMatrixSliceDMatrix(DMatrixHandle handle, const int *idxset, bst_ulong len,
660 DMatrixHandle *out);
661 /**
662 * @brief create a new dmatrix from sliced content of existing matrix
663 * @param handle instance of data matrix to be sliced
664 * @param idxset index set
665 * @param len length of index set
666 * @param out a sliced new matrix
667 * @param allow_groups allow slicing of an array with groups
668 * @return 0 when success, -1 when failure happens
669 */
670 XGB_DLL int XGDMatrixSliceDMatrixEx(DMatrixHandle handle, const int *idxset, bst_ulong len,
671 DMatrixHandle *out, int allow_groups);
672 /**
673 * @brief Free a DMatrix object.
674 *
675 * @return 0 when success, -1 when failure happens
676 */
677 XGB_DLL int XGDMatrixFree(DMatrixHandle handle);
678 /**
679 * @example c-api-demo.c inference.c external_memory.c
680 */
681
682 /**
683 * @brief Save the DMatrix object into a file. `QuantileDMatrix` and external memory
684 * DMatrix are not supported.
685 *
686 * @param handle a instance of data matrix
687 * @param fname File name
688 * @param silent print statistics when saving
689 *
690 * @return 0 when success, -1 when failure happens
691 */
692 XGB_DLL int XGDMatrixSaveBinary(DMatrixHandle handle, const char *fname, int silent);
693
694 /**
695 * @brief Set content in array interface to a content in info.
696 *
697 * @param handle An instance of data matrix
698 * @param field Field name.
699 * @param data JSON encoded __array_interface__ to values in the dense matrix/vector.
700 *
701 * @return 0 when success, -1 when failure happens
702 */
703 XGB_DLL int XGDMatrixSetInfoFromInterface(DMatrixHandle handle, char const *field,
704 char const *data);
705
706 /**
707 * @brief set float vector to a content in info
708 * @param handle a instance of data matrix
709 * @param field field name, can be label, weight
710 * @param array pointer to float vector
711 * @param len length of array
712 * @return 0 when success, -1 when failure happens
713 */
714 XGB_DLL int XGDMatrixSetFloatInfo(DMatrixHandle handle, const char *field, const float *array,
715 bst_ulong len);
716 /**
717 * @deprecated since 2.1.0
718 *
719 * Use @ref XGDMatrixSetInfoFromInterface instead.
720 */
721 XGB_DLL int XGDMatrixSetUIntInfo(DMatrixHandle handle, const char *field, const unsigned *array,
722 bst_ulong len);
723
724 /**
725 * @brief Set string encoded information of all features.
726 *
727 * Accepted fields are:
728 * - feature_name
729 * - feature_type
730 *
731 * @param handle An instance of data matrix
732 * @param field Field name
733 * @param features Pointer to array of strings.
734 * @param size Size of `features` pointer (number of strings passed in).
735 *
736 * @return 0 when success, -1 when failure happens
737 *
738 * @code{c}
739 *
740 * char const* feat_names [] {"feat_0", "feat_1"};
741 * XGDMatrixSetStrFeatureInfo(handle, "feature_name", feat_names, 2);
742 *
743 * // i for integer, q for quantitive, c for categorical. Similarly "int" and "float"
744 * // are also recognized.
745 * char const* feat_types [] {"i", "q"};
746 * XGDMatrixSetStrFeatureInfo(handle, "feature_type", feat_types, 2);
747 *
748 * @endcode
749 */
750 XGB_DLL int XGDMatrixSetStrFeatureInfo(DMatrixHandle handle, const char *field,
751 const char **features, const bst_ulong size);
752
753 /**
754 * @brief Get string encoded information of all features.
755 *
756 * Accepted fields are:
757 * - feature_name
758 * - feature_type
759 *
760 * Caller is responsible for copying out the data, before next call to any API function of
761 * XGBoost.
762 *
763 * @param handle An instance of data matrix
764 * @param field Field name
765 * @param size Size of output pointer `features` (number of strings returned).
766 * @param out_features Address of a pointer to array of strings. Result is stored in
767 * thread local memory.
768 *
769 * @return 0 when success, -1 when failure happens
770 *
771 * @code{c}
772 *
773 * char const **c_out_features = NULL;
774 * bst_ulong out_size = 0;
775 *
776 * // Asumming the feature names are already set by `XGDMatrixSetStrFeatureInfo`.
777 * XGDMatrixGetStrFeatureInfo(handle, "feature_name", &out_size,
778 * &c_out_features)
779 *
780 * for (bst_ulong i = 0; i < out_size; ++i) {
781 * // Here we are simply printing the string. Copy it out if the feature name is
782 * // useful after printing.
783 * printf("feature %lu: %s\n", i, c_out_features[i]);
784 * }
785 *
786 * @endcode
787 */
788 XGB_DLL int XGDMatrixGetStrFeatureInfo(DMatrixHandle handle, const char *field, bst_ulong *size,
789 const char ***out_features);
790
791 /**
792 * @brief Create an opaque handle to the internal category container.
793 *
794 * @since 3.2.0
795 *
796 * @note Experimental API, subject to change in the future.
797 *
798 * The container should be freed by @ref XGBCategoriesFree
799 *
800 * @param handle An instance of the data matrix.
801 * @param config Unused, reserved for the future.
802 * @param out Created handle to the category container. Set to NULL if there's no category.
803 *
804 * @return 0 when success, -1 when failure happens.
805 *
806 * @code{c}
807 * DMatrixHandle fmat;
808 * // Create a DMatrix from categorical data
809 * // ...
810 * CategoriesHandle cats;
811 * int err = XGBoosterGetCategories(fmat, NULL, &cats)
812 * if (err != 0) {
813 * exit(-1);
814 * }
815 * err = XGBCategoriesFree(cats);
816 * if (err != 0) {
817 * exit(-1);
818 * }
819 * @endcode
820 */
821 XGB_DLL int XGDMatrixGetCategories(DMatrixHandle handle, char const *config, CategoriesHandle *out);
822
823 /**
824 * @brief Create an opaque handle to the internal container and export it to arrow.
825 *
826 * @since 3.2.0
827 *
828 * @note Experimental API, subject to change in the future.
829 *
830 * The container should be freed by @ref XGBCategoriesFree
831 *
832 * @param handle An instance of the data matrix.
833 * @param config Unused, reserved for the future.
834 * @param out Created handle to the category container
835 * @param export_out JSON encoded array of categories, with length equal to the number of features.
836 *
837 * @return 0 when success, -1 when failure happens.
838 */
839 XGB_DLL int XGDMatrixGetCategoriesExportToArrow(DMatrixHandle handle, char const *config,
840 CategoriesHandle *out, char const **export_out);
841
842 /**
843 * @brief Free the opaque handle.
844 *
845 * @since 3.2.0
846 *
847 * @note Experimental API, subject to change in the future.
848 *
849 * @param handle An instance of the category container.
850 *
851 * @return 0 when success, -1 when failure happens.
852 */
853 XGB_DLL int XGBCategoriesFree(CategoriesHandle handle);
854
855 /**
856 * @deprecated since 2.1.0
857 *
858 * Use @ref XGDMatrixSetInfoFromInterface instead.
859 */
860 XGB_DLL int XGDMatrixSetDenseInfo(DMatrixHandle handle, const char *field, void const *data,
861 bst_ulong size, int type);
862
863 /**
864 * @brief Get a reference to data like label or weight.
865 *
866 * This method replaces the existing @ref XGDMatrixGetFloatInfo and @ref
867 * XGDMatrixGetUIntInfo to support non-vector (like a matrix) output. The output data
868 * directly references the internal storage, as a result, it's read-only and user should
869 * copy data before the next XGBoost call.
870 *
871 * @since 3.2.0
872 *
873 * @param handle An instance of data matrix
874 * @param field Field name
875 * @param out_array JSON encoded __(cuda)_array_interface__ to the output.
876 *
877 * @return 0 when success, -1 when failure happens
878 */
879 XGB_DLL int XGDMatrixGetInfoRef(DMatrixHandle handle, char const *field, char const **out_array);
880
881 /**
882 * @brief get float info vector from matrix.
883 * @param handle a instance of data matrix
884 * @param field field name
885 * @param out_len used to set result length
886 * @param out_dptr pointer to the result
887 * @return 0 when success, -1 when failure happens
888 */
889 XGB_DLL int XGDMatrixGetFloatInfo(const DMatrixHandle handle, const char *field, bst_ulong *out_len,
890 const float **out_dptr);
891 /**
892 * @example c-api-demo.c
893 */
894
895 /**
896 * @brief get uint32 info vector from matrix
897 * @param handle a instance of data matrix
898 * @param field field name
899 * @param out_len The length of the field.
900 * @param out_dptr pointer to the result
901 * @return 0 when success, -1 when failure happens
902 */
903 XGB_DLL int XGDMatrixGetUIntInfo(const DMatrixHandle handle, const char *field, bst_ulong *out_len,
904 const unsigned **out_dptr);
905 /**
906 * @brief Get the number of rows from a DMatrix.
907 *
908 * @param handle the handle to the DMatrix
909 * @param out The address to hold number of rows.
910 * @return 0 when success, -1 when failure happens
911 */
912 XGB_DLL int XGDMatrixNumRow(DMatrixHandle handle, bst_ulong *out);
913 /**
914 * @brief Get the number of columns from a DMatrix.
915 *
916 * @param handle the handle to the DMatrix
917 * @param out The output of number of columns
918 * @return 0 when success, -1 when failure happens
919 */
920 XGB_DLL int XGDMatrixNumCol(DMatrixHandle handle, bst_ulong *out);
921
922 /**
923 * @brief Get number of valid values from a DMatrix.
924 *
925 * @param handle the handle to the DMatrix
926 * @param out The output of number of non-missing values
927 *
928 * @return 0 when success, -1 when failure happens
929 */
930 XGB_DLL int XGDMatrixNumNonMissing(DMatrixHandle handle, bst_ulong *out);
931
932 /**
933 * @brief Get the data split mode from DMatrix.
934 *
935 * @param handle the handle to the DMatrix
936 * @param out The output of the data split mode
937 *
938 * @return 0 when success, -1 when failure happens
939 */
940 XGB_DLL int XGDMatrixDataSplitMode(DMatrixHandle handle, bst_ulong *out);
941
942 /**
943 * @brief Get the predictors from DMatrix as CSR matrix for testing. If this is a
944 * quantized DMatrix, quantized values are returned instead.
945 *
946 * Unlike most of XGBoost C functions, caller of `XGDMatrixGetDataAsCSR` is required to
947 * allocate the memory for return buffer instead of using thread local memory from
948 * XGBoost. This is to avoid allocating a huge memory buffer that can not be freed until
949 * exiting the thread.
950 *
951 * @since 1.7.0
952 *
953 * @param handle the handle to the DMatrix
954 * @param config JSON configuration string. At the moment it should be an empty document,
955 * preserved for future use.
956 * @param out_indptr indptr of output CSR matrix.
957 * @param out_indices Column index of output CSR matrix.
958 * @param out_data Data value of CSR matrix.
959 *
960 * @return 0 when success, -1 when failure happens
961 */
962 XGB_DLL int XGDMatrixGetDataAsCSR(DMatrixHandle const handle, char const *config,
963 bst_ulong *out_indptr, unsigned *out_indices, float *out_data);
964
965 /**
966 * @brief Export the quantile cuts used for training histogram-based models like `hist` and
967 * `approx`. Useful for model compression.
968 *
969 * @since 2.0.0
970 *
971 * @param handle the handle to the DMatrix
972 * @param config JSON configuration string. At the moment it should be an empty document,
973 * preserved for future use.
974 *
975 * @param out_indptr indptr of output CSC matrix represented by a JSON encoded
976 * __(cuda_)array_interface__.
977 * @param out_data Data value of CSC matrix represented by a JSON encoded
978 * __(cuda_)array_interface__.
979 */
980 XGB_DLL int XGDMatrixGetQuantileCut(DMatrixHandle const handle, char const *config,
981 char const **out_indptr, char const **out_data);
982
983 /** @} */ // End of DMatrix
984
985 /**
986 * @defgroup Booster Booster
987 *
988 * @brief The `Booster` class is the gradient-boosted model for XGBoost.
989 *
990 * During training, the booster object has many caches for improved performance. In
991 * addition to gradient and prediction, it also includes runtime buffers like leaf
992 * partitions. These buffers persist with the Booster object until either XGBoosterReset()
993 * is called or the booster is deleted by the XGBoosterFree().
994 *
995 * @{
996 */
997
998 /**
999 * @brief Create a XGBoost learner (booster)
1000 *
1001 * @param dmats matrices that are set to be cached by the booster.
1002 * @param len length of dmats
1003 * @param out handle to the result booster
1004 *
1005 * @return 0 when success, -1 when failure happens
1006 */
1007 XGB_DLL int XGBoosterCreate(const DMatrixHandle dmats[], bst_ulong len, BoosterHandle *out);
1008 /**
1009 * @example c-api-demo.c
1010 */
1011
1012 /**
1013 * @brief Delete the booster.
1014 *
1015 * @param handle The handle to be freed.
1016 *
1017 * @return 0 when success, -1 when failure happens
1018 */
1019 XGB_DLL int XGBoosterFree(BoosterHandle handle);
1020 /**
1021 * @example c-api-demo.c inference.c external_memory.c
1022 */
1023
1024 /**
1025 * @brief Reset the booster object to release data caches used for training.
1026 *
1027 * @since 3.0.0
1028 *
1029 * @return 0 when success, -1 when failure happens
1030 */
1031 XGB_DLL int XGBoosterReset(BoosterHandle handle);
1032
1033 /**
1034 * @brief Slice a model using boosting index. The slice m:n indicates taking all trees
1035 * that were fit during the boosting rounds m, (m+1), (m+2), ..., (n-1).
1036 *
1037 * @param handle Booster to be sliced.
1038 * @param begin_layer start of the slice
1039 * @param end_layer end of the slice; end_layer=0 is equivalent to
1040 * end_layer=num_boost_round
1041 * @param step step size of the slice
1042 * @param out Sliced booster.
1043 *
1044 * @return 0 when success, -1 when failure happens, -2 when index is out of bound.
1045 */
1046 XGB_DLL int XGBoosterSlice(BoosterHandle handle, int begin_layer, int end_layer, int step,
1047 BoosterHandle *out);
1048
1049 /**
1050 * @brief Get number of boosted rounds from gradient booster. When process_type is
1051 * update, this number might drop due to removed tree.
1052 * @param handle Handle to booster.
1053 * @param out Pointer to output integer.
1054 * @return 0 when success, -1 when failure happens
1055 */
1056 XGB_DLL int XGBoosterBoostedRounds(BoosterHandle handle, int *out);
1057
1058 /**
1059 * @brief set parameters
1060 * @param handle handle
1061 * @param name parameter name
1062 * @param value value of parameter
1063 * @return 0 when success, -1 when failure happens
1064 */
1065 XGB_DLL int XGBoosterSetParam(BoosterHandle handle, const char *name, const char *value);
1066 /**
1067 * @example c-api-demo.c
1068 */
1069
1070 /**
1071 * @brief get number of features
1072 * @param handle Handle to booster.
1073 * @param out number of features
1074 * @return 0 when success, -1 when failure happens
1075 */
1076 XGB_DLL int XGBoosterGetNumFeature(BoosterHandle handle, bst_ulong *out);
1077 /**
1078 * @example c-api-demo.c
1079 */
1080
1081 /**
1082 * @brief update the model in one round using dtrain
1083 * @param handle handle
1084 * @param iter current iteration rounds
1085 * @param dtrain training data
1086 * @return 0 when success, -1 when failure happens
1087 */
1088 XGB_DLL int XGBoosterUpdateOneIter(BoosterHandle handle, int iter, DMatrixHandle dtrain);
1089 /**
1090 * @example c-api-demo.c
1091 */
1092
1093 /**
1094 * @deprecated since 2.1.0
1095 */
1096 XGB_DLL int XGBoosterBoostOneIter(BoosterHandle handle, DMatrixHandle dtrain, float *grad,
1097 float *hess, bst_ulong len);
1098
1099 /**
1100 * @brief Update a model with gradient and Hessian. This is used for training with a
1101 * custom objective function.
1102 *
1103 * @since 2.0.0
1104 *
1105 * @param handle handle
1106 * @param dtrain The training data.
1107 * @param iter The current iteration round. When training continuation is used, the count
1108 * should restart.
1109 * @param grad Json encoded __(cuda)_array_interface__ for gradient.
1110 * @param hess Json encoded __(cuda)_array_interface__ for Hessian.
1111 *
1112 * @return 0 when success, -1 when failure happens
1113 */
1114 XGB_DLL int XGBoosterTrainOneIter(BoosterHandle handle, DMatrixHandle dtrain, int iter,
1115 char const *grad, char const *hess);
1116
1117 /**
1118 * @brief get evaluation statistics for xgboost
1119 * @param handle handle
1120 * @param iter current iteration rounds
1121 * @param dmats pointers to data to be evaluated
1122 * @param evnames pointers to names of each data
1123 * @param len length of dmats
1124 * @param out_result the string containing evaluation statistics
1125 * @return 0 when success, -1 when failure happens
1126 */
1127 XGB_DLL int XGBoosterEvalOneIter(BoosterHandle handle, int iter, DMatrixHandle dmats[],
1128 const char *evnames[], bst_ulong len, const char **out_result);
1129 /**
1130 * @example c-api-demo.c
1131 */
1132
1133 /**
1134 * @defgroup Prediction Prediction
1135 * @ingroup Booster
1136 *
1137 * @brief These functions are used for running prediction and explanation algorithms.
1138 *
1139 * @{
1140 */
1141
1142 /**
1143 * @brief make prediction based on dmat (deprecated, use \ref XGBoosterPredictFromDMatrix instead)
1144 * \deprecated
1145 * \see XGBoosterPredictFromDMatrix()
1146 *
1147 * @param handle handle
1148 * @param dmat data matrix
1149 * @param option_mask bit-mask of options taken in prediction, possible values
1150 * 0:normal prediction
1151 * 1:output margin instead of transformed value
1152 * 2:output leaf index of trees instead of leaf value, note leaf index is unique per tree
1153 * 4:output feature contributions to individual predictions
1154 * @param ntree_limit limit number of trees used for prediction, this is only valid for boosted trees
1155 * when the parameter is set to 0, we will use all the trees
1156 * @param training Whether the prediction function is used as part of a training loop.
1157 * Prediction can be run in 2 scenarios:
1158 * 1. Given data matrix X, obtain prediction y_pred from the model.
1159 * 2. Obtain the prediction for computing gradients. For example, DART booster performs dropout
1160 * during training, and the prediction result will be different from the one obtained by normal
1161 * inference step due to dropped trees.
1162 * Set training=false for the first scenario. Set training=true for the second scenario.
1163 * The second scenario applies when you are defining a custom objective function.
1164 * @param out_len used to store length of returning result
1165 * @param out_result used to set a pointer to array
1166 * @return 0 when success, -1 when failure happens
1167 */
1168 XGB_DLL int XGBoosterPredict(BoosterHandle handle, DMatrixHandle dmat, int option_mask,
1169 unsigned ntree_limit, int training, bst_ulong *out_len,
1170 const float **out_result);
1171
1172 /**
1173 * @brief Make prediction from DMatrix, replacing \ref XGBoosterPredict.
1174 *
1175 * @param handle Booster handle
1176 * @param dmat DMatrix handle
1177 * @param config String encoded predict configuration in JSON format, with following
1178 * available fields in the JSON object:
1179 *
1180 * "type": [0, 6]
1181 * - 0: normal prediction
1182 * - 1: output margin
1183 * - 2: predict contribution
1184 * - 3: predict approximated contribution
1185 * - 4: predict feature interaction
1186 * - 5: predict approximated feature interaction
1187 * - 6: predict leaf
1188 * "training": bool
1189 * Whether the prediction function is used as part of a training loop. **Not used
1190 * for inplace prediction**.
1191 *
1192 * Prediction can be run in 2 scenarios:
1193 * 1. Given data matrix X, obtain prediction y_pred from the model.
1194 * 2. Obtain the prediction for computing gradients. For example, DART booster performs dropout
1195 * during training, and the prediction result will be different from the one obtained by normal
1196 * inference step due to dropped trees.
1197 * Set training=false for the first scenario. Set training=true for the second
1198 * scenario. The second scenario applies when you are defining a custom objective
1199 * function.
1200 * "iteration_begin": int
1201 * Beginning iteration of prediction.
1202 * "iteration_end": int
1203 * End iteration of prediction. Set to 0 this will become the size of tree model (all the trees).
1204 * "strict_shape": bool
1205 * Whether should we reshape the output with stricter rules. If set to true,
1206 * normal/margin/contrib/interaction predict will output consistent shape
1207 * disregarding the use of multi-class model, and leaf prediction will output 4-dim
1208 * array representing: (n_samples, n_iterations, n_classes, n_trees_in_forest)
1209 *
1210 * Example JSON input for running a normal prediction with strict output shape, 2 dim
1211 * for softprob , 1 dim for others.
1212 * @code{javascript}
1213 * {
1214 * "type": 0,
1215 * "training": false,
1216 * "iteration_begin": 0,
1217 * "iteration_end": 0,
1218 * "strict_shape": true
1219 * }
1220 * @endcode
1221 *
1222 * @param out_shape Shape of output prediction (copy before use).
1223 * @param out_dim Dimension of output prediction.
1224 * @param out_result Buffer storing prediction value (copy before use).
1225 *
1226 * @return 0 when success, -1 when failure happens
1227 *
1228 * @see XGBoosterPredictFromDense XGBoosterPredictFromCSR XGBoosterPredictFromCudaArray XGBoosterPredictFromCudaColumnar
1229 */
1230 XGB_DLL int XGBoosterPredictFromDMatrix(BoosterHandle handle, DMatrixHandle dmat,
1231 char const *config, bst_ulong const **out_shape,
1232 bst_ulong *out_dim, float const **out_result);
1233 /**
1234 * @example inference.c
1235 */
1236
1237 /**
1238 * @brief Inplace prediction from CPU dense matrix.
1239 *
1240 * \note If the booster is configured to run on a CUDA device, XGBoost falls back to run
1241 * prediction with DMatrix with a performance warning.
1242 *
1243 * @param handle Booster handle.
1244 * @param values JSON encoded __array_interface__ to values.
1245 * @param config See \ref XGBoosterPredictFromDMatrix for more info.
1246 * Additional fields for inplace prediction are:
1247 * - "missing": float
1248 * @param m An optional (NULL if not available) proxy DMatrix instance
1249 * storing meta info.
1250 *
1251 * @param out_shape See \ref XGBoosterPredictFromDMatrix for more info.
1252 * @param out_dim See \ref XGBoosterPredictFromDMatrix for more info.
1253 * @param out_result See \ref XGBoosterPredictFromDMatrix for more info.
1254 *
1255 * @return 0 when success, -1 when failure happens
1256 */
1257 XGB_DLL int XGBoosterPredictFromDense(BoosterHandle handle, char const *values, char const *config,
1258 DMatrixHandle m, bst_ulong const **out_shape,
1259 bst_ulong *out_dim, const float **out_result);
1260 /**
1261 * @example inference.c
1262 */
1263
1264 /**
1265 * @brief Inplace prediction from CPU columnar data. (Table)
1266 *
1267 * @note If the booster is configured to run on a CUDA device, XGBoost falls back to run
1268 * prediction with DMatrix with a performance warning.
1269 *
1270 * @param handle Booster handle.
1271 * @param data See @ref XGDMatrixCreateFromColumnar for more info.
1272 * @param config See @ref XGBoosterPredictFromDMatrix for more info.
1273 * Additional fields for inplace prediction are:
1274 * - "missing": float
1275 * @param m An optional (NULL if not available) proxy DMatrix instance
1276 * storing meta info.
1277 *
1278 * @param out_shape See @ref XGBoosterPredictFromDMatrix for more info.
1279 * @param out_dim See @ref XGBoosterPredictFromDMatrix for more info.
1280 * @param out_result See @ref XGBoosterPredictFromDMatrix for more info.
1281 *
1282 * @return 0 when success, -1 when failure happens
1283 */
1284 XGB_DLL int XGBoosterPredictFromColumnar(BoosterHandle handle, char const *values,
1285 char const *config, DMatrixHandle m,
1286 bst_ulong const **out_shape, bst_ulong *out_dim,
1287 const float **out_result);
1288
1289 /**
1290 * @brief Inplace prediction from CPU CSR matrix.
1291 *
1292 * \note If the booster is configured to run on a CUDA device, XGBoost falls back to run
1293 * prediction with DMatrix with a performance warning.
1294 *
1295 * @param handle Booster handle.
1296 * @param indptr JSON encoded __array_interface__ to row pointer in CSR.
1297 * @param indices JSON encoded __array_interface__ to column indices in CSR.
1298 * @param values JSON encoded __array_interface__ to values in CSR..
1299 * @param ncol Number of features in data.
1300 * @param config See \ref XGBoosterPredictFromDMatrix for more info.
1301 * Additional fields for inplace prediction are:
1302 * - "missing": float
1303 * @param m An optional (NULL if not available) proxy DMatrix instance
1304 * storing meta info.
1305 *
1306 * @param out_shape See \ref XGBoosterPredictFromDMatrix for more info.
1307 * @param out_dim See \ref XGBoosterPredictFromDMatrix for more info.
1308 * @param out_result See \ref XGBoosterPredictFromDMatrix for more info.
1309 *
1310 * @return 0 when success, -1 when failure happens
1311 */
1312 XGB_DLL int XGBoosterPredictFromCSR(BoosterHandle handle, char const *indptr, char const *indices,
1313 char const *values, bst_ulong ncol, char const *config,
1314 DMatrixHandle m, bst_ulong const **out_shape,
1315 bst_ulong *out_dim, const float **out_result);
1316
1317 /**
1318 * @brief Inplace prediction from CUDA Dense matrix (cupy in Python).
1319 *
1320 * @note If the booster is configured to run on a CPU, XGBoost falls back to run
1321 * prediction with DMatrix with a performance warning.
1322 *
1323 * @param handle Booster handle
1324 * @param values JSON encoded __cuda_array_interface__ to values.
1325 * @param config See @ref XGBoosterPredictFromDMatrix for more info.
1326 * Additional fields for inplace prediction are:
1327 * - "missing": float
1328 * @param proxy An optional (NULL if not available) proxy DMatrix instance
1329 * storing meta info.
1330 * @param out_shape See @ref XGBoosterPredictFromDMatrix for more info.
1331 * @param out_dim See @ref XGBoosterPredictFromDMatrix for more info.
1332 * @param out_result See @ref XGBoosterPredictFromDMatrix for more info.
1333 *
1334 * @return 0 when success, -1 when failure happens
1335 */
1336 XGB_DLL int XGBoosterPredictFromCudaArray(BoosterHandle handle, char const *values,
1337 char const *config, DMatrixHandle proxy,
1338 bst_ulong const **out_shape, bst_ulong *out_dim,
1339 const float **out_result);
1340
1341 /**
1342 * @brief Inplace prediction from CUDA dense dataframe (cuDF in Python).
1343 *
1344 * @note If the booster is configured to run on a CPU, XGBoost falls back to run
1345 * prediction with DMatrix with a performance warning.
1346 *
1347 * @param handle Booster handle
1348 * @param data See @ref XGDMatrixCreateFromColumnar for more info.
1349 * @param config See @ref XGBoosterPredictFromDMatrix for more info.
1350 * Additional fields for inplace prediction are:
1351 * - "missing": float
1352 * @param proxy An optional (NULL if not available) proxy DMatrix instance
1353 * storing meta info.
1354 * @param out_shape See @ref XGBoosterPredictFromDMatrix for more info.
1355 * @param out_dim See @ref XGBoosterPredictFromDMatrix for more info.
1356 * @param out_result See @ref XGBoosterPredictFromDMatrix for more info.
1357 *
1358 * @return 0 when success, -1 when failure happens
1359 */
1360 XGB_DLL int XGBoosterPredictFromCudaColumnar(BoosterHandle handle, char const *data,
1361 char const *config, DMatrixHandle proxy,
1362 bst_ulong const **out_shape, bst_ulong *out_dim,
1363 const float **out_result);
1364
1365 /**@}*/ // End of Prediction
1366
1367 /**
1368 * @defgroup Serialization Serialization
1369 * @ingroup Booster
1370 *
1371 * @brief There are multiple ways to serialize a Booster object depending on the use case.
1372 *
1373 * Short note for serialization APIs. There are 3 different sets of serialization API.
1374 *
1375 * - Functions with the term "Model" handles saving/loading XGBoost model like trees or
1376 * linear weights. Striping out parameters configuration like training algorithms or
1377 * CUDA device ID. These functions are designed to let users reuse the trained model
1378 * for different tasks, examples are prediction, training continuation or model
1379 * interpretation.
1380 *
1381 * - Functions with the term "Config" handles save/loading configuration. It helps user
1382 * to study the internal of XGBoost. Also user can use the load method for specifying
1383 * parameters in a structured way. These functions were introduced in 1.0.0.
1384 *
1385 * - Functions with the term "Serialization" are combination of above two. They are used
1386 * in situations like check-pointing, or continuing training task in a distributed
1387 * environment. In these cases the task must be carried out without any user
1388 * intervention.
1389 *
1390 * @{
1391 */
1392
1393 /**
1394 * @brief Load the model from an existing file
1395 *
1396 * @param handle handle
1397 * @param fname File name. The string must be UTF-8 encoded.
1398 *
1399 * @return 0 when success, -1 when failure happens
1400 */
1401 XGB_DLL int XGBoosterLoadModel(BoosterHandle handle, const char *fname);
1402 /**
1403 * @brief Save the model into an existing file
1404 *
1405 * @param handle handle
1406 * @param fname File name. The string must be UTF-8 encoded.
1407 *
1408 * @return 0 when success, -1 when failure happens
1409 */
1410 XGB_DLL int XGBoosterSaveModel(BoosterHandle handle, const char *fname);
1411 /**
1412 * @brief load model from in memory buffer
1413 *
1414 * @param handle handle
1415 * @param buf pointer to the buffer
1416 * @param len the length of the buffer
1417 * @return 0 when success, -1 when failure happens
1418 */
1419 XGB_DLL int XGBoosterLoadModelFromBuffer(BoosterHandle handle, const void *buf, bst_ulong len);
1420
1421 /**
1422 * @brief Save model into raw bytes, return header of the array. User must copy the
1423 * result out, before next xgboost call
1424 *
1425 * @param handle handle
1426 * @param config JSON encoded string storing parameters for the function. Following
1427 * keys are expected in the JSON document:
1428 * - "format": str
1429 * - json: Output booster will be encoded as JSON.
1430 * - ubj: Output booster will be encoded as Universal binary JSON.
1431 * this format except for compatibility reasons.
1432 * @param out_len The argument to hold the output length
1433 * @param out_dptr The argument to hold the output data pointer
1434 *
1435 * @return 0 when success, -1 when failure happens
1436 */
1437 XGB_DLL int XGBoosterSaveModelToBuffer(BoosterHandle handle, char const *config, bst_ulong *out_len,
1438 char const **out_dptr);
1439
1440 /**
1441 * @brief Memory snapshot based serialization method. Saves everything states
1442 * into buffer.
1443 *
1444 * @param handle handle
1445 * @param out_len the argument to hold the output length
1446 * @param out_dptr the argument to hold the output data pointer
1447 * @return 0 when success, -1 when failure happens
1448 */
1449 XGB_DLL int XGBoosterSerializeToBuffer(BoosterHandle handle, bst_ulong *out_len,
1450 const char **out_dptr);
1451 /**
1452 * @brief Memory snapshot based serialization method. Loads the buffer returned
1453 * from \ref XGBoosterSerializeToBuffer.
1454 *
1455 * @param handle handle
1456 * @param buf pointer to the buffer
1457 * @param len the length of the buffer
1458 * @return 0 when success, -1 when failure happens
1459 */
1460 XGB_DLL int XGBoosterUnserializeFromBuffer(BoosterHandle handle, const void *buf, bst_ulong len);
1461
1462 /**
1463 * @brief Save XGBoost's internal configuration into a JSON document. Currently the
1464 * support is experimental, function signature may change in the future without
1465 * notice.
1466 *
1467 * @param handle handle to Booster object.
1468 * @param out_len length of output string
1469 * @param out_str A valid pointer to array of characters. The characters array is
1470 * allocated and managed by XGBoost, while pointer to that array needs to
1471 * be managed by caller.
1472 * @return 0 when success, -1 when failure happens
1473 */
1474 XGB_DLL int XGBoosterSaveJsonConfig(BoosterHandle handle, bst_ulong *out_len, char const **out_str);
1475 /**
1476 * @brief Load XGBoost's internal configuration from a JSON document. Currently the
1477 * support is experimental, function signature may change in the future without
1478 * notice.
1479 *
1480 * @param handle handle to Booster object.
1481 * @param config string representation of a JSON document.
1482 * @return 0 when success, -1 when failure happens
1483 */
1484 XGB_DLL int XGBoosterLoadJsonConfig(BoosterHandle handle, char const *config);
1485 /**@}*/ // End of Serialization
1486
1487 /**
1488 * @brief dump model, return array of strings representing model dump
1489 * @param handle handle
1490 * @param fmap name to fmap can be empty string
1491 * @param with_stats whether to dump with statistics
1492 * @param out_len length of output array
1493 * @param out_dump_array pointer to hold representing dump of each model
1494 * @return 0 when success, -1 when failure happens
1495 */
1496 XGB_DLL int XGBoosterDumpModel(BoosterHandle handle, const char *fmap, int with_stats,
1497 bst_ulong *out_len, const char ***out_dump_array);
1498
1499 /**
1500 * @brief dump model, return array of strings representing model dump
1501 * @param handle handle
1502 * @param fmap name to fmap can be empty string
1503 * @param with_stats whether to dump with statistics
1504 * @param format the format to dump the model in
1505 * @param out_len length of output array
1506 * @param out_dump_array pointer to hold representing dump of each model
1507 * @return 0 when success, -1 when failure happens
1508 */
1509 XGB_DLL int XGBoosterDumpModelEx(BoosterHandle handle, const char *fmap, int with_stats,
1510 const char *format, bst_ulong *out_len,
1511 const char ***out_dump_array);
1512
1513 /**
1514 * @brief dump model, return array of strings representing model dump
1515 * @param handle handle
1516 * @param fnum number of features
1517 * @param fname names of features
1518 * @param ftype types of features
1519 * @param with_stats whether to dump with statistics
1520 * @param out_len length of output array
1521 * @param out_models pointer to hold representing dump of each model
1522 * @return 0 when success, -1 when failure happens
1523 */
1524 XGB_DLL int XGBoosterDumpModelWithFeatures(BoosterHandle handle, int fnum, const char **fname,
1525 const char **ftype, int with_stats, bst_ulong *out_len,
1526 const char ***out_models);
1527
1528 /**
1529 * @brief dump model, return array of strings representing model dump
1530 * @param handle handle
1531 * @param fnum number of features
1532 * @param fname names of features
1533 * @param ftype types of features
1534 * @param with_stats whether to dump with statistics
1535 * @param format the format to dump the model in
1536 * @param out_len length of output array
1537 * @param out_models pointer to hold representing dump of each model
1538 * @return 0 when success, -1 when failure happens
1539 */
1540 XGB_DLL int XGBoosterDumpModelExWithFeatures(BoosterHandle handle, int fnum, const char **fname,
1541 const char **ftype, int with_stats, const char *format,
1542 bst_ulong *out_len, const char ***out_models);
1543
1544 /**
1545 * See @ref XGDMatrixGetCategories
1546 *
1547 * @since 3.2.0
1548 *
1549 * @note Experimental API, subject to change in the future.
1550 */
1551 XGB_DLL int XGBoosterGetCategories(BoosterHandle handle, char const *config, CategoriesHandle *out);
1552
1553 /**
1554 * See @ref XGDMatrixGetCategoriesExportToArrow
1555 *
1556 * @since 3.2.0
1557 *
1558 * @note Experimental API, subject to change in the future.
1559 */
1560 XGB_DLL int XGBoosterGetCategoriesExportToArrow(BoosterHandle handle, char const *config,
1561 CategoriesHandle *out, char const **export_out);
1562
1563 /**
1564 * @brief Get string attribute from Booster.
1565 * @param handle handle
1566 * @param key The key of the attribute.
1567 * @param out The result attribute, can be NULL if the attribute do not exist.
1568 * @param success Whether the result is contained in out.
1569 * @return 0 when success, -1 when failure happens
1570 */
1571 XGB_DLL int XGBoosterGetAttr(BoosterHandle handle, const char *key, const char **out, int *success);
1572 /**
1573 * @brief Set or delete string attribute.
1574 *
1575 * @param handle handle
1576 * @param key The key of the attribute.
1577 * @param value The value to be saved.
1578 * If nullptr, the attribute would be deleted.
1579 * @return 0 when success, -1 when failure happens
1580 */
1581 XGB_DLL int XGBoosterSetAttr(BoosterHandle handle, const char *key, const char *value);
1582 /**
1583 * @brief Get the names of all attribute from Booster.
1584 * @param handle handle
1585 * @param out_len the argument to hold the output length
1586 * @param out pointer to hold the output attribute stings
1587 * @return 0 when success, -1 when failure happens
1588 */
1589 XGB_DLL int XGBoosterGetAttrNames(BoosterHandle handle, bst_ulong *out_len, const char ***out);
1590
1591 /**
1592 * @brief Set string encoded feature info in Booster, similar to the feature
1593 * info in DMatrix.
1594 *
1595 * Accepted fields are:
1596 * - feature_name
1597 * - feature_type
1598 *
1599 * @param handle An instance of Booster
1600 * @param field Field name
1601 * @param features Pointer to array of strings.
1602 * @param size Size of `features` pointer (number of strings passed in).
1603 *
1604 * @return 0 when success, -1 when failure happens
1605 */
1606 XGB_DLL int XGBoosterSetStrFeatureInfo(BoosterHandle handle, const char *field,
1607 const char **features, const bst_ulong size);
1608
1609 /**
1610 * @brief Get string encoded feature info from Booster, similar to the feature info
1611 * in DMatrix.
1612 *
1613 * Accepted field names are:
1614 * - feature_name
1615 * - feature_type
1616 *
1617 * Caller is responsible for copying out the data, before the next call to any API
1618 * function of XGBoost.
1619 *
1620 * @param handle An instance of Booster
1621 * @param field Field name
1622 * @param len Size of output pointer `features` (number of strings returned).
1623 * @param out_features Address of a pointer to array of strings. Result is stored in
1624 * thread local memory.
1625 *
1626 * @return 0 when success, -1 when failure happens
1627 */
1628 XGB_DLL int XGBoosterGetStrFeatureInfo(BoosterHandle handle, const char *field, bst_ulong *len,
1629 const char ***out_features);
1630
1631 /**
1632 * @brief Calculate feature scores for tree models. When used on linear model, only the
1633 * `weight` importance type is defined, and output scores is a row major matrix with shape
1634 * [n_features, n_classes] for multi-class model. For tree model, out_n_feature is always
1635 * equal to out_n_scores and has multiple definitions of importance type.
1636 *
1637 * @param handle An instance of Booster
1638 * @param config Parameters for computing scores encoded as JSON. Accepted JSON keys are:
1639 * - importance_type: A JSON string with following possible values:
1640 * * 'weight': the number of times a feature is used to split the data across all trees.
1641 * * 'gain': the average gain across all splits the feature is used in.
1642 * * 'cover': the average coverage across all splits the feature is used in.
1643 * * 'total_gain': the total gain across all splits the feature is used in.
1644 * * 'total_cover': the total coverage across all splits the feature is used in.
1645 * - feature_map: An optional JSON string with URI or path to the feature map file.
1646 * - feature_names: An optional JSON array with string names for each feature.
1647 *
1648 * @param out_n_features Length of output feature names.
1649 * @param out_features An array of string as feature names, ordered the same as output scores.
1650 * @param out_dim Dimension of output feature scores.
1651 * @param out_shape Shape of output feature scores with length of `out_dim`.
1652 * @param out_scores An array of floating point as feature scores with shape of `out_shape`.
1653 *
1654 * @return 0 when success, -1 when failure happens
1655 */
1656 XGB_DLL int XGBoosterFeatureScore(BoosterHandle handle, const char *config,
1657 bst_ulong *out_n_features, char const ***out_features,
1658 bst_ulong *out_dim, bst_ulong const **out_shape,
1659 float const **out_scores);
1660 /**@}*/ // End of Booster
1661
1662 /**
1663 * @defgroup Collective Collective
1664 *
1665 * @brief Experimental support for exposing internal communicator in XGBoost.
1666 *
1667 * @note This is still under development.
1668 *
1669 * The collective communicator in XGBoost evolved from the `rabit` project of dmlc but has
1670 * changed significantly since its adoption. It consists of a tracker and a set of
1671 * workers. The tracker is responsible for bootstrapping the communication group and
1672 * handling centralized tasks like logging. The workers are actual communicators
1673 * performing collective tasks like allreduce.
1674 *
1675 * To use the collective implementation, one needs to first create a tracker with
1676 * corresponding parameters, then get the arguments for workers using
1677 * XGTrackerWorkerArgs(). The obtained arguments can then be passed to the
1678 * XGCommunicatorInit() function. Call to XGCommunicatorInit() must be accompanied with a
1679 * XGCommunicatorFinalize() call for cleanups. Please note that the communicator uses
1680 * `std::thread` in C++, which has undefined behavior in a C++ destructor due to the
1681 * runtime shutdown sequence. It's preferable to call XGCommunicatorFinalize() before the
1682 * runtime is shutting down. This requirement is similar to a Python thread or socket,
1683 * which should not be relied upon in a `__del__` function.
1684 *
1685 * Since it's used as a part of XGBoost, errors will be returned when a XGBoost function
1686 * is called, for instance, training a booster might return a connection error.
1687 *
1688 * @{
1689 */
1690
1691 /**
1692 * @brief Handle to the tracker.
1693 *
1694 * There are currently two types of tracker in XGBoost, first one is `rabit`, while the
1695 * other one is `federated`. `rabit` is used for normal collective communication, while
1696 * `federated` is used for federated learning.
1697 *
1698 */
1699 typedef void *TrackerHandle; /* NOLINT */
1700
1701 /**
1702 * @brief Create a new tracker.
1703 *
1704 * @param config JSON encoded parameters.
1705 *
1706 * - dmlc_communicator: String, the type of tracker to create. Available options are
1707 * `rabit` and `federated`. See @ref TrackerHandle for more info.
1708 * - n_workers: Integer, the number of workers.
1709 * - port: (Optional) Integer, the port this tracker should listen to.
1710 * - timeout: (Optional) Integer, timeout in seconds for various networking
1711 operations. Default is 300 seconds.
1712 *
1713 * Some configurations are `rabit` specific:
1714 *
1715 * - host: (Optional) String, Used by the the `rabit` tracker to specify the address of the host.
1716 * This can be useful when the communicator cannot reliably obtain the host address.
1717 * - sortby: (Optional) Integer.
1718 * + 0: Sort workers by their host name.
1719 * + 1: Sort workers by task IDs.
1720 *
1721 * Some `federated` specific configurations:
1722 * - federated_secure: Boolean, whether this is a secure server. False for testing.
1723 * - server_key_path: Path to the server key. Used only if this is a secure server.
1724 * - server_cert_path: Path to the server certificate. Used only if this is a secure server.
1725 * - client_cert_path: Path to the client certificate. Used only if this is a secure server.
1726 *
1727 * @param handle The handle to the created tracker.
1728 *
1729 * @return 0 when success, -1 when failure happens
1730 */
1731 XGB_DLL int XGTrackerCreate(char const *config, TrackerHandle *handle);
1732
1733 /**
1734 * @brief Get the arguments needed for running workers. This should be called after
1735 * XGTrackerRun().
1736 *
1737 * @param handle The handle to the tracker.
1738 * @param args The arguments returned as a JSON document.
1739 *
1740 * @return 0 when success, -1 when failure happens
1741 */
1742 XGB_DLL int XGTrackerWorkerArgs(TrackerHandle handle, char const **args);
1743
1744 /**
1745 * @brief Start the tracker. The tracker runs in the background and this function returns
1746 * once the tracker is started.
1747 *
1748 * @param handle The handle to the tracker.
1749 * @param config Unused at the moment, preserved for the future.
1750 *
1751 * @return 0 when success, -1 when failure happens
1752 */
1753 XGB_DLL int XGTrackerRun(TrackerHandle handle, char const *config);
1754
1755 /**
1756 * @brief Wait for the tracker to finish, should be called after XGTrackerRun(). This
1757 * function will block until the tracker task is finished or timeout is reached.
1758 *
1759 * @param handle The handle to the tracker.
1760 * @param config JSON encoded configuration. No argument is required yet, preserved for
1761 * the future.
1762 *
1763 * @return 0 when success, -1 when failure happens
1764 */
1765 XGB_DLL int XGTrackerWaitFor(TrackerHandle handle, char const *config);
1766
1767 /**
1768 * @brief Free a tracker instance. This should be called after XGTrackerWaitFor(). If the
1769 * tracker is not properly waited, this function will shutdown all connections with
1770 * the tracker, potentially leading to undefined behavior.
1771 *
1772 * @param handle The handle to the tracker.
1773 *
1774 * @return 0 when success, -1 when failure happens
1775 */
1776 XGB_DLL int XGTrackerFree(TrackerHandle handle);
1777
1778 /**
1779 * @brief Initialize the collective communicator.
1780 *
1781 * Currently the communicator API is experimental, function signatures may change in the future
1782 * without notice.
1783 *
1784 * Call this once in the worker process before using anything. Please make sure
1785 * XGCommunicatorFinalize() is called after use. The initialized commuicator is a global
1786 * thread-local variable.
1787 *
1788 * @param config JSON encoded configuration. Accepted JSON keys are:
1789 * - dmlc_communicator: The type of the communicator, this should match the tracker type.
1790 * * rabit: Use Rabit. This is the default if the type is unspecified.
1791 * * federated: Use the gRPC interface for Federated Learning.
1792 *
1793 * Only applicable to the `rabit` communicator:
1794 * - dmlc_tracker_uri: Hostname or IP address of the tracker.
1795 * - dmlc_tracker_port: Port number of the tracker.
1796 * - dmlc_task_id: ID of the current task, can be used to obtain deterministic rank assignment.
1797 * - dmlc_retry: The number of retries for connection failure.
1798 * - dmlc_timeout: Timeout in seconds.
1799 * - dmlc_nccl_path: Path to the nccl shared library `libnccl.so`.
1800 *
1801 * Only applicable to the `federated` communicator (use upper case for environment variables, use
1802 * lower case for runtime configuration):
1803 * - federated_server_address: Address of the federated server.
1804 * - federated_world_size: Number of federated workers.
1805 * - federated_rank: Rank of the current worker.
1806 * - federated_server_cert_path: Server certificate file path. Only needed for the SSL mode.
1807 * - federated_client_key_path: Client key file path. Only needed for the SSL mode.
1808 * - federated_client_cert_path: Client certificate file path. Only needed for the SSL mode.
1809 *
1810 * @return 0 when success, -1 when failure happens
1811 */
1812 XGB_DLL int XGCommunicatorInit(char const *config);
1813
1814 /**
1815 * @brief Finalize the collective communicator.
1816 *
1817 * Call this function after you have finished all jobs.
1818 *
1819 * @return 0 when success, -1 when failure happens
1820 */
1821 XGB_DLL int XGCommunicatorFinalize(void);
1822
1823 /**
1824 * @brief Get rank of the current process.
1825 *
1826 * @return Rank of the worker.
1827 */
1828 XGB_DLL int XGCommunicatorGetRank(void);
1829
1830 /**
1831 * @brief Get the total number of processes.
1832 *
1833 * @return Total world size.
1834 */
1835 XGB_DLL int XGCommunicatorGetWorldSize(void);
1836
1837 /**
1838 * @brief Get if the communicator is distributed.
1839 *
1840 * @return True if the communicator is distributed.
1841 */
1842 XGB_DLL int XGCommunicatorIsDistributed(void);
1843
1844 /**
1845 * @brief Print the message to the tracker.
1846 *
1847 * This function can be used to communicate the information of the progress to the user
1848 * who monitors the tracker.
1849 *
1850 * @param message The message to be printed.
1851 * @return 0 when success, -1 when failure happens
1852 */
1853 XGB_DLL int XGCommunicatorPrint(char const *message);
1854
1855 /**
1856 * @brief Get the name of the processor.
1857 *
1858 * @param name_str Pointer to received returned processor name.
1859 * @return 0 when success, -1 when failure happens
1860 */
1861 XGB_DLL int XGCommunicatorGetProcessorName(const char **name_str);
1862
1863 /**
1864 * @brief Broadcast a memory region to all others from root. This function is NOT
1865 * thread-safe.
1866 *
1867 * Example:
1868 * @code
1869 * int a = 1;
1870 * Broadcast(&a, sizeof(a), root);
1871 * @endcode
1872 *
1873 * @param send_receive_buffer Pointer to the send or receive buffer.
1874 * @param size Size of the data in bytes.
1875 * @param root The process rank to broadcast from.
1876 *
1877 * @return 0 when success, -1 when failure happens
1878 */
1879 XGB_DLL int XGCommunicatorBroadcast(void *send_receive_buffer, size_t size, int root);
1880
1881 /**
1882 * @brief Perform in-place allreduce. This function is NOT thread-safe.
1883 *
1884 * Example Usage: the following code gives sum of the result
1885 * @code
1886 * enum class Op {
1887 * kMax = 0, kMin = 1, kSum = 2, kBitwiseAND = 3, kBitwiseOR = 4, kBitwiseXOR = 5
1888 * };
1889 * std::vector<int> data(10);
1890 * ...
1891 * Allreduce(data.data(), data.size(), DataType:kInt32, Op::kSum);
1892 * ...
1893 * @endcode
1894
1895 * @param send_receive_buffer Buffer for both sending and receiving data.
1896 * @param count Number of elements to be reduced.
1897 * @param data_type Enumeration of data type, see xgboost::collective::DataType in communicator.h.
1898 * @param op Enumeration of operation type, see xgboost::collective::Operation in communicator.h.
1899 *
1900 * @return 0 when success, -1 when failure happens
1901 */
1902 XGB_DLL int XGCommunicatorAllreduce(void *send_receive_buffer, size_t count, int data_type, int op);
1903
1904 /**@}*/ // End of Collective
1905 #endif // XGBOOST_C_API_H_