Add an inverse-CDF path to categorical sampling - #4177
Merged
Conversation
zcbenz
approved these changes
Aug 12, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
Fixes #3847 for the single-distribution case.
categoricalsamples with Gumbel-max, drawing one perturbation per category per sample, soNcategories andMsamples build anN x Mintermediate to returnMindices. AtN = M = 1e6that is ~4 TB.When
logitsholds a single distribution and more than one sample is requested, sample byinverting the cumulative weights instead: memory goes from
O(N * M)toO(N + M)and workfrom
O(N * M)toO(N + M log N). It is composed from existing ops, so CPU, Metal and CUDAare covered with no new kernels.
searchsortedneeds a 1-D sequence, so batchedlogitsand the single-sample overload keep the Gumbel path.
Weights accumulate in
float32, so a category holding less than roughly1e-7of thetotal mass may be drawn with a distorted probability. This is noted in the docstring.
Behaviour changes
keythe affected overloads return different, identically distributed samples.-inflogits now draw uniformly rather than always returning index 0.+infentries now split the samples rather than always returning the first.Benchmarks
benchmarks/python/categorical_bench.py, Metal:CPU is 1233x and 4616x on the first two rows.
C++ 25/25 and Python 21/21 on Metal and
DEVICE=cpu. CUDA was not built or tested (Applesilicon); the change adds no backend code.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes