Skip to content

Introduce stateless shard-invariant init kernels - #205732

Open
jbschlosser wants to merge 13 commits into
gh/jbschlosser/305/basefrom
gh/jbschlosser/305/head
Open

jbschlosser wants to merge 13 commits into
gh/jbschlosser/305/basefrom
gh/jbschlosser/305/head

Conversation

@jbschlosser

@jbschlosser jbschlosser commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

This PR introduces two new python APIs to torch/func/_random.py backed 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
def shard_normal_(
    key: torch.Tensor,
    result: torch.Tensor,
    global_shape: Sequence[int | torch.SymInt],
    global_offset: Sequence[int | torch.SymInt],
    *,
    mean: float = 0.0,
    std: float = 1.0
) -> torch.Tensor:
    ...

def shard_uniform_(
    key: torch.Tensor,
    result: torch.Tensor,
    global_shape: Sequence[int | torch.SymInt],
    global_offset: Sequence[int | torch.SymInt],
    *,
    low: float = 0.0,
    high: float = 1.0
) -> torch.Tensor:
    ...
Example usage
import torch
import torch.func._random as r

key = r.key(42, device="cuda")

# Columns 2048:4096 of a (1024, 4096) weight; equals r.normal(key, (1024, 4096), std=0.02)[:, 2048:]
shard = torch.empty(1024, 2048, device="cuda")
r.shard_normal_(key, shard, (1024, 4096), (0, 2048), std=0.02)

# A DTensor parameter's local shard, using DTensor's own offset helper
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset

...
p = model.weight  # DTensor parameter
# For placements that give a rank several separate chunks (e.g. `_StridedShard`), call
# once per chunk using the offsets from `compute_local_shape_and_chunks`.
_, offset = compute_local_shape_and_global_offset(p.shape, p.device_mesh, p.placements)
with torch.no_grad():
    r.shard_uniform_(key, p.to_local(), p.shape, offset, low=-0.1, high=0.1)

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:

  • Building the set of keys to use as start points (also materializing this uses a non-trivial amount of memory for some sharding schemes)
  • Performance optimization to handle entire contiguous chunks of memory at once instead of doing this per-dim only
  • Handling for shapes not divisible by the # of elements produced per Philox (seed, offset) pair via oversampling + dropping leading values
Python reference implementation
"""Shard-invariant init built only on the documented torch.func._random key layout:
element i of a key's output is value i % E of the Philox call at offset + i // E,
with E = 4 for dtypes of <= 32 bits and E = 2 for 64-bit dtypes."""

import itertools
import math

import torch
import torch.func._random as r


def shard_normal_(key, shard, global_shape, global_offset, mean=0.0, std=1.0):
    """Fill `shard` so it equals normal(key, global_shape)[region]
    for the region at `global_offset`."""
    if shard.numel() == 0:
        return shard
    if not shard.is_contiguous():
        contiguous = shard.contiguous()
        shard_normal_(key, contiguous, global_shape, global_offset, mean, std)
        return shard.copy_(contiguous)
    # E: elements per Philox call (128 bits; 32 bits per value, or 64 for 64-bit dtypes)
    E = 2 if shard.dtype.itemsize == 8 else 4

    # A "run" is a stretch of the shard that is contiguous in the global tensor.
    # Merge trailing dims the shard fully covers, so each run is as long as possible
    # (a dim-0 shard is one run).
    j = shard.dim() - 1
    while j > 0 and shard.shape[j] == global_shape[j]:
        j -= 1
    inner = math.prod(global_shape[j + 1 :])
    shard_shape = (*shard.shape[:j], shard.shape[j] * inner)
    full_shape = (*global_shape[:j], global_shape[j] * inner)
    offset = (*global_offset[:j], global_offset[j] * inner)
    merged = shard.view(shard_shape)
    *run_grid, run_len = shard_shape

    # Global flat index where each run starts.
    starts = torch.zeros((), dtype=torch.int64)
    for dim_offset, dim_len, dim_full in zip(offset[:-1], run_grid, full_shape[:-1]):
        indices = torch.arange(dim_offset, dim_offset + dim_len)
        starts = starts.unsqueeze(-1) * dim_full + indices
    starts = starts * full_shape[-1] + offset[-1]

    # One key per run, with its offset advanced to the Philox call containing the
    # run's first element.
    keys = key.cpu().expand(*starts.shape, 2).clone()
    # uint64 add via int64 bits; wraps mod 2**64
    keys.view(torch.int64)[..., 1] += starts // E
    keys = keys.to(shard.device).unsqueeze(-2)

    # Position of each run's start within its Philox call.
    lanes = starts % E
    pad = int(lanes.max())

    # Fast path (all run starts are multiples of E): fill in place.
    if pad == 0:
        r.normal_(keys, merged, mean=mean, std=std)
        return shard

    # Slow path: oversample into a temporary, then pick each run's window at its lane.
    padded_shape = (*run_grid, run_len + pad)
    padded = r.normal(keys, padded_shape, mean=mean, std=std, dtype=shard.dtype)
    windows = padded.unfold(-1, run_len, 1)  # (*run_grid, pad + 1, run_len) view
    idx = lanes.to(shard.device)[..., None, None].expand(*run_grid, 1, run_len)
    torch.gather(windows, -2, idx, out=merged.unsqueeze(-2))
    return shard


def shard_regions(global_shape, dim, world):
    """Slices and offsets of DTensor's uneven Shard(dim) split of global_shape."""
    step = math.ceil(global_shape[dim] / world)
    for start in range(0, global_shape[dim], step):
        region, offset = [slice(None)] * len(global_shape), [0] * len(global_shape)
        region[dim], offset[dim] = slice(start, start + step), start
        yield tuple(region), tuple(offset)


if __name__ == "__main__":
    device = "cuda" if torch.cuda.is_available() else "cpu"
    key = r.key(1234, device=device)
    shapes = [(1000, 774), (512, 2048), (64, 30, 3, 3), (50257,)]
    dtypes = (torch.float32, torch.bfloat16, torch.float64)
    for full_shape, dtype in itertools.product(shapes, dtypes):
        full = r.normal(key, full_shape, std=0.02, dtype=dtype)
        bits = {2: torch.int16, 4: torch.int32, 8: torch.int64}[dtype.itemsize]
        for dim, world in itertools.product(range(len(full_shape)), (2, 3, 4)):
            for region, offset in shard_regions(full_shape, dim, world):
                shard = torch.empty(full[region].shape, device=device, dtype=dtype)
                shard_normal_(key, shard, full_shape, offset, std=0.02)
                # Compare raw bits, since float == has -0.0 == 0.0 and NaN != NaN.
                actual, expected = shard.view(bits), full.view(bits)[region]
                assert torch.equal(actual, expected), (full_shape, dtype, region)
    print(f"[{device}] every shard of every split matches the unsharded init bitwise")

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
  ┌─────────────┬─────────┬─────────┬─────────┬─────────┬────────────┬─────────┬──────────┬─────────┐
  │   global    │  shard  │  dtype  │ Python  │ kernel  │ unsharded  │ speedup │ Python   │ kernel  │
  │    shape    │         │         │   ms    │   ms    │     ms     │         │   MiB    │   MiB   │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (4096,      │ dim 0,  │ fp32 /  │ 0.118   │ 0.042   │ 0.033      │ 2.8x    │ 0        │ 0       │
  │ 14336)      │ /8      │ bf16    │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (4096,      │ dim 1,  │ fp32    │ 0.224   │ 0.053   │ 0.036      │ 4.2x    │ 0.1      │ 0       │
  │ 14336)      │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (4096,      │ dim 1,  │ bf16    │ 0.224   │ 0.051   │ 0.035      │ 4.4x    │ 0.1      │ 0       │
  │ 14336)      │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (50257,     │ dim 0,  │ fp32    │ 0.445   │ 0.368   │ 0.368      │ 1.2x    │ 0        │ 0       │
  │ 4096)       │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (50257,     │ dim 0,  │ bf16    │ 0.261   │ 0.184   │ 0.184      │ 1.4x    │ 0        │ 0       │
  │ 4096)       │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (4096,      │ dim 1,  │ fp32    │ 1.406   │ 0.316   │ 0.314      │ 4.5x    │ 98.2     │ 0       │
  │ 50257)      │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (4096,      │ dim 1,  │ bf16    │ 0.961   │ 0.304   │ 0.173      │ 3.2x    │ 49.1     │ 0       │
  │ 50257)      │ /8      │         │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (1000, 774) │ dim 1,  │ fp32 /  │ 0.22    │ 0.012   │ 0.009      │ ~19x    │ 0.5–1.0  │ 0       │
  │             │ /3      │ bf16    │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (256, 128,  │ dim 1,  │ fp32 /  │ 0.20    │ 0.012   │ 0.009      │ ~17x    │ 0.2–0.4  │ 0       │
  │ 3, 3)       │ /3      │ bf16    │         │         │            │         │          │         │
  ├─────────────┼─────────┼─────────┼─────────┼─────────┼────────────┼─────────┼──────────┼─────────┤
  │ (8192,      │ dim 1,  │ fp32 /  │ 0.30    │ 0.012   │ 0.009      │ ~27x    │ 0.1      │ 0       │
  │ 8192)       │ /64     │ bf16    │         │         │            │         │          │         │
  └─────────────┴─────────┴─────────┴─────────┴─────────┴────────────┴─────────┴──────────┴─────────┘

Test Plan:

New tests in test/test_stateless_rng.py cover 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.compile with static and dynamic
(symbolic) shard sizes and offsets, opcheck, and reinplacing of the shard ops under Inductor via peak memory.

python test/test_stateless_rng.py -k shard
python test/test_stateless_rng.py

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 19, 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 19, 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 `_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.

Findings (12):

[minor] torch/func/_random.py:362
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.

[minor] torch/func/_random.py:378
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.

[minor] torch/func/_random.py:356
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.

[minor] aten/src/ATen/native/PhiloxStatelessRNG.h:87
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`.

[minor] torch/_meta_registrations.py:789
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.

(7 more not shown, see the review run)

Reviewed commit: e3fc844 (NOT the current head 7f7fe2c)

Review run

🐛 Report a bad review

🔗 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 Failures

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

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

  • Triviality
    • New feature: adds _philox_normal_shard_ and _philox_uniform_shard_ ATen ops in native_functions.yaml with new CPU and CUDA kernels
    • New index math in philox_shard_layout and philox_shard_kernel fits no trivial change class
  • Scope
    • Also adds meta registrations, Inductor reinplace entries in reinplace.py, and shard_normal_/shard_uniform_ wrappers in torch/func/_random.py
    • Adds new autosummary entries to docs/source/func._random.md, which the Documentation class excludes
  • Tests
    • test/test_stateless_rng.py adds bitwise shard-vs-global, error, opcheck, and compile tests; the design still needs a human reviewer

reason: not_trivial
Reviewed commit: 50ab0c2 (NOT the current head 7f7fe2c)

Inference job

🐛 Report a wrong verdict

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

@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 19, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 19, 2026
@jbschlosser jbschlosser added topic: improvements topic category module: python frontend For issues relating to PyTorch's Python frontend labels Nov 19, 2026
[ghstack-poisoned]
[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed their stale review November 23, 2026 20:50

Withdrawn: the automated review of 32564d0 found nothing blocking.

@github-actions
github-actions Bot dismissed their stale review November 23, 2026 20:50

Withdrawn: the automated review of 32564d0 found nothing blocking.

[ghstack-poisoned]
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 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

mean: float = 0.0,

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&lt;double&gt;, 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.


key (Tensor): An unbatched PRNG key returned by :func:`key`,

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.


def shard_normal_(

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.


TORCH_CHECK(!c10::mul_overflows(global_numel, global_shape[d], &global_numel),

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.


def _check_philox_shard_args(op_name, self, key, global_shape, global_offset):

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.


at::assert_no_internal_overlap(self);

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&lt;16&gt;, 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.


TORCH_CHECK(grid_dims <= MAX_DIMS,

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.


def test_shard_fullgraph(self, device, gen_fn_name, dynamic):

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.


def test_shard_errors(self, device, gen_fn_name):

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.


shard = torch.empty(8, 5, dtype=dtype, device=device).t()

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.


self.assertEqual(scalar, self._gen(gen_fn_name, key, (), dtype=dtype))

Non-blocking (nit): the 0-d comparison leaves out atol=0, rtol=0; every other shard comparison passes them.


auto run_calc = OffsetCalculator<1, uint64_t>(

Non-blocking, low confidence (unmeasured): run_calc always uses 64-bit index math. OffsetCalculator&lt;1, uint64_t&gt; 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

@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 24, 2026
[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.

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

Comment thread torch/func/_random.py
>>> # 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)

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.

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]
@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Dec 1, 2026
[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 module: inductor module: python frontend For issues relating to PyTorch's Python frontend ready for review Automated review passed, ready for a final review by a maintainer. topic: improvements topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants