Repository navigation
Add unbind() stateless API - #178160
Add unbind() stateless API#178160jbschlosser wants to merge 54 commits into
Conversation
🟡 AUTOMATED REVIEW - Changes requested:
Findings (10): Reviewed commit: 🔗 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 PendingAs of commit 00af30d with merge base d39020e ( 🟡 GREEN LIGHT - PR requires human review:
reason: NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
[ghstack-poisoned]
There was a problem hiding this comment.
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
Line 144 in 00af30d
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).
Line 157 in 00af30d
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.
pytorch/test/test_stateless_rng.py
Line 1676 in 00af30d
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.
pytorch/test/test_stateless_rng.py
Line 1539 in 00af30d
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.
Line 98 in 00af30d
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.
Line 94 in 00af30d
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.
Line 214 in 00af30d
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
| 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 |
There was a problem hiding this comment.
🔴 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.
| ) -> torch.Tensor: | ||
| ndim = len(shape) | ||
| tile_shape = tuple(s // sp for s, sp in zip(shape, splits)) | ||
| data = key.view(torch.int64) |
There was a problem hiding this comment.
🔴 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.
|
|
||
| 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 |
There was a problem hiding this comment.
🔴 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.
|
Closing for now as I'm not sure this API is something we want to provide |
Stack from ghstack (oldest at bottom):