Repository navigation
Conversation
PR Status: ready for maintainer reviewA maintainer requested changes. Please address their feedback and ask for another review. 🟡 AUTOMATED REVIEW - OUTDATED (earlier commit) - Changes requested:
Findings (6): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201883
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 5be46c4 with merge base 8bf2072 ( 🟡 GREEN LIGHT - PR requires human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
## Human Note ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack): - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale is still a constexpr with unchanged codegen. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they use `guard_scale`. It specializes a symbolic scale to a float with a value guard. `evaluate_expr` needs an explicit float hint here; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward gets the raw scale, declines it, and falls back to Triton. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU inference. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: one frame across sequence lengths. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: b8757e8 Pull-Request: #201883
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
## Human Note ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack): - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with `SizeVarAllocator.guard_float` (previous PR). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward gets the raw scale, declines it, and falls back to Triton. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: one frame across sequence lengths. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 470db2c Pull-Request: #201883
## Human Note ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack) and extends it to CuteDSL templates, which render a symbolic value as a host-side Python float and omit it from their constexpr `gen_defines()`: - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with the new `SizeVarAllocator.guard_float`, the float counterpart of `guard_int`. `evaluate_expr` needs an explicit float hint for that; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward gets the raw scale, declines it, and falls back to Triton. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: on GPU one frame across sequence lengths; on CPU and MPS the value guard recompiles per length and each result matches eager. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 7917982 Pull-Request: #201883
Withdrawn: the automated review of 21f53af found nothing blocking.
## Human Note ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack) and extends it to CuteDSL templates, which render a symbolic value as a host-side Python float and omit it from their constexpr `gen_defines()`: - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with the new `SizeVarAllocator.guard_float`, the float counterpart of `guard_int`. `evaluate_expr` needs an explicit float hint for that; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward gets the raw scale, declines it, and falls back to Triton. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: on GPU one frame across sequence lengths; on CPU and MPS the value guard recompiles per length and each result matches eager. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 2a81293 Pull-Request: #201883
## Human Note Change scale from baked in constexpr to runtime float ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack) and extends it to CuteDSL templates, which render a symbolic value as a host-side Python float and omit it from their constexpr `gen_defines()`: - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with the new `SizeVarAllocator.guard_float`, the float counterpart of `guard_int`. `evaluate_expr` needs an explicit float hint for that; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward gets the raw scale, declines it, and falls back to Triton. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: on GPU one frame across sequence lengths; on CPU and MPS the value guard recompiles per length and each result matches eager. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 27d05ad Pull-Request: #201883
There was a problem hiding this comment.
Automated review of ed78294: changes requested before human review.
This PR passes flex_attention's symbolic softmax scale to the Triton and CuteDSL FLASH templates as a host-computed RuntimeFloat. On CPU, MPS and FlyDSL forward it instead specializes the scale with a new SizeVarAllocator.guard_float. Recommendation: Request Changes, because of a FLASH NameError for math.* scales, a wrong FlyDSL backward comment with a silent Triton fallback, and missing or weak tests.
🔴 7 blocking findings are attached to the code below.
⚪ 3 non-blocking findings
pytorch/torch/_inductor/sizevars.py
Line 1044 in ed78294
guard_float gets its hint differently from guard_int. guard_float substitutes shape_env.backed_var_to_val directly. guard_int goes through guarding_hint_or_throw _guarding_hint_or_throw_base (torch/fx/experimental/_size_hinting.py:121-191), which first applies shape_env.replacements and the inverse precomputed replacements, and raises GuardOnDataDependentSymNode. As a result, an unbacked symbol that has a replacement raises here even though it can be resolved, and the error is NotImplementedError instead of the type the rest of Inductor handles. Fix: build the float hint on the same replacement handling.
pytorch/test/inductor/test_flex_flash.py
Line 2711 in ed78294
FLASH tests miss math.* printing. The float(<expr>) rendering is only tested with /, //, torch.sym_float and torch._sym_sqrt. Add a scale that prints through math.*; it would catch the NameError in cutedsl_kernel.py render.
Unneeded unwrap in render. Both FLASH callers (flex_attention.py:383 and :1061) already call unwrap_if_number(), so a numeric RuntimeFloat never reaches render. Fix: drop the second unwrap_if_number() so the contract is just "symbolic RuntimeFloat or plain value". If you keep it as a defensive check, say so in a comment.
Please address the findings and push; a new commit normally gets a fresh automated review.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
| val = val.unwrap_if_number() | ||
| if isinstance(val, RuntimeFloat): | ||
| expr = self.rename_indexing(sympy.sympify(val.value)) | ||
| kwargs[name] = f"float({PythonPrinter().doprint(expr)})" |
There was a problem hiding this comment.
🔴 FLASH fails with NameError for some scales. render prints the symbolic scale with PythonPrinter into the generated CuteDSL module, but gen_imports (:250-263) imports torch and not math. The from cutlass._mlir.dialects import math as mlir_math line does not bind math. PythonPrinter emits math.log2, math.floor, math.ceil, math.trunc, math.inf, the trig functions and more (torch/utils/_sympy/printers.py:178-333). Example: scale=1.0 / math.log2(x.shape\[1\]) renders float((1.0 / math.log2(ks0))), which fails when the kernel runs on FLASH. Triton works because it computes the scale in the wrapper, and the wrapper imports math. Fix: add import math to gen_imports, or compute the value in the wrapper as Triton does.
| logsumexp, | ||
| grad_out, | ||
| grad_logsumexp, | ||
| # FlyDSL declines a symbolic scale and falls back to Triton, which |
There was a problem hiding this comment.
🔴 The FlyDSL backward comment is wrong. It says the scale is left unspecialized so Triton can compute it at runtime. But _get_flydsl_flex_attention_backward_config first calls guard_int on every q/k/v/out/grad_out size and on both block sizes (flex_flydsl_backward.py:94-108). Only after that does float(scale) raise TypeError and decline (:109-111). So the shapes are already specialized when it falls back, and not guarding the scale saves no recompile. For the default 1/sqrt(D) scale, guarding would add no specialization anyway. Net effect: a user who sets BACKEND="FLYDSL" gets a FlyDSL forward (which uses guard_float at :310) and a silent Triton backward. Fix: pass V.graph.sizevars.guard_float(scale) here as the forward does, or move the scale check ahead of the guard_int calls and correct the comment.
| score_mod_other_buffers=score_mod_other_buffers, | ||
| mask_mod_other_buffers=mask_mod_other_buffers, | ||
| scale=scale, | ||
| scale=V.graph.sizevars.guard_float(scale), |
There was a problem hiding this comment.
🔴 No symbolic-scale tests for FlyDSL. test/inductor/test_flydsl_flex_attention.py covers neither the FlyDSL forward, which now goes through guard_float here, nor the FlyDSL backward fallback (:966).
| min_val = self.evaluate_min(left, right) | ||
| return right if min_val is left else left | ||
|
|
||
| def guard_float(self, expr: Expr | float) -> float: |
There was a problem hiding this comment.
🔴 No direct unit test for SizeVarAllocator.guard_float. The CPU/MPS flex tests only exercise it indirectly. The non-Expr path, the data-dependent NotImplementedError branch and the explicit float hint are never tested on their own.
| for q_len, kv_len in ((4, 512), (8, 1024)): | ||
| q = torch.randn(1, q_len, 256, device=device, dtype=torch.float16) | ||
| kv = torch.randn(1, kv_len, 256, device=device, dtype=torch.float16) | ||
| out, (code, *_) = run_and_get_code(compiled, q, kv) |
There was a problem hiding this comment.
🔴 The decode test never checks the "one graph serves every value" claim. test_dynamic_shapes_symbolic_scale calls run_and_get_code on every iteration, and that calls torch._dynamo.reset() (torch/_inductor/utils.py:3620). So each length compiles from scratch. A regression that specialized the scale per length would still pass, and only the last compile's code is FileChecked. Fix: compile once with CompileCounterWithBackend, assert frame_count == 1, and capture the code only on the first call.
| @skip_on_cpu | ||
| @expected_not_implemented_on_mps # no backward | ||
| @config.patch({"graph_partition": True, "triton.cudagraphs": True}) | ||
| def test_dynamic_scale_from_unrelated_tensor_graph_partition(self, device): |
There was a problem hiding this comment.
🔴 The graph-partition tests don't count frames (here and in test_flex_flash.py test_dynamic_scale_from_unrelated_tensor_graph_partition). The test asserts no frame count, so silently specializing on y.shape\[0\] would still pass. Compile with CompileCounterWithBackend and assert frame_count == 1.
| self.assertLessEqual(flash_error, 2 * triton_error + atol) | ||
|
|
||
| @torch._inductor.config.patch({"graph_partition": True, "triton.cudagraphs": True}) | ||
| def test_dynamic_scale_from_unrelated_tensor_graph_partition(self): |
There was a problem hiding this comment.
🔴 The graph-partition test doesn't count frames. test_dynamic_scale_from_unrelated_tensor_graph_partition asserts no frame count, so silently specializing on y.shape\[0\] would still pass. Compile with CompileCounterWithBackend and assert frame_count == 1.
## Human Note Change scale from baked in constexpr to runtime float ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack) and extends it to CuteDSL templates, which render a symbolic value as a host-side Python float (the generated module now imports `math`, which the printer can emit) and omit it from their constexpr `gen_defines()`: - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with the new `SizeVarAllocator.guard_float`, the float counterpart of `guard_int`. `evaluate_expr` needs an explicit float hint for that; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward uses `guard_float` too, like its forward. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: on GPU one frame across sequence lengths; on CPU and MPS the value guard recompiles per length and each result matches eager. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH (one frame). - The FLASH runtime-scale test includes a `1 / math.log2(S)` scale, which fails without the `math` import. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 6ca6d05 Pull-Request: #201883
## Human Note Change scale from baked in constexpr to runtime float ## Agent note This PR was authored with an AI assistant (Claude). Fixes #201759. Under `torch.compile(dynamic=True)`, flex_attention's default `scale = 1/sqrt(query.size(-1))` reaches the Inductor lowering as a sympy float expression, e.g. `FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28))))`. The head dim is already static, but sympy cannot prove `s53 // (s53 // s28) == 64`, so the expression stays symbolic. - Triton: the templates emitted it as `SM_SCALE : tl.constexpr = FloatTrueDiv(...)`, so the generated module raised `NameError: FloatTrueDiv`. - CPU: the C++ template failed to compile (`'s53' was not declared`). This PR passes the scale as `RuntimeFloat` (previous PR in this stack) and extends it to CuteDSL templates, which render a symbolic value as a host-side Python float (the generated module now imports `math`, which the printer can emit) and omit it from their constexpr `gen_defines()`: - Triton forward, backward and decode, and FLASH forward and backward, compute a symbolic scale on the host. One graph then serves every value. For example, `scale=8.0 / x.shape[1]` now compiles once and serves every sequence length (before, it hit the same NameError). A numeric scale stays a plain float in `kernel_options`, so it is still a constexpr with unchanged codegen and `choices` overrides see the same value as before. - The three `PRESCALE_QK` sites use `tl.cast(SM_SCALE, x.dtype)`. This keeps today's rounding for both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the bf16 product. - CPU, MPS and FlyDSL forward bake the scale in, so they specialize a symbolic scale with the new `SizeVarAllocator.guard_float`, the float counterpart of `guard_int`. `evaluate_expr` needs an explicit float hint for that; without one it guards `scale == 0` (#201817). For the default scale the guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale recompiles per value on those backends; it failed before. FlyDSL backward uses `guard_float` too, like its forward. ## Test Plan New tests: - `test_dynamic_shapes_symbolic_default_scale`: the issue pattern, including CPU and MPS inference. - `test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]`: the decode template. - `test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]`: on GPU one frame across sequence lengths; on CPU and MPS the value guard recompiles per length and each result matches eager. - `test_prescale_qk_scale[dynamic]`. - `test_dynamic_scale_from_unrelated_tensor_graph_partition`, for Triton and FLASH (one frame). - The FLASH runtime-scale test includes a `1 / math.log2(S)` scale, which fails without the `math` import. - `TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime`. The NameError and frame-count tests fail without this PR, including the decode test. The static `test_prescale_qk_scale` case fails if the casts are written as `SM_SCALE.to(x.dtype)`, because a constexpr float has no `.to`. The graph-partition tests (Triton and FLASH) fail with the `TemplateBuffer` symbol tracking from the previous PR removed. ```bash python -m pytest test/inductor/test_flex_attention.py test/inductor/test_flex_decoding.py -n 16 python -m pytest test/inductor/test_flex_flash.py -n 16 ``` On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed, 10 skipped. Other validation: - **x86 CPU:** a nightly with this patch overlaid. Default scale under `dynamic=True` matches fp64 eager with 2 frames (only the head-dim change). The CPU part of `test_flex_attention.py` has no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on base. - **H100:** full flex attention, decoding and FLASH suites. The 3 failures also fail on base or pass when run alone. - **GB200 stress:** max-autotune with and without cudagraphs (autotune benchmarks get the correct float scale), decode, cpp_wrapper, an AOTI package from strict export, `fx_wrapper`, and graph partitions. - **Performance:** runtime vs constexpr `SM_SCALE` in the same kernels is within +/-2% fwd and bwd across 14 configs on GB200 (`triton.testing.do_bench` median). The SASS differs only in an immediate vs a uniform-register operand. ghstack-source-id: 17e020c Pull-Request: #201883
Stack from ghstack (oldest at bottom):
Human Note
Change scale from baked in constexpr to runtime float
Agent note
This PR was authored with an AI assistant (Claude).
Fixes #201759.
Under
torch.compile(dynamic=True), flex_attention's defaultscale = 1/sqrt(query.size(-1))reaches the Inductor lowering as a sympy float expression, e.g.
FloatTrueDiv(1.0, OpaqueUnaryFn_sqrt(ToFloat(s53 // (s53 // s28)))). The head dim is alreadystatic, but sympy cannot prove
s53 // (s53 // s28) == 64, so the expression stays symbolic.SM_SCALE : tl.constexpr = FloatTrueDiv(...), so thegenerated module raised
NameError: FloatTrueDiv.'s53' was not declared).This PR passes the scale as
RuntimeFloat(previous PR in this stack) and extends it to CuteDSLtemplates, which render a symbolic value as a host-side Python float (the generated module now
imports
math, which the printer can emit) and omit it from their constexprgen_defines():on the host. One graph then serves every value. For example,
scale=8.0 / x.shape[1]nowcompiles once and serves every sequence length (before, it hit the same NameError). A numeric
scale stays a plain float in
kernel_options, so it is still a constexpr with unchanged codegenand
choicesoverrides see the same value as before.PRESCALE_QKsites usetl.cast(SM_SCALE, x.dtype). This keeps today's roundingfor both a constexpr and a runtime fp32 scale; without the cast, the fp32 scalar promotes the
bf16 product.
SizeVarAllocator.guard_float, the float counterpart ofguard_int.evaluate_exprneeds anexplicit float hint for that; without one it guards
scale == 0(ShapeEnv.evaluate_expr truncates float expressions to int when no hint is given #201817). For the default scalethe guard is implied by the existing head-dim specialization, so it adds no recompiles. A sequence-length-dependent scale
recompiles per value on those backends; it failed before. FlyDSL backward uses
guard_floattoo, like its forward.
Test Plan
New tests:
test_dynamic_shapes_symbolic_default_scale: the issue pattern, including CPU and MPS inference.test_flex_decoding.py::test_dynamic_shapes_symbolic_scale[prescale_qk]: the decode template.test_dynamic_shapes_symbolic_scale_is_runtime[cpp_wrapper]: on GPU one frame across sequencelengths; on CPU and MPS the value guard recompiles per length and each result matches eager.
test_prescale_qk_scale[dynamic].test_dynamic_scale_from_unrelated_tensor_graph_partition, for Triton and FLASH (one frame).1 / math.log2(S)scale, which fails without themathimport.
TestFlexFlashDynamicShapes.test_dynamic_symbolic_scale_is_runtime.The NameError and frame-count tests fail without this PR, including the decode test. The static
test_prescale_qk_scalecasefails if the casts are written as
SM_SCALE.to(x.dtype), because a constexpr float has no.to.The graph-partition tests (Triton and FLASH) fail with the
TemplateBuffersymbol tracking fromthe previous PR removed.
On GB200 the first command gave 1397 passed, 78 skipped, 3 xfailed, and the second 255 passed,
10 skipped.
Other validation:
dynamic=Truematchesfp64 eager with 2 frames (only the head-dim change). The CPU part of
test_flex_attention.pyhas no new failures. First compile was 15.20 s here vs 15.47 s for an explicit-float scale on
base.
pass when run alone.
correct float scale), decode, cpp_wrapper, an AOTI package from strict export,
fx_wrapper,and graph partitions.
SM_SCALEin the same kernels is within +/-2% fwd and bwdacross 14 configs on GB200 (
triton.testing.do_benchmedian). The SASS differs only in animmediate vs a uniform-register operand.