Skip to content

Improve stateless RNG handling of strided keys and outputs - #206328

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

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

Conversation

@jbschlosser

@jbschlosser jbschlosser commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

In preparation for a move to make the stateless RNG APIs public, this PR addresses a few minor issues:

  • CUDA: read a batched key with a non-unit last-dim stride correctly (previously gave wrong values), and
    copy an 8-byte-aligned single key to aligned memory before the 16-byte vector load (previously
    crashed). Batched keys with a unit last-dim stride are read in place instead of copied.
  • Reject an output whose elements share memory, or that overlaps a dense key, before doing any work.
    Previously internal overlap errored only in eager, after the compute, from copy_, and key aliasing
    wasn't caught at all. Meta checks internal overlap too. assert_no_overlap can't see overlap with a
    non-dense key, so CUDA copies a key that shares storage with the output instead of reading it while it's
    overwritten.
  • Write non-contiguous or misaligned outputs to a fresh buffer instead of a copy of the old values.
  • Make eager and meta validation agree: CPU and CUDA share one key/output check, so errors come in the
    same order on every path; meta checks tensor bounds before the key, like eager; CPU uniform_/normal_
    reject integer outputs with a clear error; and meta randint_ rejects an empty range.

Test Plan:

python test/test_stateless_rng.py -k test_noncontig_key -k test_overlapping_output -k
test_tensor_bounds_errors -k test_error_wrong_self_dtype -k test_error_op_empty_range
python test/test_stateless_rng.py

Authored with the assistance of an AI coding assistant (Claude).

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR fixes how the stateless Philox RNG ops handle strided or misaligned keys
and outputs: it rejects outputs that overlap themselves or a dense key, and
makes the CPU, CUDA and meta paths validate in the same order. Recommendation:
Approve. The earlier finding is fixed and only non-blocking points remain.

Findings (2):

[minor] test/test_stateless_rng.py:843
Non-blocking: the new `perm` case in `test_noncontig_key` can't fail.
`perm.unsqueeze(-2)` has shape (4,3,1,2) and strides (2,8,2,1), so it is
non-overlapping and dense. `clone()` defaults to `preserve_format`, which keeps
those strides, so `expected = gen(k.clone(), ...)` sends the same permuted
strides down the same CUDA in-place path (`PhiloxDistribution.cu:182, 220-227`)
as the call under test. A bug in how `OffsetCalculator` handles permuted strides
would give the same wrong values on both sides and the assertion would still
pass. Fix: build `expected` from `k.contiguous()` for this loop. The other cases
(`keys[::2]`, `expand`, offset slice) are fine because their clones come out
contiguous.

[minor] aten/src/ATen/native/cuda/PhiloxDistribution.cu:182
Non-blocking (code the last review already covered): an expanded key can now be
copied in full when the old code read it in place. `canUse32BitIndexMath(key)`
returns false whenever `key.numel() >= INT32_MAX`, before it looks at offsets,
so a stride-0 expanded key with a tiny largest offset still gets copied by
`key.contiguous()`. Example: a (2^30,) float32 output with
`random.key(0).expand(2**30, 2)` allocates a 16 GiB key copy; the merge-base
code read such a key in place through its strides. The in-place read only needs
the largest element offset (sum of `(size-1)*stride`) to fit in the `uint32`
index math of `OffsetCalculator<1>`, so checking that offset instead of `numel`
would avoid the copy. Normal size-1 broadcast keys are unaffected.

Reviewed commit: 6ac8a26 (NOT the current head ce5d5b0)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ You can merge normally! (1 Unrelated Failure), 1 Unclassified Failure

As of commit ce5d5b0 with merge base bcff2f4 (image):

🟢 GREEN LIGHT - OUTDATED (earlier commit) - PR approved to be merged without human review:

  • Triviality
    • Single-cause bugfixes in PhiloxDistribution.cu: multi-key kernel now indexes key_contig with its own strides, and a misaligned key is cloned before ld_vec<16>
    • Established pattern: meta overlap check copies the free_unbacked_symbols + _debug_has_internal_overlap guard already at _meta_registrations.py:6334
    • Behavior-neutral: non-contiguous or misaligned outputs get at::empty instead of a copy, since the kernels overwrite every element before self.copy_(output)
  • Correctness
    • Multi-key kernel reads keys[elem_offset] and keys[elem_offset + 1], which are adjacent only in the contiguous key_contig now passed in
    • at::assert_no_internal_overlap(self) runs after the existing shape checks in both CPU and CUDA kernels, and the meta message matches its text
  • Tests
    • test_noncontig_key covers strided and 8-byte-aligned keys; test_internal_overlap_output covers eager and FakeTensorMode rejection
  • User-facing surface
    • All touched ops are private (aten._philox_*, torch.func._random), so the earlier overlap error is not a breaking change

reason: clean
Reviewed commit: 90d975b (NOT the current head ce5d5b0)

Inference job

🐛 Report a wrong verdict

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • trunk / macos-py3-arm64 / test (default, 1, 3, macos-m1-stable) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/inductor/test_mps_basic.py::MPSBasicTestsAOTI::test_compiled_model_does_not_depend_on_unused_openmp

    AI verdict: AI verdict: probably not related

    The test failed because of a bug in the test itself. It checks for OpenMP by looking for the substring "omp" in each dependency's file name. The hash-named wrapper.so lists itself as a dependency, and this time its name was c3id72jxtomph2rrgn7..., which contains "omp" ("jxtOMPh"). The suspect only changes stateless Philox RNG code (CUDA kernel, CPU op, meta registrations, autograd, tests), none of which touches MPS AOTI linking.

    Full reasoning on HUD →

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

pytorchgreenlight[bot]
pytorchgreenlight Bot previously approved these changes Nov 23, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/approved Approved by GreenLight label Nov 23, 2026
@jbschlosser
jbschlosser requested review from albanD and ngimel and removed request for Aidyn-A, eee4017, eqy and syed-ahmed November 23, 2026 19:32
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
@pytorchgreenlight
pytorchgreenlight Bot dismissed their stale review November 23, 2026 21:38

Superseded by a newer greenlight verdict.

@pytorchgreenlight pytorchgreenlight Bot added GL/human GreenLight marked as needing human review and removed GL/approved Approved by GreenLight labels Nov 23, 2026
github-actions[bot]

This comment was marked as outdated.

@albanD albanD left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

okok

[ghstack-poisoned]
@jbschlosser

jbschlosser commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor Author

AI-generated summary of changes (reviewed by me)

  1. Meta/eager check order: Fixed. The internal-overlap check in meta now runs after the key checks. The .Tensor overloads now validate bounds before the key in eager (CPU and CUDA, via a shared philox_check_gen_args) and in meta.
  2. Output/key overlap: Eager now calls at::assert_no_overlap(self, key) on CPU and CUDA. Meta intentionally doesn't mirror it. Python metas don't mirror pairwise assert_no_overlap checks for other ops either (e.g. gather, index_put_), and there's no Python helper for get_overlap_status. Under fake this only means deliberate aliasing gets traced, and eager still rejects it at runtime.
  3. CPU half/bf16 normal.Tensor checks late: Fixed. Key and output validation now runs before the scratch buffer is allocated.
  4. data_ptr() on a read-only key: Fixed. Both sites use const_data_ptr().
  5. Eager half of test_internal_overlap_output: Left as is. Eager can't observably tell the early check from the old late failure: both raise the same error and leave self untouched. That half covers eager/fake parity. The new key-overlap case in test_overlapping_output does fail without this PR.
  6. Multi-key path copies keys: Fixed. Keys with stride(-1) == 1 are read in place (falling back to a copy if offsets wouldn't fit in 32-bit index math), and the 16-byte alignment clone only runs on the single-key path. test_noncontig_key now covers sliced, expanded, and misaligned batched keys.
  7. CUDA race with a non-dense key aliasing the output: Fixed. As philox_prepare_bound does, the key is cloned when it shares storage with the output. test_overlapping_output now covers a sliced key that lies inside other keys' outputs. It's sized (4096 keys x 64) so the cross-block race reliably showed up before the fix: ~20-30% of elements mismatched on all three ops. CPU was already safe, because contiguous() copies any non-dense key.

Also fixed: CPU uniform_/normal_ now raise "self must be a floating point tensor" for integer outputs, matching CUDA and meta, and meta randint_ now rejects an empty [low, high) range like eager.

@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/approved Approved by GreenLight labels Dec 1, 2026
@jbschlosser jbschlosser added in progress PR is being worked on by the author, until the automated review accepts it and removed ready for review Automated review passed, ready for a final review by a maintainer. labels Dec 1, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
[ghstack-poisoned]

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated review of 6ac8a26: nothing blocking; ready for human review.

This PR fixes how the stateless Philox RNG ops handle strided or misaligned keys and outputs: it rejects outputs that overlap themselves or a dense key, and makes the CPU, CUDA and meta paths validate in the same order. Recommendation: Approve. The earlier finding is fixed and only non-blocking points remain.

⚪ 2 non-blocking findings are attached to the code below, collapsed.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

Comment thread test/test_stateless_rng.py Outdated
for batched in batches:
k = batched.unsqueeze(-2)
shape = (*k.shape[:-2], 33)
expected = gen(k.clone(), shape, **kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ Non-blocking: the new perm case in test_noncontig_key can't fail. perm.unsqueeze(-2) has shape (4,3,1,2) and strides (2,8,2,1), so it is…

Non-blocking: the new perm case in test_noncontig_key can't fail. perm.unsqueeze(-2) has shape (4,3,1,2) and strides (2,8,2,1), so it is non-overlapping and dense. clone() defaults to preserve_format, which keeps those strides, so expected = gen(k.clone(), ...) sends the same permuted strides down the same CUDA in-place path (PhiloxDistribution.cu:182, 220-227) as the call under test. A bug in how OffsetCalculator handles permuted strides would give the same wrong values on both sides and the assertion would still pass. Fix: build expected from k.contiguous() for this loop. The other cases (keys\[::2\], expand, offset slice) are fine because their clones come out contiguous.

Report this finding

// single-key kernel loads it with ld_vec<16>, which needs 16-byte alignment.
// A key read in place must not share memory with output, and
// assert_no_overlap can't detect overlap with a non-dense key.
auto key_in = key.stride(-1) == 1 && canUse32BitIndexMath(key) ? key : key.contiguous();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ Non-blocking (code the last review already covered): an expanded key can now be copied in full when the old code read it in place.…

Non-blocking (code the last review already covered): an expanded key can now be copied in full when the old code read it in place. canUse32BitIndexMath(key) returns false whenever key.numel() &gt;= INT32_MAX, before it looks at offsets, so a stride-0 expanded key with a tiny largest offset still gets copied by key.contiguous(). Example: a (2^30,) float32 output with random.key(0).expand(2**30, 2) allocates a 16 GiB key copy; the merge-base code read such a key in place through its strides. The in-place read only needs the largest element offset (sum of (size-1)*stride) to fit in the uint32 index math of OffsetCalculator&lt;1&gt;, so checking that offset instead of numel would avoid the copy. Normal size-1 broadcast keys are unaffected.

Report this finding

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Dec 2, 2026
@jbschlosser jbschlosser added release notes: python_frontend python frontend release notes category topic: improvements topic category labels Dec 2, 2026
[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Dec 2, 2026
@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

Starting merge as part of PR stack under #206339

@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). Blocking jobs that the merge waited on for a Dr.CI or AI CI Advisor classification: 1.

Details for Dev Infra team

Raised by workflow job

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #206339

2 similar comments
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #206339

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #206339

pytorchmergebot pushed a commit that referenced this pull request Dec 2, 2026
Expands `fold_in()` to support int64 scalar tensor data. This is useful because uint64 has limited support within PyTorch, and requiring it as the dtype for data makes doing math on such data annoying:
```python
import torch
import torch.func._random as random

key = random.key(42, device="cuda")
step = torch.tensor(0, device="cuda")  # int64, e.g. a training-step counter

# New: int64 data is accepted directly.
k = random.fold_in(key, step)

# Old (uint64 only): reinterpret the bits first. view() is zero-copy and
# matches the int overload for negatives; .to(torch.uint64) would add a copy.
k_old = random.fold_in(key, step.view(torch.uint64))
```
Pull Request resolved: #206339
Approved by: https://github.com/albanD
ghstack dependencies: #204472, #206328
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-triage-error ciflow/trunk Trigger trunk jobs on your pull request GL/superseded GreenLight review is superseded by changes Merged ready for review Automated review passed, ready for a final review by a maintainer. release notes: python_frontend python frontend release notes category topic: improvements topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants