Skip to content

Implement stateless RNG dropout - #204280

Open
jbschlosser wants to merge 17 commits into
gh/jbschlosser/300/basefrom
gh/jbschlosser/300/head
Open

jbschlosser wants to merge 17 commits into
gh/jbschlosser/300/basefrom
gh/jbschlosser/300/head

Conversation

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 10, 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.

@pytorch-bot

pytorch-bot Bot commented Nov 10, 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:

The PR adds `aten::_philox_dropout`, a stateless dropout whose mask comes from a
PRNG key, with CPU/CUDA kernels, an `auto_linear` derivative, a meta kernel, and
the `torch.func._random.dropout` wrapper. Both blocking findings from the last
review are fixed at HEAD. Recommendation: Approve; every remaining point is
non-blocking.

Findings (6):

[minor] torch/func/_random.py:692
Non-blocking, carried over: `if p < 0.0 or p > 1.0` is false for NaN. With
`training=False`, a NaN `p` silently returns `input`. With `training=True`, NaN
reaches the kernel or meta check and raises `RuntimeError`, while -0.1 and 1.1
raise `ValueError` from the wrapper, so the same public function raises two
different exception types for invalid `p`. `test_errors`
(`test/test_stateless_rng.py:1652-1653`) pins this behavior. Fix: `if not 0.0 <=
p <= 1.0: raise ValueError(...)`, and update that assertion to expect
`ValueError`.

[minor] torch/func/_random.py:671
Non-blocking, carried over: the docstring says the leading dims of `input` must
be "broadcastable with `*batch`". The kernels actually require two different
things: `key.dim() == input.dim() + 1`, and the key batch must expand one way to
the input shape (`is_expandable_to`), which is not two-way broadcasting. The
sentence was copied from the sibling docstrings, so a module-wide follow-up is
fine.

[minor] test/test_stateless_rng.py:1635
Non-blocking: `test_opcheck` checks less than it seems to. `test_faketensor`
compares nothing for an `aten`-namespace op: `fake_check` runs
`CrossRefFakeMode(ignore_op_fn=is_builtin)`. `test_autograd_registration`
returns early (with `requires_grad=False` at `generate_tests.py:78-82`, and with
`requires_grad=True` at `autograd_registration.py:99-102`, because
`derivatives.yaml` registers an Autograd kernel). Only `test_schema` and
`test_aot_dispatch_dynamic` do meaningful work, and the latter runs the same
kernel on both sides, so it cannot catch wrong values from the strided path.
Meta strides are still checked by the `FakeTensorMode` assertion in
`test_noncontig_input`. Either say so in a comment, or check the meta kernel
directly under `CrossRefFakeMode()` without `ignore_op_fn`.

[minor] test/test_stateless_rng.py:1661
Non-blocking, carried over: the "same device" regex matches the generic
"Expected all tensors to be on the same device" error from the dispatcher, or
`FakeTensorDeviceMismatchError` under fake mode. The op's own check
(`PhiloxDistribution.cu:173-175`) and the meta check never run. Tighten the
regex or add a comment.

[minor] test/test_stateless_rng.py:1603
Non-blocking, carried over: two parts of `test_noncontig_input` add little.
`offset.copy_(x)` is contiguous, so it takes the plain contiguous branch and
cannot reach the helper's realignment branch. `out.stride() ==
torch.empty_like(inp).stride()` (:1610) just restates the implementation.

[minor] aten/src/ATen/native/PhiloxStatelessRNG.cpp:294
Non-blocking, carried over: the CPU path (:289-325) still allocates a full-size
fp32/fp64 `samples` buffer (twice the input's size for half/bf16) and then makes
a second `cpu_kernel` pass to apply the mask. The shared fill loop (:150-161) is
serial. Passing the element index to the CPU helper's `param_func`, as the CUDA
helper does, would allow a single pass.

Reviewed commit: fc1bd4e (NOT the current head 73087f8)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 7 Unclassified Failures

As of commit 73087f8 with merge base bcff2f4 (image):

🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:

  • Triviality
    • Adds a new ATen op _philox_dropout in native_functions.yaml with new CPU and CUDA kernels, outside every trivial class
    • Numerics: kernels compute in dist_acctype and scale by 1 / (1 - p), a never-trivial area a human should check
  • Scope
    • Touches kernels, derivatives.yaml autograd formula, meta registration, torch/func/_random.py API, and torchgen/model.py tagging
    • torchgen/model.py now exempts every _philox_ op from the nondeterministic_seeded dropout branch, not only the rand branch
  • Socialization
    • New user-callable dropout in torch/func/_random.py; pytorch-bot flagged the FC window for new native_functions.yaml ops

reason: not_trivial
Reviewed commit: 5f48573 (NOT the current head 73087f8)

Inference job

🐛 Report a wrong verdict

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

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

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 10, 2026
jbschlosser added a commit that referenced this pull request Nov 10, 2026
ghstack-source-id: de484ab
Pull-Request: #204280
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 10, 2026
github-actions[bot]

This comment was marked as outdated.

@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 Nov 10, 2026

@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.

I haven't validated the fine grain part of the sampling kernel, but sounds good.

Comment thread torch/func/_random.py Outdated


def dropout(
key: torch.Tensor, input: torch.Tensor, p: float = 0.5, training: bool = True

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.

Let's do the same positional and kwarg only as the other APIs here?

"_philox_dropout: self must be a floating point tensor, got ",
self.scalar_type());
TORCH_CHECK(p >= 0 && p <= 1, "_philox_dropout: p must be in [0, 1], got ", p);
auto result = at::empty_like(self);

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.

This comment from the review is real:
On CUDA, a non-contiguous input (channels_last, transposed) causes up to three extra full copies, though the result is still correct. (1) at::empty_like(self) keeps the input's strides, so the helper's self.contiguous() (:194) copies the uninitialized result. (2) The kernel's output is then copy_'d back (:255). (3) Separately, input = self.contiguous() copies the input. Allocating the kernel's output contiguously and copying only when needed removes the copy of uninitialized memory. An offset calculator over self's strides, like make_bounds_offset_calculator in the sibling philox_uniform_tensor_cuda, would remove the input copy.

@pytorch-bot pytorch-bot Bot 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 Nov 11, 2026
@jbschlosser jbschlosser added release notes: python_frontend python frontend release notes category topic: improvements topic category labels Nov 11, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 11, 2026
github-actions[bot]

This comment was marked as outdated.

[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 fc1bd4e: nothing blocking; ready for human review.

The PR adds aten::_philox_dropout, a stateless dropout whose mask comes from a PRNG key, with CPU/CUDA kernels, an auto_linear derivative, a meta kernel, and the torch.func._random.dropout wrapper. Both blocking findings from the last review are fixed at HEAD. Recommendation: Approve; every remaining point is non-blocking.

⚪ 6 non-blocking findings

if p < 0.0 or p > 1.0:

Non-blocking, carried over: if p &lt; 0.0 or p &gt; 1.0 is false for NaN. With training=False, a NaN p silently returns input. With training=True, NaN reaches the kernel or meta check and raises RuntimeError, while -0.1 and 1.1 raise ValueError from the wrapper, so the same public function raises two different exception types for invalid p. test_errors (test/test_stateless_rng.py:1652-1653) pins this behavior. Fix: if not 0.0 &lt;= p &lt;= 1.0: raise ValueError(...), and update that assertion to expect ValueError.


dimensions of ``input`` must be broadcastable with ``*batch`` and each key

Non-blocking, carried over: the docstring says the leading dims of input must be "broadcastable with *batch". The kernels actually require two different things: key.dim() == input.dim() + 1, and the key batch must expand one way to the input shape (is_expandable_to), which is not two-way broadcasting. The sentence was copied from the sibling docstrings, so a module-wide follow-up is fine.


def test_opcheck(self, device, requires_grad):

Non-blocking: test_opcheck checks less than it seems to. test_faketensor compares nothing for an aten-namespace op: fake_check runs CrossRefFakeMode(ignore_op_fn=is_builtin). test_autograd_registration returns early (with requires_grad=False at generate_tests.py:78-82, and with requires_grad=True at autograd_registration.py:99-102, because derivatives.yaml registers an Autograd kernel). Only test_schema and test_aot_dispatch_dynamic do meaningful work, and the latter runs the same kernel on both sides, so it cannot catch wrong values from the strided path. Meta strides are still checked by the FakeTensorMode assertion in test_noncontig_input. Either say so in a comment, or check the meta kernel directly under CrossRefFakeMode() without ignore_op_fn.


with self.assertRaisesRegex(RuntimeError, "same device"):

Non-blocking, carried over: the "same device" regex matches the generic "Expected all tensors to be on the same device" error from the dispatcher, or FakeTensorDeviceMismatchError under fake mode. The op's own check (PhiloxDistribution.cu:173-175) and the meta check never run. Tighten the regex or add a comment.


offset.copy_(x),

Non-blocking, carried over: two parts of test_noncontig_input add little. offset.copy_(x) is contiguous, so it takes the plain contiguous branch and cannot reach the helper's realignment branch. out.stride() == torch.empty_like(inp).stride() (:1610) just restates the implementation.


auto samples = at::empty(self.sizes(), self.options().dtype(

Non-blocking, carried over: the CPU path (:289-325) still allocates a full-size fp32/fp64 samples buffer (twice the input's size for half/bf16) and then makes a second cpu_kernel pass to apply the mask. The shared fill loop (:150-161) is serial. Passing the element index to the CPU helper's param_func, as the CUDA helper does, would allow a single pass.

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

@github-actions
github-actions Bot dismissed stale reviews from themself November 13, 2026 17:27

Withdrawn: the automated review of fc1bd4e found nothing blocking.

@pytorch-bot
pytorch-bot Bot requested a review from albanD November 13, 2026 18:32
@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 Nov 13, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

@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.

THanks thanks!

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GL/superseded GreenLight review is superseded by changes 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.

3 participants