Medial Code Documentation
Loading...
Searching...
No Matches
column_matrix.h
Go to the documentation of this file.
1
8#ifndef XGBOOST_COMMON_COLUMN_MATRIX_H_
9#define XGBOOST_COMMON_COLUMN_MATRIX_H_
10
11#include <algorithm>
12#include <cstddef> // for size_t, byte
13#include <cstdint> // for uint8_t
14#include <limits>
15#include <memory>
16#include <type_traits> // for enable_if_t, is_same_v, is_signed_v
17#include <utility> // for move
18
19#include "../data/adapter.h"
20#include "../data/gradient_index.h"
21#include "algorithm.h"
22#include "bitfield.h" // for RBitField8
23#include "hist_util.h"
24#include "ref_resource_view.h" // for RefResourceView
25#include "xgboost/base.h" // for bst_bin_t
26#include "xgboost/span.h" // for Span
27
28namespace xgboost::common {
29class ColumnMatrix;
30class AlignedFileWriteStream;
31class AlignedResourceReadStream;
32
34enum ColumnType : std::uint8_t { kDenseColumn, kSparseColumn };
35
40template <typename BinIdxType>
41class Column {
42 public:
43 static constexpr bst_bin_t kMissingId = -1;
44
46 : index_(index), index_base_(least_bin_idx) {}
47 virtual ~Column() = default;
48
49 [[nodiscard]] bst_bin_t GetGlobalBinIdx(size_t idx) const {
50 return index_base_ + static_cast<bst_bin_t>(index_[idx]);
51 }
52
53 /* returns number of elements in column */
54 [[nodiscard]] size_t Size() const { return index_.size(); }
55
56 private:
57 /* bin indexes in range [0, max_bins - 1] */
59 /* bin index offset for specific feature */
60 bst_bin_t const index_base_;
61};
62
63template <typename BinIdxT>
64class SparseColumnIter : public Column<BinIdxT> {
65 private:
66 using Base = Column<BinIdxT>;
67 /* indexes of rows */
69 size_t idx_;
70
71 [[nodiscard]] size_t const* RowIndices() const { return row_ind_.data(); }
72
73 public:
75 common::Span<const size_t> row_ind, bst_row_t first_row_idx)
76 : Base{index, least_bin_idx}, row_ind_(row_ind) {
77 // first_row_id is the first row in the leaf partition
78 const size_t* row_data = RowIndices();
79 const size_t column_size = this->Size();
80 // search first nonzero row with index >= rid_span.front()
81 // note that the input row partition is always sorted.
82 const size_t* p = std::lower_bound(row_data, row_data + column_size, first_row_idx);
83 // column_size if all missing
84 idx_ = p - row_data;
85 }
86 SparseColumnIter(SparseColumnIter const&) = delete;
88
89 [[nodiscard]] size_t GetRowIdx(size_t idx) const { return RowIndices()[idx]; }
90 bst_bin_t operator[](size_t rid) {
91 const size_t column_size = this->Size();
92 if (!((idx_) < column_size)) {
93 return this->kMissingId;
94 }
95 // find next non-missing row
96 while ((idx_) < column_size && GetRowIdx(idx_) < rid) {
97 ++(idx_);
98 }
99 if (((idx_) < column_size) && GetRowIdx(idx_) == rid) {
100 // non-missing row found
101 return this->GetGlobalBinIdx(idx_);
102 } else {
103 // at the end of column
104 return this->kMissingId;
105 }
106 }
107};
108
113template <typename BinIdxT, bool any_missing>
114class DenseColumnIter : public Column<BinIdxT> {
115 private:
116 using Base = Column<BinIdxT>;
117 /* flags for missing values in dense columns */
118 LBitField32 missing_flags_;
119 size_t feature_offset_;
120
121 public:
122 explicit DenseColumnIter(common::Span<const BinIdxT> index, bst_bin_t index_base,
123 LBitField32 missing_flags, size_t feature_offset)
124 : Base{index, index_base}, missing_flags_{missing_flags}, feature_offset_{feature_offset} {}
125 DenseColumnIter(DenseColumnIter const&) = delete;
126 DenseColumnIter(DenseColumnIter&&) = default;
127
128 [[nodiscard]] bool IsMissing(size_t ridx) const {
129 return missing_flags_.Check(feature_offset_ + ridx);
130 }
131
132 bst_bin_t operator[](size_t ridx) const {
133 if (any_missing) {
134 return IsMissing(ridx) ? this->kMissingId : this->GetGlobalBinIdx(ridx);
135 } else {
136 return this->GetGlobalBinIdx(ridx);
137 }
138 }
139};
140
152 struct MissingIndicator {
153 using BitFieldT = LBitField32;
154 using T = typename BitFieldT::value_type;
155
156 BitFieldT missing;
157 RefResourceView<T> storage;
158 static_assert(std::is_same_v<T, std::uint32_t>);
159
160 template <typename U>
161 [[nodiscard]] std::enable_if_t<!std::is_signed_v<U>, U> static InitValue(bool init) {
162 return init ? ~U{0} : U{0};
163 }
164
165 MissingIndicator() = default;
170 MissingIndicator(std::size_t n_elements, bool init) {
171 auto m_size = missing.ComputeStorageSize(n_elements);
172 storage = common::MakeFixedVecWithMalloc(m_size, InitValue<T>(init));
173 this->InitView();
174 }
176 void SetValid(typename LBitField32::index_type i) { missing.Clear(i); }
178 void InitView() {
179 missing = LBitField32{Span{storage.data(), storage.size()}};
180 }
181
182 void GrowTo(std::size_t n_elements, bool init) {
183 CHECK(storage.Resource()->Type() == ResourceHandler::kMalloc)
184 << "[Internal Error]: Cannot grow the vector when external memory is used.";
185 auto m_size = missing.ComputeStorageSize(n_elements);
186 CHECK_GE(m_size, storage.size());
187 if (m_size == storage.size()) {
188 return;
189 }
190 // grow the storage
191 auto resource = std::dynamic_pointer_cast<common::MallocResource>(storage.Resource());
192 CHECK(resource);
193 resource->Resize(m_size * sizeof(T), InitValue<std::byte>(init));
194 storage = RefResourceView<T>{resource->DataAs<T>(), m_size, resource};
195
196 this->InitView();
197 }
198 };
199
200 void InitStorage(GHistIndexMatrix const& gmat, double sparse_threshold);
201
202 template <typename ColumnBinT, typename BinT, typename RIdx>
203 void SetBinSparse(BinT bin_id, RIdx rid, bst_feature_t fid, ColumnBinT* local_index) {
204 if (type_[fid] == kDenseColumn) {
205 ColumnBinT* begin = &local_index[feature_offsets_[fid]];
206 begin[rid] = bin_id - index_base_[fid];
207 // not thread-safe with bit field.
208 // FIXME(jiamingy): We can directly assign kMissingId to the index to avoid missing
209 // flags.
210 missing_.SetValid(feature_offsets_[fid] + rid);
211 } else {
212 ColumnBinT* begin = &local_index[feature_offsets_[fid]];
213 begin[num_nonzeros_[fid]] = bin_id - index_base_[fid];
214 row_ind_[feature_offsets_[fid] + num_nonzeros_[fid]] = rid;
215 ++num_nonzeros_[fid];
216 }
217 }
218
219 public:
220 // get number of features
221 [[nodiscard]] bst_feature_t GetNumFeature() const {
222 return static_cast<bst_feature_t>(type_.size());
223 }
224
225 ColumnMatrix() = default;
226 ColumnMatrix(GHistIndexMatrix const& gmat, double sparse_threshold) {
227 this->InitStorage(gmat, sparse_threshold);
228 }
229
234 void InitFromSparse(SparsePage const& page, const GHistIndexMatrix& gmat, double sparse_threshold,
235 int32_t n_threads) {
236 auto batch = data::SparsePageAdapterBatch{page.GetView()};
237 this->InitStorage(gmat, sparse_threshold);
238 // ignore base row id here as we always has one column matrix for each sparse page.
239 this->PushBatch(n_threads, batch, std::numeric_limits<float>::quiet_NaN(), gmat, 0);
240 }
241
249 void InitFromGHist(Context const* ctx, GHistIndexMatrix const& gmat) {
250 auto n_threads = ctx->Threads();
251 if (!any_missing_) {
252 // row index is compressed, we need to dispatch it.
253 DispatchBinType(gmat.index.GetBinTypeSize(), [&, size = gmat.Size(), n_threads = n_threads,
254 n_features = gmat.Features()](auto t) {
255 using RowBinIdxT = decltype(t);
256 SetIndexNoMissing(gmat.base_rowid, gmat.index.data<RowBinIdxT>(), size, n_features,
257 n_threads);
258 });
259 } else {
261 }
262 }
263
264 [[nodiscard]] bool IsInitialized() const { return !type_.empty(); }
265
273 template <typename Batch>
274 void PushBatch(int32_t n_threads, Batch const& batch, float missing, GHistIndexMatrix const& gmat,
275 size_t base_rowid) {
276 // pre-fill index_ for dense columns
277 if (!any_missing_) {
278 // row index is compressed, we need to dispatch it.
279
280 // use base_rowid from input parameter as gmat is a single matrix that contains all
281 // the histogram index instead of being only a batch.
282 DispatchBinType(gmat.index.GetBinTypeSize(), [&, size = batch.Size(), n_threads = n_threads,
283 n_features = gmat.Features()](auto t) {
284 using RowBinIdxT = decltype(t);
285 SetIndexNoMissing(base_rowid, gmat.index.data<RowBinIdxT>(), size, n_features, n_threads);
286 });
287 } else {
288 SetIndexMixedColumns(base_rowid, batch, gmat, missing);
289 }
290 }
291
292 /* Set the number of bytes based on numeric limit of maximum number of bins provided by user */
293 void SetTypeSize(size_t max_bin_per_feat) {
294 if ((max_bin_per_feat - 1) <= static_cast<int>(std::numeric_limits<uint8_t>::max())) {
295 bins_type_size_ = kUint8BinsTypeSize;
296 } else if ((max_bin_per_feat - 1) <= static_cast<int>(std::numeric_limits<uint16_t>::max())) {
297 bins_type_size_ = kUint16BinsTypeSize;
298 } else {
299 bins_type_size_ = kUint32BinsTypeSize;
300 }
301 }
302
303 template <typename BinIdxType>
304 auto SparseColumn(bst_feature_t fidx, bst_row_t first_row_idx) const {
305 const size_t feature_offset = feature_offsets_[fidx]; // to get right place for certain feature
306 const size_t column_size = feature_offsets_[fidx + 1] - feature_offset;
307 common::Span<const BinIdxType> bin_index = {
308 reinterpret_cast<const BinIdxType*>(&index_[feature_offset * bins_type_size_]),
309 column_size};
310 return SparseColumnIter<BinIdxType>(bin_index, index_base_[fidx],
311 {&row_ind_[feature_offset], column_size}, first_row_idx);
312 }
313
314 template <typename BinIdxType, bool any_missing>
315 auto DenseColumn(bst_feature_t fidx) const {
316 const size_t feature_offset = feature_offsets_[fidx]; // to get right place for certain feature
317 const size_t column_size = feature_offsets_[fidx + 1] - feature_offset;
318 common::Span<const BinIdxType> bin_index = {
319 reinterpret_cast<const BinIdxType*>(&index_[feature_offset * bins_type_size_]),
320 column_size};
321 return std::move(DenseColumnIter<BinIdxType, any_missing>{
322 bin_index, static_cast<bst_bin_t>(index_base_[fidx]), missing_.missing, feature_offset});
323 }
324
325 // all columns are dense column and has no missing value
326 // FIXME(jiamingy): We don't need a column matrix if there's no missing value.
327 template <typename RowBinIdxT>
328 void SetIndexNoMissing(bst_row_t base_rowid, RowBinIdxT const* row_index, const size_t n_samples,
329 const size_t n_features, int32_t n_threads) {
330 missing_.GrowTo(feature_offsets_[n_features], false);
331
332 DispatchBinType(bins_type_size_, [&](auto t) {
333 using ColumnBinT = decltype(t);
334 auto column_index = Span<ColumnBinT>{reinterpret_cast<ColumnBinT*>(index_.data()),
335 index_.size() / sizeof(ColumnBinT)};
336 ParallelFor(n_samples, n_threads, [&](auto rid) {
337 rid += base_rowid;
338 const size_t ibegin = rid * n_features;
339 const size_t iend = (rid + 1) * n_features;
340 for (size_t i = ibegin, j = 0; i < iend; ++i, ++j) {
341 const size_t idx = feature_offsets_[j];
342 // No need to add offset, as row index is compressed and stores the local index
343 column_index[idx + rid] = row_index[i];
344 }
345 });
346 });
347 }
348
352 template <typename Batch>
353 void SetIndexMixedColumns(size_t base_rowid, Batch const& batch, const GHistIndexMatrix& gmat,
354 float missing) {
355 auto n_features = gmat.Features();
356
357 missing_.GrowTo(feature_offsets_[n_features], true);
358 auto const* row_index = gmat.index.data<std::uint32_t>() + gmat.row_ptr[base_rowid];
359 if (num_nonzeros_.empty()) {
360 num_nonzeros_ = common::MakeFixedVecWithMalloc(n_features, std::size_t{0});
361 } else {
362 CHECK_EQ(num_nonzeros_.size(), n_features);
363 }
364
365 auto is_valid = data::IsValidFunctor{missing};
366
367 DispatchBinType(bins_type_size_, [&](auto t) {
368 using ColumnBinT = decltype(t);
369 ColumnBinT* local_index = reinterpret_cast<ColumnBinT*>(index_.data());
370 size_t const batch_size = batch.Size();
371 size_t k{0};
372 for (size_t rid = 0; rid < batch_size; ++rid) {
373 auto line = batch.GetLine(rid);
374 for (size_t i = 0; i < line.Size(); ++i) {
375 auto coo = line.GetElement(i);
376 if (is_valid(coo)) {
377 auto fid = coo.column_idx;
378 const uint32_t bin_id = row_index[k];
379 SetBinSparse(bin_id, rid + base_rowid, fid, local_index);
380 ++k;
381 }
382 }
383 }
384 });
385 }
386
392 auto n_features = gmat.Features();
393
394 missing_ = MissingIndicator{feature_offsets_[n_features], true};
395 num_nonzeros_ = common::MakeFixedVecWithMalloc(n_features, std::size_t{0});
396
397 DispatchBinType(bins_type_size_, [&](auto t) {
398 using ColumnBinT = decltype(t);
399 ColumnBinT* local_index = reinterpret_cast<ColumnBinT*>(index_.data());
400 CHECK(this->any_missing_);
402 [&](auto bin_idx, std::size_t, std::size_t ridx, bst_feature_t fidx) {
403 SetBinSparse(bin_idx, ridx, fidx, local_index);
404 });
405 });
406 }
407
408 [[nodiscard]] BinTypeSize GetTypeSize() const { return bins_type_size_; }
409 [[nodiscard]] auto GetColumnType(bst_feature_t fidx) const { return type_[fidx]; }
410
411 // And this returns part of state
412 [[nodiscard]] bool AnyMissing() const { return any_missing_; }
413
414 // IO procedures for external memory.
415 [[nodiscard]] bool Read(AlignedResourceReadStream* fi, uint32_t const* index_base);
416 [[nodiscard]] std::size_t Write(AlignedFileWriteStream* fo) const;
417 [[nodiscard]] MissingIndicator const& Missing() const { return missing_; }
418
419 private:
420 RefResourceView<std::uint8_t> index_;
421
422 RefResourceView<ColumnType> type_;
424 RefResourceView<std::size_t> row_ind_;
426 RefResourceView<std::size_t> feature_offsets_;
428 RefResourceView<std::size_t> num_nonzeros_;
429
430 // index_base_[fid]: least bin id for feature fid
431 std::uint32_t const* index_base_;
432
433 MissingIndicator missing_;
434
435 BinTypeSize bins_type_size_;
436 bool any_missing_;
437};
438} // namespace xgboost::common
439#endif // XGBOOST_COMMON_COLUMN_MATRIX_H_
Copyright 2019-2023, XGBoost Contributors.
preprocessed global index matrix, in CSR format.
Definition gradient_index.h:38
common::RefResourceView< std::size_t > row_ptr
row pointer to rows by element position
Definition gradient_index.h:140
common::Index index
The histogram index.
Definition gradient_index.h:144
In-memory storage unit of sparse batch, stored in CSR format.
Definition data.h:328
Column major matrix for gradient index on CPU.
Definition column_matrix.h:148
void SetIndexMixedColumns(size_t base_rowid, Batch const &batch, const GHistIndexMatrix &gmat, float missing)
Set column index for both dense and sparse columns.
Definition column_matrix.h:353
void SetIndexMixedColumns(const GHistIndexMatrix &gmat)
Set column index for both dense and sparse columns, but with only GHistMatrix available and requires ...
Definition column_matrix.h:391
void PushBatch(int32_t n_threads, Batch const &batch, float missing, GHistIndexMatrix const &gmat, size_t base_rowid)
Push batch of data for Quantile DMatrix support.
Definition column_matrix.h:274
void InitFromSparse(SparsePage const &page, const GHistIndexMatrix &gmat, double sparse_threshold, int32_t n_threads)
Initialize ColumnMatrix from GHistIndexMatrix with reference to the original SparsePage.
Definition column_matrix.h:234
void InitFromGHist(Context const *ctx, GHistIndexMatrix const &gmat)
Initialize ColumnMatrix from GHistIndexMatrix without reference to actual data.
Definition column_matrix.h:249
a column storage, to be used with ApplySplit. Note that each bin id is stored as index[i] + index_bas...
Definition column_matrix.h:41
Column stored as a dense vector.
Definition column_matrix.h:114
A vector-like type that holds a reference counted resource.
Definition ref_resource_view.h:26
auto Resource() const
Get the underlying resource.
Definition ref_resource_view.h:103
span class implementation, based on ISO++20 span<T>. The interface should be the same.
Definition span.h:424
Definition column_matrix.h:64
Definition adapter.h:1202
Copyright 2017-2023 by XGBoost Contributors.
Copyright 2015-2023 by XGBoost Contributors.
Copyright 2017-2023, XGBoost Contributors.
Definition span.h:77
ColumnType
column type
Definition column_matrix.h:34
auto DispatchBinType(BinTypeSize type, Fn &&fn)
Dispatch for bin type, fn is a function that accepts a scalar of the bin type.
Definition hist_util.h:187
RefResourceView< T > MakeFixedVecWithMalloc(std::size_t n_elements, T const &init)
Make a fixed size RefResourceView with malloc resource.
Definition ref_resource_view.h:160
uint32_t bst_feature_t
Type for data column (feature) index.
Definition base.h:101
void AssignColumnBinIndex(GHistIndexMatrix const &page, Fn &&assign)
Helper for recovering feature index from row-based storage of histogram bin.
Definition gradient_index.h:265
std::size_t bst_row_t
Type for data row index.
Definition base.h:110
int32_t bst_bin_t
Type for histogram bin index.
Definition base.h:103
Runtime context for XGBoost.
Definition context.h:84
std::int32_t Threads() const
Returns the automatically chosen number of threads based on the nthread parameter and the system sett...
Definition context.cc:203
Definition adapter.h:88