Repository navigation
Introduce stateless RNG APIs for randint / raw bits - #190253
jbschlosser wants to merge 8 commits into
Conversation
🔗 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 JobsAs of commit 8bbb788 with merge base 0768654 ( 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. |
Attention! native_functions.yaml was changedIf 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. |
|
@claude investigate the CI failures; for those that are related, how should they be addressed? |
|
@claude are any of the CI failures related? |
|
Claude finished @jbschlosser's task in 1m 47s —— View job Yes — one of them is real
Detailed investigationTriage
I agree with Dr. CI's AI verdicts on the two inductor jobs: The real failureFrom the This fires at module import in Root cause is a one-line omission. The two sibling ops from earlier in this stack — both also Tensor._philox_normal_,
Tensor._philox_uniform_,
FixAdd one line to the 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
Why the earlier investigation looked differentThe previous Not verified locallyThere is no built I did not push any changes — this is a ghstack PR and my write operations are disabled for it, so the one-line |
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 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 teamRaised by workflow job |
|
@claude are the CI failures related? |
|
Claude finished @jbschlosser's task in 4m 35s —— View job No — the one remaining failure is unrelated
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 investigationCI status at head (
|
| 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 |
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 onlynative_functions.yaml(+7),HasDecompTest...expect(+3) — the new op's entriestorch/func/_random.py(+322),test/test_stateless_rng.py(+412/-6) — new Python API and its teststorch/overrides.py(+1) —Tensor._philox_randint_ignore entrytorch/_meta_registrations.py— addsmeta_philox_randint_and factors the shared arg checks into_check_philox_gen_args; the pre-existing_check_philox_distribution_argsbehavior is unchangedtorch/_inductor/fx_passes/reinplace.py(+3/-1) — one newinplaceable_opsentry keyed onaten._philox_randint.defaulttorchgen/model.py(+4/-2) — narrows the"rand" in nameauto-tagging heuristic so_philox_*ops don't getnondeterministic_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.
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
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 5 checks: inductor / unit-test / inductor-cpu-test / test (inductor_amx, 2, 2, mt-l-x86iamx-8-64), inductor / unit-test / inductor-cpu-test / test (inductor_amx, 1, 2, mt-l-x86iamx-8-64), inductor / unit-test / inductor-test-cuda132 / test (inductor, 1, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test-cuda132 / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g), inductor / unit-test / inductor-test / test (inductor, 2, 2, mt-l-x86aavx2-29-113-a10g) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…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
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
…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
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
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.uint8torch.int16/torch.uint16torch.int32/torch.uint32torch.int64/torch.uint64All 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.
NOTE 1: The new
randint()API differs significantly fromtorch.randint()API to be consistent with thenormal()anduniform()APIs intorch.func._random. Positional integers are treated as shapes rather than bounds, and bounds are provided kw-only. Ex: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:
This gives the following table:
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: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