Debian Codegraph @

src/include/xgboost/data.h

raw symbols SCIP
1 /**
2 * Copyright 2015-2025, XGBoost Contributors
3 * \file data.h
4 * \brief The input data structure of xgboost.
5 * \author Tianqi Chen
6 */
7 #ifndef XGBOOST_DATA_H_
8 #define XGBOOST_DATA_H_
9
10 #include <dmlc/base.h>
11 #include <dmlc/io.h> // for Stream
12 #include <dmlc/serializer.h> // for Handler
13 #include <xgboost/base.h>
14 #include <xgboost/host_device_vector.h>
15 #include <xgboost/linalg.h>
16 #include <xgboost/span.h>
17 #include <xgboost/string_view.h>
18
19 #include <algorithm>
20 #include <array> // for array
21 #include <cstdint> // for int32_t, uint8_t
22 #include <limits>
23 #include <memory>
24 #include <string>
25 #include <utility>
26 #include <vector>
27
28 namespace xgboost {
29 // forward declare dmatrix.
30 class DMatrix;
31 struct Context;
32
33 /*! \brief data type accepted by xgboost interface */
34 enum class DataType : uint8_t { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4, kStr = 5 };
35
36 enum class FeatureType : uint8_t { kNumerical = 0, kCategorical = 1 };
37
38 enum class DataSplitMode : int { kRow = 0, kCol = 1 };
39
40 // Forward declaration of the container used by the meta info.
41 class CatContainer;
42
43 /** @brief Used as a reference to a linalg::Matrix, or a vector */
44 struct TypedArrayRef {
45 using SizeType = linalg::VectorView<float>::SizeType;
46 // 2-dim is the maximum for return type, we can use larger ones if needed.
47 using Shape = std::array<SizeType, 2>;
48
49 DataType dtype{DataType::kFloat32};
50 Shape shape{0, 0};
51 SizeType ndim{0};
52 void const* data{nullptr};
53
54 [[nodiscard]] std::string ArrayInterfaceStr() const;
55 [[nodiscard]] SizeType Size() const {
56 if (ndim == 1) {
57 return shape[0];
58 } else {
59 return shape[0] * shape[1];
60 }
61 }
62 };
63
64 /**
65 * @brief Meta information about dataset, always sit in memory.
66 */
67 class MetaInfo {
68 public:
69 /*! \brief number of data fields in MetaInfo */
70 static constexpr uint64_t kNumField = 13;
71
72 /*! \brief number of rows in the data */
73 bst_idx_t num_row_{0}; // NOLINT
74 /*! \brief number of columns in the data */
75 uint64_t num_col_{0}; // NOLINT
76 /*! \brief number of nonzero entries in the data */
77 uint64_t num_nonzero_{0}; // NOLINT
78 /*! \brief label of each instance */
79 linalg::Tensor<float, 2> labels;
80 /*! \brief data split mode */
81 DataSplitMode data_split_mode{DataSplitMode::kRow};
82 /*!
83 * \brief the index of begin and end of a group
84 * needed when the learning task is ranking.
85 */
86 std::vector<bst_group_t> group_ptr_; // NOLINT
87 /*! \brief weights of each instance, optional */
88 HostDeviceVector<bst_float> weights_; // NOLINT
89 /*!
90 * \brief initialized margins,
91 * if specified, xgboost will start from this init margin
92 * can be used to specify initial prediction to boost from.
93 */
94 linalg::Matrix<float> base_margin_; // NOLINT
95 /*!
96 * \brief lower bound of the label, to be used for survival analysis (censored regression)
97 */
98 HostDeviceVector<bst_float> labels_lower_bound_; // NOLINT
99 /*!
100 * \brief upper bound of the label, to be used for survival analysis (censored regression)
101 */
102 HostDeviceVector<bst_float> labels_upper_bound_; // NOLINT
103
104 /*!
105 * \brief Name of type for each feature provided by users. Eg. "int"/"float"/"i"/"q"
106 */
107 std::vector<std::string> feature_type_names;
108 /*!
109 * \brief Name for each feature.
110 */
111 std::vector<std::string> feature_names;
112 /*
113 * \brief Type of each feature. Automatically set when feature_type_names is specifed.
114 */
115 HostDeviceVector<FeatureType> feature_types;
116 /*
117 * \brief Weight of each feature, used to define the probability of each feature being
118 * selected when using column sampling.
119 */
120 HostDeviceVector<float> feature_weights;
121
122 MetaInfo();
123 MetaInfo(MetaInfo&& that) = default;
124 MetaInfo(MetaInfo const& that) = delete;
125 MetaInfo& operator=(MetaInfo&& that) = default;
126 MetaInfo& operator=(MetaInfo const& that) = delete;
127
128 /**
129 * @brief Validate all metainfo.
130 */
131 void Validate(DeviceOrd device) const;
132 /**
133 * @brief Slice the meta info.
134 *
135 * The device of ridxs is specified by the ctx object.
136 *
137 * @param ridxs Index of selected rows.
138 * @param nnz The number of non-missing values.
139 */
140 MetaInfo Slice(Context const* ctx, common::Span<bst_idx_t const> ridxs, bst_idx_t nnz) const;
141
142 MetaInfo Copy() const;
143 /**
144 * @brief Whether the matrix is dense.
145 */
146 bool IsDense() const { return num_col_ * num_row_ == num_nonzero_; }
147 /*!
148 * \brief Get weight of each instances.
149 * \param i Instance index.
150 * \return The weight.
151 */
152 inline bst_float GetWeight(size_t i) const {
153 return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f;
154 }
155 /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */
156 const std::vector<size_t>& LabelAbsSort(Context const* ctx) const;
157 /*! \brief clear all the information */
158 void Clear();
159 /*!
160 * \brief Load the Meta info from binary stream.
161 * \param fi The input stream
162 */
163 void LoadBinary(dmlc::Stream* fi);
164 /*!
165 * \brief Save the Meta info to binary stream
166 * \param fo The output stream.
167 */
168 void SaveBinary(dmlc::Stream* fo) const;
169 /**
170 * @brief Set information in the meta info with array interface.
171 *
172 * @param key The key of the information.
173 * @param in_array String representation of json format array interface.
174 */
175 void SetInfo(Context const& ctx, StringView key, StringView in_array);
176 /** @brief Return an array reference for a meta info. */
177 [[nodiscard]] TypedArrayRef GetInfo(Context const* ctx, StringView key) const;
178
179 void SetFeatureInfo(const char* key, const char** info, const bst_ulong size);
180 void GetFeatureInfo(const char* field, std::vector<std::string>* out_str_vecs) const;
181
182 /**
183 * @brief Extend with other MetaInfo.
184 *
185 * @param that The other MetaInfo object.
186 *
187 * @param accumulate_rows Whether rows need to be accumulated in this function. If
188 * client code knows number of rows in advance, set this
189 * parameter to false.
190 * @param check_column Whether the extend method should check the consistency of
191 * columns.
192 */
193 void Extend(MetaInfo const& that, bool accumulate_rows, bool check_column);
194 /**
195 * @brief Synchronize the number of columns across all workers.
196 *
197 * Normally we just need to find the maximum number of columns across all workers, but
198 * in vertical federated learning, since each worker loads its own list of columns,
199 * we need to sum them.
200 */
201 void SynchronizeNumberOfColumns(Context const* ctx, DataSplitMode split_mode);
202
203 /** @brief Whether the data is split row-wise. */
204 [[nodiscard]] bool IsRowSplit() const { return data_split_mode == DataSplitMode::kRow; }
205 /** @brief Whether the data is split column-wise. */
206 [[nodiscard]] bool IsColumnSplit() const { return data_split_mode == DataSplitMode::kCol; }
207 /** @brief Whether this is a learning to rank data. */
208 [[nodiscard]] bool IsRanking() const { return !group_ptr_.empty(); }
209
210 /**
211 * @brief A convenient method to check if we are doing vertical federated learning, which requires
212 * some special processing.
213 */
214 [[nodiscard]] bool IsVerticalFederated() const;
215
216 /*!
217 * \brief A convenient method to check if the MetaInfo should contain labels.
218 *
219 * Normally we assume labels are available everywhere. The only exception is in vertical federated
220 * learning where labels are only available on worker 0.
221 */
222 bool ShouldHaveLabels() const;
223 /**
224 * @brief Flag for whether the DMatrix has categorical features.
225 */
226 bool HasCategorical() const { return has_categorical_; }
227 /**
228 * @brief Getters for categories.
229 */
230 [[nodiscard]] CatContainer const* Cats() const;
231 [[nodiscard]] CatContainer* Cats();
232 [[nodiscard]] std::shared_ptr<CatContainer const> CatsShared() const;
233 /**
234 * @brief Setter for categories.
235 */
236 void Cats(std::shared_ptr<CatContainer> cats);
237
238 private:
239 void SetInfoFromHost(Context const* ctx, StringView key, Json arr);
240 void SetInfoFromCUDA(Context const* ctx, StringView key, Json arr);
241
242 /*! \brief argsort of labels */
243 mutable std::vector<size_t> label_order_cache_;
244 bool has_categorical_{false};
245
246 std::shared_ptr<CatContainer> cats_;
247 };
248
249 /*! \brief Element from a sparse vector */
250 struct Entry {
251 /*! \brief feature index */
252 bst_feature_t index;
253 /*! \brief feature value */
254 bst_float fvalue;
255 /*! \brief default constructor */
256 Entry() = default;
257 /*!
258 * \brief constructor with index and value
259 * \param index The feature or row index.
260 * \param fvalue The feature value.
261 */
262 XGBOOST_DEVICE Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {}
263 /*! \brief reversely compare feature values */
264 inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; }
265 static bool CmpIndex(Entry const& a, Entry const& b) { return a.index < b.index; }
266 inline bool operator==(const Entry& other) const {
267 return (this->index == other.index && this->fvalue == other.fvalue);
268 }
269 };
270
271 /**
272 * @brief Parameters for constructing histogram index batches.
273 */
274 struct BatchParam {
275 /**
276 * @brief Maximum number of bins per feature for histograms.
277 */
278 bst_bin_t max_bin{0};
279 /**
280 * @brief Hessian, used for sketching with future approx implementation.
281 */
282 common::Span<float const> hess;
283 /**
284 * @brief Whether should we force DMatrix to regenerate the batch. Only used for
285 * GHistIndex.
286 */
287 bool regen{false};
288 /**
289 * @brief Forbid regenerating the gradient index. Used for internal validation.
290 */
291 bool forbid_regen{false};
292 /**
293 * @brief Parameter used to generate column matrix for hist.
294 */
295 double sparse_thresh{std::numeric_limits<double>::quiet_NaN()};
296 /**
297 * @brief Used for GPU external memory. Whether to copy the data into device.
298 *
299 * This affects only the current round of iteration.
300 */
301 bool prefetch_copy{true};
302 /**
303 * @brief The number of batches to pre-fetch for external memory.
304 */
305 std::int32_t n_prefetch_batches{3};
306 /**
307 * @brief Exact or others that don't need histogram.
308 */
309 BatchParam() = default;
310 /**
311 * @brief Used by the hist tree method.
312 */
313 BatchParam(bst_bin_t max_bin, double sparse_thresh)
314 : max_bin{max_bin}, sparse_thresh{sparse_thresh} {}
315 /**
316 * @brief Used by the approx tree method.
317 *
318 * Get batch with sketch weighted by hessian. The batch will be regenerated if the
319 * span is changed, so caller should keep the span for each iteration.
320 */
321 BatchParam(bst_bin_t max_bin, common::Span<float const> hessian, bool regenerate)
322 : max_bin{max_bin}, hess{hessian}, regen{regenerate} {}
323
324 [[nodiscard]] bool ParamNotEqual(BatchParam const& other) const {
325 // Check non-floating parameters.
326 bool cond = max_bin != other.max_bin;
327 // Check sparse thresh.
328 bool l_nan = std::isnan(sparse_thresh);
329 bool r_nan = std::isnan(other.sparse_thresh);
330 bool st_chg = (l_nan != r_nan) || (!l_nan && !r_nan && (sparse_thresh != other.sparse_thresh));
331 cond |= st_chg;
332
333 return cond;
334 }
335 [[nodiscard]] bool Initialized() const { return max_bin != 0; }
336 /**
337 * @brief Make a copy of self for DMatrix to describe how its existing index was generated.
338 */
339 [[nodiscard]] BatchParam MakeCache() const {
340 auto p = *this;
341 // These parameters have nothing to do with how the gradient index was generated in the
342 // first place.
343 p.regen = false;
344 p.forbid_regen = false;
345 return p;
346 }
347 };
348
349 struct HostSparsePageView {
350 using Inst = common::Span<Entry const>;
351
352 common::Span<bst_idx_t const> offset;
353 common::Span<Entry const> data;
354
355 [[nodiscard]] Inst operator[](std::size_t i) const {
356 auto size = *(offset.data() + i + 1) - *(offset.data() + i);
357 return {data.data() + *(offset.data() + i), static_cast<Inst::index_type>(size)};
358 }
359
360 [[nodiscard]] size_t Size() const { return offset.size() == 0 ? 0 : offset.size() - 1; }
361 };
362
363 /*!
364 * \brief In-memory storage unit of sparse batch, stored in CSR format.
365 */
366 class SparsePage {
367 public:
368 // Offset for each row.
369 HostDeviceVector<bst_idx_t> offset;
370 /*! \brief the data of the segments */
371 HostDeviceVector<Entry> data;
372
373 size_t base_rowid{0};
374
375 /*! \brief an instance of sparse vector in the batch */
376 using Inst = common::Span<Entry const>;
377
378 [[nodiscard]] HostSparsePageView GetView() const {
379 return {offset.ConstHostSpan(), data.ConstHostSpan()};
380 }
381
382 /*! \brief constructor */
383 SparsePage() { this->Clear(); }
384
385 SparsePage(SparsePage const& that) = delete;
386 SparsePage(SparsePage&& that) = default;
387 SparsePage& operator=(SparsePage const& that) = delete;
388 SparsePage& operator=(SparsePage&& that) = default;
389 virtual ~SparsePage() = default;
390
391 /*! \return Number of instances in the page. */
392 [[nodiscard]] size_t Size() const { return offset.Size() == 0 ? 0 : offset.Size() - 1; }
393
394 /*! \return estimation of memory cost of this page */
395 [[nodiscard]] size_t MemCostBytes() const {
396 return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry);
397 }
398
399 /*! \brief clear the page */
400 inline void Clear() {
401 base_rowid = 0;
402 auto& offset_vec = offset.HostVector();
403 offset_vec.clear();
404 offset_vec.push_back(0);
405 data.HostVector().clear();
406 }
407
408 /*! \brief Set the base row id for this page. */
409 inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; }
410
411 [[nodiscard]] SparsePage GetTranspose(int num_columns, int32_t n_threads) const;
412
413 /**
414 * \brief Sort the column index.
415 */
416 void SortIndices(int32_t n_threads);
417 /**
418 * \brief Check wether the column index is sorted.
419 */
420 [[nodiscard]] bool IsIndicesSorted(int32_t n_threads) const;
421 /**
422 * \brief Reindex the column index with an offset.
423 */
424 void Reindex(uint64_t feature_offset, int32_t n_threads);
425
426 void SortRows(int32_t n_threads);
427
428 /**
429 * \brief Pushes external data batch onto this page
430 *
431 * \tparam AdapterBatchT
432 * \param batch
433 * \param missing
434 * \param nthread
435 *
436 * \return The maximum number of columns encountered in this input batch. Useful when pushing many adapter batches to work out the total number of columns.
437 */
438 template <typename AdapterBatchT>
439 bst_idx_t Push(AdapterBatchT const& batch, float missing, std::int32_t nthread);
440
441 /*!
442 * \brief Push a sparse page
443 * \param batch the row page
444 */
445 void Push(const SparsePage& batch);
446 /*!
447 * \brief Push a SparsePage stored in CSC format
448 * \param batch The row batch to be pushed
449 */
450 void PushCSC(const SparsePage& batch);
451 };
452
453 class CSCPage : public SparsePage {
454 public:
455 CSCPage() : SparsePage() {}
456 explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {}
457 };
458
459 /**
460 * \brief Sparse page for exporting DMatrix. Same as SparsePage, just a different type to
461 * prevent being used internally.
462 */
463 class ExtSparsePage {
464 public:
465 std::shared_ptr<SparsePage const> page;
466 explicit ExtSparsePage(std::shared_ptr<SparsePage const> p) : page{std::move(p)} {}
467 };
468
469 class SortedCSCPage : public SparsePage {
470 public:
471 SortedCSCPage() : SparsePage() {}
472 explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {}
473 };
474
475 class EllpackPage;
476 class GHistIndexMatrix;
477
478 template <typename T>
479 class BatchIteratorImpl {
480 public:
481 using iterator_category = std::forward_iterator_tag; // NOLINT
482 virtual ~BatchIteratorImpl() = default;
483 virtual const T& operator*() const = 0;
484 virtual BatchIteratorImpl& operator++() = 0;
485 [[nodiscard]] virtual bool AtEnd() const = 0;
486 virtual std::shared_ptr<T const> Page() const = 0;
487 };
488
489 template <typename T>
490 class BatchIterator {
491 public:
492 using iterator_category = std::forward_iterator_tag; // NOLINT
493 explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); }
494 explicit BatchIterator(std::shared_ptr<BatchIteratorImpl<T>> impl) { impl_ = impl; }
495
496 BatchIterator& operator++() {
497 CHECK(impl_ != nullptr);
498 ++(*impl_);
499 return *this;
500 }
501
502 const T& operator*() const {
503 CHECK(impl_ != nullptr);
504 return *(*impl_);
505 }
506
507 [[nodiscard]] bool operator!=(const BatchIterator&) const { return !this->AtEnd(); }
508
509 [[nodiscard]] bool AtEnd() const {
510 CHECK(impl_ != nullptr);
511 return impl_->AtEnd();
512 }
513
514 [[nodiscard]] std::shared_ptr<T const> Page() const { return impl_->Page(); }
515
516 private:
517 std::shared_ptr<BatchIteratorImpl<T>> impl_;
518 };
519
520 template <typename T>
521 class BatchSet {
522 public:
523 explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(std::move(begin_iter)) {}
524 BatchIterator<T> begin() { return begin_iter_; } // NOLINT
525 BatchIterator<T> end() { return BatchIterator<T>(nullptr); } // NOLINT
526
527 private:
528 BatchIterator<T> begin_iter_;
529 };
530
531 struct XGBAPIThreadLocalEntry;
532
533 // Configuration for external memoroy DMatrix.
534 struct ExtMemConfig {
535 // Cache prefix, not used if the cache is in the host memory. (on_host is true)
536 std::string cache;
537 // Whether the ellpack page is stored in the host memory.
538 bool on_host;
539 // Host cache/Total cache for the GPU impl.
540 float cache_host_ratio;
541 // Minimum number of of bytes for each ellpack page in cache. Only used for in-host
542 // ExtMemQdm.
543 std::int64_t min_cache_page_bytes;
544 // Missing value.
545 float missing;
546 // The number of CPU threads.
547 std::int32_t n_threads{0};
548 // The ratio of the cache that can be compressed. Used for testing.
549 float hw_decomp_ratio{std::numeric_limits<float>::quiet_NaN()};
550 // Fallback to using nvcomp. Used for testing.
551 bool allow_decomp_fallback{false};
552
553 ExtMemConfig() = delete;
554 ExtMemConfig(std::string cache, bool on_host, float h_ratio, std::int64_t min_cache,
555 float missing, std::int32_t n_threads)
556 : cache{std::move(cache)},
557 on_host{on_host},
558 cache_host_ratio{h_ratio},
559 min_cache_page_bytes{min_cache},
560 missing{missing},
561 n_threads{n_threads} {}
562
563 ExtMemConfig& SetParamsForTest(float _hw_decomp_ratio, bool _allow_decomp_fallback) {
564 this->hw_decomp_ratio = _hw_decomp_ratio;
565 this->allow_decomp_fallback = _allow_decomp_fallback;
566 return *this;
567 }
568 };
569
570 /**
571 * @brief Internal data structured used by XGBoost to hold all external data.
572 *
573 * There are multiple variants of the DMatrix class and can be accessed through the
574 * @ref Create() methods. The DMatrix itself holds the predictor `X`, and other data
575 * including labels and sample weights are stored in the @ref MetaInfo class.
576 */
577 class DMatrix {
578 public:
579 /*! \brief default constructor */
580 DMatrix() = default;
581 /** @brief meta information of the dataset */
582 [[nodiscard]] virtual MetaInfo& Info() = 0;
583 virtual void SetInfo(const char* key, std::string const& interface_str) {
584 auto const& ctx = *this->Ctx();
585 this->Info().SetInfo(ctx, key, StringView{interface_str});
586 }
587 /** @brief meta information of the dataset */
588 [[nodiscard]] virtual const MetaInfo& Info() const = 0;
589
590 /*! \brief Get thread local memory for returning data from DMatrix. */
591 [[nodiscard]] XGBAPIThreadLocalEntry& GetThreadLocal() const;
592 /**
593 * @brief Get the context object of this DMatrix. The context is created during construction of
594 * DMatrix with user specified `nthread` parameter.
595 */
596 [[nodiscard]] virtual Context const* Ctx() const = 0;
597
598 /**
599 * @brief Gets batches. Use range based for loop over BatchSet to access individual batches.
600 */
601 template <typename T>
602 BatchSet<T> GetBatches();
603 template <typename T>
604 BatchSet<T> GetBatches(Context const* ctx);
605 template <typename T>
606 BatchSet<T> GetBatches(Context const* ctx, const BatchParam& param);
607 template <typename T>
608 [[nodiscard]] bool PageExists() const;
609
610 /**
611 * @return Whether the contains a single batch.
612 *
613 * The naming is legacy.
614 */
615 [[nodiscard]] bool SingleColBlock() const { return this->NumBatches() == 1; }
616 [[nodiscard]] virtual std::int32_t NumBatches() const { return 1; }
617
618 virtual ~DMatrix();
619
620 /**
621 * @brief Whether the matrix is dense.
622 */
623 [[nodiscard]] bool IsDense() const { return this->Info().IsDense(); }
624
625 /**
626 * @brief Load DMatrix from URI.
627 *
628 * @param uri The URI of input.
629 * @param silent Whether print information during loading.
630 * @param data_split_mode Indicate how the data was split beforehand.
631 * @return The created DMatrix.
632 */
633 static DMatrix* Load(const std::string& uri, bool silent = true,
634 DataSplitMode data_split_mode = DataSplitMode::kRow);
635
636 /**
637 * @brief Creates a new DMatrix from an external data adapter.
638 *
639 * @tparam AdapterT Type of the adapter.
640 * @param [in,out] adapter View onto an external data.
641 * @param missing Values to count as missing.
642 * @param nthread Number of threads for construction.
643 * @param cache_prefix (Optional) The cache prefix for external memory.
644 * @param data_split_mode (Optional) Data split mode.
645 *
646 * @return a Created DMatrix.
647 */
648 template <typename AdapterT>
649 static DMatrix* Create(AdapterT* adapter, float missing, int nthread,
650 const std::string& cache_prefix = "",
651 DataSplitMode data_split_mode = DataSplitMode::kRow);
652
653 /**
654 * @brief Create a new Quantile based DMatrix used for histogram based algorithm.
655 *
656 * @tparam DataIterHandle External iterator type, defined in C API.
657 * @tparam DMatrixHandle DMatrix handle, defined in C API.
658 * @tparam DataIterResetCallback Callback for reset, prototype defined in C API.
659 * @tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API.
660 *
661 * @param iter External data iterator
662 * @param proxy A hanlde to ProxyDMatrix
663 * @param ref Reference Quantile DMatrix.
664 * @param reset Callback for reset
665 * @param next Callback for next
666 * @param missing Value that should be treated as missing.
667 * @param nthread number of threads used for initialization.
668 * @param max_bin Maximum number of bins.
669 *
670 * @return A created quantile based DMatrix.
671 */
672 template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback,
673 typename XGDMatrixCallbackNext>
674 static DMatrix* Create(DataIterHandle iter, DMatrixHandle proxy, std::shared_ptr<DMatrix> ref,
675 DataIterResetCallback* reset, XGDMatrixCallbackNext* next, float missing,
676 std::int32_t nthread, bst_bin_t max_bin, std::int64_t max_quantile_blocks);
677
678 /**
679 * @brief Create an external memory DMatrix with callbacks.
680 *
681 * @tparam DataIterHandle External iterator type, defined in C API.
682 * @tparam DMatrixHandle DMatrix handle, defined in C API.
683 * @tparam DataIterResetCallback Callback for reset, prototype defined in C API.
684 * @tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API.
685 *
686 * @param iter External data iterator
687 * @param proxy A hanlde to ProxyDMatrix
688 * @param reset Callback for reset
689 * @param next Callback for next
690 * @param config Configuration for the cache.
691 *
692 * @return A created external memory DMatrix.
693 */
694 template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback,
695 typename XGDMatrixCallbackNext>
696 static DMatrix* Create(DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback* reset,
697 XGDMatrixCallbackNext* next, ExtMemConfig const& config);
698
699 /**
700 * @brief Create an external memory quantile DMatrix with callbacks.
701 *
702 * Parameters are a combination of the external memory DMatrix and the quantile DMatrix.
703 *
704 * @return A created external memory quantile DMatrix.
705 */
706 template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback,
707 typename XGDMatrixCallbackNext>
708 static DMatrix* Create(DataIterHandle iter, DMatrixHandle proxy, std::shared_ptr<DMatrix> ref,
709 DataIterResetCallback* reset, XGDMatrixCallbackNext* next,
710 bst_bin_t max_bin, std::int64_t max_quantile_blocks,
711 ExtMemConfig const& config);
712
713 virtual DMatrix* Slice(common::Span<int32_t const> ridxs) = 0;
714
715 /**
716 * @brief Slice a DMatrix by columns.
717 *
718 * @param num_slices Total number of slices
719 * @param slice_id Index of the current slice
720 * @return DMatrix containing the slice of columns
721 */
722 virtual DMatrix* SliceCol(int num_slices, int slice_id) = 0;
723 /**
724 * @brief Accessor for the string representation of the categories.
725 */
726 [[nodiscard]] CatContainer const* Cats() const { return this->CatsShared().get(); }
727 [[nodiscard]] std::shared_ptr<CatContainer const> CatsShared() const {
728 return this->Info().CatsShared();
729 }
730
731 protected:
732 virtual BatchSet<SparsePage> GetRowBatches() = 0;
733 virtual BatchSet<CSCPage> GetColumnBatches(Context const* ctx) = 0;
734 virtual BatchSet<SortedCSCPage> GetSortedColumnBatches(Context const* ctx) = 0;
735 virtual BatchSet<EllpackPage> GetEllpackBatches(Context const* ctx, BatchParam const& param) = 0;
736 virtual BatchSet<GHistIndexMatrix> GetGradientIndex(Context const* ctx,
737 BatchParam const& param) = 0;
738 virtual BatchSet<ExtSparsePage> GetExtBatches(Context const* ctx, BatchParam const& param) = 0;
739
740 [[nodiscard]] virtual bool EllpackExists() const = 0;
741 [[nodiscard]] virtual bool GHistIndexExists() const = 0;
742 [[nodiscard]] virtual bool SparsePageExists() const = 0;
743 };
744
745 template <>
746 inline BatchSet<SparsePage> DMatrix::GetBatches() {
747 return GetRowBatches();
748 }
749
750 template <>
751 inline bool DMatrix::PageExists<EllpackPage>() const {
752 return this->EllpackExists();
753 }
754
755 template <>
756 inline bool DMatrix::PageExists<GHistIndexMatrix>() const {
757 return this->GHistIndexExists();
758 }
759
760 template <>
761 inline bool DMatrix::PageExists<SparsePage>() const {
762 return this->SparsePageExists();
763 }
764
765 template <>
766 inline BatchSet<SparsePage> DMatrix::GetBatches(Context const*) {
767 return GetRowBatches();
768 }
769
770 template <>
771 inline BatchSet<CSCPage> DMatrix::GetBatches(Context const* ctx) {
772 return GetColumnBatches(ctx);
773 }
774
775 template <>
776 inline BatchSet<SortedCSCPage> DMatrix::GetBatches(Context const* ctx) {
777 return GetSortedColumnBatches(ctx);
778 }
779
780 template <>
781 inline BatchSet<EllpackPage> DMatrix::GetBatches(Context const* ctx, BatchParam const& param) {
782 return GetEllpackBatches(ctx, param);
783 }
784
785 template <>
786 inline BatchSet<GHistIndexMatrix> DMatrix::GetBatches(Context const* ctx, BatchParam const& param) {
787 return GetGradientIndex(ctx, param);
788 }
789
790 template <>
791 inline BatchSet<ExtSparsePage> DMatrix::GetBatches(Context const* ctx, BatchParam const& param) {
792 return GetExtBatches(ctx, param);
793 }
794 } // namespace xgboost
795
796 DECLARE_FIELD_ENUM_CLASS(xgboost::DataSplitMode);
797
798 namespace dmlc {
799 DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true);
800
801 namespace serializer {
802
803 template <>
804 struct Handler<xgboost::Entry> {
805 inline static void Write(Stream* strm, const xgboost::Entry& data) {
806 strm->Write(data.index);
807 strm->Write(data.fvalue);
808 }
809
810 inline static bool Read(Stream* strm, xgboost::Entry* data) {
811 return strm->Read(&data->index) && strm->Read(&data->fvalue);
812 }
813 };
814
815 } // namespace serializer
816 } // namespace dmlc
817 #endif // XGBOOST_DATA_H_