diff --git a/python/cuml/cuml/preprocessing/_target_encoder.py b/python/cuml/cuml/preprocessing/_target_encoder.py index 76c9f62cfe..741f644583 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 @@ -31,6 +32,58 @@ _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 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): """ @@ -89,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 @@ -357,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( @@ -465,6 +526,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,9 +535,21 @@ def _fit_transform_independent(self, df, x_cols, fold_ids): encode_all_i = self._compute_single_feature_encoding_median( df, col ) + # 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 = self._compute_single_feature_encoding( - df, col, out_col_i + encode_all_i, encoded = self._encode_single_feature(df, col) + # 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) @@ -486,42 +560,65 @@ 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) + 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 - 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 +631,67 @@ 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)), - } + 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 + # 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) + 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. Missing categories are excluded + # from `hit` below. + lookup = cats + 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") + 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 + # 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. + """ + key_dtype = encode_all[col].dtype + 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. + 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( + dtype="float64", na_value=np.nan ) - 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() + return np.where(np.isnan(out), float(self.mean), out) def _make_fold_column(self, n_samples, fold_ids): """ diff --git a/python/cuml/tests/test_target_encoder.py b/python/cuml/tests/test_target_encoder.py index 142625516a..f44fa7d069 100644 --- a/python/cuml/tests/test_target_encoder.py +++ b/python/cuml/tests/test_target_encoder.py @@ -556,3 +556,158 @@ 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] + ) + + +@pytest.mark.parametrize("path", ["host", "device"]) +@pytest.mark.parametrize( + "dtype, big", [("int64", 2**53), ("uint64", 2**63 + 2**11)] +) +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=smooth, multi_feature_mode="independent", output_type="numpy" + ) + encoder.fit( + cudf.DataFrame({"a": cudf.Series(keys, dtype=dtype)}), + cudf.Series(y), + ) + + (categories,) = encoder.categories_ + assert categories[:-1].tolist() == [7, big, big + 1] + assert np.isnan(categories[-1]) + (encodings,) = encoder._encodings_per_feature + np.testing.assert_allclose( + 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", + [ + 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", lambda _, limit=limit: 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])