Skip to content

Add tensor bounds support to stateless uniform API - #199790

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

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

Conversation

@jbschlosser

@jbschlosser jbschlosser commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

I've received beta tester feedback that it's useful to specify different bounds per generated item where bounds may be trained (i.e. allow gradients to flow). This PR addresses this by supporting an overload with tensor low, high bounds for the stateless RNG API uniform (future work will apply to normal / randint if this lands):

 _philox_uniform_.Tensor(Tensor(a!) self, Tensor key, Tensor low, Tensor high) -> Tensor(a!)

Example usage:

import torch
from torch.func import _random as random

key = random.key(42)

# Per-row bounds, broadcast against the output shape.
low = torch.tensor([[0.0], [10.0], [100.0]])
high = torch.tensor([[1.0], [20.0], [200.0]])
x = random.uniform(key, (3, 4), low=low, high=high)
# tensor([[  0.9177,   0.9581,   0.7473,   0.2606],
#         [ 18.5597,  17.2823,  15.5997,  13.0479],
#         [142.1908, 152.8775, 130.2454, 103.7679]])

# Tensor and scalar bounds can be mixed.
y = random.uniform(key, (3, 4), low=low, high=1000.0)

# Gradients flow to tensor bounds, as for a reparameterized sample.
low.requires_grad_()
random.uniform(key, (3, 4), low=low, high=high).sum().backward()

Some details:

  • On CPU, this is implemented by first generating in [0, 1) and doing a second TensorIterator-based pass to rescale appropriately. TensorIterator handles broadcasting with non-contiguous bounds tensors, etc.
  • On CUDA, it is kept as a single pass and this pass is enhanced to apply the correct scale per generated item using an OffsetCalculator for broadcasting with non-contiguous bounds tensors, etc.

The key thing this overload gives is better performance vs. a post-applied manual scaling on U(0, 1) samples.

Measured in us on my local GPU:
  ┌──────────┬─────────────┬───────────┬───────────┬─────────┬──────────────┬──────────────┬─────────┐
  │ Elements │   Bounds    │  Eager    │  Eager    │ Speedup │  Compiled    │  Compiled    │ Speedup │
  │          │             │  manual   │  kernel   │         │    manual    │    kernel    │         │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 1M       │ per-row (N, │ 40        │ 10        │ 4.1x    │ 22           │ 11           │ 2.0x    │
  │          │  1)         │           │           │         │              │              │         │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 1M       │ full        │ 63        │ 40        │ 1.6x    │ 48           │ 39           │ 1.2x    │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 16M      │ per-row (N, │ 861       │ 158       │ 5.5x    │ 515          │ 158          │ 3.3x    │
  │          │  1)         │           │           │         │              │              │         │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 16M      │ full        │ 1716      │ 535       │ 3.2x    │ 866          │ 533          │ 1.6x    │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 64M      │ per-row (N, │ 3430      │ 714       │ 4.8x    │ 2040         │ 644          │ 3.2x    │
  │          │  1)         │           │           │         │              │              │         │
  ├──────────┼─────────────┼───────────┼───────────┼─────────┼──────────────┼──────────────┼─────────┤
  │ 64M      │ full        │ 6801      │ 2084      │ 3.3x    │ 3296         │ 2084         │ 1.6x    │
  └──────────┴─────────────┴───────────┴───────────┴─────────┴──────────────┴──────────────┴─────────┘

Peak memory at 16M elements, CUDA eager:

  ┌─────────┬────────┬────────┐
  │ Bounds  │ Manual │ Kernel │
  ├─────────┼────────┼────────┤
  │ per-row │ 128 MB │ 64 MB  │
  ├─────────┼────────┼────────┤
  │ full    │ 192 MB │ 64 MB  │
  └─────────┴────────┴────────┘

There's also a minor benefit that we bitwise match the eager numerics of the CUDA scalar bounds overload, since this kernel uses a fused multiply-add.

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 Oct 5, 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 Oct 5, 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 a Tensor-bounds overload of _philox_uniform_ with CPU and CUDA
kernels, a meta registration, a reparameterized backward, a reinplace entry, and
tests that check it matches the scalar overload bit for bit on CPU and CUDA.
Nothing blocks a maintainer from reviewing it. The remaining issues are smaller:
bounds that alias the output, double-backward and forward-mode AD, and a few
gaps in test coverage.

Findings (4):

[minor] aten/src/ATen/native/PhiloxStatelessRNG.cpp:268
When low/high aliases self and already has self's dtype, low.to() returns self.
CPU then overwrites self with [0,1) samples before reading the bound, while CUDA
reads the original bound values, so the two backends disagree (e.g.
t._philox_uniform_(key, t, t + 1)). The CUDA path also has no overlap check, so
a bound that partially overlaps self (s[:1]) races with the writes. Add
at::assert_no_overlap(self, low/high) or clone the bounds when they overlap.

[minor] tools/autograd/derivatives.yaml:1404
The backward regenerates u with at::_philox_uniform(grad, key), and the scalar
_philox_uniform has no derivative entry. Under create_graph=True (double
backward, hessian) this raises 'derivative not implemented'; use grad.detach()
or empty_like(grad) as the template. There is also no result: formula, so
forward-mode AD (jvp/jacfwd) is unsupported.

[minor] test/test_stateless_rng.py:697
The eager grad test uses bounds with the same shape as the output, so the sum_to
reduction is only checked compiled-vs-eager, never against a closed form. There
is also no gradcheck. Add a check of broadcast (8,1) bounds against
(grad*(1-u)).sum(1, keepdim=True), or a float64 gradcheck.

[minor] test/test_stateless_rng.py:643
The batched-key cases use elems_per_key of 37 and 3, neither a multiple of epc,
so the vectorized branch of philox_multi_key_kernel (param_func(..., base + j))
never runs with tensor bounds. Add a batched case with an inner size divisible
by 4.

Reviewed commit: 3d36afa (NOT the current head a8123be)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ No Failures

As of commit a8123be with merge base d39020e (image):
💚 Looks good so far! There are no failures yet. 💚

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

  • Never trivial: numerics and kernels
    • Adds new CPU and CUDA sampling kernels _philox_uniform_tensor_cpu_ and _philox_uniform_tensor_cuda_ with per-element bounds via OffsetCalculator
    • Changes the param_func signature at every call site in philox_single_key_kernel and philox_multi_key_kernel in PhiloxDistribution.cu
  • New operator and autograd surface
    • Adds _philox_uniform_.Tensor to native_functions.yaml, plus new backward and forward-AD formulas in tools/autograd/derivatives.yaml
    • Adds philox_uniform_bounds_backward in FunctionsManual.cpp and a reinplace entry in torch/_inductor/fx_passes/reinplace.py
  • Socialization
    • torch.func._random.uniform and uniform_ now accept tensor low/high and send gradients through them, which is a new user-facing behavior
    • Adds compiled-autograd skip files for test_uniform_tensor_bounds_grad, so a reviewer should confirm that gap is acceptable

reason: not_trivial
Reviewed commit: 3fd10fb (NOT the current head a8123be)

Inference job

🐛 Report a wrong verdict

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

[ghstack-poisoned]
[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude is the CI failure related?

@claude

claude Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Claude finished @jbschlosser's task in 30s —— View job


No, the CI failure isn't related to this PR. The torchtitan job fails with the same error on the merge base, so trunk is already broken.

Details

The only failing workflow is torchtitan-test: run 37945766873, job test (torchtitan_features_integration, 1, 1, ...).

  • Error: ImportError: pyarrow requires NumPy 2.0 or newer, found 1.26.4. That is a dependency version mismatch in the test environment. It fails at import time, before any PhiloxStatelessRNG / _philox_uniform_.Tensor code runs.
  • Trunk failure: Dr. CI matched it to the same failure on merge base 70647d0 (trunk failure) and labeled it BROKEN TRUNK.
  • Everything else: no other workflow runs failed.

To get a green signal, rebase onto viable/strict once trunk is fixed. You can also merge as-is, since Dr. CI reports "You can merge normally".

@albanD albanD added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 13, 2026

@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 3d36afa: nothing blocking; ready for human review.

The PR adds a Tensor-bounds overload of philox_uniform with CPU and CUDA kernels, a meta registration, a reparameterized backward, a reinplace entry, and tests that check it matches the scalar overload bit for bit on CPU and CUDA. Nothing blocks a maintainer from reviewing it. The remaining issues are smaller: bounds that alias the output, double-backward and forward-mode AD, and a few gaps in test coverage.

⚪ 4 non-blocking findings

.add_owned_const_input(low.to(self.scalar_type()))

When low/high aliases self and already has self's dtype, low.to() returns self. CPU then overwrites self with [0,1) samples before reading the bound, while CUDA reads the original bound values, so the two backends disagree (e.g. t.philox_uniform(key, t, t + 1)). The CUDA path also has no overlap check, so a bound that partially overlaps self (s[:1]) races with the writes. Add at::assert_no_overlap(self, low/high) or clone the bounds when they overlap.


low: at::sum_to(grad * (1 - at::_philox_uniform(grad, key)), low.sym_sizes())

The backward regenerates u with at::_philox_uniform(grad, key), and the scalar _philox_uniform has no derivative entry. Under create_graph=True (double backward, hessian) this raises 'derivative not implemented'; use grad.detach() or empty_like(grad) as the template. There is also no result: formula, so forward-mode AD (jvp/jacfwd) is unsupported.


def test_uniform_tensor_bounds_grad(self, device):

The eager grad test uses bounds with the same shape as the output, so the sum_to reduction is only checked compiled-vs-eager, never against a closed form. There is also no gradcheck. Add a check of broadcast (8,1) bounds against (grad*(1-u)).sum(1, keepdim=True), or a float64 gradcheck.


key = random.split(key, 3).unsqueeze(-2)

The batched-key cases use elems_per_key of 37 and 3, neither a multiple of epc, so the vectorized branch of philox_multi_key_kernel (param_func(..., base + j)) never runs with tensor bounds. Add a batched case with an inner size divisible by 4.

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

@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 Oct 13, 2026
[ghstack-poisoned]
@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude re-review this and make sure the findings from the automated review have been addressed

@claude

claude Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

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


Three of the four earlier findings are fixed in 1a99e6a. The one left is forward-mode AD: the .Tensor derivative still has no result: formula.

Status of earlier findings, plus one new item

Status of earlier findings

# Earlier finding Status
1 A bound that aliases or overlaps self gives different results on CPU and CUDA, and races on CUDA Fixed. philox_check_bound now calls at::assert_no_overlap(self, bound) (PhiloxStatelessRNG.h:33). It runs on both CPU and CUDA before low.to(...), so a bound that aliases or overlaps self is rejected. test_uniform_tensor_bounds_errors checks the low=out case.
2a Double backward failed because _philox_uniform has no derivative Fixed. The backward now draws u from at::empty_like(grad)._philox_uniform_(key), which doesn't require grad, so the second-order gradient flows only through grad. gradgradcheck covers it.
2b Forward-mode AD (jvp/jacfwd) is not supported Not addressed. There is still no result: entry for _philox_uniform.Tensor in tools/autograd/derivatives.yaml:1401. torch.func.jvp on uniform(..., low=t) will raise "derivative not implemented". Either add a formula that regenerates u (e.g. result: low_t * (1 - u) + high_t * u, with u from at::empty_like(result)._philox_uniform_(key)), or say in the docstring that only reverse mode is supported.
3 Grad test didn't check sum_to with broadcast bounds against a closed form, and had no gradcheck Fixed. test_uniform_tensor_bounds_grad uses (8, 1) bounds and checks them against (grad * (1 - u)).sum(1, keepdim=True). It also runs float64 gradcheck/gradgradcheck with bounds broadcast on different dims ((8,1), (1,5)).
4 The vectorized branch of the multi-key kernel was never run with tensor bounds Fixed. test_uniform_tensor_bounds_rows_vary now also uses cols=36, so batched keys get elems_per_key=36, which divides evenly by epc of both 4 and 2.

New finding

Performance: at tools/autograd/derivatives.yaml:1404-1405, the low and high formulas each regenerate the full uniform sample. When both bounds require grad, every backward runs the Philox kernel twice and allocates two full-size buffers. Inductor can't merge them, because they are separate in-place fallback calls. Move both into one formula (low, high: ...) that calls a helper in FunctionsManual.cpp, which draws u once and returns both sum_to results.

Recommendation

Approve once 2b is addressed or documented. Everything else from the earlier review is fixed and tested. I checked the changes by reading the code only; I didn't run anything locally.

@jbschlosser

Copy link
Copy Markdown
Contributor Author

@claude are the CI failures related?

@claude

claude Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

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


Yes, the 3 dynamo_wrapped failures come from this PR. They all fail in the new gradgradcheck call that 1a99e6a added to test_uniform_tensor_bounds_grad. The 4th failure (torchtitan pyarrow requires NumPy 2.0) is broken trunk and not related.

Details

Failing jobs

All 3 fail on the same test, TestStatelessRNGDistributionCPU::test_uniform_tensor_bounds_grad_cpu, on py3.11, py3.14 and py3.14t. It fails the same way on every rerun.

test/test_stateless_rng.py:715  self.assertTrue(gradgradcheck(f, bounds))
gradcheck.py:2178  _test_undefined_backward_mode(func, outputs, tupled_inputs)
gradcheck.py:1338  check_undefined_grad_support -> torch.autograd.grad(...)
torch/_dynamo/compiled_autograd.py:1266  runtime_wrapper -> compiled_fn(...)
TypeError: add(): argument 'input' (position 1) must be Tensor, not NoneType

Likely cause

I read the log but did not reproduce this locally.

  • The error is raised in gradgradcheck's undefined-grad check (_test_undefined_backward_mode), and it only happens when the backward runs through compiled autograd (the dynamo_wrapped config). The non-dynamo test jobs pass, and so does the gradcheck call on line 714.
  • In the double backward, grad feeds both the low formula and the high formula (tools/autograd/derivatives.yaml:1404-1405). So gradients for grad arrive from two paths and have to be added together.
  • The undefined-grad check passes one of those gradients in as undefined. The eager engine skips an undefined gradient when it adds them. The compiled-autograd graph seems to turn it into None and then call add(None, x).
  • This looks like a compiled-autograd gap rather than a wrong derivative formula, since the eager gradgradcheck passes.

Possible fixes (pick one)

  1. Turn off only the undefined-grad check: gradgradcheck(f, bounds, check_undefined_grad=False).
  2. Skip only the gradgradcheck under dynamo, with if not TEST_WITH_TORCHDYNAMO: or @skipIfTorchDynamo("compiled autograd: undefined grad accumulation") on a separate test.
  3. Merge the two formulas into one low, high: formula backed by a FunctionsManual.cpp helper. This was also suggested earlier for performance. It might avoid the two-path accumulation in the double backward, but I haven't checked that.

Option 1 is the smallest change and keeps the second-order check in every config.

Not related

  • torchtitan_features_integration: ImportError: pyarrow requires NumPy 2.0 or newer, found 1.26.4. The same failure is on merge base 70647d0 (broken trunk).

[ghstack-poisoned]
[ghstack-poisoned]
@jbschlosser jbschlosser added release notes: python_frontend python frontend release notes category topic: improvements topic category labels Oct 21, 2026
[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 27, 2026
@ngimel

ngimel commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator

I think this is a fine thing to support

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

Merge failed

Reason: 1 jobs have failed, first few of them are: Check mergeability of ghstack PR / ghstack-mergeability-check

Details for Dev Infra team

Raised by workflow job

@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 pushed a commit that referenced this pull request Dec 2, 2026
Follow-up from #199790, applying the analogous extension to support tensor bounds for `normal()`.

This PR also addresses a few leftover issues for `uniform()` that came up during review:
* aliased parameters are now cloned instead of giving silently wrong results
* adds a CPU check that self is floating point
* uniform's forward-AD formula moved into a FunctionsManual helper
* uniform's tests merged with normal's

Pull Request resolved: #204472
Approved by: https://github.com/ngimel
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 GL/superseded GreenLight review is superseded by changes Merged module: inductor 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