Repository navigation
Introduce stateless shard-invariant init kernels - #205732
jbschlosser wants to merge 13 commits into
Conversation
[ghstack-poisoned]
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. |
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (12): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/205732
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 7f7fe2c with merge base bcff2f4 ( 🟡 GREEN LIGHT - OUTDATED (earlier commit) - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Withdrawn: the automated review of 32564d0 found nothing blocking.
Withdrawn: the automated review of 32564d0 found nothing blocking.
[ghstack-poisoned]
[ghstack-poisoned]
There was a problem hiding this comment.
Automated review of e3fc844: nothing blocking; ready for human review.
The PR adds _philox_normal_shard_/_philox_uniform_shard_ ATen ops (CPU, CUDA, meta, Inductor reinplace) and torch.func._random.shard_normal_/shard_uniform_ wrappers that fill a shard with exactly the values the unsharded stateless call would produce. Recommendation: Approve no blocking issues; all eight carried-over and four new points are non-blocking.
⚪ 12 non-blocking findings
Line 362 in e3fc844
Non-blocking: tensor-valued mean/std/low/high are accepted and their gradients are dropped. These are typed float (also :411-412) and passed straight to the op, whose schema has only float params. toIValue uses py::cast<double>, which falls back to Tensor.__float__, so shard_normal_(key, w, gs, go, std=torch.tensor(0.02, requires_grad=True)) runs, warns once, and silently loses the gradient (and forces a device sync on CUDA). Under FakeTensor it fails with "cannot extract float from tensor with meta storage". The siblings normal_/uniform_ accept float | Tensor and route tensors to the differentiable .Tensor overload. Fix: reject tensors explicitly in the wrapper, or document that only Python floats are accepted.
Line 378 in e3fc844
Non-blocking (docs nit): the key docstring (also :427-428) says "An unbatched PRNG key returned by :func:key, :func:split, or :func:fold_in", but split always returns a batched key; the PR's own test_shard_errors passes random.split(key, 3) as a bad key. Suggested wording: "a single key of shape (2,), e.g. from key, fold_in, or one element of split's output". Also, docs/source/func._random.md:20-21 tells users to pass batched keys instead of using vmap and does not mention that the new shard functions reject them.
Line 356 in e3fc844
Non-blocking (nit): shard name order is inconsistent. The ATen ops put it last (_philox_normal_shard_), the Python wrappers put it first (shard_normal_), while every other wrapper maps directly (normal_ _philox_normal_). Cheap to align now, before randint/bits shard variants copy one of the patterns.
Non-blocking: a zero-size global dim turns off the overflow guard. Once any global_shape\[d\] == 0, global_numel stays 0 and mul_overflows never fires. E.g. out (0, 1, 1), global_shape=(0, 2**62, 2**62), offset (0, 2**62-1, 0) passes every check, then signed int64 overflows in the layout loop (lines 110-111); both launchers build the layout before their numel() == 0 early return. The guard is also dim-order dependent: (2**62, 2**62, 0) is rejected as "too many elements" despite having zero elements. Fix: return a default PhiloxShardLayout right after validation when global_numel == 0.
pytorch/torch/_meta_registrations.py
Line 789 in e3fc844
Non-blocking: the meta function has no counterpart to the eager "too many elements" check, e.g. out (4, 5) with global_shape=(2**62, 5) passes under FakeTensor/torch.compile and fails only when the kernel runs. Related: _check_philox_distribution_args only checks is_floating_point, so float8 outputs pass meta and then fail eager dispatch (AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16)); sibling metas share the gap. Lower priority: meta and eager run checks in different order, so some invalid inputs get different error messages.
Non-blocking, low severity: no self/key overlap check. philox_shard_layout only calls assert_no_internal_overlap(self). When self is contiguous and aligned, the CUDA kernel writes it directly while every thread re-reads the key via ld_vec<16>, so a uint64 view of self's storage used as the key gives nondeterministic output (CPU reads seed/offset once, so unaffected). Non-shard kernels share this gap, while tensor bounds are guarded in philox_prepare_bound. Adding at::assert_no_overlap(self, key) here would close it for both backends.
Non-blocking: the CUDA-only MAX_DIMS limit counts size-1 leading dims. Every dim before j goes into grid_sizes, including dims where self.size(d) == 1, so output \[1\]*26 + \[3\] over \[1\]*26 + \[5\] works on CPU and under compile but raises on CUDA; on ROCm 17 such leading dims suffice. Fix: fold size-1 dims into base instead of adding them to the grid.
pytorch/test/test_stateless_rng.py
Line 1058 in e3fc844
Non-blocking: test_shard_fullgraph can't tell a working dynamic=True from a recompile; nothing counts compiles. Use CompileCounterWithBackend("aot_eager") and assert frame_count == 1 when dynamic is true. The test also never checks the passed-in out buffer; it should assert actual is out or compare out directly.
pytorch/test/test_stateless_rng.py
Line 648 in e3fc844
Non-blocking: test_shard_errors skips several error paths: non-floating-point output, key dtype, device mismatch, and "too many elements". So the Test Plan's claim of "every error in both eager and FakeTensorMode" is not accurate yet. Adding "too many elements" to the FakeTensorMode loop would currently fail because of the meta gap.
pytorch/test/test_stateless_rng.py
Line 632 in e3fc844
Non-blocking: no shard test uses a contiguous output with a misaligned pointer, so the CUDA aligned fallback (PhiloxDistribution.cu, the aligned / at::empty path) is never reached. Reusing the existing torch.empty(1001)\[1:\] layout would cover it.
pytorch/test/test_stateless_rng.py
Line 639 in e3fc844
Non-blocking (nit): the 0-d comparison leaves out atol=0, rtol=0; every other shard comparison passes them.
Non-blocking, low confidence (unmeasured): run_calc always uses 64-bit index math. OffsetCalculator<1, uint64_t> divides with plain 64-bit / and %, which NVIDIA GPUs emulate in software. The tensor-bounds kernels in the same file already switch to 32-bit indexing via canUse32BitIndexMath; doing the same might narrow the bf16 dim-1 benchmark gap (0.304 ms vs a 0.173 ms floor).
This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review
[ghstack-poisoned]
albanD
left a comment
There was a problem hiding this comment.
Sounds good if we can confirm that users like titan / megatron can use this out of the box.
Also a small benchmark to compare with the non-shard version of the kernel sampling the same amount of data would be helpful to understand where we stand (as the python version is clearly slow/memory hungry and not a great baseline).
Tentative approve given the confirmation above
| >>> # Rows 512:1024 of a (1024, 4096) parameter. | ||
| >>> shard = torch.empty(512, 4096, device="cuda") # doctest: +SKIP | ||
| >>> torch.func._random.shard_normal_( # doctest: +SKIP | ||
| ... key, shard, (1024, 4096), (512, 0) |
There was a problem hiding this comment.
nit: here and below. Can we add the full sized sample and an assert that the slice match as a concrete example of what we guarantee?
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
This PR introduces two new python APIs to
torch/func/_random.pybacked by ATen ops that provide in-place initialization of a shard that is guaranteed to give the same values as the corresponding region of the full initialization(e.g.
normal(key, global_shape, dtype=result.dtype)).New APIs
Example usage
In theory, this can be implemented on the python side using the guarantees that the stateless RNG APIs provide. However, doing this correctly can be complex / inefficient due to:
Python reference implementation
Rather than require users to handle the above manually, this PR provides shard-invariant init through a new PyTorch core API. This also gives performance benefits; see the below comparison. Note that the perf is benchmarked over the last shard and "unsharded ms" is a comparison against a typical in-place stateless RNG init as a performance floor.
Benchmarking results
Test Plan:
New tests in
test/test_stateless_rng.pycover bitwise shard-vs-global equality for uneven splits along every dim(all floating dtypes, non-default distribution parameters, keys near offset wraparound), non-contiguous / empty /
0-d / misaligned-key cases, every error in both eager and FakeTensorMode,
torch.compilewith static and dynamic(symbolic) shard sizes and offsets,
opcheck, and reinplacing of the shard ops under Inductor via peak memory.Agent details
This PR was authored with the assistance of an AI coding assistant (Claude).
cc @albanD @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo