Skip to content

Introduce Inductor lowering for stateless RNG uniform - #204307

Open
jbschlosser wants to merge 17 commits into
gh/jbschlosser/301/basefrom
gh/jbschlosser/301/head
Open

jbschlosser wants to merge 17 commits into
gh/jbschlosser/301/basefrom
gh/jbschlosser/301/head

Conversation

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

PR Status: in progress

Please address review feedback on your PR either with a code/PR description change. If a review comment is irrelevant, react with 👎 on that specific comment to reject it, and leave a short reply explaining why. The change must pass any running CI and existing failures must be classified as unrelated (see status below in this comment).

Passing automated review does not guarantee that this PR will be merged. It still requires maintainer review and may be closed if its design or direction does not align with the project.

To minimize iteration time, feel free to run the pr-review skill from the repo locally. To trigger a fresh automated review, make a new push or comment @pytorchbot review. To bypass automated review, please add the "no automated review" label.

🟡 AUTOMATED REVIEW - Changes requested:

The PR lowers aten._philox_uniform (.default and .Tensor) on Triton devices to
fusible pointwise code via a new ops.philox_rand op and
triton_helpers.philox_rand helper, and stops reinplacing those ops on Triton.
Recommendation: Request Changes  three earlier blocking findings remain at HEAD:
a 0-d constant `low` (freezing) crashes compilation, the is_triton gate enables
the lowering on XPU/MTIA/Triton-CPU, and
test_reinplacement_canonicalizes_philox_result now fails on GPU.

Findings (12):

[major] torch/_inductor/lowering.py:3550
Blocking: a 0-d constant `low` crashes compilation. GraphLowering.get_attr
(graph.py:1708-1720) returns a bare ir.Constant, not a TensorBox, for a 0-d
tensor attribute (the default unless runtime constant folding,
always_keep_tensor_constants, or a mutated named buffer applies). With
type_promotion_kind=None and no broadcast, transform_args passes it through
unchanged, so `isinstance(low, TensorBox)` is False and `torch.tensor([low,
high], dtype=torch.float64)` at line 3561 runs on IR nodes and raises. Hit by a
module with register_buffer("low", torch.tensor(0.1)) passed as uniform(key,
shape, low=self.low, ...) under config.freezing=True (AOTI likely too,
inferred). Regression: the extern fallback handled Constant via
ExternKernel.realize_input. Fix: branch on `V.graph.current_node.target is
aten._philox_uniform.Tensor` or on `isinstance(low, ir.IRNode)`; expand()
already accepts ir.BaseConstant.

[major] torch/_inductor/lowering.py:3535
Blocking: the is_triton gate is broader than the devices eager supports.
ir.is_triton is True for XPU by default (xpu_backend="triton"), CPU when
cpu_backend="triton", and any device whose scheduler subclasses
TritonScheduling, but eager _philox_uniform/_philox_uniform_ only have CPU and
CUDA kernels. On XPU/MTIA eager raises while compiled code silently returns
values; on Triton-CPU the eager kernel computes x * (hi - lo) + lo without the
FMA the lowering emits, so bits can differ. The new tests
(only_for=("cpu","cuda")) cover none of this. Fix: use one shared predicate here
and in fx_passes/reinplace.py:377-380: `is_triton(device) and device.type ==
"cuda"` (not a bare CUDA check, since cuda_backend="halide"/"pallas" would emit
ops.philox_rand into backends that raise NotImplementedError). That helper is
also the place for the fallback_random check.

[major] torch/_inductor/fx_passes/reinplace.py:377
Blocking: an existing GPU test now fails.
test/inductor/test_inplacing_pass.py:694-715
test_reinplacement_canonicalizes_philox_result runs with device = GPU_TYPE and
no skip, calls reinplace_inplaceable_ops_core (which ANDs in extra_check), and
at line 705 asserts _philox_uniform.default was retargeted to
_philox_uniform_.default. should_reinplace_philox returns False on CUDA and XPU,
so the assertion fails under ciflow/inductor; the PR doesn't touch that file.
Fix: switch the test to random.normal or random.randint, or assert that uniform
is not reinplaced on Triton.

[minor] torch/_inductor/lowering.py:3561
Non-blocking: the scalar-bounds path doesn't use round_scalar_to_dtype.
torch.tensor([low, high], dtype=torch.float64).to(dtype) is created with no
device=, so it follows any ambient default-device context. The already-imported
round_scalar_to_dtype (utils.py:997-1002) pins device="cpu" for exactly this
reason (NOTE [torch.tensor, lift_fresh, and device movement]) and other
lowerings use it. Use it for low and high, and keep the span as
round(round(high) - round(low)).

[minor] torch/_inductor/lowering.py:3537
Non-blocking: the CPU fallback now bypasses the implicit-fallback path. Calling
fallback_handler(op, add_to_fallback_set=False) directly skips
config.implicit_fallbacks and the tag-derived layout constraint that
graph.py:1515-1556 applied to this op before. No correctness impact, but it is
an undocumented behaviour change.

(7 more not shown, see the review run)

Reviewed commit: b99aa43

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

❌ You can merge normally! (1 Unrelated Failure), 7 Unclassified Failures

As of commit b99aa43 with merge base bcff2f4 (image):

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New feature: registers an Inductor lowering philox_uniform for aten._philox_uniform in torch/_inductor/lowering.py, outside every trivial class
    • Adds a new op philox_rand to ops_handler.py, dtype_propagation.py, and the triton, cpp, and halide backends
  • Numerics
    • New Triton RNG math in triton_helpers.philox_rand (bit masking, scaling by 1 << DIGITS) and an ops.fma with explicit dtype rounding in the lowering
    • Eager equivalence is a numerics question for a human, even though the new tests use atol=0, rtol=0
  • Compiled behavior change
    • should_reinplace_philox in fx_passes/reinplace.py turns off reinplacing of _philox_uniform on Triton devices, so it now lowers as fused pointwise code
  • Defects
    • None found: is_triton, sympy_dot, and ops.fma all exist in the checkout, and the CPU path falls back to fallback_handler

reason: not_trivial
Reviewed commit: b99aa43

Inference job

🐛 Report a wrong verdict

UNCLASSIFIED FAILURES - DrCI could not classify the following jobs because the workflow did not run on the merge base. The failures may be pre-existing on trunk or introduced by this PR:

  • pull / dynamo-cpython-test / test (dynamo_wrapped, 2, 7, mt-l-x86iavx512-8-64) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The PR adds both the failing test (TestStatelessRNGDropout.test_noncontig_input) and the meta-registration internal-overlap check that raises in it. The check runs on dropout's read-only input, so the expanded (x[:1].expand) input trips it under FakeTensorMode. It fails the same way on every rerun.

    Full reasoning on HUD →

  • pull / linux-jammy-aarch64-py3.11 / test (default, 2, 7, mt-l-arm64g4-16-62) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16
    AI verdict: AI verdict: pending

  • pull / linux-jammy-py3.11-clang21 / test (default, 2, 10, mt-l-x86iavx512-16-128) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The failure comes from code the PR adds. The new internal-overlap check in _check_philox_gen_args (torch/_meta_registrations.py) is also run on the read-only input of the new _philox_dropout meta function. The PR's own test feeds that op an expanded, non-contiguous input under FakeTensorMode, so the check raises.

    Full reasoning on HUD →

  • pull / linux-jammy-py3.11-clang21-asan / test (default, 2, 18, mt-l-x86iavx512-16-128) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The test fails on its fake-tensor path because the meta function for _philox_dropout raises a memory-overlap RuntimeError. The PR added that overlap check to the meta registrations, and it also added the dropout op and the failing test. So this is a genuine regression in the PR, not a flake or an infra problem.

    Full reasoning on HUD →

  • pull / linux-jammy-py3.11-gcc11 / test (default, 4, 10, mt-l-x86iavx512-16-128) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The failing test, TestStatelessRNGDropout.test_noncontig_input, is new in this PR, and so are the aten._philox_dropout op and its meta registration. Neither exists at the merge base or on current main. The meta function runs the internal-overlap check meant for write targets against the dropout input, so it raises on the expanded input that the test passes in.

    Full reasoning on HUD →

  • pull / linux-jammy-py3.14-clang21 / test (default, 2, 10, mt-l-x86iavx512-16-128) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The failing test TestStatelessRNGDropoutCPU.test_noncontig_input and the aten._philox_dropout meta function it exercises are both introduced by this PR's ghstack (absent at merge base and main). The meta function wrongly applies the in-place internal-overlap check to the read-only expanded input, so the fake-tensor path raises deterministically on every run.

    Full reasoning on HUD →

  • pull / linux-jammy-py3.14t-clang21 / test (default, 2, 11, mt-l-x86iavx512-16-128) (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)
    test/test_stateless_rng.py::TestStatelessRNGDropoutCPU::test_noncontig_input_cpu_bfloat16

    AI verdict: AI verdict: related

    The PR adds the failing test (TestStatelessRNGDropout.test_noncontig_input), the new aten._philox_dropout op, and its meta registration. The meta function runs the internal-overlap check meant for in-place outputs on the dropout input. With a non-contiguous (overlapping) input under FakeTensor, that check raises, so the PR's own code causes this failure.

    Full reasoning on HUD →

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@pytorch-bot

pytorch-bot Bot commented Nov 10, 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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests labels Nov 10, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 10, 2026
@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 10, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 11, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 13, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 16, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 19, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 19, 2026
[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 23, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 23, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 23, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 23, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Nov 24, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Dec 1, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Dec 1, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Dec 1, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Dec 2, 2026
[ghstack-poisoned]
jbschlosser added a commit that referenced this pull request Dec 2, 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 b99aa43: changes requested before human review.

The PR lowers aten._philox_uniform (.default and .Tensor) on Triton devices to fusible pointwise code via a new ops.philox_rand op and triton_helpers.philox_rand helper, and stops reinplacing those ops on Triton. Recommendation: Request Changes three earlier blocking findings remain at HEAD: a 0-d constant low (freezing) crashes compilation, the is_triton gate enables the lowering on XPU/MTIA/Triton-CPU, and test_reinplacement_canonicalizes_philox_result now fails on GPU.

🔴 3 blocking findings are attached to the code below.

⚪ 9 non-blocking findings are attached to the code below, collapsed.

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

rounded = ops.to_dtype(x, dtype, use_compute_types=False)
return ops.to_dtype(rounded, acc_dtype)

if isinstance(low, TensorBox):

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: a 0-d constant low crashes compilation. GraphLowering.get_attr (graph.py:1708-1720) returns a bare ir.Constant, not a TensorBox, for a 0-d tensor attribute (the default unless runtime constant folding, always_keep_tensor_constants, or a mutated named buffer applies). With type_promotion_kind=None and no broadcast, transform_args passes it through unchanged, so isinstance(low, TensorBox) is False and torch.tensor(\[low, high\], dtype=torch.float64) at line 3561 runs on IR nodes and raises. Hit by a module with register_buffer("low", torch.tensor(0.1)) passed as uniform(key, shape, low=self.low, ...) under config.freezing=True (AOTI likely too, inferred). Regression: the extern fallback handled Constant via ExternKernel.realize_input. Fix: branch on V.graph.current_node.target is aten._philox_uniform.Tensor or on isinstance(low, ir.IRNode); expand() already accepts ir.BaseConstant.

Report this finding


@register_lowering(philox_uniform_ops, type_promotion_kind=None)
def philox_uniform(self, key, low=0.0, high=1.0):
if not is_triton(key):

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 is_triton gate is broader than the devices eager supports. ir.is_triton is True for XPU by default (xpu_backend="triton"), CPU when cpu_backend="triton", and any device whose scheduler subclasses TritonScheduling, but eager _philox_uniform/philox_uniform only have CPU and CUDA kernels. On XPU/MTIA eager raises while compiled code silently returns values; on Triton-CPU the eager kernel computes x * (hi - lo) + lo without the FMA the lowering emits, so bits can differ. The new tests (only_for=("cpu","cuda")) cover none of this. Fix: use one shared predicate here and in fx_passes/reinplace.py:377-380: is_triton(device) and device.type == "cuda" (not a bare CUDA check, since cuda_backend="halide"/"pallas" would emit ops.philox_rand into backends that raise NotImplementedError). That helper is also the place for the fallback_random check.

Report this finding

return root.op == "call_function" and root.target in _FRESH_ALLOCATION_OPS


def should_reinplace_philox(node: torch.fx.Node) -> bool:

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: an existing GPU test now fails. test/inductor/test_inplacing_pass.py:694-715 test_reinplacement_canonicalizes_philox_result runs with device = GPU_TYPE and no skip, calls reinplace_inplaceable_ops_core (which ANDs in extra_check), and at line 705 asserts _philox_uniform.default was retargeted to philox_uniform.default. should_reinplace_philox returns False on CUDA and XPU, so the assertion fails under ciflow/inductor; the PR doesn't touch that file. Fix: switch the test to random.normal or random.randint, or assert that uniform is not reinplaced on Triton.

Report this finding


else:
# Computed here because Inductor's constant folding skips float32 rounding.
low_t, high_t = torch.tensor([low, high], dtype=torch.float64).to(dtype)

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.

⚪ Non-blocking: the scalar-bounds path doesn't use round_scalar_to_dtype. torch.tensor([low, high], dtype=torch.float64).to(dtype) is created with no…

Non-blocking: the scalar-bounds path doesn't use round_scalar_to_dtype. torch.tensor([low, high], dtype=torch.float64).to(dtype) is created with no device=, so it follows any ambient default-device context. The already-imported round_scalar_to_dtype (utils.py:997-1002) pins device="cpu" for exactly this reason (NOTE [torch.tensor, lift_fresh, and device movement]) and other lowerings use it. Use it for low and high, and keep the span as round(round(high) - round(low)).

Report this finding

def philox_uniform(self, key, low=0.0, high=1.0):
if not is_triton(key):
op = V.graph.current_node.target
return fallback_handler(op, add_to_fallback_set=False)(self, key, low, high)

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.

⚪ Non-blocking: the CPU fallback now bypasses the implicit-fallback path.

Calling fallback_handler(op, add_to_fallback_set=False) directly skips config.implicit_fallbacks and the tag-derived layout constraint that graph.py:1515-1556 applied to this op before. No correctness impact, but it is an undocumented behaviour change.

Report this finding

"""Computes inductor_prims.randint. offset has dtype int32."""
raise NotImplementedError

def philox_rand(self, seed: T, offset: T, idx: T, dtype: torch.dtype) -> T:

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.

⚪ Non-blocking: stale comments.

The reinplace comment at fx_passes/reinplace.py:621 and this OpsHandler.philox_rand docstring, which claims all philox* kernels match, are out of date.

Report this finding

return f"randint64_cpu({seed}, {offset}, {low}, {high})"

@staticmethod
def philox_rand(seed, offset, idx, dtype):

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.

⚪ Non-blocking: the NotImplementedError("philox_rand") stubs are duplicated in cpp.py and halide.py.

Report this finding

self.assertIn("triton_helpers.philox_rand", code[0])

@dtypes(*all_floating_dtypes)
def test_uniform_compiled_fused_matches_unfused(self, device, dtype):

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.

⚪ Non-blocking: four of the five new tests can't tell the lowering from the fallback. test_uniform_compiled_fused_matches_unfused, _dynamic,…

Non-blocking: four of the five new tests can't tell the lowering from the fallback. test_uniform_compiled_fused_matches_unfused, _dynamic, _emulate_precision_casts and _noncontig_inplace would pass unchanged with the extern kernel, which produces the same bits. Add the run_and_get_code / assertIn("triton_helpers.philox_rand", ...) check that test_uniform_compiled_exact uses.

Report this finding

# extra copy.
aten._philox_uniform.default: InplaceableOp(aten._philox_uniform_.default, 0),
aten._philox_uniform.default: InplaceableOp(
aten._philox_uniform_.default, 0, extra_check=should_reinplace_philox

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.

⚪ Non-blocking: some existing uniform coverage is stale on CUDA. test_generation_no_corruption_from_buffer_reuse (test_stateless_rng.py:1198-1214) uses…

Non-blocking: some existing uniform coverage is stale on CUDA. test_generation_no_corruption_from_buffer_reuse (test_stateless_rng.py:1198-1214) uses only uniform, so on CUDA it no longer exercises the in-place buffer-reuse regression it guards now that uniform isn't reinplaced on Triton. The same applies to the op=uniform case of test_generation_returned_directly_with_cudagraphs and the comment at line 1170.

Report this finding



@triton.jit
def philox_rand(seed, offset, idx, DIGITS: tl.constexpr):

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.

⚪ Non-blocking: the generated code repeats Philox work.

Each element calls tl.randint4x and keeps one lane 4x eager's Philox work (2x for fp64) and standalone generation pays it too now that reinplacing is off on Triton. The result isn't added to should_realize_on_reuse, so every consumer kernel reruns the 10 Philox rounds.

Report this finding

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

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests GL/human GreenLight marked as needing human review in progress PR is being worked on by the author, until the automated review accepts it module: inductor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants