Repository navigation
Add an XGBOOST dictionary layout and the predictXGBoost function - #109999
Conversation
|
Workflow [PR], commit [4d66a72] Summary: ✅
AI ReviewSummaryThis PR adds an experimental Findings
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 4d66a72.
Changed lines: Changed C/C++ lines covered: 637/685 (92.99%) · Uncovered code |
53abf46 to
68a11e7
Compare
…ost` Add an `XGBOOST` dictionary layout that loads a trained XGBoost model, and a scalar function `predictXGBoost` that scores rows against a loaded model. The model file is removed when the dictionary is dropped. Add `xgboost` as a contrib with a hand-written CMake build, and gate the whole feature behind the experimental setting `allow_experimental_xgboost`.
`check_submodules.sh` rejects submodules whose pinned commit declares its own submodules. This is not only a style issue: nothing in CI checks out submodules recursively, so `contrib/xgboost/dmlc-core` would be an empty directory on a CI machine and the build would fail on missing sources. Point `contrib/xgboost` at the `ClickHouse/xgboost` fork, branch `ClickHouse/v3.3.0` - upstream `v3.3.0` with the `dmlc-core` gitlink removed and `.gitmodules` emptied - and add `dmlc-core` as a top-level submodule pinned at `4baa84e`, the same commit upstream `v3.3.0` referenced. No version change. Follows the existing `contrib/aws-crt-cpp` pattern.
038603b to
021c4c4
Compare
|
Can you add a test that tests the access works correctly? Like tests/queries/0_stateless/04404_naive_bayes_access.sh Probably add the following since it was covered in earlier reviews:
|
george-larionov
left a comment
There was a problem hiding this comment.
Looks good overall, nice job! See my comments. A few more things:
- Can you add a test running multiple blocks through it? You can use
max_block_sizeto set a small block size and keep the test small that way. - Just a suggestion, probably you have already done this, but try running it on some larger datasets locally, maybe compare with the XGBoost library.
| for (const auto & key_attribute : *dict_struct.key) | ||
| { | ||
| const WhichDataType which(key_attribute.type); | ||
| if (!which.isNativeNumber() || which.isEnum()) |
There was a problem hiding this comment.
I don't think something can be NativeNumber and an Enum.
| { | ||
| auto type = col.type; | ||
| WhichDataType which(type->getTypeId()); | ||
| if (!which.isNativeNumber() || which.isEnum()) |
There was a problem hiding this comment.
There was a problem hiding this comment.
Removed here as well.
| SELECT element_count, bytes_allocated FROM system.dictionaries | ||
| WHERE database = currentDatabase() AND name = 'model_04509_eager'; | ||
| DROP DICTIONARY model_04509_eager; | ||
|
|
There was a problem hiding this comment.
Can you add a test testing query_count
There was a problem hiding this comment.
Added 05264_xgboost_query_count: 0 before any prediction and after a call over no rows, +1000 for 1000 predicted rows, and +1 for a call over 1000 rows whose features are all constant, which the default implementation for constants now evaluates once. found_rate is checked alongside. 05266_xgboost_multiple_blocks also checks that every row of every block is counted.
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "No training data was provided"); | ||
|
|
||
| // Validate the parameters provided by the user | ||
| const auto params = sanitizeTrainingParams(hps); |
There was a problem hiding this comment.
I agree with the bot, there's no reason for this check to happen after all the data has been loaded, it should probably be moved into startTraining.
There was a problem hiding this comment.
Moved sanitizeTrainingParams into startTraining, which XGBoostDictionary::trainModel calls before source_ptr->loadAll, so an invalid layout parameter is now rejected before any source data is read.
| SELECT 'Error: num_iterations must be a positive integer'; | ||
| CREATE DICTIONARY model_04509_bad (x1 Float64, x2 Float64, y Float64) | ||
| PRIMARY KEY (x1, x2) SOURCE(CLICKHOUSE(TABLE 'training_04509')) | ||
| LAYOUT(XGBOOST(num_iterations 0)) LIFETIME(0); |
There was a problem hiding this comment.
Can you add a test for non numeric num_iterations? LAYOUT(XGBOOST(num_iterations 'abc'))
There was a problem hiding this comment.
Added in 05260_xgboost_num_iterations_parsing: 'abc', '10abc', 1.5, 0, 2147483647, 2147483648 and 4000000000, each checked against the expected error message.
| if (key == "num_iterations") | ||
| { | ||
| int parsed_iterations = 0; | ||
| if (!tryParse(parsed_iterations, value) || parsed_iterations <= 0) |
There was a problem hiding this comment.
I believe that tryParse will also return false if the value doesn't fit the type, something like 4000000000. Can you add a test for this? Also in this case the error would be a little confusing.
|
|
||
| -- `iteration_begin` and `iteration_end` address the boosting rounds of the model, so every round of the | ||
| -- default 100 is a valid bound. | ||
| SELECT sum(isFinite(predictXGBoost('model_04509_xgb', x1, x2, map('iteration_begin', 1, 'iteration_end', 100)))) FROM inference_04509; |
There was a problem hiding this comment.
These tests prove that the params passed don't error but they don't really prove that they are actually consumed since the result is never checked. It's pretty minor but would be quick to add/modify them to actually prove that some of these params produce different results.
`sanitizeTrainingParams` ran in `finalizeTraining`, after `loadAll` and `addTrainingData` had already scanned and buffered the whole source table, so a typo in `LAYOUT(XGBOOST(...))` paid the full read before failing. It now runs in `startTraining`, which `XGBoostDictionary::trainModel` calls before `loadAll`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`num_iterations` was parsed into an `int`, so a positive integer that does not fit, such as `4000000000`, was rejected as "must be a positive integer". It is now parsed as `UInt64`, and a value above the `int` iteration index of `XGBoosterUpdateOneIter` reports the maximum instead. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`WhichDataType::isNativeNumber` is already false for `Enum8` and `Enum16`, which have their own `TypeIndex`, so `|| which.isEnum()` never changed the result. A dictionary cannot have an `Enum` column anyway: `CREATE DICTIONARY` rejects it. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…atures once `predictXGBoost` inherited the default implementation for NULLs, so a NULL feature made the prediction NULL and the result type `Nullable(Float64)`, contradicting the documented `Float64`. A NULL feature is now passed to the model as NaN, the missing-value marker the matrix is created with, so it is predicted the way the model was trained to handle a missing value. The default implementation for constants is enabled, so with every feature constant the model is evaluated once. As it unwraps an all-constant call, the check that `params` is constant moved from `executeImpl` to `getReturnTypeImpl`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…er log The `xgboost.mdx` page was hand-written and outside the dictionary-layout documentation generator. Its body is now the `Documentation.description` of the `xgboost` layout registration, the page is regenerated with the `AUTOGENERATED` markers, and `xgboost` is checked by `test_dictionary_layout_pages.py`. The repeated `CREATE DICTIONARY model` example is renamed and the machine-specific `response` block is dropped. The `predictXGBoost` documentation examples used a `model` dictionary that nothing created, without `enable_xgboost`, so they failed the `Docs examples` check. They now set up the dictionary themselves. XGBoost wrote its messages to `stderr`. They are now forwarded through `XGBRegisterLogCallback` to the `XGBoost` logger, at the level XGBoost gives them and attached to the query, so they also reach `system.text_log`. The callback is kept per thread by XGBoost, so it is registered before training and before each prediction. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109999&sha=97dd7ba6e68e9934d7f39b45d371931a4b2c9c20&name_0=PR&name_1=Docs%20examples ClickHouse#109999 Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ks and access - `05264_xgboost_query_count`: `query_count` counts the rows passed to the model, and an all-constant call counts once. - `05265_xgboost_parameters_change_result`: training and prediction parameters change the result, compared by value rather than only checked to be finite. - `05266_xgboost_multiple_blocks`: predicting over many small blocks matches predicting over one. - `05267_xgboost_access`: without the `dictGet` grant, `predictXGBoost` is denied before anything else, also for no rows, for a dictionary of another layout and for a missing dictionary. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Manerone
left a comment
There was a problem hiding this comment.
Thanks for the review! I addressed all of the comments.
| throw Exception(ErrorCodes::BAD_ARGUMENTS, "No training data was provided"); | ||
|
|
||
| // Validate the parameters provided by the user | ||
| const auto params = sanitizeTrainingParams(hps); |
There was a problem hiding this comment.
Moved sanitizeTrainingParams into startTraining, which XGBoostDictionary::trainModel calls before source_ptr->loadAll, so an invalid layout parameter is now rejected before any source data is read.
| if (key == "num_iterations") | ||
| { | ||
| int parsed_iterations = 0; | ||
| if (!tryParse(parsed_iterations, value) || parsed_iterations <= 0) |
| SELECT 'Error: num_iterations must be a positive integer'; | ||
| CREATE DICTIONARY model_04509_bad (x1 Float64, x2 Float64, y Float64) | ||
| PRIMARY KEY (x1, x2) SOURCE(CLICKHOUSE(TABLE 'training_04509')) | ||
| LAYOUT(XGBOOST(num_iterations 0)) LIFETIME(0); |
There was a problem hiding this comment.
Added in 05260_xgboost_num_iterations_parsing: 'abc', '10abc', 1.5, 0, 2147483647, 2147483648 and 4000000000, each checked against the expected error message.
| for (const auto & key_attribute : *dict_struct.key) | ||
| { | ||
| const WhichDataType which(key_attribute.type); | ||
| if (!which.isNativeNumber() || which.isEnum()) |
| SELECT element_count, bytes_allocated FROM system.dictionaries | ||
| WHERE database = currentDatabase() AND name = 'model_04509_eager'; | ||
| DROP DICTIONARY model_04509_eager; | ||
|
|
There was a problem hiding this comment.
Added 05264_xgboost_query_count: 0 before any prediction and after a call over no rows, +1000 for 1000 predicted rows, and +1 for a call over 1000 rows whose features are all constant, which the default implementation for constants now evaluates once. found_rate is checked alongside. 05266_xgboost_multiple_blocks also checks that every row of every block is counted.
|
|
||
| -- `iteration_begin` and `iteration_end` address the boosting rounds of the model, so every round of the | ||
| -- default 100 is a valid bound. | ||
| SELECT sum(isFinite(predictXGBoost('model_04509_xgb', x1, x2, map('iteration_begin', 1, 'iteration_end', 100)))) FROM inference_04509; |
|
@george-larionov Regarding the suggestion to compare with XGBoost directly, I tested locally and found no significant differences. Here is the setup and the result. Setup: 500k training rows (8 features, non-linear target with noise), trained with the same parameters in an
|
# Conflicts: # src/Common/ErrorCodes.cpp # src/Interpreters/InterpreterCreateQuery.cpp
The default implementation for constants evaluates `predictXGBoost` once per block, not once per query, so the docs and the `query_count` note no longer promise a single evaluation for a whole query. `05264_xgboost_query_count` pins `max_block_size` so that its expectation does not depend on the randomized block size. `iteration_end` is an exclusive bound, one past the last boosting round to include, and is now described as such; `iteration_begin` is described as inclusive and counted from `0`. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…tion as introduced in 26.10 The checked-in `machine-learning-functions.mdx` had no `predictXGBoost` section, so the function was missing from the published function reference. It is regenerated from the `FunctionDocumentation`. The `XGBOOST` layout and `predictXGBoost` were marked as introduced in 26.9, which is already released; they land in 26.10, as the `enable_xgboost` settings history already says. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`executeImpl` returns early on an empty block, so as not to load and train the dictionary, and the checks of the number of features and of the prediction parameters came after that return: an invalid call over no rows succeeded. The feature count is now checked in `getReturnTypeImpl` from the dictionary structure, which does not load the dictionary, and so are the prediction parameters, by the new `XGBoostModel::validatePredictParams`. Only the upper bound of `iteration_begin` and `iteration_end`, which needs the trained model, is still checked when predicting. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
| SELECT sum(isFinite(predictXGBoost('model_05264_xgb', toFloat64(number), 2.0))) FROM numbers(1000) SETTINGS max_block_size = 65536; | ||
| SELECT query_count, found_rate FROM system.dictionaries WHERE database = currentDatabase() AND name = 'model_05264_xgb'; | ||
|
|
||
| SELECT 'All features constant: evaluated once per block'; |
There was a problem hiding this comment.
This still does not prove the documented once per block behavior for constant features. With numbers(1000) and max_block_size = 65536, the query always runs as a single block, so the reference 1001 would also pass if constant folding regressed to once per query.
Please force at least two blocks here (or add a focused companion case) and assert that query_count increases by the number of blocks, not just by 1.
A `Map` may repeat a key, and `buildPredictParams` kept the first value, so a contradictory call such
as `map('iteration_end', 0, 'iteration_end', 1)` silently ran with one of them. A repeated
prediction parameter is now rejected with `BAD_ARGUMENTS`.
`05264_xgboost_query_count` checked the all-constant case over a single block, which could not tell
once per block from once per query. It now runs ten blocks and checks that `query_count` grows by
at least one and at most the number of blocks.
`05266_xgboost_multiple_blocks` reads a `MergeTree` table while predicting with a dictionary that
exists only on the initiator, so it is tagged `no-parallel-replicas` like the other such tests.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds an experimental XGBoost integration: a new vendored library, an XGBOOST dictionary layout, the predictXGBoost function, an enable_xgboost setting (off by default) and an lgammaf compatibility shim. No ClickBench or TPC-H query calls any of this, so none of the flagged ClickBench slowdowns can be attributed to the PR. Q18 (+19.5%) and Q33 (+5.7%) are downgraded to not_sure. Q16 (+16.6%) and Q32 (+25.3%) were already within master's recent range and stay not_sure. All four are GROUP BY queries with more CPU time across the board, and both source ClickBench runs shared one machine, which matches environment variance rather than a code effect. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
f16642d
…85293 Conflicts resolved: - InterpreterCreateQuery.cpp: master's XGBoost layout gate (ClickHouse#109999), then the empty SQL SECURITY default kept to view shapes, since supportSQLSecurity() now also accepts dictionaries. Picks up ClickHouse#124928 (05316_secret_arguments_declared_by_engines under DatabaseReplicated). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Related: #80363
XGBoost gradient-boosted models can be trained and served as ClickHouse dictionaries, using the same lifecycle as any other dictionary:
CREATE DICTIONARY,SYSTEM RELOAD DICTIONARY,LIFETIME, access control andsystem.dictionaries.What changed
A dictionary declared with the
XGBOOSTlayout trains an XGBoost model at load time from its source table. The feature columns are thePRIMARY KEYand the single remaining attribute is the target, so the "key" is the feature vector to predict from rather than a lookup key. Training hyperparameters are given as layout parameters:Inference is exposed through a single function,
predictXGBoost(dictionary_name, feature1, feature2, ...[, params]): the features are passed positionally in key order, with an optional trailingMapof prediction parameters. Both the training hyperparameters and the prediction parameters are validated against an allowlist, so a typo fails the load rather than being silently ignored.The integration is experimental and gated behind the new
enable_xgboostsetting, which defaults tofalse:CREATE DICTIONARY ... LAYOUT(XGBOOST(...))is rejected withSUPPORT_IS_DISABLEDunless the setting is enabled. The check runs only when the loading strictness level isCREATE, soATTACH,RESTOREand replicated DDL replay are not affected: a dictionary created while the feature was enabled still attaches after a server restart, and a backup taken then stays restorable on a server where the setting is off.predictXGBoostis rejected unless the setting is enabled, even against an already-created dictionary. Since it is the only way to reach the model, the setting governs every prediction.Notes and limitations
dictGet,dictHas,SELECT * FROM dictand joining the dictionary as a table all reportUNSUPPORTED_METHODand point atpredictXGBoostinstead. A trained model has no stored attribute to look up and no keys to test.SYSTEM RELOAD DICTIONARYand aLIFETIME-driven reload retrain it. A reload that fails keeps serving the previously trained model rather than failing predictions;last_successful_update_timeandlast_exceptioninsystem.dictionariesshow whether the model still reflects the source data.nthreadis accepted and forwarded but currently has no effect. Concurrent predictions on one model are serialized with a mutex, since XGBoost's prediction is not thread-safe on a shared booster.predictXGBoostreturns oneFloat64per row, so the multi-value prediction types (SHAP contributions, feature interactions, leaf index) are rejected, and so are multiclass objectives, which would neednum_class.system.dictionariesreportselement_countandbytes_allocatedas0, as adirectdictionary does: this dictionary holds a model instead of rows.query_countandfound_ratecount the rows predicted throughpredictXGBoost.no-fasttest. It is disabled onloongarch64, whose sysroot does not ship<linux/mempolicy.h>.docs/reference/statements/create/dictionary/layouts/xgboost.mdx;predictXGBoostis documented through itsFunctionDocumentation.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added support for training and serving XGBoost gradient-boosted models as dictionaries. A dictionary with the
XGBOOSTlayout trains a model at load time from its source table - the feature columns are the key and the single attribute is the target - and the newpredictXGBoostfunction runs inference. The generic dictionary interface, such asdictGet, is not supported for this layout. Training hyperparameters such asobjective,max_depth,etaandnum_iterationsare passed as layout parameters. The feature is experimental and must be enabled with theenable_xgboostsetting. Available only in builds that include the XGBoost contrib library.Workflow [PR]
Sync PR [sync-upstream/pr/109999]
Version info
26.10.1.1944-master(included in26.10and later)