Repository navigation
Introduce Inductor lowering for stateless RNG uniform - #204307
jbschlosser wants to merge 17 commits into
Conversation
[ghstack-poisoned]
PR Status: in progressPlease 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:
Findings (12): Reviewed commit: 🔗 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 FailuresAs of commit b99aa43 with merge base bcff2f4 ( 🟡 GREEN LIGHT - PR requires human review:
reason: 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:
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. |
This PR needs a
|
[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]
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
🔴 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.
|
|
||
| @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): |
There was a problem hiding this comment.
🔴 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.
| return root.op == "call_function" and root.target in _FRESH_ALLOCATION_OPS | ||
|
|
||
|
|
||
| def should_reinplace_philox(node: torch.fx.Node) -> bool: |
There was a problem hiding this comment.
🔴 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.
|
|
||
| else: | ||
| # Computed here because Inductor's constant folding skips float32 rounding. | ||
| low_t, high_t = torch.tensor([low, high], dtype=torch.float64).to(dtype) |
There was a problem hiding this comment.
⚪ 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)).
| 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) |
There was a problem hiding this comment.
⚪ 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.
| """Computes inductor_prims.randint. offset has dtype int32.""" | ||
| raise NotImplementedError | ||
|
|
||
| def philox_rand(self, seed: T, offset: T, idx: T, dtype: torch.dtype) -> T: |
There was a problem hiding this comment.
⚪ 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.
| return f"randint64_cpu({seed}, {offset}, {low}, {high})" | ||
|
|
||
| @staticmethod | ||
| def philox_rand(seed, offset, idx, dtype): |
There was a problem hiding this comment.
⚪ Non-blocking: the NotImplementedError("philox_rand") stubs are duplicated in cpp.py and halide.py.
| self.assertIn("triton_helpers.philox_rand", code[0]) | ||
|
|
||
| @dtypes(*all_floating_dtypes) | ||
| def test_uniform_compiled_fused_matches_unfused(self, device, dtype): |
There was a problem hiding this comment.
⚪ 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.
| # 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 |
There was a problem hiding this comment.
⚪ 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.
|
|
||
|
|
||
| @triton.jit | ||
| def philox_rand(seed, offset, idx, DIGITS: tl.constexpr): |
There was a problem hiding this comment.
⚪ 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.
Stack from ghstack (oldest at bottom):
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo