Skip to content

Introduce stateless RNG APIs for randint / raw bits - #190253

Closed
jbschlosser wants to merge 8 commits into
gh/jbschlosser/286/basefrom
gh/jbschlosser/286/head
Closed

jbschlosser wants to merge 8 commits into
gh/jbschlosser/286/basefrom
gh/jbschlosser/286/head

Conversation

@jbschlosser

@jbschlosser jbschlosser commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This PR introduces new stateless RNG APIs for generating integers / raw bits:

  • randint(key, *shape, low=0, high=None, dtype=torch.int32)
  • randint_(key, result, *, low=0, high=None)
  • bits(key, *shape, dtype=torch.int32)
  • bits_(key, result)

randint() / randint_() can produce bounded or full-range random integers. bits() / bits_() are convenience wrappers for full-range generation of the given dtype.

Supported dtypes: all signed and unsigned integral types except torch.bool:

  • torch.int8 / torch.uint8
  • torch.int16 / torch.uint16
  • torch.int32 / torch.uint32
  • torch.int64 / torch.uint64

All 32-bit or smaller dtypes come from sampling 32 bits of randomness and downcasting as necessary. For 64-bit dtypes,
64 bits of randomness is sampled per output value.

import torch
from torch.func import _random as r

key = r.key(42, device="cuda")

a = r.randint(key, 2, 3)  # int32 generation of shape (2, 3) with bounds [0, INT32_MAX]
b = r.randint(key, 2, 3, high=10)  # int32 generation of shape (2, 3) with bounds [0, 10)
c = r.randint(key, 2, 3, low=4, high=7)  # int32 generation of shape (2, 3) with bounds [4, 7)
d = r.randint(key, 2, 3, low=None, high=0)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, 0)
e = r.randint(key, 2, 3, low=None, high=None)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, INT32_MAX]

# in-place into a preallocated tensor
out = torch.empty(2, 3, dtype=torch.int32, device="cuda")
r.randint_(key, out, low=3, high=10)

# bits() outputs are equivalent to passing low=None and high=None to randint
x = r.bits(key, 10)                      # 10x uint32 worth of bits; 
y = r.bits(key, 10, dtype=torch.uint64)  # 10x uint64 worth of bits

# in-place into a preallocated tensor
out = torch.empty(10, dtype=torch.uint32, device="cuda")
r.bits_(key, out)

NOTE 1: The new randint() API differs significantly from torch.randint() API to be consistent with the normal() and uniform() APIs in torch.func._random. Positional integers are treated as shapes rather than bounds, and bounds are provided kw-only. Ex:

# shape (2, 3) with bounds [0, 10)
torch.randint(10, (2, 3))  
randint(key, (2, 3), high=10)  # OR randint(key, 2, 3, high=10)

# shape (2, 3) with bounds [1, 5)
torch.randint(1, 5, (2, 3))
randint(key, (2, 3), low=1, high=5)  # OR randint(key, 2, 3, low=1, high=5)

NOTE 2: Bounded integer generation utilizing the modulo operator is subject to modulo bias when the generation range does not evenly divide the range of the dtype. For large ranges that are not powers of 2, the bias can become substantial. For a 32-bit RNG sample:

R = high - low  # range
W = 32  # sampled bitwidth (32 bits for all dtypes except 64-bit dtypes)
bias(R) = 0           if 2**W % R == 0
          R / (2**W)  otherwise

This gives the following table:

================================
Range up to     Max relative bias
================================
``2 ** 8``      0.000006%
``2 ** 16``     0.0015%
``2 ** 20``     0.024%
``2 ** 24``     0.39%
``2 ** 26``     1.6%
``2 ** 27``     3.1%
``2 ** 28``     6.25%
================================

The preexisting torch.randint() op deals with this by sampling 64 bits per 32-bit output when the range >= 2**28. To keep a static amount of RNG sample per output value, we always sample 32 bits per 32-bit output and simply error if the range is a large enough non-power-of-2 such that the bias will meet or exceed 6.25%. The error indicates to the user that they should either:

  • Sample with a 64-bit dtype instead OR
  • Round up the range to the nearest power of 2 and manually perform rejection sampling or a similar strategy

Another way to deal with this is to do batched sampling (see e.g. this paper). If we utilize e.g. 64 bits of randomness for two 32-bit outputs, we can move the bias threshold around so that a given range has comparatively less bias. Since Philox produces 4x32 outputs per 10x rounds, it's also natural to utilize 128 bits of randomness for four 32-bit outputs to further reduce the bias. However, this only moves the bias threshold around and does not completely remove regions of very high bias (up to 100%). Given this, some perf implications, and the fact that batched sampling changes output values, breaking consistency with 1:1 sampling for dtypes < 32 bits, we chose not to implement this.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/190253

Note: Links to docs will display an error until the docs builds have been completed.

❌ 2 New Failures, 3 Cancelled Jobs

As of commit 8bbb788 with merge base 0768654 (image):

NEW FAILURES - The following jobs have failed:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Jul 16, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.

[ghstack-poisoned]
@jbschlosser jbschlosser added the topic: not user facing topic category label Jul 30, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@jbschlosser jbschlosser changed the title Introduce stateless RNG API for raw bits Introduce stateless RNG APIs for randint / raw bits Aug 18, 2026
[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude investigate the CI failures; for those that are related, how should they be addressed?

@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude are any of the CI failures related?

@claude

claude Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Claude finished @jbschlosser's task in 1m 47s —— View job


Yes — one of them is real

  • Pull CI status for head commit 529fbd4a
  • Triage each failure as related vs unrelated
  • Root-cause the related one
  • Recommend fix

trunk / macos-py3-arm64 / test (default, 1, 3) is a genuine failure caused by this PR. It is a hard failure that will reproduce every time, not a flake, and it also explains why the merge was blocked. The two inductor failures are unrelated.

Detailed investigation

Triage

Job Failure Verdict
trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) test_overrides collection-time AssertionError Related — real, deterministic
inductor / inductor-test / test (inductor, 2, 2) test_forward_ad_linalg_householder_product_cuda_float32 Unrelated flake
inductor / inductor-test-cuda132 / test (inductor, 2, 2) same test Unrelated flake (same test, same shard)
7 cancelled jobs received SIGINT Infra — retry

I agree with Dr. CI's AI verdicts on the two inductor jobs: linalg.householder_product forward-AD numerics shares no code path with this stack, and the same shard passes on trunk. Retry them.

The real failure

From the macos-py3-arm64 log:

File "test/test_overrides.py", line 370, in generate_tensor_like_torch_implementations
  raise AssertionError(msg.format(pprint.pformat(untested_funcs)))
AssertionError: The following functions are not tested for __torch_function__ support,
please ensure there is an entry in the dict returned by torch.overrides.get_testing_overrides
for this function or if a __torch_function__ override does not make sense, add an entry to
the tuple returned by torch._overrides.get_ignored_functions.

["<class 'torch.Tensor'>._philox_randint_"]

This fires at module import in test_overrides.py:382, so the whole file fails to collect — hence No stepcurrent file found and the shard going red.

Root cause is a one-line omission. _philox_randint_ is declared with variants: function, method (aten/src/ATen/native/native_functions.yaml:6641-6646), so it lands on torch.Tensor as a method. test_overrides.py walks every public/underscore-prefixed Tensor method and asserts each is either in get_testing_overrides() or in get_ignored_functions(). _philox_randint_ is in neither.

The two sibling ops from earlier in this stack — both also variants: function, method — were correctly added to the ignore list at torch/overrides.py:387-388:

Tensor._philox_normal_,
Tensor._philox_uniform_,

_philox_randint_ just needs the same treatment. Note _philox_key_split / _philox_key_fold_in are variants: function only, which is why they never needed an entry.

Fix

Add one line to the get_ignored_functions() set in torch/overrides.py:389:

        Tensor._philox_normal_,
        Tensor._philox_uniform_,
        Tensor._philox_randint_,
    }

Ignore rather than test is the right call here and matches the precedent: these are private stateless-RNG plumbing ops, not part of the user-facing surface that __torch_function__ subclasses are expected to intercept, and the two ops added earlier in this stack are already ignored. Adding a get_testing_overrides entry instead would imply a subclass contract you don't intend to support.

torch/overrides.py is not currently in the changed-files list for this PR, so this is a new edit to the commit.

Fix this →

Why the earlier investigation looked different

The previous @claude run on this PR (commit b4675e09) reported two dynamo_wrapped torch.iinfo-unhashable crashes. Those are gone from the current head's failure set — the test refactor in 529fbd4a that moved torch.iinfo calls to module level addressed them, consistent with workaround #1 from that analysis. The test_overrides failure is a different, newly-surfaced issue.

Not verified locally

There is no built torch in this checkout, so I could not run python test/test_overrides.py to confirm the fix clears the assertion. The diagnosis is pinned to exact lines (the assertion names the method literally, and the two sibling ops establish the pattern), but the one-line change should be confirmed by CI or a local test_overrides run.

I did not push any changes — this is a ghstack PR and my write operations are disabled for it, so the one-line torch/overrides.py edit is yours to apply (leave it uncommitted per the repo's ghstack guidance, or amend if you're about to re-submit).
| Branch: gh/jbschlosser/286/head

[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable)

Details for Dev Infra team Raised by workflow job

[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: inductor / unit-test / inductor-test-cuda132 / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g)

Details for Dev Infra team Raised by workflow job

@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude are the CI failures related?

@claude

claude Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Claude finished @jbschlosser's task in 4m 35s —— View job


No — the one remaining failure is unrelated

  • Pull CI status for head commit 8bbb788f
  • Triage each failure as related vs unrelated
  • Root-cause / recommend next step

pull, trunk, Lint, docs-build, BC Lint, TSan, and torchtitan-test are all green on 8bbb788f. The only red is test_forward_ad_linalg_householder_product_cuda_float32 in the inductor shard, and it is a float32 tolerance overshoot in a linalg op with no code path in common with this stack. The test_overrides and torch.iinfo issues from my previous two investigations are both gone.

The practical problem is that retrying will not clear it — you have now lost three merge attempts to this same test on the same shard. Recommendation at the bottom.

Detailed investigation

CI status at head (8bbb788f)

Workflow Conclusion
pull ✅ success
trunk ✅ success
Lint (both runs) ✅ success
docs-build ✅ success
BC Lint ✅ success
TSan ✅ success
torchtitan-test ✅ success
Check mergeability of ghstack PR ✅ success
inductor ⚠️ cancelled — 1 test failure in 1 shard

Note that trunk is now green, so the macos-py3-arm64 / test_overrides failure I flagged on 529fbd4a is fixed — Tensor._philox_randint_ is in get_ignored_functions at torch/overrides.py in the current diff (+1/-0). The two dynamo_wrapped torch.iinfo-unhashable aborts from the b4675e09 investigation are also gone.

The remaining failure

FAILED test_ops.py::TestCompositeComplianceCUDA::test_forward_ad_linalg_householder_product_cuda_float32
  - Exception: Tensor-likes are not close!

Mismatched elements: 2 / 50 (4.0%)
Greatest absolute difference: 1.341104507446289e-05 at index (0, 0, 2, 0) (up to 1e-05 allowed)
Greatest relative difference: 2.4471964934491552e-05 at index (0, 0, 2, 0) (up to 1.3e-06 allowed)

Caused by sample input at index 2: SampleInput(input=Tensor[size=(2, 1, 5, 5), ..., dtype=torch.float32],
                                              args=TensorList[Tensor[size=(2, 1, 5), ...]])

2 of 50 elements miss, and the absolute miss is only 1.34x over the allowed atol (1.34e-05 vs 1e-05). This is forward-mode AD through linalg.householder_product on a 5x5 f32 matrix — a sequential product of reflectors, so f32 rounding accumulates. The op already carries several tolerance/skip decorators for exactly this reason (torch/testing/_internal/opinfo/definitions/linalg.py:1556-1601, including a toleranceOverride to atol=6e-5 for TestEagerFusionOpInfo and a ROCm skip for "f32 precision difference that exceeds the default tolerance"). There is no toleranceOverride covering TestCompositeComplianceCUDA under PYTORCH_TEST_WITH_INDUCTOR=1, which is the configuration that fails.

Everything else in that shard passed: 1 failed, 332 passed, 686 skipped, 5 xfailed, 2 rerun. The job stops after the first failure, so the rest of the shard is untested — but nothing else went red before it.

Why it can't be this PR

The full diff is 11 files, and every one is confined to the stateless-Philox surface:

  • aten/src/ATen/native/PhiloxStatelessRNG.{cpp,h}, cuda/PhiloxDistribution.cu — new _philox_randint_ kernels only
  • native_functions.yaml (+7), HasDecompTest...expect (+3) — the new op's entries
  • torch/func/_random.py (+322), test/test_stateless_rng.py (+412/-6) — new Python API and its tests
  • torch/overrides.py (+1) — Tensor._philox_randint_ ignore entry
  • torch/_meta_registrations.py — adds meta_philox_randint_ and factors the shared arg checks into _check_philox_gen_args; the pre-existing _check_philox_distribution_args behavior is unchanged
  • torch/_inductor/fx_passes/reinplace.py (+3/-1) — one new inplaceable_ops entry keyed on aten._philox_randint.default
  • torchgen/model.py (+4/-2) — narrows the "rand" in name auto-tagging heuristic so _philox_* ops don't get nondeterministic_seeded

The two files that touch shared infrastructure are the only ones worth a second look, and both are inert here. The reinplace.py change adds a dict entry keyed on a brand-new op — it cannot alter reinplacing decisions for linalg_householder_product. The torchgen/model.py change only removes a tag, only from names containing _philox_, so linalg_householder_product (which contains no rand/dropout/_philox_) takes the identical branch it did before. linalg.householder_product is not random, not reinplaceable-in-place, and has no Philox dependency.

Dr. CI's AI verdict reached the same conclusion independently on both affected jobs.

The part worth acting on

This is not a random flake — it has now blocked three separate merge attempts, always the same test, always the same shard and runner class:

Merge attempt Blocking job
2026-08-20 inductor-test / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g)
2026-08-21 17:38 macos-py3-arm64 / test_overrides (real; since fixed)
2026-08-21 21:23 inductor-test-cuda132 / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g)

Within a single job it also failed all three reruns. So it reproduces deterministically for a given runner + sample, which is what you'd expect from a tolerance sitting 1.3x under the observed error on a specific SM/library combination — not something a retry will shake off. @pytorchbot merge will keep failing on it.

Two ways forward:

1. Force-merge (what I'd do). Everything attributable to this PR is green, ngimel has approved, and the blocker is a pre-existing tolerance gap in an unrelated linalg op:

@pytorchbot merge -f "unrelated linalg.householder_product f32 tolerance failure in inductor shard; all PR-relevant CI green"

2. Fix the tolerance separately. If you'd rather unblock it properly for everyone hitting this, the durable fix is a toleranceOverride on the linalg.householder_product OpInfo scoped to composite-compliance forward-AD, alongside the existing TestEagerFusionOpInfo overrides at torch/testing/_internal/opinfo/definitions/linalg.py:1566-1575:

DecorateInfo(
    toleranceOverride({torch.float32: tol(atol=6e-5, rtol=6e-5)}),
    "TestCompositeCompliance",
    "test_forward_ad",
),

That belongs in its own PR, not bundled into this stack — it touches unrelated test infra and would pull linalg reviewers into an RNG change. A disable-test issue would work too, but a tolerance bump is more honest given the error is only 1.34x over atol.

Fix this →

Not verified

I could not query HUD's flaky-test history API or gh issue list for a pre-existing disable issue on this test — those calls need approvals I don't have in this run, so I can't tell you whether it's already tracked or how far back it goes on trunk. The attribution argument above rests on reading the full diff rather than on trunk-history comparison, but the diff is small and entirely Philox-scoped, so the conclusion is solid regardless.

I made no changes — everything in this PR's own surface is green, and the recommended tolerance fix belongs in a separate PR off main.
| Branch: gh/jbschlosser/286/head

@jbschlosser

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Aug 25, 2026
…e loop (#190036)

Follow-up from #189767 to reduce complexity of `split()` / `fold_in()` kernels. On an H100, this generally results in neutral perf or speedups, with some exceptions:

```
  split()

  ┌─────┬────────────┬─────────────┬────────────┬─────────┐
  │ num │     n      │ before (µs) │ after (µs) │ speedup │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │          1 │        6.63 │       6.51 │  1.02x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │      1,024 │        6.49 │       6.58 │  0.99x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │     16,384 │        6.51 │       6.60 │  0.99x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │     65,536 │        6.50 │       6.68 │  0.97x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │    262,144 │        6.49 │       6.64 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │  1,048,576 │       21.55 │      21.19 │  1.02x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │  4,194,304 │      140.07 │     127.49 │  1.10x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │ 16,777,216 │      533.07 │     492.19 │  1.08x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │          1 │        6.50 │       6.43 │  1.01x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │      1,024 │        6.47 │       6.60 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │     16,384 │        6.55 │       6.52 │  1.00x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │     65,536 │        8.89 │       8.14 │  1.09x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │    262,144 │       40.50 │      33.04 │  1.23x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │  1,048,576 │      183.46 │     182.13 │  1.01x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │  4,194,304 │      953.47 │     975.40 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │          1 │        6.38 │       6.51 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │      1,024 │        6.43 │       6.61 │  0.97x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │     16,384 │       14.32 │      13.95 │  1.03x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │     65,536 │       70.55 │      58.48 │  1.21x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │    262,144 │      299.95 │     241.81 │  1.24x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │  1,048,576 │     1312.20 │    1419.08 │  0.92x  │
  └─────┴────────────┴─────────────┴────────────┴─────────┘

  fold_in()

  ┌─────────┬────────────┬─────────────┬────────────┬─────────┐
  │ variant │     n      │ before (µs) │ after (µs) │ speedup │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │          1 │        7.22 │       6.96 │  1.04x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │      1,024 │        6.93 │       6.91 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │     16,384 │        7.01 │       6.99 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │     65,536 │        6.93 │       6.96 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │    262,144 │        6.93 │       7.02 │  0.99x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │  1,048,576 │        7.63 │       7.04 │  1.09x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │  4,194,304 │       70.33 │      66.66 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │ 16,777,216 │      272.30 │     249.00 │  1.09x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │          1 │        6.98 │       6.58 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │      1,024 │        6.74 │       6.74 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │     16,384 │        6.79 │       6.64 │  1.02x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │     65,536 │        6.68 │       6.61 │  1.01x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │    262,144 │        6.70 │       6.70 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │  1,048,576 │        7.12 │       6.77 │  1.05x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │  4,194,304 │       70.29 │      66.66 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │ 16,777,216 │      272.57 │     248.86 │  1.10x  │
  └─────────┴────────────┴─────────────┴────────────┴─────────┘
```
Pull Request resolved: #190036
Approved by: https://github.com/ngimel
ghstack dependencies: #190253
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
This PR introduces new stateless RNG APIs for generating integers / raw bits:
* `randint(key, *shape, low=0, high=None, dtype=torch.int32)`
* `randint_(key, result, *, low=0, high=None)`
* `bits(key, *shape, dtype=torch.int32)`
* `bits_(key, result)`

`randint()` / `randint_()` can produce bounded or full-range random integers. `bits()` / `bits_()` are convenience wrappers for full-range generation of the given dtype.

Supported dtypes: all signed and unsigned integral types **except `torch.bool`**:
* `torch.int8` / `torch.uint8`
* `torch.int16` / `torch.uint16`
* `torch.int32` / `torch.uint32`
* `torch.int64` / `torch.uint64`

All 32-bit or smaller dtypes come from sampling 32 bits of randomness and downcasting as necessary. For 64-bit dtypes,
64 bits of randomness is sampled per output value.

```python
import torch
from torch.func import _random as r

key = r.key(42, device="cuda")

a = r.randint(key, 2, 3)  # int32 generation of shape (2, 3) with bounds [0, INT32_MAX]
b = r.randint(key, 2, 3, high=10)  # int32 generation of shape (2, 3) with bounds [0, 10)
c = r.randint(key, 2, 3, low=4, high=7)  # int32 generation of shape (2, 3) with bounds [4, 7)
d = r.randint(key, 2, 3, low=None, high=0)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, 0)
e = r.randint(key, 2, 3, low=None, high=None)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, INT32_MAX]

# in-place into a preallocated tensor
out = torch.empty(2, 3, dtype=torch.int32, device="cuda")
r.randint_(key, out, low=3, high=10)

# bits() outputs are equivalent to passing low=None and high=None to randint
x = r.bits(key, 10)                      # 10x uint32 worth of bits;
y = r.bits(key, 10, dtype=torch.uint64)  # 10x uint64 worth of bits

# in-place into a preallocated tensor
out = torch.empty(10, dtype=torch.uint32, device="cuda")
r.bits_(key, out)
```

**NOTE 1:** The new `randint()` API differs significantly from `torch.randint()` API to be consistent with the `normal()` and `uniform()` APIs in `torch.func._random`. Positional integers are treated as shapes rather than bounds, and bounds are provided kw-only. Ex:
```python
# shape (2, 3) with bounds [0, 10)
torch.randint(10, (2, 3))
randint(key, (2, 3), high=10)  # OR randint(key, 2, 3, high=10)

# shape (2, 3) with bounds [1, 5)
torch.randint(1, 5, (2, 3))
randint(key, (2, 3), low=1, high=5)  # OR randint(key, 2, 3, low=1, high=5)
```

**NOTE 2:** Bounded integer generation utilizing the modulo operator is subject to modulo bias when the generation range does not evenly divide the range of the dtype. For large ranges that are not powers of 2, the bias can become substantial. For a 32-bit RNG sample:
```
R = high - low  # range
W = 32  # sampled bitwidth (32 bits for all dtypes except 64-bit dtypes)
bias(R) = 0           if 2**W % R == 0
          R / (2**W)  otherwise
```

This gives the following table:
```
================================
Range up to     Max relative bias
================================
``2 ** 8``      0.000006%
``2 ** 16``     0.0015%
``2 ** 20``     0.024%
``2 ** 24``     0.39%
``2 ** 26``     1.6%
``2 ** 27``     3.1%
``2 ** 28``     6.25%
================================
```

The preexisting `torch.randint()` op deals with this by sampling 64 bits per 32-bit output when the range >= 2**28. To keep a static amount of RNG sample per output value, we always sample 32 bits per 32-bit output and simply error if the range is a large enough non-power-of-2 such that the bias will meet or exceed 6.25%. The error indicates to the user that they should either:
* Sample with a 64-bit dtype instead OR
* Round up the range to the nearest power of 2 and manually perform rejection sampling or a similar strategy

Another way to deal with this is to do batched sampling (see e.g. [this paper](https://arxiv.org/pdf/2408.06213)). If we utilize e.g. 64 bits of randomness for two 32-bit outputs, we can move the bias threshold around so that a given range has comparatively less bias. Since Philox produces 4x32 outputs per 10x rounds, it's also natural to utilize 128 bits of randomness for four 32-bit outputs to further reduce the bias. However, this only moves the bias threshold around and does not completely remove regions of very high bias (up to 100%). Given this, some perf implications, and the fact that batched sampling changes output values, breaking consistency with 1:1 sampling for dtypes < 32 bits, we chose not to implement this.

Pull Request resolved: pytorch#190253
Approved by: https://github.com/ngimel
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…e loop (pytorch#190036)

Follow-up from pytorch#189767 to reduce complexity of `split()` / `fold_in()` kernels. On an H100, this generally results in neutral perf or speedups, with some exceptions:

```
  split()

  ┌─────┬────────────┬─────────────┬────────────┬─────────┐
  │ num │     n      │ before (µs) │ after (µs) │ speedup │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │          1 │        6.63 │       6.51 │  1.02x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │      1,024 │        6.49 │       6.58 │  0.99x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │     16,384 │        6.51 │       6.60 │  0.99x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │     65,536 │        6.50 │       6.68 │  0.97x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │    262,144 │        6.49 │       6.64 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │  1,048,576 │       21.55 │      21.19 │  1.02x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │  4,194,304 │      140.07 │     127.49 │  1.10x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 2   │ 16,777,216 │      533.07 │     492.19 │  1.08x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │          1 │        6.50 │       6.43 │  1.01x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │      1,024 │        6.47 │       6.60 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │     16,384 │        6.55 │       6.52 │  1.00x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │     65,536 │        8.89 │       8.14 │  1.09x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │    262,144 │       40.50 │      33.04 │  1.23x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │  1,048,576 │      183.46 │     182.13 │  1.01x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 16  │  4,194,304 │      953.47 │     975.40 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │          1 │        6.38 │       6.51 │  0.98x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │      1,024 │        6.43 │       6.61 │  0.97x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │     16,384 │       14.32 │      13.95 │  1.03x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │     65,536 │       70.55 │      58.48 │  1.21x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │    262,144 │      299.95 │     241.81 │  1.24x  │
  ├─────┼────────────┼─────────────┼────────────┼─────────┤
  │ 128 │  1,048,576 │     1312.20 │    1419.08 │  0.92x  │
  └─────┴────────────┴─────────────┴────────────┴─────────┘

  fold_in()

  ┌─────────┬────────────┬─────────────┬────────────┬─────────┐
  │ variant │     n      │ before (µs) │ after (µs) │ speedup │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │          1 │        7.22 │       6.96 │  1.04x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │      1,024 │        6.93 │       6.91 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │     16,384 │        7.01 │       6.99 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │     65,536 │        6.93 │       6.96 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │    262,144 │        6.93 │       7.02 │  0.99x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │  1,048,576 │        7.63 │       7.04 │  1.09x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │  4,194,304 │       70.33 │      66.66 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ int     │ 16,777,216 │      272.30 │     249.00 │  1.09x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │          1 │        6.98 │       6.58 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │      1,024 │        6.74 │       6.74 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │     16,384 │        6.79 │       6.64 │  1.02x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │     65,536 │        6.68 │       6.61 │  1.01x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │    262,144 │        6.70 │       6.70 │  1.00x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │  1,048,576 │        7.12 │       6.77 │  1.05x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │  4,194,304 │       70.29 │      66.66 │  1.06x  │
  ├─────────┼────────────┼─────────────┼────────────┼─────────┤
  │ tensor  │ 16,777,216 │      272.57 │     248.86 │  1.10x  │
  └─────────┴────────────┴─────────────┴────────────┴─────────┘
```
Pull Request resolved: pytorch#190036
Approved by: https://github.com/ngimel
ghstack dependencies: pytorch#190253
aeytkn pushed a commit to aeytkn/pytorch that referenced this pull request Sep 3, 2026
This PR introduces new stateless RNG APIs for generating integers / raw bits:
* `randint(key, *shape, low=0, high=None, dtype=torch.int32)`
* `randint_(key, result, *, low=0, high=None)`
* `bits(key, *shape, dtype=torch.int32)`
* `bits_(key, result)`

`randint()` / `randint_()` can produce bounded or full-range random integers. `bits()` / `bits_()` are convenience wrappers for full-range generation of the given dtype.

Supported dtypes: all signed and unsigned integral types **except `torch.bool`**:
* `torch.int8` / `torch.uint8`
* `torch.int16` / `torch.uint16`
* `torch.int32` / `torch.uint32`
* `torch.int64` / `torch.uint64`

All 32-bit or smaller dtypes come from sampling 32 bits of randomness and downcasting as necessary. For 64-bit dtypes,
64 bits of randomness is sampled per output value.

```python
import torch
from torch.func import _random as r

key = r.key(42, device="cuda")

a = r.randint(key, 2, 3)  # int32 generation of shape (2, 3) with bounds [0, INT32_MAX]
b = r.randint(key, 2, 3, high=10)  # int32 generation of shape (2, 3) with bounds [0, 10)
c = r.randint(key, 2, 3, low=4, high=7)  # int32 generation of shape (2, 3) with bounds [4, 7)
d = r.randint(key, 2, 3, low=None, high=0)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, 0)
e = r.randint(key, 2, 3, low=None, high=None)  # int32 generation of shape (2, 3) with bounds [INT32_MIN, INT32_MAX]

# in-place into a preallocated tensor
out = torch.empty(2, 3, dtype=torch.int32, device="cuda")
r.randint_(key, out, low=3, high=10)

# bits() outputs are equivalent to passing low=None and high=None to randint
x = r.bits(key, 10)                      # 10x uint32 worth of bits;
y = r.bits(key, 10, dtype=torch.uint64)  # 10x uint64 worth of bits

# in-place into a preallocated tensor
out = torch.empty(10, dtype=torch.uint32, device="cuda")
r.bits_(key, out)
```

**NOTE 1:** The new `randint()` API differs significantly from `torch.randint()` API to be consistent with the `normal()` and `uniform()` APIs in `torch.func._random`. Positional integers are treated as shapes rather than bounds, and bounds are provided kw-only. Ex:
```python
# shape (2, 3) with bounds [0, 10)
torch.randint(10, (2, 3))
randint(key, (2, 3), high=10)  # OR randint(key, 2, 3, high=10)

# shape (2, 3) with bounds [1, 5)
torch.randint(1, 5, (2, 3))
randint(key, (2, 3), low=1, high=5)  # OR randint(key, 2, 3, low=1, high=5)
```

**NOTE 2:** Bounded integer generation utilizing the modulo operator is subject to modulo bias when the generation range does not evenly divide the range of the dtype. For large ranges that are not powers of 2, the bias can become substantial. For a 32-bit RNG sample:
```
R = high - low  # range
W = 32  # sampled bitwidth (32 bits for all dtypes except 64-bit dtypes)
bias(R) = 0           if 2**W % R == 0
          R / (2**W)  otherwise
```

This gives the following table:
```
================================
Range up to     Max relative bias
================================
``2 ** 8``      0.000006%
``2 ** 16``     0.0015%
``2 ** 20``     0.024%
``2 ** 24``     0.39%
``2 ** 26``     1.6%
``2 ** 27``     3.1%
``2 ** 28``     6.25%
================================
```

The preexisting `torch.randint()` op deals with this by sampling 64 bits per 32-bit output when the range >= 2**28. To keep a static amount of RNG sample per output value, we always sample 32 bits per 32-bit output and simply error if the range is a large enough non-power-of-2 such that the bias will meet or exceed 6.25%. The error indicates to the user that they should either:
* Sample with a 64-bit dtype instead OR
* Round up the range to the nearest power of 2 and manually perform rejection sampling or a similar strategy

Another way to deal with this is to do batched sampling (see e.g. [this paper](https://arxiv.org/pdf/2408.06213)). If we utilize e.g. 64 bits of randomness for two 32-bit outputs, we can move the bias threshold around so that a given range has comparatively less bias. Since Philox produces 4x32 outputs per 10x rounds, it's also natural to utilize 128 bits of randomness for four 32-bit outputs to further reduce the bias. However, this only moves the bias threshold around and does not completely remove regions of very high bias (up to 100%). Given this, some perf implications, and the fact that batched sampling changes output values, breaking consistency with 1:1 sampling for dtypes < 32 bits, we chose not to implement this.

Pull Request resolved: pytorch#190253
Approved by: https://github.com/ngimel
@github-actions
github-actions Bot deleted the gh/jbschlosser/286/head branch November 7, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants