From c22b91657a009d29bc1caa20959dfbb84ab6864f Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 22 Oct 2026 19:39:22 +0000 Subject: [PATCH 1/7] TargetEncoder: factorize + bincount per feature instead of groupby/merge The per-feature fit path paid two groupbys, two merges and a sort per column, each with tens of milliseconds of fixed cudf overhead, plus a merge and sort per column to order the encodings by categories_. Factorize the column, bincount sums and counts, gather the per-row encoding, and resolve the per-category table on the host. Outputs are unchanged. 195k x 32 fit_transform: 2.5 s -> 0.8 s; 250k x 128: 10.5 s -> 3.4 s. Part of #8807. Co-Authored-By: Claude Fable 5.1 --- .../cuml/preprocessing/_target_encoder.py | 128 ++++++++++++------ 1 file changed, 84 insertions(+), 44 deletions(-) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 76c9f62cfe..9eff58c95a 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -7,6 +7,7 @@ import cudf import cupy as cp import numpy as np +import pandas as pd from sklearn.utils import ClassifierTags from cuml.internals.base import Base @@ -465,6 +466,7 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): self._encodings_per_feature = [] self.encode_all = [] result_cols = [] + merged = False for i, col in enumerate(x_cols): out_col_i = f"out_{i}" @@ -473,10 +475,18 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): encode_all_i = self._compute_single_feature_encoding_median( df, col ) - else: - encode_all_i = self._compute_single_feature_encoding( - df, col, out_col_i + # Merge encoding into df for this feature + df = df.merge( + encode_all_i.rename(columns={"out": out_col_i}), + on=col, + how="left", ) + df[out_col_i] = df[out_col_i].nans_to_nulls() + df[out_col_i] = df[out_col_i].fillna(self.y_stat_val) + merged = True + else: + encode_all_i, encoded = self._encode_single_feature(df, col) + df[out_col_i] = encoded self.encode_all.append(encode_all_i) @@ -486,42 +496,58 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): encode_all_i, col, self.categories_[i] ) ) - - # Merge encoding into df for this feature - df = df.merge( - encode_all_i.rename(columns={"out": out_col_i}), - on=col, - how="left", - ) - df[out_col_i] = df[out_col_i].nans_to_nulls() - df[out_col_i] = df[out_col_i].fillna(self.y_stat_val) result_cols.append(out_col_i) - # Sort by original index and return results - df = df.sort_values("id").reset_index(drop=True) + if merged: + # Merges do not preserve row order; restore the original order + df = df.sort_values("id").reset_index(drop=True) res = df[result_cols].to_cupy() return res, df - def _compute_single_feature_encoding(self, train, col, out_col): - """Compute target encoding for a single feature column.""" - # Group by single feature and compute stats - df_count = train.groupby(col, as_index=False, dropna=False).agg( - {"y": "count"} - ) - df_count.columns = [col, "y_count"] + def _encode_single_feature(self, train, col): + """Smoothed mean encoding of one feature, by factorizing it. - df_sum = train.groupby(col, as_index=False, dropna=False).agg( - {"y": "sum"} - ) - df_sum.columns = [col, "y_sum"] + Returns the per-category table (``col``, ``out``), with a null row + for a missing category if one is present, and the per-row encodings + aligned with ``train``. - df = df_sum.merge(df_count, on=col, how="left") + This replaces two groupbys and two merges per column with a + factorize, two ``bincount`` calls and a gather. The cudf operations + each cost tens of milliseconds of fixed overhead regardless of row + count, which dominated ``fit_transform`` on wide inputs. + """ + codes, uniques = train[col].factorize() + codes = cp.asarray(codes) + n_cats = len(uniques) + has_null = bool((codes < 0).any()) + if has_null: + codes = cp.where(codes < 0, n_cats, codes) + n_buckets = n_cats + int(has_null) + + y = train["y"].to_cupy(na_value=np.nan) + if train["y"].has_nulls: + # Match the groupby semantics: null targets count for nothing + valid = ~cp.isnan(y) + counts = cp.bincount(codes[valid], minlength=n_buckets) + sums = cp.bincount( + codes[valid], weights=y[valid], minlength=n_buckets + ) + else: + counts = cp.bincount(codes, minlength=n_buckets) + sums = cp.bincount(codes, weights=y, minlength=n_buckets) - # Apply smoothing smooth = self.smooth - df["out"] = (df.y_sum + smooth * self.mean) / (df.y_count + smooth) - - return df[[col, "out"]] + mean = float(self.mean) + out = (sums + smooth * mean) / (counts.astype(sums.dtype) + smooth) + + keys = cudf.Series(uniques) + if has_null: + keys = cudf.concat( + [keys, cudf.Series([None], dtype=keys.dtype)], + ignore_index=True, + ) + encode_all = cudf.DataFrame({col: keys, "out": out}) + return encode_all, out[codes] def _compute_single_feature_encoding_median(self, train, col): """Compute median target encoding for a single feature column.""" @@ -534,22 +560,36 @@ def _compute_single_feature_encoding_median(self, train, col): def _category_encodings(self, encode_all, col, categories): """Encodings of `categories` in order, falling back to the mean. - Uses a merge rather than comparing values so that a missing - category matches the missing key in `encode_all`. + `encode_all` has one row per category, so this is a small table. + It is resolved on the host: a cudf merge plus sort here costs tens + of milliseconds of fixed overhead per column, which dominated + ``fit_transform`` on wide inputs. A missing category (NaN/None) is + matched to the null key in `encode_all` explicitly, since NaN does + not compare equal to itself. """ - # A missing category has to be null to match the null key in - # `encode_all`. `_cats_to_series` hardcodes `nan_as_null=True` - # (cudf's default) so the behavior doesn't switch when cudf.pandas - # is active. - cats = cudf.DataFrame( - { - col: _cats_to_series(categories), - "pos": cp.arange(len(categories)), - } + enc = encode_all[[col, "out"]].to_pandas() + keys = enc[col] + vals = enc["out"].to_numpy(dtype="float64", na_value=np.nan) + key_missing = keys.isna().to_numpy() + lut = dict( + zip(keys[~key_missing].tolist(), vals[~key_missing].tolist()) + ) + mean = float(self.mean) + + cats = np.asarray(categories) + cat_missing = np.asarray(pd.isna(cats), dtype=bool) + out = np.array( + [ + mean if missing else lut.get(cat, mean) + for cat, missing in zip(cats.tolist(), cat_missing) + ], + dtype="float64", ) - cats = cats.merge(encode_all[[col, "out"]], on=col, how="left") - out = cats.sort_values("pos")["out"].fillna(float(self.mean)) - return out.to_numpy() + if cat_missing.any() and key_missing.any(): + out[cat_missing] = vals[key_missing][0] + # `out` of an empty group can be NaN for some statistics; the merge + # path filled those with the mean as well. + return np.where(np.isnan(out), mean, out) def _make_fold_column(self, n_samples, fold_ids): """ From e41b583b3c71b27d4e73b3ba60d73ccb9756ee93 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Thu, 22 Oct 2026 21:28:43 +0000 Subject: [PATCH 2/7] TargetEncoder: normalize column metadata of the stored train frame A frame only modified in place keeps the column metadata it was constructed with, which under cudf.pandas holds proxied pandas objects that cannot be pickled (check_estimators_pickle in the cudf.pandas integration job). The previous merge-based path happened to rebuild it. Reassign the column labels, 0.8 ms at 195k rows. Co-Authored-By: Claude Fable 5.1 --- python/cuml/cuml/preprocessing/_target_encoder.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 9eff58c95a..6362b836b3 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -501,6 +501,13 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): if merged: # Merges do not preserve row order; restore the original order df = df.sort_values("id").reset_index(drop=True) + else: + # `df` is stored as `self.train`. A frame only modified in place + # keeps the column metadata it was constructed with, which under + # cudf.pandas holds proxied pandas objects that cannot be + # pickled; the merge path happened to rebuild it. Reassigning + # the labels normalizes the metadata (0.8 ms at 195k rows). + df.columns = list(df.columns) res = df[result_cols].to_cupy() return res, df From 252de6cb15ac1af1e2654e8ed8f103c8655df9b0 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Mon, 26 Oct 2026 21:25:49 +0100 Subject: [PATCH 3/7] TargetEncoder: impute NaN training encodings in independent mode With smooth=0, a category whose targets are all null encodes as 0/0 = NaN. The merge path on main filled the per-row training encodings with y_stat_val; the bincount path assigned them directly. Fill them the same way and add a test. Co-Authored-By: Claude Opus 5.5 --- .../cuml/cuml/preprocessing/_target_encoder.py | 6 +++++- python/cuml/tests/test_target_encoder.py | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 6362b836b3..16303688d7 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -486,7 +486,11 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): merged = True else: encode_all_i, encoded = self._encode_single_feature(df, col) - df[out_col_i] = encoded + # A category with no non-null targets encodes as NaN when + # smooth=0; impute it as the merge path does + df[out_col_i] = cp.where( + cp.isnan(encoded), self.y_stat_val, encoded + ) self.encode_all.append(encode_all_i) diff --git a/python/cuml/tests/test_target_encoder.py b/python/cuml/tests/test_target_encoder.py index 142625516a..7d3a40099c 100644 --- a/python/cuml/tests/test_target_encoder.py +++ b/python/cuml/tests/test_target_encoder.py @@ -556,3 +556,20 @@ def test_as_sklearn_missing_category_matches_cuml(multi_feature_mode): np.testing.assert_allclose( sklearn_model.transform(X_new), encoder.transform(X_new), rtol=1e-5 ) + + +def test_independent_fit_transform_all_null_target_category(): + """With smooth=0 a category whose targets are all null has no encoding + of its own; its training rows fall back to `y_stat_val`, not NaN.""" + X = np.array(["a", "a", "c", "b", "b"], dtype=object)[:, None] + y = np.array([1.0, 1.0, 4.0, np.nan, np.nan]) + + encoder = TargetEncoder( + smooth=0, multi_feature_mode="independent", output_type="numpy" + ) + train_encoded = encoder.fit_transform(X, y) + + assert encoder.y_stat_val == 2.0 + np.testing.assert_allclose( + train_encoded, np.array([1.0, 1.0, 4.0, 2.0, 2.0])[:, None] + ) From 98a6447988bae5f270a6a69a480f6fbe2af8a606 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Wed, 11 Nov 2026 10:14:53 +0100 Subject: [PATCH 4/7] TargetEncoder: vectorize the per-category encoding lookup `_category_encodings` looked each category up in a dict from a Python loop, which costs about 0.4 s per feature at a million categories, more than main's GPU merge for that step. Use `pd.Index.get_indexer` instead (28 ms at a million categories). Missing categories are still matched to the null key explicitly. Results are identical, including for unseen, NaN/None, string and all-missing keys. Co-Authored-By: Claude Opus 5.5 --- .../cuml/cuml/preprocessing/_target_encoder.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 16303688d7..1729e5d0c3 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -582,20 +582,17 @@ def _category_encodings(self, encode_all, col, categories): keys = enc[col] vals = enc["out"].to_numpy(dtype="float64", na_value=np.nan) key_missing = keys.isna().to_numpy() - lut = dict( - zip(keys[~key_missing].tolist(), vals[~key_missing].tolist()) - ) mean = float(self.mean) cats = np.asarray(categories) cat_missing = np.asarray(pd.isna(cats), dtype=bool) - out = np.array( - [ - mean if missing else lut.get(cat, mean) - for cat, missing in zip(cats.tolist(), cat_missing) - ], - dtype="float64", - ) + # Vectorized lookup: a Python loop over the categories costs about + # 0.4 s per feature at a million categories. `encode_all` comes from + # a groupby, so its keys are unique. + pos = pd.Index(keys[~key_missing]).get_indexer(cats) + hit = (pos >= 0) & ~cat_missing + out = np.full(len(cats), mean, dtype="float64") + out[hit] = vals[~key_missing][pos[hit]] if cat_missing.any() and key_missing.any(): out[cat_missing] = vals[key_missing][0] # `out` of an empty group can be NaN for some statistics; the merge From 51bacb5c64615808bde006b46ef527d7a59fba4b Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Fri, 13 Nov 2026 23:02:49 +0100 Subject: [PATCH 5/7] TargetEncoder: keep integer category keys exact in the host lookup An integer column with a null came back from to_pandas() as float64, so distinct keys above 2**53 merged and get_indexer raised InvalidIndexError. Drop the null key on the device first so the keys stay integer, and look up integer-valued float categories as integers (also ~2.5x faster). Co-Authored-By: Claude Opus 5.5 --- .../cuml/preprocessing/_target_encoder.py | 20 ++++++++++++----- python/cuml/tests/test_target_encoder.py | 22 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 1729e5d0c3..977599e115 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -578,10 +578,14 @@ def _category_encodings(self, encode_all, col, categories): matched to the null key in `encode_all` explicitly, since NaN does not compare equal to itself. """ - enc = encode_all[[col, "out"]].to_pandas() - keys = enc[col] - vals = enc["out"].to_numpy(dtype="float64", na_value=np.nan) - key_missing = keys.isna().to_numpy() + key_col = encode_all[col] + missing = key_col.isna() + key_missing = missing.to_numpy() + # Drop the null key before leaving the device: an integer column + # with a null comes back from to_pandas() as float64, which merges + # distinct keys above 2**53 into one and makes the index non-unique. + keys = key_col[~missing].to_pandas() + vals = encode_all["out"].to_numpy(dtype="float64", na_value=np.nan) mean = float(self.mean) cats = np.asarray(categories) @@ -589,7 +593,13 @@ def _category_encodings(self, encode_all, col, categories): # Vectorized lookup: a Python loop over the categories costs about # 0.4 s per feature at a million categories. `encode_all` comes from # a groupby, so its keys are unique. - pos = pd.Index(keys[~key_missing]).get_indexer(cats) + lookup = cats + if keys.dtype.kind in "iu" and cats.dtype.kind == "f": + # `categories_` of an integer column with a null is float64. + # Compare as integers: it is about 3x faster than a float + # lookup, and missing categories are excluded from `hit` below. + lookup = np.where(cat_missing, 0, cats).astype(keys.dtype) + pos = pd.Index(keys).get_indexer(lookup) hit = (pos >= 0) & ~cat_missing out = np.full(len(cats), mean, dtype="float64") out[hit] = vals[~key_missing][pos[hit]] diff --git a/python/cuml/tests/test_target_encoder.py b/python/cuml/tests/test_target_encoder.py index 7d3a40099c..6698d9649e 100644 --- a/python/cuml/tests/test_target_encoder.py +++ b/python/cuml/tests/test_target_encoder.py @@ -573,3 +573,25 @@ def test_independent_fit_transform_all_null_target_category(): np.testing.assert_allclose( train_encoded, np.array([1.0, 1.0, 4.0, 2.0, 2.0])[:, None] ) + + +@pytest.mark.parametrize( + "dtype, big", [("int64", 2**53), ("uint64", 2**63 + 2**11)] +) +def test_independent_fit_integer_keys_beyond_float64_with_null(dtype, big): + """Integer keys that are distinct but equal as float64, in a column that + also has a null, must not collapse into a non-unique lookup index.""" + keys = [big, big + 1, None, big, big + 1, 7] + X = cudf.DataFrame({"a": cudf.Series(keys, dtype=dtype)}) + y = cudf.Series([0.0, 1.0, 0.5, 0.0, 1.0, 0.25]) + + encoder = TargetEncoder( + smooth=0, multi_feature_mode="independent", output_type="numpy" + ) + encoder.fit(X, y) + + (encodings,) = encoder._encodings_per_feature + assert len(encodings) == len(encoder.categories_[0]) + np.testing.assert_allclose( + encoder.transform(X).ravel(), [0.0, 1.0, 0.5, 0.0, 1.0, 0.25] + ) From 5a2e4502dc98a462fcaa5fbaebed596eb3e42dcb Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Sat, 14 Nov 2026 22:09:54 +0100 Subject: [PATCH 6/7] TargetEncoder: resolve large category tables with a device merge The host lookup's cost grows with the number of categories: at ~1M categories per column fit_transform was 2.5x slower than main. Above 50k categories, resolve the encodings with a cudf merge as main did (casting float categories of an integer column back to the key dtype so keys above 2**53 still match once). Co-Authored-By: Claude Opus 5.5 --- .../cuml/preprocessing/_target_encoder.py | 30 +++++++++++++++++++ python/cuml/tests/test_target_encoder.py | 29 ++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 977599e115..31a74313e2 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -32,6 +32,14 @@ _safe_is_nan, ) +# Above this many categories, `TargetEncoder._category_encodings` resolves +# the encodings with a device merge instead of a host lookup. The host lookup +# avoids the merge's ~3 ms fixed cost, which dominates wide inputs with few +# categories, but grows with the number of categories: on an RTX 5090 it +# breaks even at ~30k string or ~250k integer categories, and at 1M string +# categories it is 9x slower than the merge. +_HOST_LOOKUP_MAX_CATEGORIES = 50_000 + class TargetEncoder(InteropMixin, Base): """ @@ -578,6 +586,8 @@ def _category_encodings(self, encode_all, col, categories): matched to the null key in `encode_all` explicitly, since NaN does not compare equal to itself. """ + if len(categories) > _HOST_LOOKUP_MAX_CATEGORIES: + return self._category_encodings_device(encode_all, col, categories) key_col = encode_all[col] missing = key_col.isna() key_missing = missing.to_numpy() @@ -609,6 +619,26 @@ def _category_encodings(self, encode_all, col, categories): # path filled those with the mean as well. return np.where(np.isnan(out), mean, out) + def _category_encodings_device(self, encode_all, col, categories): + """`_category_encodings` as a cudf merge, for large category tables. + + Its fixed cost is higher than the host lookup's, but it does not + grow with the number of categories on the host. + """ + cats = _cats_to_series(categories) + key_dtype = encode_all[col].dtype + if key_dtype.kind in "iu" and cats.dtype.kind == "f": + # `categories_` of an integer column with a null is float64; + # merging float64 against the integer keys would match distinct + # keys above 2**53 more than once. + cats = cats.astype(key_dtype) + table = cudf.DataFrame({col: cats, "pos": cp.arange(len(cats))}) + table = table.merge(encode_all[[col, "out"]], on=col, how="left") + out = table.sort_values("pos")["out"].to_numpy( + dtype="float64", na_value=np.nan + ) + return np.where(np.isnan(out), float(self.mean), out) + def _make_fold_column(self, n_samples, fold_ids): """ Create a fold id column for each split diff --git a/python/cuml/tests/test_target_encoder.py b/python/cuml/tests/test_target_encoder.py index 6698d9649e..1a7ff97b18 100644 --- a/python/cuml/tests/test_target_encoder.py +++ b/python/cuml/tests/test_target_encoder.py @@ -595,3 +595,32 @@ def test_independent_fit_integer_keys_beyond_float64_with_null(dtype, big): np.testing.assert_allclose( encoder.transform(X).ravel(), [0.0, 1.0, 0.5, 0.0, 1.0, 0.25] ) + + +@pytest.mark.parametrize( + "keys", + [ + pytest.param([3, 1, None, 3, 2, 1], id="int64-null"), + pytest.param([2**53, 2**53 + 1, None, 2**53, 7, 7], id="int64-2**53"), + pytest.param([1.5, np.nan, 2.5, 1.5, 0.5, 2.5], id="float-nan"), + pytest.param(["b", None, "a", "b", "c", "a"], id="str-null"), + ], +) +def test_category_encodings_device_path_matches_host(monkeypatch, keys): + """Large category tables are resolved with a device merge; it must give + the same per-category encodings as the host lookup.""" + import cuml.preprocessing._target_encoder as te + + dtype = "int64" if isinstance(keys[0], int) else None + X = cudf.DataFrame({"a": cudf.Series(keys, dtype=dtype)}) + y = cudf.Series([0.0, 1.0, 0.5, 0.25, 1.0, 0.75]) + + encodings = [] + for limit in (1 << 62, 0): + monkeypatch.setattr(te, "_HOST_LOOKUP_MAX_CATEGORIES", limit) + encoder = TargetEncoder(smooth=0.5, multi_feature_mode="independent") + encoder.fit(X, y) + (enc,) = encoder._encodings_per_feature + assert len(enc) == len(encoder.categories_[0]) + encodings.append(enc) + np.testing.assert_array_equal(encodings[0], encodings[1]) From 5f25d1412e569e9e3d51bb2c7000e4764ac06318 Mon Sep 17 00:00:00 2001 From: Max Buckley Date: Tue, 17 Nov 2026 11:22:52 +0100 Subject: [PATCH 7/7] TargetEncoder: keep integer categories exact, route lookups by dtype `categories_` of an integer column with a null went through float64, so distinct values beyond 2**53 (e.g. 2**53 and 2**53 + 1) collapsed into one category, and `_encodings_per_feature` and the sklearn export held the wrong encodings. Such categories are now an object array of Python ints with a trailing NaN; integer columns with a null that float64 holds exactly keep float64 categories, as sklearn does, so the sklearn export still accepts numeric input. Both lookup paths compare as integers. The host/device lookup threshold now depends on the key dtype: 100k integer, 75k floating-point and 50k other categories. Tests check the categories, the per-category encodings, `transform` on data other than the training input, and the sklearn export, on both lookup paths. Co-Authored-By: Claude Opus 5.5 --- .../cuml/preprocessing/_target_encoder.py | 94 +++++++++++---- python/cuml/tests/test_target_encoder.py | 109 ++++++++++++++++-- 2 files changed, 172 insertions(+), 31 deletions(-) diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 31a74313e2..741f644583 100644 --- a/python/cuml/cuml/preprocessing/_target_encoder.py +++ b/python/cuml/cuml/preprocessing/_target_encoder.py @@ -34,11 +34,55 @@ # Above this many categories, `TargetEncoder._category_encodings` resolves # the encodings with a device merge instead of a host lookup. The host lookup -# avoids the merge's ~3 ms fixed cost, which dominates wide inputs with few -# categories, but grows with the number of categories: on an RTX 5090 it -# breaks even at ~30k string or ~250k integer categories, and at 1M string -# categories it is 9x slower than the merge. -_HOST_LOOKUP_MAX_CATEGORIES = 50_000 +# avoids the merge's fixed cost, which dominates wide inputs with few +# categories, but grows with the number of categories, fastest for strings. +# Limits by key dtype, from benchmarks on RTX PRO 6000 Blackwell, DGX Spark +# and H100 with the default and `cuml.accel` allocators. +_HOST_LOOKUP_MAX_INT_CATEGORIES = 100_000 +_HOST_LOOKUP_MAX_FLOAT_CATEGORIES = 75_000 +_HOST_LOOKUP_MAX_OTHER_CATEGORIES = 50_000 + + +def _host_lookup_max_categories(dtype): + """The most categories with keys of `dtype` to look up on the host.""" + kind = getattr(dtype, "kind", "O") + if kind in "iu": + return _HOST_LOOKUP_MAX_INT_CATEGORIES + if kind == "f": + return _HOST_LOOKUP_MAX_FLOAT_CATEGORIES + return _HOST_LOOKUP_MAX_OTHER_CATEGORIES + + +def _exact_integer_categories(column, categories): + """`categories` of `column`, keeping integers exact. + + `_compute_categories` returns the categories of an integer column with a + null as float64, with a trailing NaN, as sklearn does. That is exact up + to 2**53; beyond it distinct integers round to the same float. Then the + categories are returned as an object array of Python ints instead, with + the trailing NaN. + """ + if column.dtype.kind not in "iu" or categories.dtype.kind != "f": + return categories + if len(categories) == 1: + # Only the missing category + return categories + exact = 2**53 + if -exact <= int(column.min()) and int(column.max()) <= exact: + return categories + values = column.dropna().drop_duplicates().sort_values().to_numpy() + return np.append(values.astype(object), np.nan) + + +def _integer_lookup_keys(categories, missing, dtype): + """`categories` cast to the integer key `dtype`, 0 where `missing`. + + The categories of an integer column with a null are float64 (exact by + construction, see `_exact_integer_categories`) or Python ints in an + object array. Comparing as integers is exact, and about 3x faster than a + float lookup on the host. + """ + return np.where(missing, 0, categories).astype(dtype) class TargetEncoder(InteropMixin, Base): @@ -98,7 +142,10 @@ class TargetEncoder(InteropMixin, Base): categories_ : list of cupy.ndarray The categories of each input feature determined during fitting. Each element is an array of unique category values for that feature, - sorted in ascending order. + sorted in ascending order, with a missing category last as NaN. As in + sklearn, the categories of an integer feature with missing values are + float64, unless that would round distinct values beyond 2**53 to the + same float; then they are an object array of Python ints. target_type_ : str Type of target. classes_ : numpy.ndarray or None @@ -366,7 +413,12 @@ def _fit_transform(self, X, y, fold_ids): df = self._check_X_y(X, y) x_cols = [n for n in df.columns.tolist() if n.startswith("X_")] - self.categories_ = _compute_categories(df[x_cols]) + self.categories_ = [ + _exact_integer_categories(df[col], cats) + for col, cats in zip( + x_cols, _compute_categories(df[x_cols]), strict=True + ) + ] if self.multi_feature_mode not in {"combination", "independent"}: raise ValueError( @@ -586,9 +638,9 @@ def _category_encodings(self, encode_all, col, categories): matched to the null key in `encode_all` explicitly, since NaN does not compare equal to itself. """ - if len(categories) > _HOST_LOOKUP_MAX_CATEGORIES: - return self._category_encodings_device(encode_all, col, categories) key_col = encode_all[col] + if len(categories) > _host_lookup_max_categories(key_col.dtype): + return self._category_encodings_device(encode_all, col, categories) missing = key_col.isna() key_missing = missing.to_numpy() # Drop the null key before leaving the device: an integer column @@ -602,13 +654,11 @@ def _category_encodings(self, encode_all, col, categories): cat_missing = np.asarray(pd.isna(cats), dtype=bool) # Vectorized lookup: a Python loop over the categories costs about # 0.4 s per feature at a million categories. `encode_all` comes from - # a groupby, so its keys are unique. + # a groupby, so its keys are unique. Missing categories are excluded + # from `hit` below. lookup = cats - if keys.dtype.kind in "iu" and cats.dtype.kind == "f": - # `categories_` of an integer column with a null is float64. - # Compare as integers: it is about 3x faster than a float - # lookup, and missing categories are excluded from `hit` below. - lookup = np.where(cat_missing, 0, cats).astype(keys.dtype) + if keys.dtype.kind in "iu" and cats.dtype.kind in "fO": + lookup = _integer_lookup_keys(cats, cat_missing, keys.dtype) pos = pd.Index(keys).get_indexer(lookup) hit = (pos >= 0) & ~cat_missing out = np.full(len(cats), mean, dtype="float64") @@ -625,13 +675,17 @@ def _category_encodings_device(self, encode_all, col, categories): Its fixed cost is higher than the host lookup's, but it does not grow with the number of categories on the host. """ - cats = _cats_to_series(categories) key_dtype = encode_all[col].dtype - if key_dtype.kind in "iu" and cats.dtype.kind == "f": - # `categories_` of an integer column with a null is float64; - # merging float64 against the integer keys would match distinct + cats = cp.asnumpy(categories) + if key_dtype.kind in "iu" and cats.dtype.kind in "fO": + # Merge as integers: float64 keys would match distinct integer # keys above 2**53 more than once. - cats = cats.astype(key_dtype) + missing = np.asarray(pd.isna(cats), dtype=bool) + cats = cudf.Series( + _integer_lookup_keys(cats, missing, key_dtype) + ).mask(missing) + else: + cats = _cats_to_series(cats) table = cudf.DataFrame({col: cats, "pos": cp.arange(len(cats))}) table = table.merge(encode_all[[col, "out"]], on=col, how="left") out = table.sort_values("pos")["out"].to_numpy( diff --git a/python/cuml/tests/test_target_encoder.py b/python/cuml/tests/test_target_encoder.py index 1a7ff97b18..f44fa7d069 100644 --- a/python/cuml/tests/test_target_encoder.py +++ b/python/cuml/tests/test_target_encoder.py @@ -575,28 +575,113 @@ def test_independent_fit_transform_all_null_target_category(): ) +@pytest.mark.parametrize("path", ["host", "device"]) @pytest.mark.parametrize( "dtype, big", [("int64", 2**53), ("uint64", 2**63 + 2**11)] ) -def test_independent_fit_integer_keys_beyond_float64_with_null(dtype, big): - """Integer keys that are distinct but equal as float64, in a column that - also has a null, must not collapse into a non-unique lookup index.""" - keys = [big, big + 1, None, big, big + 1, 7] - X = cudf.DataFrame({"a": cudf.Series(keys, dtype=dtype)}) - y = cudf.Series([0.0, 1.0, 0.5, 0.0, 1.0, 0.25]) +def test_independent_integer_categories_beyond_float64_with_null( + monkeypatch, path, dtype, big +): + """Integer categories that are distinct but equal as float64, in a + column that also has a null, keep their own encodings in `categories_`, + in the per-category encodings, in `transform` and in the sklearn + export.""" + import cuml.preprocessing._target_encoder as te + + limit = 1 << 62 if path == "host" else 0 + monkeypatch.setattr(te, "_host_lookup_max_categories", lambda _: limit) + + keys = [big, big + 1, None, big, big + 1, 7, None, 7] + y = [0.0, 1.0, 0.5, 0.25, 0.75, 2.0, 1.5, 3.0] + smooth = 0.5 + mean = np.mean(y) + + def expected(key): + ys = [y_i for k, y_i in zip(keys, y) if k == key] + return (sum(ys) + smooth * mean) / (len(ys) + smooth) encoder = TargetEncoder( - smooth=0, multi_feature_mode="independent", output_type="numpy" + smooth=smooth, multi_feature_mode="independent", output_type="numpy" + ) + encoder.fit( + cudf.DataFrame({"a": cudf.Series(keys, dtype=dtype)}), + cudf.Series(y), ) - encoder.fit(X, y) + (categories,) = encoder.categories_ + assert categories[:-1].tolist() == [7, big, big + 1] + assert np.isnan(categories[-1]) (encodings,) = encoder._encodings_per_feature - assert len(encodings) == len(encoder.categories_[0]) np.testing.assert_allclose( - encoder.transform(X).ravel(), [0.0, 1.0, 0.5, 0.0, 1.0, 0.25] + encodings, [expected(k) for k in [7, big, big + 1, None]] + ) + + # Not the training input, so `transform` does not return the cached + # training encodings + new_keys = [big + 1, None, 3, big, 7] + want = [ + expected(big + 1), + expected(None), + mean, + expected(big), + expected(7), + ] + X_new = cudf.DataFrame({"a": cudf.Series(new_keys, dtype=dtype)}) + np.testing.assert_allclose(encoder.transform(X_new).ravel(), want) + + sklearn_model = encoder.as_sklearn() + assert sklearn_model.categories_[0][:3].tolist() == [7, big, big + 1] + np.testing.assert_allclose( + sklearn_model.transform( + pandas.DataFrame({"a": new_keys}, dtype=object) + ), + np.array(want)[:, None], + ) + + +def test_integer_categories_with_null_stay_float64(): + """Integer categories with a null that float64 holds exactly stay + float64, as in sklearn, so the sklearn export accepts numeric input.""" + keys = [3, 1, None, 3, 2, 1] + y = [0.0, 1.0, 0.5, 0.25, 1.0, 0.75] + encoder = TargetEncoder( + smooth=0, multi_feature_mode="independent", output_type="numpy" + ) + encoder.fit( + cudf.DataFrame({"a": cudf.Series(keys, dtype="int64")}), + cudf.Series(y), + ) + + (categories,) = encoder.categories_ + assert categories.dtype == np.float64 + np.testing.assert_array_equal(categories, [1.0, 2.0, 3.0, np.nan]) + np.testing.assert_allclose( + encoder._encodings_per_feature[0], [0.875, 1.0, 0.125, 0.5] + ) + + X_new = pandas.DataFrame({"a": [2.0, np.nan, 3.0, 5.0]}) + np.testing.assert_allclose( + encoder.as_sklearn().transform(X_new), + np.array([1.0, 0.5, 0.125, np.mean(y)])[:, None], ) +@pytest.mark.parametrize( + "dtype, limit", + [ + ("int32", 100_000), + ("uint64", 100_000), + ("float64", 75_000), + ("object", 50_000), + ("bool", 50_000), + ], +) +def test_host_lookup_max_categories(dtype, limit): + from cuml.preprocessing._target_encoder import _host_lookup_max_categories + + assert _host_lookup_max_categories(np.dtype(dtype)) == limit + + @pytest.mark.parametrize( "keys", [ @@ -617,7 +702,9 @@ def test_category_encodings_device_path_matches_host(monkeypatch, keys): encodings = [] for limit in (1 << 62, 0): - monkeypatch.setattr(te, "_HOST_LOOKUP_MAX_CATEGORIES", limit) + monkeypatch.setattr( + te, "_host_lookup_max_categories", lambda _, limit=limit: limit + ) encoder = TargetEncoder(smooth=0.5, multi_feature_mode="independent") encoder.fit(X, y) (enc,) = encoder._encodings_per_feature