Repository navigation
ENH : Speed up TargetEncoder.transform for small batches - #32368
gautamvarmadatla wants to merge 87 commits into
Conversation
… expand coverage to hit changed lines
…aced pandas with attribute based functions. Deleted coverage test files to test code coverage
…) while preserving exact parity
ogrisel
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:
|
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 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. |
|
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 |
…hub.com/gautamvarmadatla/scikit-learn into target_transform_speedup_low_batch_size
This comment was marked as outdated.
This comment was marked as outdated.
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 locallyfrom __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() |
|
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 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 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. |
|
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 Is there an up-to-date table or plot of absolute execution times for 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
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. |
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 comparisionThe comparison uses a single-feature synthetic dataset with 200k rows and 100k categories
|
|
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:
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.. |
|
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. |
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. |
|
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. |
|
I am not blocking. Would be interested in @lesteve‘s opinion. 2 question:
|
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
peakmem_transform_default ( latest code ) / peakmem_transform_forced_vectorized ( main )
time_fit / time_fit_no_lut
time_transform_default ( latest code ) / time_transform_forced_vectorized ( main )
|
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 |
There was a problem hiding this comment.
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 | |||
|
|
|||
There was a problem hiding this comment.
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_lutbenchmarks 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) |
There was a problem hiding this comment.
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_outOne 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?
There was a problem hiding this comment.
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_ |
There was a problem hiding this comment.
_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).
| _check_n_features(_estimator, X, reset=reset) | ||
|
|
||
| return out | ||
|
|
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
loop, move _NAKey to _missing.py
adrinjalali
left a comment
There was a problem hiding this comment.
I think this is now minimal enough for it to be a much easier merge.
| 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] |
There was a problem hiding this comment.
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
|
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 The fast-path for small batches implemented in this shortcuts both:
Conclusion: the optimization should be done at the 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 @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? |
|
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. |
|
Should we close this PR already or will you remember to do that when you open and link the follow up @cakedev0 ? |
|
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:
|
|
Agree with #32368 (comment), let's close this. |
Fixes #30952
What does this implement/fix?
This PR adds a small-batch fast path for
TargetEncoder.transformthat removes the large, fixed overhead observed for tiny batches, while preserving bit-for-bit parity with the existing vectorized implementation for:None,np.nan, duck-typedpandas.NA,pandas.NaT, NumPyNaT),target_mean_),classes_).High-level idea
After
fit, we eagerly precompute per-feature structures:categories_[j],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,
transformnormalizes keys via_norm_key(x)using distinct, hashable enum sentinels:None→_NAKey.NONE_NAKey.NANpandas.NA→_NAKey.PD_NApandas.NaT→_NAKey.PD_NATdatetime64/timedelta64NaT→_NAKey.NATThe same normalization is applied when building the maps during
fitand when looking up duringtransform. 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 toclasses_.Benchmarks
Environment: Windows, CPython 3.12 (64-bit), NumPy MKL,
pytest-benchmark.Setup: I benchmarked both paths ( Fast and vec ) for both dtypes:
int64andobject. 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):
int64: strictly integral, no missing sentinels.object: Python objects; whenn_small ≥ 2, injectNone(first row) andnp.nan(last row)._small_batch_threshold = 1e9(forces fast path)._small_batch_threshold = 0(forces vectorized path).seed = n_smallfor 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).
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
Benchmarks and Lineprofiler helper code ( Latency )
Benchmark harness (pytest-benchmark)
Line-profiler helper (top-k hottest lines in ms)
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)
Thanks for reviewing! Happy to make further changes if required!