Skip to content

ENH : Speed up TargetEncoder.transform for small batches - #32368

Closed
gautamvarmadatla wants to merge 87 commits into
scikit-learn:mainfrom
gautamvarmadatla:target_transform_speedup_low_batch_size
Closed

gautamvarmadatla wants to merge 87 commits into
scikit-learn:mainfrom
gautamvarmadatla:target_transform_speedup_low_batch_size

Conversation

@gautamvarmadatla

@gautamvarmadatla gautamvarmadatla commented Oct 4, 2025 •

Copy link
Copy Markdown
Contributor

Fixes #30952

What does this implement/fix?

This PR adds a small-batch fast path for TargetEncoder.transform that removes the large, fixed overhead observed for tiny batches, while preserving bit-for-bit parity with the existing vectorized implementation for:

  • missing-like values (None, np.nan, duck-typed pandas.NA, pandas.NaT, NumPy NaT),
  • unseen categories (fallback to target_mean_),
  • multiclass outputs (columns grouped by feature with class order consistent with classes_).

High-level idea

  • After fit, we eagerly precompute per-feature structures:

    • a dict mapping normalized category → index in categories_[j],
    • a direct view of the learned encodings (encodings_) and per-feature defaults (target_mean_ or per-class vector).
  • In transform, for small batches we do a tight loop of dictionary lookups and write the corresponding encodings directly.

  • For larger inputs, we fall back to the unchanged vectorized path.

  • The cutoff is a private heuristic (_small_batch_threshold) and does not change the public API.

Correctness details (parity)

To match the vectorized reference exactly, transform normalizes keys via _norm_key(x) using distinct, hashable enum sentinels:

  • None → _NAKey.NONE
  • float / NumPy NaN → _NAKey.NAN
  • duck-typed pandas.NA → _NAKey.PD_NA
  • duck-typed pandas.NaT → _NAKey.PD_NAT
  • NumPy datetime64/timedelta64 NaT → _NAKey.NAT

The same normalization is applied when building the maps during fit and when looking up during transform. Everything else is used as-is. Unseen categories map to per-feature defaults (target_mean_ or the per-class mean vector). In the multiclass case, columns are written feature-major with class order aligned to classes_.


Benchmarks

Environment: Windows, CPython 3.12 (64-bit), NumPy MKL, pytest-benchmark.

Setup: I benchmarked both paths ( Fast and vec ) for both dtypes: int64 and object. Here fast = per-row lookups into a precomputed map (Basically new logic foer small batches ) and vec = fully vectorized NumPy with more setup cost that win on larger batches. ( Current sklearn implementation ) . I basically forced data to explicitly flow through these paths.

Data & procedure (per run):

  • Fit: 500,000 rows with ~100,000 categories (integer-coded), binary target.
  • Transform batches: sizes sweep over {1, 2, 4, …, 256,000}.
  • Dtypes:
    • int64: strictly integral, no missing sentinels.
    • object: Python objects; when n_small ≥ 2, inject None (first row) and np.nan (last row).
  • Paths:
    • fast: _small_batch_threshold = 1e9 (forces fast path).
    • vec: _small_batch_threshold = 0 (forces vectorized path).
  • RNG: seed = n_small for reproducibility.

I ran separate benchmarks for int64 and object because they exercise very different code paths. With int64, NumPy gives a tight, contiguous buffer and the vectorized implementation is highly efficient, so the fast-path only wins for tiny batches and the crossover comes early (around 2^12 rows on my machine). With object dtype, we're dealing with python pointers and mixed NA sentinels, so normalization and lookups are inherently pricier and cache-unfriendly; the small-batch path stays competitive much longer, and the crossover shifts way out (around 2^18 rows).

output op3

Notes ( Threshold selection Logic )

  • I’m keeping _small_batch_threshold as a fixed number for now. The point where the fast path wins jumps around a lot depending on dtype (object vs int64), our CPU/cache, NumPy build, and Python version, so an “adaptive” rule might pick the wrong cutoff on someone else’s machine. A conservative constant would keep the performance much more predictable and still give the small-batch speedups. So, I’m using a nujmber ( 2^10) slightly lower than the int64 break-even (~2^12 on my machine as we can see in plots ) because integer-coded categories are super common in practice (factorize, Categorical.codes, IDs stored as ints) and that crossover we see in above plots is much earlier. At 2^10 as we can see, we see significant gains for both int64 and object dtypes. I’m not using the object-array crossover (it’s much higher) because object dtype has extra Python overhead (boxing, hashing, NA handling), and its threshold swings more with hardware/software.

  • So, TL;DR: fixed threshold of ~2^10 for now, but happy to discuss and refine a adaptive heuristic.


Line-level profiling

  • FAST
prof1
  • VEC
prof2

Benchmarks and Lineprofiler helper code ( Latency )

Benchmark harness (pytest-benchmark)
# tests_local/test_target_encoder_bench_local.py
import os, io, time, cProfile, pstats, tracemalloc
from pathlib import Path
import numpy as np, pytest
from sklearn.preprocessing import TargetEncoder

pytestmark = pytest.mark.benchmark(group="TargetEncoder-small-batch")

def _make_data(n_fit=300_000, n_cats=200_000, n_small=1, seed=0):
    rng = np.random.default_rng(seed)
    X_fit = rng.integers(0, n_cats, size=(n_fit, 1)).astype(object)
    y_fit = rng.integers(0, 2, size=(n_fit,))
    X_small = rng.integers(0, n_cats * 2, size=(n_small, 1)).astype(object)
    if n_small >= 2:
        X_small[0, 0] = None
        X_small[-1, 0] = np.nan
    return X_fit, y_fit, X_small

@pytest.mark.parametrize("n_small", [1, 2, 16, 32, 64, 128, 255, 256, 257, 512, 1024, 2048])
def test_te_adaptive_threshold_benchmark(benchmark, n_small):
    Xf, yf, Xs = _make_data(n_small=n_small, seed=n_small)
    enc = TargetEncoder().fit(Xf, yf)
    benchmark(enc.transform, Xs)
Line-profiler helper (top-k hottest lines in ms)
# notebooks or local script
import numpy as np, pandas as pd, inspect, linecache
from line_profiler import LineProfiler
from tabulate import tabulate
from sklearn.preprocessing import TargetEncoder

def make_data(n_fit=300_000, n_cats=200_000, n_small=256, seed=0):
    rng = np.random.default_rng(seed)
    X_fit = rng.integers(0, n_cats, size=(n_fit, 1)).astype(object)
    y_fit = rng.integers(0, 2, size=(n_fit,))
    X = rng.integers(0, n_cats * 2, size=(n_small, 1)).astype(object)
    if n_small >= 2:
        X[0, 0] = None
        X[-1, 0] = np.nan
    return X_fit, y_fit, X

def profile_te_transform_top_ms(enc, X, top_k=3, warmup_n=32, verbose=True):
    f = getattr(TargetEncoder, "transform")
    f = getattr(f, "__wrapped__", f)  # bypass sklearn wrapper if present
    src_file = inspect.getsourcefile(f)
    if not src_file:
        raise RuntimeError("Could not locate Python source for TargetEncoder.transform")
    f(enc, X[: min(warmup_n, len(X))])  # warmup
    lp = LineProfiler(); lp.add_function(f); lp(f)(enc, X)
    stats = lp.get_stats(); sec_per_tick = float(stats.unit)
    if verbose:
        print(f"[line_profiler] seconds per tick: {sec_per_tick:.9g}")
    rows = []
    for (filename, _start, _name), timing_list in stats.timings.items():
        if filename != src_file:
            continue
        for lineno, hits, ticks in timing_list:
            rows.append({
                "line": lineno,
                "code": linecache.getline(src_file, lineno).rstrip(),
                "time_ms": (ticks * sec_per_tick) * 1e3,
            })
    if not rows:
        raise RuntimeError("No per-line timings captured. Is line_profiler installed?")
    df = (pd.DataFrame(rows)
            .groupby(["line","code"], as_index=False)["time_ms"].sum()
            .sort_values("time_ms", ascending=False)
            .head(top_k)
            .reset_index(drop=True))
    table = tabulate(
        [[r["line"], r["code"], f'{r["time_ms"]:.3f}'] for _, r in df.iterrows()],
        headers=["line", "code", "time_ms"], tablefmt="github"
    )
    print(table)
    return df

Memory benchmarks :

peakmem_fit: RSS observed while running TargetEncoder.fit(X, y)
peakmem_transform_large: RSS during TargetEncoder.transform(X_large) on a big batch (vectorized path)
peakmem_transform_small: RSS during transform(X_small) on a tiny batch (small-batch fast path)

image

Thanks for reviewing! Happy to make further changes if required!

@github-actions

github-actions Bot commented Oct 4, 2025 •

Copy link
Copy Markdown

✔️ Linting Passed

All linting checks passed. Your pull request is in excellent shape! ☀️

Generated for commit: f74c474. Link to the linter CI: here

@gautamvarmadatla gautamvarmadatla changed the title ENH : Speed up TargetEncoder.transform for small batches (adaptive fast-path) ENH : Speed up TargetEncoder.transform for small batches Oct 4, 2025

@ogrisel ogrisel 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.

I find this PR hard to review because of the overly defensive code. Please remove it.

Also, could you please use a log scale for the y axis of the benchmark results? Could you please plot both the speed-up and the throughput or latency for each code branch ?

@adrinjalali adrinjalali 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.

This looks like AI generated code, and AI generated PR description.

Looking at the code itself, it looks pretty much nothing like the code we usually have in scikit-learn.

I'm inclined to close this PR. @gautamvarmadatla , please explain how this code was written, why it's written as it is, and how much of it is your code, and please avoid using AI to generate answers to this question.

For more context, see:

@adrinjalali adrinjalali added the Closing candidate indicating we might close this one soon / at a later review label Oct 7, 2025
@ogrisel

ogrisel commented Oct 7, 2025 •

Copy link
Copy Markdown
Member

Actually, the main problem is not that it's AI generated or not, but rather if the can contributors properly assess the value and the code complexity / performance trade-offs involved in the changes they propose via the PR.

The fact that this PR's contributor blindly trusted their AI tool to output such a high complexity / verbose contribution (the __setstate__ override in particular) makes me believe that future collaboration on this PR will not be productive, and I agree that we should close it.

scikit-learn maintainers are not interested in iteratively refining automated contributions, mostly written by AI tools indirectly via the GitHub PR review interface. If we want to leverage AI automation, we can do it ourselves and do the judgment or the AI output quality on our own before issuing the PR for review by other maintainers.

@gautamvarmadatla, assuming you are a real person, I would advise you to deepen your understanding of programming by refraining from using generative coding tools so liberally when attempting to contribute to open source projects. Limit your use of code assistant tools to explain code you don't understand to you (and only you), and always exercise your own judgment on the quality of its suggestions before imposing it onto others.

@ogrisel ogrisel closed this Oct 7, 2025
@adrinjalali adrinjalali reopened this Oct 7, 2025
@adrinjalali

Copy link
Copy Markdown
Member

Note that we don't support loading pickles from older sklearn versions.

@gautamvarmadatla

gautamvarmadatla commented Oct 7, 2025 •

Copy link
Copy Markdown
Contributor Author

Note that we don't support loading pickles from older sklearn versions.

Sure! I'll update the code add new benchmarks by EOD today :) Sorry for the confusion

@gautamvarmadatla

This comment was marked as outdated.

@gautamvarmadatla

Copy link
Copy Markdown
Contributor Author

There is a lot going on in this PR. The speed ups are pretty impressive. From thinking about it on a high level I think that this is a classic trade off between memory and computation. We are buying the speed up by using more memory (for the look up tables). We compute the helpers as part of fit, when we don't yet know if they will be used. The question I am left with at the end: how much more memory than main will this consume?

I looked at the screenshot in the top comment of this PR that shows memory usage, but I have to admit I am not sure what I am looking at. I am pretty sure it doesn't tell me how much extra memory is being used.

@gautamvarmadatla did you study this? Maybe it was discussed in one of the many existing comments (apologies for me not reading them all)?

hi @betatim,

Yes! You are absolutely right, it's a memory vs computation trade off . For the latest code we have (( let's say we are using 200k training rows, 100k unique categories per feature, and 1 feature) ) , compared to main , this PR adds about +0.38 MB per feature for int64 inputs due to the integer LUT (lookup table), while for object inputs the bigger cost appears only after the first transform, when index_maps materializes (about +8.4 MB per feature at 100k categories).

Sample code to test locally
from __future__ import annotations

import argparse
import gc
import json
import os
import subprocess
import sys
import time
from dataclasses import dataclass
from typing import Any, Dict, List, Tuple

import numpy as np
import psutil
from pympler import asizeof
from sklearn.preprocessing import TargetEncoder


def fmt_bytes_signed(n: int) -> str:
    sign = "-" if n < 0 else ""
    x = float(abs(n))
    for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
        if x < 1024.0:
            return f"{sign}{x:,.2f} {unit}"
        x /= 1024.0
    return f"{sign}{x:,.2f} PiB"


def fmt_bytes(n: int) -> str:
    x = float(n)
    for unit in ["B", "KiB", "MiB", "GiB", "TiB"]:
        if x < 1024.0:
            return f"{x:,.2f} {unit}"
        x /= 1024.0
    return f"{x:,.2f} PiB"


def rss_bytes() -> int:
    p = psutil.Process(os.getpid())
    return int(p.memory_info().rss)


def force_gc():
    gc.collect()
    time.sleep(0.05)


def deep_size(obj: Any) -> int:
    return int(asizeof.asizeof(obj))


def deep_size_or_zero(obj: Any) -> int:
    return 0 if obj is None else deep_size(obj)


def estimate_extras(enc: TargetEncoder) -> Dict[str, int]:
    extras: Dict[str, int] = {}
    extras["categories_"] = deep_size_or_zero(getattr(enc, "categories_", None))
    extras["encodings_"] = deep_size_or_zero(getattr(enc, "encodings_", None))
    extras["_index_maps_"] = deep_size_or_zero(getattr(enc, "_index_maps_", None))
    extras["_int_lookup_"] = deep_size_or_zero(getattr(enc, "_int_lookup_", None))
    return extras


def build_data(
    rng: np.random.Generator,
    n_fit: int,
    n_rows_transform: int,
    n_features: int,
    n_cats: int,
    dtype: str,
    target_type: str,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    X_fit_int = rng.integers(0, n_cats, size=(n_fit, n_features), dtype=np.int64)
    if dtype == "int64":
        X_fit = X_fit_int
    elif dtype == "object":
        X_fit = X_fit_int.astype(object)
        if n_fit >= 200 and n_features >= 1:
            X_fit[:100, 0] = None
            X_fit[100:200, 0] = np.nan
    else:
        raise ValueError(f"Unknown dtype: {dtype}")
    if target_type == "binary":
        y = rng.integers(0, 2, size=n_fit, dtype=np.int64)
    elif target_type == "multiclass":
        y = rng.integers(0, 5, size=n_fit, dtype=np.int64)
    elif target_type == "continuous":
        y = rng.normal(size=n_fit).astype(np.float64)
    else:
        raise ValueError(f"Unknown target_type: {target_type}")
    X_tr_int = rng.integers(0, 2 * n_cats, size=(n_rows_transform, n_features), dtype=np.int64)
    if dtype == "int64":
        X_tr = X_tr_int
    else:
        X_tr = X_tr_int.astype(object)
        if n_rows_transform >= 1 and n_features >= 1:
            X_tr[0, 0] = None
        if n_rows_transform >= 2 and n_features >= 1:
            X_tr[-1, 0] = np.nan

    return X_fit, y, X_tr


@dataclass
class CaseResult:
    dtype: str
    target_type: str
    materialize: bool
    rss_delta_median: int
    rss_delta_all: List[int]
    est_deep: int
    extras: Dict[str, int]


def median_int(xs: List[int]) -> int:
    xs_sorted = sorted(xs)
    mid = len(xs_sorted) // 2
    if len(xs_sorted) % 2 == 1:
        return xs_sorted[mid]
    return int((xs_sorted[mid - 1] + xs_sorted[mid]) / 2)



def worker_run_one(
    dtype: str,
    target_type: str,
    materialize: bool,
    n_fit: int,
    n_rows_transform: int,
    n_features: int,
    n_cats: int,
    seed: int,
) -> Dict[str, Any]:
    rng = np.random.default_rng(seed)
    X_fit, y, X_tr = build_data(
        rng=rng,
        n_fit=n_fit,
        n_rows_transform=n_rows_transform,
        n_features=n_features,
        n_cats=n_cats,
        dtype=dtype,
        target_type=target_type,
    )
    force_gc()
    before = rss_bytes()
    enc = TargetEncoder(target_type=target_type, random_state=0)
    enc.fit(X_fit, y)
    if materialize:
        enc.transform(X_tr[: min(len(X_tr), 8)])
    force_gc()
    after = rss_bytes()
    extras = estimate_extras(enc)
    out = {
        "dtype": dtype,
        "target_type": target_type,
        "materialize": materialize,
        "rss_delta": int(after - before),
        "est_deep": int(deep_size(enc)),
        "extras": extras,
    }
    return out


def run_one_in_subprocess(script_path: str, args: Dict[str, Any]) -> Dict[str, Any]:
    cmd = [
        sys.executable,
        script_path,
        "--worker",
        "--dtype", args["dtype"],
        "--target-type", args["target_type"],
        "--materialize", "1" if args["materialize"] else "0",
        "--n-fit", str(args["n_fit"]),
        "--n-rows-transform", str(args["n_rows_transform"]),
        "--n-features", str(args["n_features"]),
        "--n-cats", str(args["n_cats"]),
        "--seed", str(args["seed"]),
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True)
    if proc.returncode != 0:
        raise RuntimeError(
            "Worker failed.\n"
            f"CMD: {' '.join(cmd)}\n"
            f"STDOUT:\n{proc.stdout}\n"
            f"STDERR:\n{proc.stderr}"
        )
    return json.loads(proc.stdout.strip())



def print_table(results: List[CaseResult]):
    header = (
        f"{'dtype':8s} {'target_type':12s} {'stage':18s} "
        f"{'RSS delta (median)':>18s} {'RSS deltas':>22s} "
        f"{'est deep':>14s} {'_index_maps_':>14s} {'_int_lookup_':>14s}"
    )
    print("\n" + header)
    print("-" * len(header))
    for r in results:
        stage = "after fit" if not r.materialize else "after 1st transform"
        deltas_preview = "[" + ", ".join(fmt_bytes_signed(x) for x in r.rss_delta_all) + "]"
        print(
            f"{r.dtype:8s} {r.target_type:12s} {stage:18s} "
            f"{fmt_bytes_signed(r.rss_delta_median):>18s} {deltas_preview:>22s} "
            f"{fmt_bytes(r.est_deep):>14s} "
            f"{fmt_bytes(r.extras.get('_index_maps_', 0)):>14s} "
            f"{fmt_bytes(r.extras.get('_int_lookup_', 0)):>14s}"
        )



def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--n-fit", type=int, default=200_000)
    ap.add_argument("--n-cats", type=int, default=100_000)
    ap.add_argument("--n-features", type=int, default=1)
    ap.add_argument("--n-rows-transform", type=int, default=2048)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--repeats", type=int, default=3)
    ap.add_argument("--worker", action="store_true")
    ap.add_argument("--dtype", choices=["int64", "object"], default="int64")
    ap.add_argument("--target-type", choices=["binary", "multiclass", "continuous"], default="binary")
    ap.add_argument("--materialize", choices=["0", "1"], default="0")
    args = ap.parse_args()

    if args.worker:
        out = worker_run_one(
            dtype=args.dtype,
            target_type=args.target_type,
            materialize=(args.materialize == "1"),
            n_fit=args.n_fit,
            n_rows_transform=args.n_rows_transform,
            n_features=args.n_features,
            n_cats=args.n_cats,
            seed=args.seed,
        )
        print(json.dumps(out))
        return

    dtypes = ["int64", "object"]
    target_types = ["binary", "multiclass", "continuous"]
    materialize_opts = [False, True]

    script_path = os.path.abspath(__file__)

    results: List[CaseResult] = []
    for dtype in dtypes:
        for target_type in target_types:
            for materialize in materialize_opts:
                rss_deltas: List[int] = []
                last_payload: Dict[str, Any] | None = None

                for r_i in range(args.repeats):
                    payload = run_one_in_subprocess(
                        script_path,
                        {
                            "dtype": dtype,
                            "target_type": target_type,
                            "materialize": materialize,
                            "n_fit": args.n_fit,
                            "n_rows_transform": args.n_rows_transform,
                            "n_features": args.n_features,
                            "n_cats": args.n_cats,
                            "seed": args.seed + r_i,
                        },
                    )
                    rss_deltas.append(int(payload["rss_delta"]))
                    last_payload = payload

                assert last_payload is not None
                results.append(
                    CaseResult(
                        dtype=dtype,
                        target_type=target_type,
                        materialize=materialize,
                        rss_delta_median=median_int(rss_deltas),
                        rss_delta_all=rss_deltas,
                        est_deep=int(last_payload["est_deep"]),
                        extras={k: int(v) for k, v in last_payload["extras"].items()},
                    )
                )
    print_table(results)


if __name__ == "__main__":
    main()

@gautamvarmadatla

Copy link
Copy Markdown
Contributor Author

Hi @adrinjalali and @OmarManzoor,

The changes we’ve made sicne the initial PR introduced a performance regression. To address this, I refactored the small-batch fast path to improve performance, particularly for integer categories. In my local measurements, the small-batch transform now runs in about 0.1 to 0.3 ms for n_rows <= 512 and about 0.3 to 0.4 ms at n_rows = 1024 for int64. The forced vectorized path for the same sizes is about 1.5 to 2.9 ms, which is roughly a 20 to 30x speedup for small batches. Once n_rows crosses the cutoff (for example n_rows >= 2048), we fall back to the vectorized path (about 5 to 6 ms in my run).

As requested, I’ve also added an ASV benchmark file so you can test the impact locally. For line profiling you can use test using code i gave in PR description.

Side note: for object inputs, the fast path is only beneficial for extremely small batches. For example, n_rows = 1 to 2 is about 0.2 to 0.7 ms on the fast path versus about 70 ms on the vectorized path, but it becomes slower as n_rows grows. For example, n_rows = 1024 is about 360 to 380 ms on the fast path versus about 70 ms on the vectorized path. If you see similar numbers locally, we can tweak the cutoff for object dtype (use a much smaller threshold) to avoid regressions there.

Thanks a lot for all the time and detailed feedback on this PR. I know it has gotten pretty long, and I really appreciate you sticking with it. If you feel the PR still needs more refinement and you are tight on bandwidth, please feel free to close it for now. I can always iterate further and reopen a follow-up PR once things are cleaner or better scoped.

@betatim

betatim commented Jan 28, 2026

Copy link
Copy Markdown
Member

Thanks for the memory benchmark. I think adding <1MB per feature seems reasonable. And if I understand correctly the extra ~8MB (which I think is quite big) only occurs after the user uses the "fast path" for the first time. Is that right? If yes, then I think this is fine - the user is getting the benefit and has to pay the price. What happens if the user only transforms on large batches??

Is there an up-to-date table or plot of absolute execution times for main and this PR? The reason I'm asking is that the times in the previous comment are all very small. Even 380ms is very fast. If the typical numbers are all on this order of magnitude for realistic use-cases, do we need to speed them up? Yes a 20x speed up is nice, but if it is taking something that takes less than half a second down to something even faster - do we care? The changes in this PR are not super complicated or complex, but they are not trivial either.


My philosophy for speed ups is that we have to move from one category to another for the speed up to matter to real humans. The categories I use are

  • "instant" - executes so fast that your thought process is not interrupted when running interactively) - less than half a second
  • "almost instant" - takes a few seconds, but certainly below less than 5s
  • "annoyingly slow" - takes up to a minute or two, you might just manage to stay focussed while waiting
  • "news reading time" - takes 2-5minutes, time to read the news/scroll cat pictures, you lose focus while waiting
  • "I'm getting a coffee" - takes more than 5minutes, you walk off to get a coffee or work on a different task, focus and context lost

The point being that moving something around inside a category doesn't really matter. 15minutes or 4hours is basically the same (yes the difference matters if you are grid searching and things like this, but the apply this rule to the total job length, not an individual estimator) - I will pause the task and come back later the same day or tomorrow.

@gautamvarmadatla

gautamvarmadatla commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the memory benchmark. I think adding <1MB per feature seems reasonable. And if I understand correctly the extra ~8MB (which I think is quite big) only occurs after the user uses the "fast path" for the first time. Is that right? If yes, then I think this is fine - the user is getting the benefit and has to pay the price. What happens if the user only transforms on large batches??

Is there an up-to-date table or plot of absolute execution times for main and this PR? The reason I'm asking is that the times in the previous comment are all very small. Even 380ms is very fast. If the typical numbers are all on this order of magnitude for realistic use-cases, do we need to speed them up? Yes a 20x speed up is nice, but if it is taking something that takes less than half a second down to something even faster - do we care? The changes in this PR are not super complicated or complex, but they are not trivial either.

My philosophy for speed ups is that we have to move from one category to another for the speed up to matter to real humans. The categories I use are

  • "instant" - executes so fast that your thought process is not interrupted when running interactively) - less than half a second
  • "almost instant" - takes a few seconds, but certainly below less than 5s
  • "annoyingly slow" - takes up to a minute or two, you might just manage to stay focussed while waiting
  • "news reading time" - takes 2-5minutes, time to read the news/scroll cat pictures, you lose focus while waiting
  • "I'm getting a coffee" - takes more than 5minutes, you walk off to get a coffee or work on a different task, focus and context lost

The point being that moving something around inside a category doesn't really matter. 15minutes or 4hours is basically the same (yes the difference matters if you are grid searching and things like this, but the apply this rule to the total job length, not an individual estimator) - I will pause the task and come back later the same day or tomorrow.

  1. Yes, that’s right. For object dtype, the extra ~8 MiB only shows up after the first time transform goes through the small-batch path. Until then it stays lazy and is about ~675 KiB. For large batches, we always take the existing vectorized path, so behavior and runtime are essentially the same as main.

  2. Yes, I agree with your “category changes” framing for human-perceived latency. The motivation here is repeated small-batch usage (request-time scoring, streaming, interactive inference), not one-off batch transforms. I worked on this because, in my recsys experience, we often do request-time scoring with a mix of batch-precomputed and real-time features, and encoders end up on the hot path. Even if each call feels “instant”, shaving ~1 ms per request at ~1k RPS is roughly 1 CPU-second per second saved, plus improved tail latency, which is why I think this speedup matters in practice. This compounds further at larger scale ( Imagine we have multiple carousels on multiple surfaces and very high traffic like millions of rps ), and it also adds up in loop-heavy workflows (evaluation/simulation) where per-call speedups directly reduce end-to-end job time.

That said, here are the number comparing this PR's latest code with main. Again this was just one of the most recent runs on my machine and could slightly change + we need to discuss on cutoff for object dtype as mentioned in previous comment. Based of my machine 128 seems to be the sweet spot for object dtype.

Vectorized path ( main ) vs PR comparision

The comparison uses a single-feature synthetic dataset with 200k rows and 100k categories

dtype target rows main (µs) branch (µs) speedup
int64 binary 1 1296.55 43.30 29.94x
int64 binary 2 1554.19 40.85 38.04x
int64 binary 4 1477.03 43.60 33.88x
int64 binary 8 2712.27 44.42 61.06x
int64 binary 16 4144.09 45.86 90.36x
int64 binary 32 3623.28 42.09 86.08x
int64 binary 64 3991.71 42.84 93.18x
int64 binary 128 3893.50 59.17 65.81x
int64 binary 256 4608.35 44.98 102.46x
int64 binary 512 5031.21 49.18 102.29x
int64 binary 1024 5949.61 54.48 109.21x
int64 binary 2048 7117.26 3061.16 2.33x
int64 binary 4096 7736.07 3536.51 2.19x
int64 multiclass 1 3333.95 46.44 71.80x
int64 multiclass 2 3159.08 49.28 64.10x
int64 multiclass 4 3062.32 51.18 59.83x
int64 multiclass 8 3278.71 52.51 62.44x
int64 multiclass 16 4092.35 51.07 80.13x
int64 multiclass 32 3816.29 50.55 75.50x
int64 multiclass 64 3761.94 146.37 25.70x
int64 multiclass 128 3380.75 140.90 23.99x
int64 multiclass 256 3533.85 136.28 25.93x
int64 multiclass 512 4404.47 166.50 26.45x
int64 multiclass 1024 4734.23 197.35 23.99x
int64 multiclass 2048 4866.03 5282.66 0.92x
int64 multiclass 4096 6144.80 6400.13 0.96x
object binary 1 132436.79 77.95 1699.07x
object binary 2 129782.48 79.16 1639.46x
object binary 4 130702.95 2290.31 57.07x
object binary 8 130944.63 6948.94 18.84x
object binary 16 129403.41 16210.50 7.98x
object binary 32 128642.88 34039.46 3.78x
object binary 64 130043.52 56324.50 2.31x
object binary 128 134526.84 140556.94 0.96x
object binary 256 130904.75 259998.84 0.50x
object binary 512 131184.77 624336.11 0.21x
object binary 1024 127902.85 717347.95 0.18x
object binary 2048 130885.72 79646.79 1.64x
object binary 4096 135561.87 80249.23 1.69x
object multiclass 1 156158.26 34.36 4545.25x
object multiclass 2 124983.07 39.62 3154.73x
object multiclass 4 78560.37 887.63 88.51x
object multiclass 8 80236.81 2446.88 32.79x
object multiclass 16 75327.90 5790.05 13.01x
object multiclass 32 76273.53 12149.20 6.28x
object multiclass 64 75730.59 26708.34 2.84x
object multiclass 128 75563.23 52024.01 1.45x
object multiclass 256 75756.20 101493.88 0.75x
object multiclass 512 78603.87 203952.90 0.39x
object multiclass 1024 79850.83 401792.26 0.20x
object multiclass 2048 80376.96 81370.78 0.99x
object multiclass 4096 80569.57 87581.94 0.92x

@betatim

betatim commented Feb 16, 2026

Copy link
Copy Markdown
Member

Thanks for the reply and many details and thoughts. The fact that people use scikit-learn in inference pipeplines with small batches was a blindspot for me. In that context speed ups like this make more sense.

My impression is that the exact threshold for switching between the two modes depends on a lot of things. The dtype, maybe what machine you used, and other things we haven't yet found. This has me wondering: instead of introducing a threshold that has a value that has a high chance of being "wrong" (for a concrete use-case) should we add a constructor parameter that unconditionally enables the optimisation? That way people who want to use the model for inference pipelines can turn it on (after doing some benchmarking to see if this makes sense for them). The next thought I had is: should there be an "inference optimised versions of estimators" library?

In summary: I think I understand the motivation for the optimisation and think it makes sense to have it. Arbitrary values like the threshold are not my favourite. We need to be smart about not adding too much complexity (for users and maintainers) to the code. The last point is what has me thinking this isn't a home run PR yet.

What do people think?

@gautamvarmadatla

Copy link
Copy Markdown
Contributor Author

Thanks for the reply and many details and thoughts. The fact that people use scikit-learn in inference pipeplines with small batches was a blindspot for me. In that context speed ups like this make more sense.

My impression is that the exact threshold for switching between the two modes depends on a lot of things. The dtype, maybe what machine you used, and other things we haven't yet found. This has me wondering: instead of introducing a threshold that has a value that has a high chance of being "wrong" (for a concrete use-case) should we add a constructor parameter that unconditionally enables the optimisation? That way people who want to use the model for inference pipelines can turn it on (after doing some benchmarking to see if this makes sense for them). The next thought I had is: should there be an "inference optimised versions of estimators" library?

In summary: I think I understand the motivation for the optimisation and think it makes sense to have it. Arbitrary values like the threshold are not my favourite. We need to be smart about not adding too much complexity (for users and maintainers) to the code. The last point is what has me thinking this isn't a home run PR yet.

What do people think?

Thanks @betatim. I agree the threshold is workload, dtype, and machine dependent, and that is exactly the part I have been waiting for feedback on and is the last piece of this PR. Picking one number risks being “wrong” for someone.

I see two practical options:

  1. Keep this as a behind-the-scenes optimization, but only apply it where it is almost certainly a win. We can use a very conservative cutoff (for example n_samples <= 32 or <= 64) and keep everything lazy so large-batch users pay nothing. The motivation is that at these tiny batch sizes the benchmarks show a clear win for both int and object dtypes. This way, even with a fixed threshold, we still deliver a reliable and meaningful benefit to users, without any changes to API.

  2. Give users full control. Add a constructor knob to enable the fast path (and optionally set the threshold) so inference users can benchmark on their machine and choose what works best for their setup.

My preference is (1) because it delivers the tiny-batch win without adding new API and gives the benefit immediately to all users, but I am happy to do (2) if the group would rather avoid any built-in threshold..

@betatim

betatim commented Feb 17, 2026

Copy link
Copy Markdown
Member

Would these very small batch sizes help you out with your use-case or are they too small?

Let's see what others think about the possible trade-offs.

@lorentzenchr

lorentzenchr commented Feb 17, 2026 •

Copy link
Copy Markdown
Member

an "inference optimised versions of estimators" library

To my knowledge, this is the main use case of ONNX and sklearn-onnx (and maybe others).

Maybe we should decide, for which use case we accept optimisation PRs and for which we don’t.

@adrinjalali

Copy link
Copy Markdown
Member

To me, this matters when you put estimators in production, and I think at this point in the scikit-learn project we should care about those issues. So I'm very happy with this PR and the improvement.

I don't see why we'd block this one from being merged. It's true that it adds a bit of complexity to the code, but to me it's worth the improvement we get.

@adrinjalali adrinjalali added this to Labs Mar 3, 2026
@github-project-automation github-project-automation Bot moved this to Todo in Labs Mar 3, 2026
@adrinjalali adrinjalali moved this from Todo to In progress in Labs Mar 3, 2026
@lorentzenchr

Copy link
Copy Markdown
Member

I am not blocking. Would be interested in @lesteve‘s opinion.

2 question:

  • Who is willing to review?
  • What is the impact on time and memory of fit?

@gautamvarmadatla

Copy link
Copy Markdown
Contributor Author
  • What is the impact on time and memory of fit?

Hi @lorentzenchr ! We already have benchmark to measure time, but i just updated it to inlcudde memory as well. Here's results from latest run ( 1024 cutoff for both dtypes )

peakmem_fit / peakmem_fit_no_lut
1 2 4 8 16 32 64 128 256 512 1024 2048 4096
int64/binary 0.992x 1x 1x 1.01x 1x 1x 1x 1x 1x 1x 1x 1x 1.01x
int64/multiclass 0.992x 1x 1x 1.02x 1x 0.992x 1.01x 1.02x 1x 1x 1x 1x 1x
object/binary 1x 0.993x 1.01x 1.01x 0.993x 0.993x 1x 0.986x 1x 1x 1x 1.01x 1x
object/multiclass 0.981x 1.01x 1x 0.993x 0.993x 0.987x 1x 1x 1.01x 1x 1x 1.01x 0.993x
peakmem_transform_default ( latest code ) / peakmem_transform_forced_vectorized ( main )
1 2 4 8 16 32 64 128 256 512 1024 2048 4096
int64/binary 1.01x 1x 0.991x 1x 1x 1x 1x 1x 1x 0.991x 1x 1x 1x
int64/multiclass 1x 1x 1.01x 1x 1x 1x 1x 1x 1x 1x 0.992x 1x 1.01x
object/binary 1.01x 0.986x 0.986x 1.01x 1x 0.986x 1x 0.986x 1.01x 1.01x 1.02x 1.01x 1.01x
object/multiclass 1.01x 0.993x 1.01x 1x 0.993x 1.01x 1.01x 1.01x 1.01x 0.993x 0.993x 1x 1x
time_fit / time_fit_no_lut
1 2 4 8 16 32 64 128 256 512 1024 2048 4096
int64/binary 1x 0.991x 1.05x 1.08x 0.989x 0.927x 1.09x 0.996x 0.963x 0.945x 0.931x 1.01x 1.04x
int64/multiclass 0.951x 0.941x 0.983x 1.04x 0.943x 0.97x 1.03x 0.987x 0.987x 0.94x 0.972x 1.08x 1.07x
object/binary 0.961x 1.05x 1.02x 0.979x 0.995x 0.965x 0.98x 0.979x 1.01x 0.99x 1.1x 1.05x 1.12x
object/multiclass 0.99x 0.925x 1.04x 1.04x 1.01x 1.02x 0.947x 1.01x 0.99x 1.01x 1.04x 1x 0.991x
time_transform_default ( latest code ) / time_transform_forced_vectorized ( main )
1 2 4 8 16 32 64 128 256 512 1024 2048 4096
int64/binary 0.069x 0.0862x 0.0631x 0.062x 0.0672x 0.0619x 0.0593x 0.067x 0.0556x 0.0631x 0.0527x 0.977x 1.02x
int64/multiclass 0.079x 0.0787x 0.0859x 0.0686x 0.0832x 0.0675x 0.0759x 0.0814x 0.0594x 0.0704x 0.0726x 1.09x 1.03x
object/binary 0.00961x 0.00213x 0.0166x 0.0353x 0.0783x 0.146x 0.328x 0.604x 1.27x 2.67x 6.04x 0.934x 1.01x
object/multiclass 0.019x 0.00238x 0.016x 0.0323x 0.0759x 0.152x 0.345x 0.643x 1.33x 2.68x 4.39x 1.02x 1.12x

@betatim

betatim commented Mar 4, 2026

Copy link
Copy Markdown
Member

I see two practical options:

1. Keep this as a behind-the-scenes optimization, but only apply it where it is almost certainly a win. We can use a very conservative cutoff (for example `n_samples <= 32` or `<= 64`) and keep everything lazy so large-batch users pay nothing. The motivation is that at these tiny batch sizes the benchmarks show a clear win for both int and object dtypes. This way, even with a fixed threshold, we still deliver a reliable and meaningful benefit to users, without any changes to API.

2. Give users full control. Add a constructor knob to enable the fast path (and optionally set the threshold) so inference users can benchmark on their machine and choose what works best for their setup.

My preference is (1) because it delivers the tiny-batch win without adding new API and gives the benefit immediately to all users, but I am happy to do (2) if the group would rather avoid any built-in threshold..

Having pondered it I think I also prefer option (1). We can always add a constructor argument for it alter (taking it away is a bit more work).

check_consistent_length,
check_is_fitted,
)
from sklearn.utils.validation import _normalize_na_key as _norm_key

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.

I think a separate class for this adds unnecessary complexity. We can just build plain dicts eagerly in fit() — something like:

self._category_maps_ = [
    {_norm_key(cat): i for i, cat in enumerate(cats)}
    for cats in self.categories_
]

This is simpler, avoids the lazy initialization pattern (which adds a mutable-on-read concern), and for the number of categories we typically see, the upfront cost in fit() is negligible compared to the fit itself.

The lazy pattern was a response to ogrisel's earlier feedback about not mutating state in transform, but eagerly building in fit solves that more cleanly.

@@ -393,6 +426,106 @@ def fit_transform(self, X, y, **params):
)
return X_out

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.

I'd suggest removing this entire method and the integer LUT approach. The dict-based lookup is already O(1) per sample and plenty fast for batches ≤ 1024. The dense LUT adds:

  • ~40 lines of code with memory budget logic, density heuristics, dtype checks
  • A second code path through _transform_small_batch (the integer branch)
  • Extra fitted state (_int_lookup_)
  • The time_fit_no_lut / peakmem_fit_no_lut benchmarks that test this internal detail

All of this for a micro-optimization within an already-fast path. The dict lookup on ≤1024 items is going to be sub-millisecond regardless. Let's keep the fast path simple: one code path using the dict maps.

"""Fast-path transform for small inputs (n_samples <= threshold)."""
_, n_samples, n_features = self._check_X(X, ensure_all_finite="allow-nan")
_check_feature_names(self, X, reset=False)
_check_n_features(self, X, reset=False)

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.

This method is doing too much: it has two major branches (integer LUT vs object/dict), each with a multiclass sub-branch, totaling ~70 lines. If we drop the integer LUT (see comment above), this simplifies dramatically. The whole method could be roughly:

def _transform_small_batch(self, X):
    n_samples = _num_samples(X)
    _check_feature_names(self, X, reset=False)
    _check_n_features(self, X, reset=False)
    X_arr = np.asarray(X, dtype=object)
    n_features = X_arr.shape[1]

    is_multi = self.target_type_ == "multiclass"
    n_classes = len(self.classes_) if is_multi else 0
    n_cols = n_features * n_classes if is_multi else n_features
    X_out = np.empty((n_samples, n_cols), dtype=np.float64)

    for j in range(n_features):
        cat_map = self._category_maps_[j]
        for i in range(n_samples):
            idx = cat_map.get(_norm_key(X_arr[i, j]), -1)
            if is_multi:
                base = j * n_classes
                for c in range(n_classes):
                    X_out[i, base + c] = (
                        self.encodings_[base + c][idx] if idx >= 0
                        else self.target_mean_[c]
                    )
            else:
                X_out[i, j] = (
                    self.encodings_[j][idx] if idx >= 0
                    else self.target_mean_
                )
    return X_out

One loop, one code path, easy to read and maintain, and genuinely curious about how it impacts the times in your benchmark, could you please check?

@gautamvarmadatla gautamvarmadatla Mar 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hi @adrinjalali, ran the benchmarks after making all the changes. The simplification works well for object dtype with a clean crossover at the threshold ( Basically same speedups and similar code as my intial version ) . int64 regresses at n=16 though, which makes sense since I added LUT specifically for integer speedups. Without it, np.asarray(X, dtype=object) can't compete with numpy's vectorized integer path.

If we want back LUT please lmk i can revert the latest commit i made. LUT results are in comment i made two weeks ago.

Benchmark ratios by batch size
dataset / target         1         2         4         8        16        32        64       128       256       512      1024      2048      4096
-------------------------------------------------------------------------------------------------------------------------------------------------------
int64/binary         8.911x    6.462x    2.857x    1.404x    0.770x    0.423x    0.205x    0.118x    0.063x    0.034x    0.020x    0.968x    0.961x
int64/multiclass     9.212x    6.174x    2.181x    1.544x    0.780x    0.442x    0.213x    0.113x    0.064x    0.038x    0.022x    0.962x    1.096x
object/binary      755.865x 5113.387x  418.856x  200.609x   74.757x   38.585x   18.214x    9.006x    4.609x    2.181x    1.083x    1.006x    1.005x
object/multiclass  753.766x 5574.437x  507.229x  184.634x   82.970x   38.816x   18.121x    9.212x    4.616x    2.401x    1.142x    0.985x    0.911x

_check_feature_names(self, X, reset=False)
_check_n_features(self, X, reset=False)
X_arr = np.asarray(X)
index_maps = self._index_maps_

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.

_check_X does quite a bit of work internally (builds ordinal encoding structures, etc.). If the whole point of the fast path is to avoid the overhead of the vectorized path for small batches, we should keep validation minimal.

You already call _check_feature_names and _check_n_features on the next lines, so the _check_X call is redundant. Replace with just _num_samples(X) and np.asarray(X).

Comment thread sklearn/utils/validation.py Outdated
_check_n_features(_estimator, X, reset=reset)

return out

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 sentinel enum approach is sound. It's pickle-safe and collision-free, which matters here. But as @OmarManzoor flagged, this is the first private Enum in scikit-learn's utils.

I'd suggest moving both _NAKey and _normalize_na_key into sklearn/utils/_missing.py alongside the existing is_scalar_nan and is_pandas_na helpers. That's their natural home. validation.py is already very long and these are fundamentally missing-value utilities, not validation utilities.

self.enc_vec.transform(self.X)

def time_fit(self, dtype: str, target_type: str, n_rows: int):
TargetEncoder(target_type=self.target_type, random_state=0).fit(

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.

If we remove the integer LUT (see comments on _init_int_lookup), these *_no_lut benchmarks go away. Even if we keep the LUT, benchmarking with _init_int_lookup = lambda: None is testing an internal implementation detail: if that method gets renamed/refactored, the benchmark silently breaks.

I'd drop these and keep only time_fit / time_transform_default / time_transform_forced_vectorized.

@adrinjalali adrinjalali 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.

I think this is now minimal enough for it to be a much easier merge.

Comment on lines +441 to +447
X_arr = np.asarray(X, dtype=object)
if X_arr.ndim != 2:
raise ValueError("Expected 2D array. Reshape your data.")
n_samples = _num_samples(X_arr)
_check_feature_names(self, X, reset=False)
_check_n_features(self, X_arr, reset=False)
n_features = X_arr.shape[1]

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 only part making me uncomfortable here is this one. We have our validation in _BaseEncoder._transform, and here that logic is duplicated. Probably the cleanest / easiest way is to replace this with:

        X_list, n_samples, n_features = self._check_X(
            X, ensure_all_finite=ensure_all_finite
        )
        validate_data(self, X=X, reset=False, skip_check_array=True)

exactly as is in _transform

@cakedev0

cakedev0 commented Jul 6, 2026

Copy link
Copy Markdown
Member

I took a look and I'd prefer not to merge this PR in this form, but the overall idea is good (a fast path for small batches).

I did some profiling and I found out that the main problem is that transform has some O(n_categories) processing for the object path, which indeed is a real problem for people putting models in production. It can be arbitrary slow: it's ~50ms for 100k categories, 500ms for 1M, 5s for 10M... (for transform on one single sample).
This is a real big problem for backend latency and optimizing it away is important, it's not like going from 0.5ms to 0.01ms for the int path (this is not a speed-up we care about honestly).

The fast-path for small batches implemented in this shortcuts both:

  • self._transform: this is _BaseEncoder._transform, it's common with one-hot & ordinal encoding. It's where O(n_categories) happens.
  • self._transform_X_ordinal: this is really simple and not very different from what happens in the fast path => we should rewrite this part twice.

Conclusion: the optimization should be done at the _BaseEncoder._transform level.

Also, I would prefer to find something that is not a specialized fast path, but just a nice refactor that avoids the O(n_categories) processing. That might be hard to do though, and maybe the best solution is to adapt what have been done in this PR to _BaseEncoder._transform.

@gautamvarmadatla : I propose to open a PR that supersedes this one, I'll credit you in the changelog and in the PR description as a co-author. Would you be ok with that?

@gautamvarmadatla

Copy link
Copy Markdown
Contributor Author

hi @cakedev0

Sounds good, please feel free to work on it, I currently don't have the bandwidth.

Agreed the object path is the real cost, every transform rebuilds the full category set and dict so you pay for all the categories regardless of batch size.

My only pushback is, I wouldn't write off the int path. A speedup is still a speedup at high throughput, and a proper caching fix gets both anyway. Also worth keeping in mind, caching in _BaseEncoder means OrdinalEncoder and OneHotEncoder carry the map too (betatim's memory point), so lazy on first transform beats eager in fit.

@betatim

betatim commented Jul 8, 2026

Copy link
Copy Markdown
Member

Should we close this PR already or will you remember to do that when you open and link the follow up @cakedev0 ?

@cakedev0

cakedev0 commented Jul 8, 2026

Copy link
Copy Markdown
Member

Let's close this PR and open an issue instead.

@gautamvarmadatla if you want to open an issue that would be very helpful, especially if you have an example of how you had to work around it to put a model in production.

Otherwise I'll do it.


I've given it a first vibe-try / investigation pass and here are my findings:

  • I checked if PRF: Encoders (very) fast path for pandas/polars categoricals #34393 solved this problem and it doesn't, so it's worth continuing in the direction of this PR.
  • The memory trade-off is indeed real when there are many categories, in which case you're more likely to benefit from the optimization. It might be possible to do a cache-like pattern that doesn't make the first transform much slower than the current speed, which would IMO solve this trade-off quite well.

@lesteve

lesteve commented Aug 4, 2026

Copy link
Copy Markdown
Member

Agree with #32368 (comment), let's close this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve TargetEncoder predict time for single rows and many categories

9 participants