Skip to content

Add unbind() stateless API - #178160

Closed
jbschlosser wants to merge 54 commits into
gh/jbschlosser/260/basefrom
gh/jbschlosser/260/head
Closed

jbschlosser wants to merge 54 commits into
gh/jbschlosser/260/basefrom
gh/jbschlosser/260/head

Conversation

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
🟡 AUTOMATED REVIEW - Changes requested:

The PR adds `torch.func._random.unbind`, which turns a Philox key into a grid of
offset-shifted sub-keys so a tensor can be generated tile by tile and match the
full generation exactly. However, the offset math uses the wrong unit (elements
rather than Philox calls), the documented N-D usage raises an error, and the
documented batched keys crash or give wrong keys. Recommendation: Request
Changes.

Findings (10):

[major] torch/func/_random.py:146
Blocking: the offsets count elements, but the kernels count Philox calls. The
kernels advance the offset once per Philox 4x32 call, and each call fills
`elems_per_call` elements: 4 for float32/half/bf16/ints of 32 bits or fewer, 2
for float64/int64/uint64 (PhiloxStatelessRNG.h:17-18, CPU
PhiloxStatelessRNG.cpp:148-158, CUDA PhiloxDistribution.cu:88-107;
`test_offset_shift_consistency` checks this). `unbind` adds `tile_index *
tile_elems * outputs_per_elem` (1, or 2 for float64), so
`unbind(k,(100,),(10,))[1]` gets offset 10 and generates elements 40..49, not
10..19. Tiles whose first flat index isn't a multiple of `elems_per_call` can't
be represented at all (e.g. 1-D tile of 10 in float32, the 3-D
(12,20,30)/(3,4,3) test). int64/uint64 are also 8-byte but only float64 is
special-cased; the docstring at :124-126 is wrong. At :201 the last-dim term
isn't multiplied by `strides[-1]`. The value-checking TestUnbind tests should
fail at HEAD. Fix: compute flat element offsets, divide by `epc = 2 if
dtype.itemsize == 8 else 4` (dtype=None -> 4-byte defaults), raise ValueError
unless `tile_shape[-1] % epc == 0` and `shape[-1] % epc == 0`, and document that
rule.

[major] torch/func/_random.py:155
Blocking: batched keys are documented but not supported (docstring at :120 says
key may be `(..., 2)`). 1-D path: a `(B, 2)` key gives `base_offset` of shape
`(B,)`; adding it to `arange(splits[0])` fails to broadcast unless B == 1 or B
== splits[0], and when B == splits[0] key i is silently paired only with tile i,
giving wrong keys with no error. N-D path (:203-209): `offset + base_offset`
broadcasts the batch into the trailing size-1 dim, so `squeeze(-1)` does nothing
and `reshape(target_shape)` raises. Every sibling API (`split`, `fold_in`,
`uniform`, `normal`, `randint`) supports batched keys. Either implement
`(*batch, *splits, ..., 2)` or require a `(2,)` key and raise otherwise.

[major] torch/func/_random.py:116
Blocking: the documented N-D usage raises an error (:114-117, :129-131).
`keys[t0, ..., t_{n-1}]` has shape `(*tile_shape[:-1], 2)`, so its ndim equals
the output's ndim, but batched keys must have `key.dim() == output.dim() + 1`
(PhiloxStatelessRNG.cpp:103-106 and CUDA equivalent). So `uniform(keys[t...],
tile_shape)` raises, which is why every N-D test adds `.unsqueeze(-2)`. It also
makes 1-D and N-D results behave differently, so callers must branch on ndim.
Return `(*splits, *tile_shape[:-1], 1, 2)` so tile keys can be passed straight
in, or at least document the `unsqueeze`.

[minor] torch/func/_random.py:144
Non-blocking: input validation is missing (:139-155). `splits` containing 0
raises ZeroDivisionError at :144; a negative split passes the divisibility check
(`100 % -10 == 0`) then fails inside `torch.arange` with an unrelated error; a
negative shape entry silently produces negative offsets that wrap as uint64;
`shape=()` raises IndexError on `splits[-1]` (:186). The key's dtype and shape
are never checked: 8-byte non-uint64 keys are silently reinterpreted by
`key.view(torch.int64)`, 4-byte keys fail with an obscure IndexError, and a
`(3,)` key silently drops its last element. The ATen ops raise clear errors for
these (PhiloxStatelessRNG.cpp:97-102, :171-176).

(6 more not shown, see the review run)

Reviewed commit: 00af30d

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ 1 New Failure, 14 Pending

As of commit 00af30d with merge base d39020e (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • Adds new function unbind and helper _philox_unbind in torch/func/_random.py; new feature logic fits no trivial class
    • Computes Philox stream offsets per tile and per row, with outputs_per_elem of 2 for torch.float64, which is RNG numerics
  • Correctness needs a human
    • N-D offset math uses broadcast, reshape and permute over 2 * (ndim - 1) + 2 dims and needs careful review
    • test_1d_near_max_offset relies on int64 wraparound of offsets viewed from torch.uint64 keys, an edge case worth a reviewer check
  • Socialization
    • New RNG entry point whose name, return layout (*splits, *tile_shape[:-1], 2) and dtype coupling are API design choices

reason: not_trivial
Reviewed commit: 00af30d

Inference job

🐛 Report a wrong verdict

NEW FAILURE - The following job has failed:

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

@pytorch-bot

pytorch-bot Bot commented Mar 23, 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.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Mar 23, 2026
ghstack-source-id: 30d2b9e
Pull-Request: #178160
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@jbschlosser jbschlosser changed the title Add grid_split() stateless API Add unbind() stateless API Mar 27, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Oct 27, 2026
@albanD albanD added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 10, 2026
[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 00af30d: changes requested before human review.

The PR adds torch.func._random.unbind, which turns a Philox key into a grid of offset-shifted sub-keys so a tensor can be generated tile by tile and match the full generation exactly. However, the offset math uses the wrong unit (elements rather than Philox calls), the documented N-D usage raises an error, and the documented batched keys crash or give wrong keys. Recommendation: Request Changes.

🔴 3 blocking findings are attached to the code below.

⚪ 7 non-blocking findings

if s % sp != 0:

Non-blocking: input validation is missing (:139-155). splits containing 0 raises ZeroDivisionError at :144; a negative split passes the divisibility check (100 % -10 == 0) then fails inside torch.arange with an unrelated error; a negative shape entry silently produces negative offsets that wrap as uint64; shape=() raises IndexError on splits\[-1\] (:186). The key's dtype and shape are never checked: 8-byte non-uint64 keys are silently reinterpreted by key.view(torch.int64), 4-byte keys fail with an obscure IndexError, and a (3,) key silently drops its last element. The ATen ops raise clear errors for these (PhiloxStatelessRNG.cpp:97-102, :171-176).


base_offset = data[..., 1]

Non-blocking: the key layout and consumption rule are reimplemented in Python (:146, :155-157). split/fold_in call ATen ops that validate the key and do uint64 offset arithmetic; unbind reads the (seed, offset) layout directly, bypassing the "internal representation depends on the algorithm" contract key() documents (:36-39), and duplicates elems_per_call, whose header says to keep it in one place so kernels can't drift (PhiloxStatelessRNG.h:8-10) that drift has already happened. Consider a small ATen primitive, e.g. _philox_key_advance(key, elem_offsets, dtype), doing the uint64 add with elems_per_call<scalar_t> and a TORCH_CHECK for alignment, with a meta registration; Python keeps only the index math.


def test_1d_near_max_offset(self, device, dtype):

Non-blocking: several tests can't catch offset-math errors, and float64 N-D is untested. test_1d_near_max_offset doesn't wrap where its docstring says: under per-call semantics, 100 float32 elements from 2**64 - 48 use 25 calls and never cross 2^64; only float64 (50 calls) does. Once offsets are fixed, pick a base offset that wraps for every dtype tested. test_cross_device_consistency_1d/_2d (:1714-1733) run the same integer arithmetic on both devices, so they pass regardless of correctness; the rest of the file uses @ onlyAccelerator with key.to(device), not @ onlyCUDA. No 2-D or 3-D test uses float64 or a 64-bit integer dtype, which is how the missing strides\[-1\] factor at _random.py:201 went unnoticed.


def test_1d_uniform_reconstruction(self, device):

Non-blocking: the tests don't follow the file's conventions. The uniform and normal reconstruction tests are copy-pasted pairs (:1539/:1550, :1585/:1601); elsewhere the file uses @ parametrize("gen_fn_name", \["normal", "uniform"\]) with self._gen. @ dtypes(torch.float32, torch.float64) (:1675) lists dtypes by hand; the rest of the file uses all_floating_dtypes, which also covers half and bf16.


dtype: torch.dtype | None = None,

Non-blocking: the signature and docstring don't match the sibling functions. dtype is positional, while uniform, normal, randint and bits take it keyword-only; use def unbind(key, shape, splits, *, dtype=None). shape/splits are hinted as bare tuple; Sequence\[int\] is more accurate. Siblings have an Example:: section with # doctest: +SKIP; unbind has only an inline literal block (:106-112), whose assert would fail because of the offset bug. dtype is not None and dtype == torch.float64 (:146) has a redundant is not None check.


def unbind(

Non-blocking: the name unbind collides with torch.unbind / Tensor.unbind, which split a tensor along a dim into a tuple of views; this function returns a single tensor of tile-aligned keys. The module is private and experimental (torch/func/__init__.py:17-18), so now is the cheap time to choose something like tile_keys.


offset = offset.permute(tile_perm + inner_perm).contiguous()

Non-blocking: offset.permute(...).contiguous() makes an extra copy, because torch.stack at :217 creates a new contiguous tensor anyway.

Please address the findings and push; a new commit normally gets a fresh automated review.

Disagree with a finding? Reply with your reasoning, then comment @pytorchbot review to request a re-review. This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

Comment thread torch/func/_random.py
for i, (s, sp) in enumerate(zip(shape, splits)):
if s % sp != 0:
raise ValueError(f"splits[{i}]={sp} does not evenly divide shape[{i}]={s}")
outputs_per_elem = 2 if dtype is not None and dtype == torch.float64 else 1

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.

🔴 Blocking: the offsets count elements, but the kernels count Philox calls. The kernels advance the offset once per Philox 4x32 call, and each call fills elems_per_call elements: 4 for float32/half/bf16/ints of 32 bits or fewer, 2 for float64/int64/uint64 (PhiloxStatelessRNG.h:17-18, CPU PhiloxStatelessRNG.cpp:148-158, CUDA PhiloxDistribution.cu:88-107; test_offset_shift_consistency checks this). unbind adds tile_index * tile_elems * outputs_per_elem (1, or 2 for float64), so unbind(k,(100,),(10,))\[1\] gets offset 10 and generates elements 40..49, not 10..19. Tiles whose first flat index isn't a multiple of elems_per_call can't be represented at all (e.g. 1-D tile of 10 in float32, the 3-D (12,20,30)/(3,4,3) test). int64/uint64 are also 8-byte but only float64 is special-cased; the docstring at :124-126 is wrong. At :201 the last-dim term isn't multiplied by strides\[-1\]. The value-checking TestUnbind tests should fail at HEAD. Fix: compute flat element offsets, divide by epc = 2 if dtype.itemsize == 8 else 4 (dtype=None -> 4-byte defaults), raise ValueError unless tile_shape\[-1\] % epc == 0 and shape\[-1\] % epc == 0, and document that rule.

Report this finding

Comment thread torch/func/_random.py
) -> torch.Tensor:
ndim = len(shape)
tile_shape = tuple(s // sp for s, sp in zip(shape, splits))
data = key.view(torch.int64)

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.

🔴 Blocking: batched keys are documented but not supported (docstring at :120 says key may be (..., 2)). 1-D path: a (B, 2) key gives base_offset of shape (B,); adding it to arange(splits\[0\]) fails to broadcast unless B == 1 or B == splits[0], and when B == splits[0] key i is silently paired only with tile i, giving wrong keys with no error. N-D path (:203-209): offset + base_offset broadcasts the batch into the trailing size-1 dim, so squeeze(-1) does nothing and reshape(target_shape) raises. Every sibling API (split, fold_in, uniform, normal, randint) supports batched keys. Either implement (*batch, *splits, ..., 2) or require a (2,) key and raise otherwise.

Report this finding

Comment thread torch/func/_random.py

For N-D, each tile key is a batched key with per-row sub-keys. The tile
shape is ``shape[i] // splits[i]`` along each dimension, and
``uniform(keys[t0, ..., t_{n-1}], tile_shape)`` reproduces the

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.

🔴 Blocking: the documented N-D usage raises an error (:114-117, :129-131). keys\[t0, ..., t_{n-1}\] has shape (*tile_shape\[:-1\], 2), so its ndim equals the output's ndim, but batched keys must have key.dim() == output.dim() + 1 (PhiloxStatelessRNG.cpp:103-106 and CUDA equivalent). So uniform(keys\[t...\], tile_shape) raises, which is why every N-D test adds .unsqueeze(-2). It also makes 1-D and N-D results behave differently, so callers must branch on ndim. Return (*splits, *tile_shape\[:-1\], 1, 2) so tile keys can be passed straight in, or at least document the unsqueeze.

Report this finding

@jbschlosser

Copy link
Copy Markdown
Contributor Author

Closing for now as I'm not sure this API is something we want to provide

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

Labels

GL/human GreenLight marked as needing human review in progress PR is being worked on by the author, until the automated review accepts it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants