Skip to content

Refactor Naive Bayes Classifier as a dictionary layout NAIVE_BAYES - #108773

Merged
nihalzp merged 186 commits into
ClickHouse:masterfrom
nihalzp:naive-bayes-dictionary
Jul 16, 2026
Merged

nihalzp merged 186 commits into
ClickHouse:masterfrom
nihalzp:naive-bayes-dictionary

Conversation

@nihalzp

@nihalzp nihalzp commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

Previously, naiveBayesClassifier was very hard to use: user had to setup configurations files and produce model in a specific binary format. This PR solves the problem by allowing data source to be a normal ClickHouse table! For example, now using the classifier is as simple as:

Have some training data in this format:

CREATE TABLE sentiment_ngrams (class_id UInt32, ngram String, count UInt64)
ENGINE = MergeTree ORDER BY (class_id, ngram);

INSERT INTO sentiment_ngrams VALUES
    (0,'good',10),(0,'great',8),(0,'excellent',6),(0,'love',7),(0,'happy',5),
    (0,'amazing',4),(0,'wonderful',3),(0,'best',3),(0,'fantastic',2),(0,'nice',4),
    (1,'bad',10),(1,'terrible',8),(1,'awful',6),(1,'hate',7),(1,'worst',5),
    (1,'horrible',4),(1,'poor',3),(1,'disappointing',3),(1,'ugly',2),(1,'sad',4);

Create the model:

CREATE DICTIONARY sentiment (ngram String, class_id UInt32, count UInt64)
PRIMARY KEY ngram
SOURCE(CLICKHOUSE(TABLE 'sentiment_ngrams'))
LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 1 mode 'token'))
LIFETIME(0);

Notice that 0 means positive sentiment and 1 means negative sentiment.

Now, we can just do:

SELECT naiveBayesClassifier('sentiment', 'this is great');  -- dictionary name, input text
   ┌─naiveBayesCl⋯ is great')─┐
1. │                        0 │ -- positive sentiment
   └──────────────────────────┘
SELECT naiveBayesClassifier('sentiment', 'this is terrible');
   ┌─naiveBayesCl⋯ terrible')─┐
1. │                        1 │ -- negative sentiment
   └──────────────────────────┘

Since it's a dictionary, we can achieve the same using dictGet:

SELECT dictGet('sentiment', 'class_id', 'this is great');
   ┌─dictGet('sen⋯ is great')─┐
1. │                        0 │
   └──────────────────────────┘

Additionally, we have two new functions:

Get prediction + probability:

SELECT naiveBayesClassifierWithProb('sentiment', 'this is good');
   ┌─naiveBayesClassif⋯, 'this is good')─┐
1. │ {                                  ↴│
   │↳  "class_id": 0,                   ↴│
   │↳  "probability": 0.9166666715061128↴│
   │↳}                                   │
   └─────────────────────────────────────┘

Get all class probability:

SELECT naiveBayesClassifierWithAllProbs('sentiment', 'this is good');
   ┌─naiveBayesClassifi⋯, 'this is good')─┐
1. │ [{                                  ↴│
   │↳  "class_id": 0,                    ↴│
   │↳  "probability": 0.9166666715061128 ↴│
   │↳},{                                 ↴│
   │↳  "class_id": 1,                    ↴│
   │↳  "probability": 0.08333332849388708↴│
   │↳}]                                   │
   └──────────────────────────────────────┘

Additionally, this PR optimizes internal representation of the model data which means load time, peak memory usage and classification rate would be significantly faster!

For codepoint_3 model (9.7 MB in size):

Metric Master PR Improvement
Resident model memory 1.84 GiB 38.0 MiB ~49× smaller
Peak memory during load ~1.84 GiB ~88 MiB ~21× smaller
Load time ~732 ms 62 ms ~11.8× faster
Query classification rate 104,767 rows/s 1,183,432 rows/s ~11.3× faster

Try out the codepoint_2 model that's inside the repo for testing:

DROP DICTIONARY IF EXISTS lang_codepoint_2;
DROP TABLE IF EXISTS test_table;

CREATE TABLE test_table (class_id UInt32, ngram String, count UInt64)
ENGINE = MergeTree ORDER BY (class_id, ngram);

-- Load the training data
INSERT INTO test_table
SELECT * FROM url(
    'https://raw.githubusercontent.com/nihalzp/ClickHouse/naive-bayes-dictionary/tests/queries/0_stateless/data_naive_bayes_classifier/nb_model_lang_codepoint_2.tsv.zst',
    'TabSeparated',
    'class_id UInt32, ngram String, count UInt64');

SELECT 'rows_loaded', count() FROM test_table;

-- Create the dictionary from the layout
CREATE DICTIONARY lang_codepoint_2
(
    ngram String,
    class_id UInt32,
    count UInt64
)
PRIMARY KEY ngram
SOURCE(CLICKHOUSE(TABLE 'test_table'))
LAYOUT(NAIVE_BAYES(class_attribute 'class_id' n 2 mode 'codepoint'))
LIFETIME(0);

-- class_id: 0=Bengali, 1=Mandarin Chinese, 2=German, 3=Greek, 4=English, 5=French, 6=Russian, 7=Spanish
SELECT naiveBayesClassifier('lang_codepoint_2', 'He forgot his umbrella at the cafe.');
SELECT naiveBayesClassifier('lang_codepoint_2', 'Мы гуляли в парке до заката');
SELECT naiveBayesClassifier('lang_codepoint_2', '她每天早上喝一杯绿茶');
SELECT naiveBayesClassifier('lang_codepoint_2', 'Le chat regarde par la fenêtre');

Changelog category (leave one):

  • Backward Incompatible Change

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Naive Bayes models (used by naiveBayesClassifier) are now configured as a dictionary with the NAIVE_BAYES layout, built at load time from a table of pre-aggregated per-class n-gram counts, instead of the previous server-side configuration (an XML config file referencing serialized .bin model files), which is no longer supported — existing models must be recreated as dictionaries. Three new functions are added alongside naiveBayesClassifier: naiveBayesClassifierWithProb returns the predicted class together with its probability, naiveBayesClassifierWithAllProbs returns every class with its probability, and naiveBayesNgrams tokenizes text into n-grams the same way the dictionary does, for building the training data from raw labelled text. Additionally, several performance optimizations have been applied: on a 9.7 MiB code-point trigram language model, it uses ~49× less memory (from 1.84 GiB to 38 MiB), loads ~11× faster, and classifies ~11× faster.

nihalzp added 30 commits June 22, 2026 15:11
@alexey-milovidov

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

@george-larionov george-larionov self-assigned this Jul 7, 2026
alexey-milovidov and others added 2 commits July 14, 2026 13:30
Under parallel replicas the secondary queries carry a fully-qualified table
name but keep their own current database (`default`), so the unqualified
dictionary names passed to `naiveBayesClassifier` could not be resolved on the
remote replicas and the query failed with `BAD_ARGUMENTS` "Dictionary not
found" (the same limitation as `dictGet`). Qualify the dictionary references
with `${CLICKHOUSE_DATABASE}` so they resolve regardless of the secondary
query's current database, which keeps the ParallelReplicas CI coverage active
instead of disabling it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108773&sha=6873626a93cf75cca0dfb59f8bc370dc70806b72&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#108773

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged the latest master (the branch was ~1 week stale) and fixed the only red check — the 03512_naive_bayes_classifier_general failure under Stateless tests (ParallelReplicas, s3 storage).

Root cause: under parallel replicas the secondary queries carry a fully-qualified table name but keep their own current database (default), so the unqualified dictionary names passed to naiveBayesClassifier could not be resolved on the remote replicas and the query failed with BAD_ARGUMENTS "Dictionary not found". This is the same node-local behaviour that dictGet has. I qualified the dictionary references in the test with ${CLICKHOUSE_DATABASE} so they resolve regardless of the secondary query's current database — this keeps the ParallelReplicas coverage active rather than disabling it, and confirms the feature works under parallel replicas when the dictionary is qualified.

Verified locally against a 3-replica default_parallel_replicas cluster: the unqualified form reproduces the exact CI error, the qualified form succeeds, and all 34 naive_bayes tests pass both in normal mode and with parallel replicas forced.

On the AI-review "Needs follow-up" doc items (docs/reference/.../machine-learning-functions.mdx, docs/reference/system-tables/events.mdx): per docs/AGENTS.md those Mintlify files "should not be edited yet" — only docs/en/ is edited for now. The editable tree is already consistent: the PR removed the stale NaiveBayesClassifierModels* profile-event lines from metric_log.md/query_metric_log.md, events.md has no manual event list, and the naiveBayesClassifier doc text is autogenerated from the (updated) FunctionDocumentation, which now describes the NAIVE_BAYES dictionary layout rather than the old <nb_models>/.bin setup. So the substance is fixed at the source; the stale Mintlify sections will regenerate/get cleaned up by the docs migration.

@rschu1ze rschu1ze added the hold Skip for auto-updating. label Jul 14, 2026

@george-larionov george-larionov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes look really nice to me overall, great improvement over the old implementation! I have added a few mostly minor comments.

Comment thread src/Dictionaries/NaiveBayesModel.h Resolved
Comment thread src/Dictionaries/NaiveBayesModel.h Resolved
Comment thread src/Dictionaries/NaiveBayesModel.h Resolved
Comment thread src/Functions/naiveBayesClassifier.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.90% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 78.10% 78.10% +0.00%

Changed lines: Changed C/C++ lines covered: 1251/1278 (97.89%) · Uncovered code

Full report · Diff report

@nihalzp
nihalzp added this pull request to the merge queue Jul 16, 2026
Merged via the queue into ClickHouse:master with commit 99a759b Jul 16, 2026
351 of 352 checks passed
@nihalzp
nihalzp deleted the naive-bayes-dictionary branch July 16, 2026 12:18
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 16, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Under parallel replicas the secondary queries carry a fully-qualified table
name but keep their own current database (`default`), so the unqualified
dictionary names passed to `naiveBayesClassifier` could not be resolved on the
remote replicas and the query failed with `BAD_ARGUMENTS` "Dictionary not
found" (the same limitation as `dictGet`). Qualify the dictionary references
with `${CLICKHOUSE_DATABASE}` so they resolve regardless of the secondary
query's current database, which keeps the ParallelReplicas CI coverage active
instead of disabling it.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108773&sha=6873626a93cf75cca0dfb59f8bc370dc70806b72&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20ParallelReplicas%2C%20s3%20storage%2C%20parallel%29
PR: ClickHouse#108773

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Refactor Naive Bayes Classifier as a dictionary layout `NAIVE_BAYES`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hold Skip for auto-updating. pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants