XGBoost implements a set of C API designed for various bindings, we maintain its stability
and the CMake/make build interface. See C API Tutorial for an
introduction and demo/c-api/ for related examples. Also one can generate doxygen
document by providing -DBUILD_C_DOC=ON as parameter to CMake during build, or
simply look at function comments in include/xgboost/c_api.h. The reference is exported
to sphinx with the help of breathe, which doesn’t contain links to examples but might be
easier to read. For the original doxygen pages please visit:
The output variable is only written if it’s not NULL.
Parameters:
major – Store the major version number.
DMatrix
groupDMatrix
DMatrix is the basic data storage for XGBoost used by all XGBoost algorithms including both training, prediction and explanation. There are a few variants of DMatrix including normal DMatrix, which is a CSR matrix, QuantileDMatrix, which is used by histogram-based tree methods for saving memory, and lastly the experimental external-memory-based DMatrix, which reads data in batches during training. For the last two variants, see the Streaming group.
A special type of input to the DMatrix is the columnar format, which refers to column-based dataframes. XGBoost can accept both numeric data types like integers and floats, along with the categorical type, called dictionary in arrow’s term. The addition of categorical type is introduced in 3.1.0. The dataframe is represented by a list array interfaces with one object for each column.
This method replaces the existing XGDMatrixGetFloatInfo and to support non-vector (like a matrix) output. The output data directly references the internal storage, as a result, it’s read-only and user should copy data before the next XGBoost call.
Quantile DMatrix and external memory DMatrix can be created from batches of data.
There are 2 sets of data callbacks for DMatrix. The first one is currently exclusively used by JVM packages. It uses XGBoostBatchCSR to accept batches for CSR formated input, and concatenate them into 1 final big CSR. The related functions are:
Another set is used by external data iterator. It accepts foreign data iterators as callbacks. There are 2 different senarios where users might want to pass in callbacks instead of raw data. First it’s the Quantile DMatrix used by the hist and GPU-based hist tree method. For this case, the data is first compressed by quantile sketching then merged. This is particular useful for distributed setting as it eliminates 2 copies of data. First one by a from external library to make the data into a blob for normal DMatrix initialization, another one by the internal CSR copy of DMatrix.
Booster
groupBooster
The Booster class is the gradient-boosted model for XGBoost.
During training, the booster object has many caches for improved performance. In addition to gradient and prediction, it also includes runtime buffers like leaf partitions. These buffers persist with the Booster object until either XGBoosterReset() is called or the booster is deleted by the XGBoosterFree().
There are multiple ways to serialize a Booster object depending on the use case.
Short note for serialization APIs. There are 3 different sets of serialization API.
Functions with the term “Model” handles saving/loading XGBoost model like trees or linear weights. Striping out parameters configuration like training algorithms or CUDA device ID. These functions are designed to let users reuse the trained model for different tasks, examples are prediction, training continuation or model interpretation.
Functions with the term “Config” handles save/loading configuration. It helps user to study the internal of XGBoost. Also user can use the load method for specifying parameters in a structured way. These functions were introduced in 1.0.0.
Functions with the term “Serialization” are combination of above two. They are used in situations like check-pointing, or continuing training task in a distributed environment. In these cases the task must be carried out without any user intervention.
Functions
,
Collective
groupCollective
Experimental support for exposing internal communicator in XGBoost.
The collective communicator in XGBoost evolved from the rabit project of dmlc but has changed significantly since its adoption. It consists of a tracker and a set of workers. The tracker is responsible for bootstrapping the communication group and handling centralized tasks like logging. The workers are actual communicators performing collective tasks like allreduce.
To use the collective implementation, one needs to first create a tracker with corresponding parameters, then get the arguments for workers using XGTrackerWorkerArgs(). The obtained arguments can then be passed to the XGCommunicatorInit() function. Call to XGCommunicatorInit() must be accompanied with a XGCommunicatorFinalize() call for cleanups. Please note that the communicator uses std::thread in C++, which has undefined behavior in a C++ destructor due to the runtime shutdown sequence. It’s preferable to call XGCommunicatorFinalize() before the runtime is shutting down. This requirement is similar to a Python thread or socket, which should not be relied upon in a __del__ function.
Since it’s used as a part of XGBoost, errors will be returned when a XGBoost function is called, for instance, training a booster might return a connection error.
Typedefs
typedefvoid*TrackerHandle
Handle to the tracker.
There are currently two types of tracker in XGBoost, first one is rabit, while the other one is federated. rabit is used for normal collective communication, while federated is used for federated learning.
dmlc_communicator: String, the type of tracker to create. Available options are rabit and . See for more info.
minor – Store the minor version number.
patch – Store the patch (revision) number.
intXGBuildInfo(charconst**out)
Get compile information of the shared XGBoost library.
Parameters:
out – string encoded JSON object containing build flags and dependency versions.
Returns:
0 when success, -1 when failure happens
constchar*XGBGetLastError()
Get the string message of the last error.
Most functions in XGBoost returns 0 when success and non-zero when an error occurred. In the case of error, XGBGetLastError can be used to retrieve the error message
register callback function for LOG(INFO) messages — helpful messages that are not errors.
Returns:
0 when success, -1 when failure happens
intXGBSetGlobalConfig(charconst*config)
Set global configuration (collection of parameters that apply globally). This function accepts the list of key-value pairs representing the global-scope parameters to be configured. The list of key-value pairs are passed in as a JSON string.
Parameters:
config – a JSON string representing the list of key-value pairs. The JSON object shall be flat: no value can be a JSON object or an array.
Returns:
0 when success, -1 when failure happens
intXGBGetGlobalConfig(charconst**out_config)
Get current global configuration (collection of parameters that apply globally).
Parameters:
out_config – pointer to received returned global configuration, represented as a JSON string.
silent (optional): Whether to print message during loading. Default to true.
data_split_mode (optional): Whether the file was split by row or column beforehand for distributed computing. Default to row.
out – a loaded data matrix
Returns:
0 when success, -1 when failure happens
A categorical type is represented by 3 buffers, the validity mask, the names of the categories (called index for most of the dataframe implementation), and the codes used to represent the categories in the rows. XGBoost consumes a categorical column by accepting two JSON-encoded arrow arrays in a list. The first item in the list is a JSON object with {"offsets":IntegerArray,"values":StringArray} representing the string names defined by the arrow columnar format. The second buffer is an masked integer array that stores the categorical codes along with the validity mask:
[// categorical column, represented as an array (list)[{'offsets':{'data':(129412626415808,True),'typestr':'<i4','version':3,'strides':None,'shape':(3,),'mask':None},'values':{'data':(129412626416000,True),'typestr':'<i1','version':3,'strides':None,'shape':(7,),'mask':None}},{'data':(106200854378448,True),'typestr':'<i1','version':3,'strides':None,'shape':(2,),'mask':None}],// numeric column, represented as an object, same number of rows as the previous column (2){'data':(106200854378448,True),'typestr':'<f4','version':3,'strides':None,'shape':(2,),'mask':None}]
As for numeric inputs, it’s the same as dense array.
charconst*feat_names[]{"feat_0","feat_1"};XGDMatrixSetStrFeatureInfo(handle,"feature_name",feat_names,2);// i for integer, q for quantitive, c for categorical. Similarly "int" and "float"// are also recognized.charconst*feat_types[]{"i","q"};XGDMatrixSetStrFeatureInfo(handle,"feature_type",feat_types,2);
Parameters:
handle – An instance of data matrix
field – Field name
features – Pointer to array of strings.
size – Size of features pointer (number of strings passed in).
Returns:
0 when success, -1 when failure happens
Accepted fields are:
feature_name
feature_type
Caller is responsible for copying out the data, before next call to any API function of XGBoost.
charconst**c_out_features=NULL;bst_ulongout_size=0;// Asumming the feature names are already set by `XGDMatrixSetStrFeatureInfo`.XGDMatrixGetStrFeatureInfo(handle,"feature_name",&out_size,&c_out_features)for(bst_ulongi=0;i<out_size;++i){// Here we are simply printing the string. Copy it out if the feature name is// useful after printing.printf("feature %lu: %s\n",i,c_out_features[i]);}
Parameters:
handle – An instance of data matrix
field – Field name
size – Size of output pointer features (number of strings returned).
out_features – Address of a pointer to array of strings. Result is stored in thread local memory.
Returns:
0 when success, -1 when failure happens
Since
3.2.0
DMatrixHandlefmat;// Create a DMatrix from categorical data// ...CategoriesHandlecats;interr=XGBoosterGetCategories(fmat,NULL,&cats)if(err!=0){exit(-1);}err=XGBCategoriesFree(cats);if(err!=0){exit(-1);}
Parameters:
handle – An instance of the data matrix.
config – Unused, reserved for the future.
out – Created handle to the category container. Set to NULL if there’s no category.
Returns:
0 when success, -1 when failure happens.
Create an opaque handle to the internal container and export it to arrow.
out_array – JSON encoded __(cuda)_array_interface__ to the output.
Returns:
0 when success, -1 when failure happens
Parameters:
handle – a instance of data matrix
field – field name
out_len – used to set result length
out_dptr – pointer to the result
Returns:
0 when success, -1 when failure happens
Parameters:
handle – a instance of data matrix
field – field name
out_len – The length of the field.
out_dptr – pointer to the result
Returns:
0 when success, -1 when failure happens
:
0 when success, -1 when failure happens
:
0 when success, -1 when failure happens
:
0 when success, -1 when failure happens
:
0 when success, -1 when failure happens
Get the predictors from DMatrix as CSR matrix for testing. If this is a quantized DMatrix, quantized values are returned instead.
Unlike most of XGBoost C functions, caller of XGDMatrixGetDataAsCSR is required to allocate the memory for return buffer instead of using thread local memory from XGBoost. This is to avoid allocating a huge memory buffer that can not be freed until exiting the thread.
Since
1.7.0
Parameters:
handle – the handle to the DMatrix
config – JSON configuration string. At the moment it should be an empty document, preserved for future use.
out_indptr – indptr of output CSR matrix.
out_indices – Column index of output CSR matrix.
out_data – Data value of CSR matrix.
Returns:
0 when success, -1 when failure happens
Export the quantile cuts used for training histogram-based models like hist and approx. Useful for model compression.
Since
2.0.0
Parameters:
handle – the handle to the DMatrix
config – JSON configuration string. At the moment it should be an empty document, preserved for future use.
out_indptr – indptr of output CSC matrix represented by a JSON encoded __(cuda_)array_interface__.
out_data – Data value of CSC matrix represented by a JSON encoded __(cuda_)array_interface__.
concat
The second use case is external memory support where users can pass a custom data iterator into XGBoost for loading data in batches. For both cases, the iterator is only used during the construction of the DMatrix and can be safely freed after construction finishes. There are short notes on each of the use cases in respected DMatrix factory function.
Create a DMatrix proxy for setting data, can be freed by XGDMatrixFree.
Second set of callback functions, used by constructing Quantile DMatrix or external memory DMatrix using a custom iterator.
The DMatrix proxy is only a temporary reference (wrapper) to the actual user data. For instance, if a dense matrix (like a numpy array) is passed into the proxy DMatrix via the XGProxyDMatrixSetDataDense method, then the proxy DMatrix holds only a reference and the input array cannot be freed until the next iteration starts, signaled by a call to the XGDMatrixCallbackNext by XGBoost. It’s called because it reuses the interface of the DMatrix class in XGBoost, but it’s just a mid interface for the and related constructors to consume various user input types.
out – The result attribute, can be NULL if the attribute do not exist.
success – Whether the result is contained in out.
Returns:
0 when success, -1 when failure happens
key – The key of the attribute.
value – The value to be saved. If nullptr, the attribute would be deleted.
Returns:
0 when success, -1 when failure happens
handle – handle
out_len – the argument to hold the output length
out – pointer to hold the output attribute stings
Returns:
0 when success, -1 when failure happens
Accepted fields are:
feature_name
feature_type
Parameters:
handle – An instance of Booster
field – Field name
features – Pointer to array of strings.
size – Size of features pointer (number of strings passed in).
Returns:
0 when success, -1 when failure happens
Accepted field names are:
feature_name
feature_type
Caller is responsible for copying out the data, before the next call to any API function of XGBoost.
Parameters:
handle – An instance of Booster
field – Field name
len – Size of output pointer features (number of strings returned).
out_features – Address of a pointer to array of strings. Result is stored in thread local memory.
Returns:
0 when success, -1 when failure happens
*
out_dim
bst_ulong
const
*
*
out_shape
float
const
*
*
out_scores
)
Calculate feature scores for tree models. When used on linear model, only the weight importance type is defined, and output scores is a row major matrix with shape [n_features, n_classes] for multi-class model. For tree model, out_n_feature is always equal to out_n_scores and has multiple definitions of importance type.
Parameters:
handle – An instance of Booster
config – Parameters for computing scores encoded as JSON. Accepted JSON keys are:
importance_type: A JSON string with following possible values:
’weight’: the number of times a feature is used to split the data across all trees.
’gain’: the average gain across all splits the feature is used in.
’cover’: the average coverage across all splits the feature is used in.
’total_gain’: the total gain across all splits the feature is used in.
’total_cover’: the total coverage across all splits the feature is used in.
feature_map: An optional JSON string with URI or path to the feature map file.
feature_names: An optional JSON array with string names for each feature.
out_n_features – Length of output feature names.
out_features – An array of string as feature names, ordered the same as output scores.
out_dim – Dimension of output feature scores.
out_shape – Shape of output feature scores with length of out_dim.
out_scores – An array of floating point as feature scores with shape of out_shape.
option_mask – bit-mask of options taken in prediction, possible values 0:normal prediction 1:output margin instead of transformed value 2:output leaf index of trees instead of leaf value, note leaf index is unique per tree 4:output feature contributions to individual predictions
ntree_limit – limit number of trees used for prediction, this is only valid for boosted trees when the parameter is set to 0, we will use all the trees
training – Whether the prediction function is used as part of a training loop. Prediction can be run in 2 scenarios:
Given data matrix X, obtain prediction y_pred from the model.
Obtain the prediction for computing gradients. For example, DART booster performs dropout during training, and the prediction result will be different from the one obtained by normal inference step due to dropped trees. Set training=false for the first scenario. Set training=true for the second scenario. The second scenario applies when you are defining a custom objective function.
out_len – used to store length of returning result
6: predict leaf “training”: bool Whether the prediction function is used as part of a training loop. Not used for inplace prediction.
Prediction can be run in 2 scenarios:
Given data matrix X, obtain prediction y_pred from the model.
Obtain the prediction for computing gradients. For example, DART booster performs dropout during training, and the prediction result will be different from the one obtained by normal inference step due to dropped trees. Set training=false for the first scenario. Set training=true for the second scenario. The second scenario applies when you are defining a custom objective function. “iteration_begin”: int Beginning iteration of prediction. “iteration_end”: int End iteration of prediction. Set to 0 this will become the size of tree model (all the trees). “strict_shape”: bool Whether should we reshape the output with stricter rules. If set to true, normal/margin/contrib/interaction predict will output consistent shape disregarding the use of multi-class model, and leaf prediction will output 4-dim array representing: (n_samples, n_iterations, n_classes, n_trees_in_forest)
Example JSON input for running a normal prediction with strict output shape, 2 dim for softprob , 1 dim for others.
Save XGBoost’s internal configuration into a JSON document. Currently the support is experimental, function signature may change in the future without notice.
Parameters:
handle – handle to Booster object.
out_len – length of output string
out_str – A valid pointer to array of characters. The characters array is allocated and managed by XGBoost, while pointer to that array needs to be managed by caller.
Load XGBoost’s internal configuration from a JSON document. Currently the support is experimental, function signature may change in the future without notice.
Parameters:
handle – handle to Booster object.
config – string representation of a JSON document.
port: (Optional) Integer, the port this tracker should listen to.
timeout: (Optional) Integer, timeout in seconds for various networking operations. Default is 300 seconds.
Some configurations are rabit specific:
host: (Optional) String, Used by the the rabit tracker to specify the address of the host. This can be useful when the communicator cannot reliably obtain the host address.
sortby: (Optional) Integer.
0: Sort workers by their host name.
1: Sort workers by task IDs.
Some federated specific configurations:
federated_secure: Boolean, whether this is a secure server. False for testing.
server_key_path: Path to the server key. Used only if this is a secure server.
server_cert_path: Path to the server certificate. Used only if this is a secure server.
client_cert_path: Path to the client certificate. Used only if this is a secure server.
Wait for the tracker to finish, should be called after XGTrackerRun(). This function will block until the tracker task is finished or timeout is reached.
Parameters:
handle – The handle to the tracker.
config – JSON encoded configuration. No argument is required yet, preserved for the future.
Free a tracker instance. This should be called after XGTrackerWaitFor(). If the tracker is not properly waited, this function will shutdown all connections with the tracker, potentially leading to undefined behavior.
Parameters:
handle – The handle to the tracker.
Returns:
0 when success, -1 when failure happens
intXGCommunicatorInit(charconst*config)
Initialize the collective communicator.
Currently the communicator API is experimental, function signatures may change in the future without notice.
Call this once in the worker process before using anything. Please make sure XGCommunicatorFinalize() is called after use. The initialized commuicator is a global thread-local variable.
Only applicable to the rabit communicator:
dmlc_tracker_uri: Hostname or IP address of the tracker.
dmlc_tracker_port: Port number of the tracker.
dmlc_task_id: ID of the current task, can be used to obtain deterministic rank assignment.
dmlc_retry: The number of retries for connection failure.
dmlc_timeout: Timeout in seconds.
dmlc_nccl_path: Path to the nccl shared library libnccl.so.
Only applicable to the federated communicator (use upper case for environment variables, use lower case for runtime configuration):
federated_server_address: Address of the federated server.
federated_world_size: Number of federated workers.
federated_rank: Rank of the current worker.
federated_server_cert_path: Server certificate file path. Only needed for the SSL mode.
federated_client_key_path: Client key file path. Only needed for the SSL mode.
federated_client_cert_path: Client certificate file path. Only needed for the SSL mode.
nthread (optional): Number of threads used for initializing DMatrix.
max_bin (optional): Maximum number of bins for building histogram. Must be consistent with the corresponding booster training parameter.
max_quantile_blocks (optional): For GPU-based inputs, XGBoost handles incoming batches with multiple growing substreams. This parameter sets the maximum number of batches before XGBoost can cut the sub-stream and create a new one. This can help bound the memory usage. By default, XGBoost grows new sub-streams exponentially until batches are exhausted. Only used for the training dataset and the default is None (unbounded).
cache_host_ratio (optioinal): For GPU-based inputs, XGBoost can split the cache into host and device portitions to reduce the data transfer overhead. This parameter specifies the size of host cache compared to the size of the entire cache: host/(host+device).
cache_prefix: The path of cache file, caller must initialize all the directories in this path.
nthread (optional): Number of threads used for initializing DMatrix.
max_bin (optional): Maximum number of bins for building histogram. Must be consistent with the corresponding booster training parameter.
on_host (optional): Whether the data should be placed on host memory. Used by GPU inputs.
min_cache_page_bytes (optional): The minimum number of bytes for each internal GPU page. Set to 0 to disable page concatenation. Automatic configuration if the parameter is not provided or set to None.
max_quantile_blocks (optional): For GPU-based inputs, XGBoost handles incoming batches with multiple growing substreams. This parameter sets the maximum number of batches before XGBoost can cut the sub-stream and create a new one. This can help bound the memory usage. By default, XGBoost grows new sub-streams exponentially until batches are exhausted. Only used for the training dataset and the default is None (unbounded).
Returns:
0 when success, -1 when failure happens
XGProxyDMatrixCreate
data – Null terminated JSON document string representation of CUDA array interface.