Skip to content

[cutedsl] Fix the full host sum's fallback and its divisor's reciprocal - #4816

Merged
choijon5 merged 1 commit into
mainfrom
choijon5/cute-norm-bwd/6
Nov 29, 2026
Merged

choijon5 merged 1 commit into
mainfrom
choijon5/cute-norm-bwd/6

Conversation

@choijon5

@choijon5 choijon5 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[cutedsl] Fix the full host sum's fallback and its divisor's reciprocal

For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and
rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as
layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe
backend.

Kernels: none gets faster; two fixes to what runs when the helper of a full
host sum declines, which it does on every Torch build but the audited one.
Under cute_host_paired_sum "mapped" or "narrow", a kernel whose host tail
assigns a full sum to the name of its operand (out = torch.sum(out)) or of
its divisor (n = torch.sum(out) / n) raised a TypeError, and a scaled sum
(torch.sum(out) / x.size(0)) evaluated its divisor twice. A third fix is
to the helper's own arithmetic: it multiplied by another reciprocal than
ATen does for divisors such as 1.1.

Regression check for attention, which was hillclimbed before this stack:
the 12 pull requests of this stack together (#4811 to #4822) against plain
main (74ac871), on a B200.

  • Generated code, rendered on CPU for the B200 target: all 1,298 configs
    that main renders for 145 attention cases generate the same source with
    the stack, and no seed list changes. The cases are the kernels of
    examples/attention.py (forward and backward), flex_attention.py,
    blackwell_attention.py and fp8_attention.py, and of
    benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs
    are each case's default and every compiler seed.
  • The same with the attention stack ([testing] Time the long-kernel probe test against the traced call itself #4797 to [cutedsl] Run the plain causal flash pair in the persistent work-item loop #4810) under both sides: 759
    forward and 626 backward and attention-gym configs (defaults, seeds,
    pinned configs), 7,493 more configs that the search reaches on 12
    forward cases (one knob changed at a time, random draws) and 3,861 with
    random draws on the backward and attention-gym kernels generate the same
    source with and without this stack, and the 11 kernels compiled on the
    GPU (the eight forward shapes below and three fp8 attention inputs) have
    the same MLIR bytecode.
  • Time: the eight forward shapes of examples/attention.py (dense and
    causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned
    configs, with and without this stack, interleaved, a new process for
    every reading, 4 to 8 rounds a shape. The best readings with the stack
    are 0.994 to 1.007 times those without. On this power-capped GPU every
    implementation, cuDNN SDPA included, reads one of two levels 3 to 5%
    apart from process to process; both sides read the same two levels.

With "mapped" or "narrow" a full host sum goes to a runtime helper
(try_full_sum), and the original statement runs when the helper returns
None. Two things kept that statement from running as it was written.

Its operand. The rewrite assigned the helper's answer to the statement's
target:

out = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
if out is None:
    out = torch.sum(out)

so the fallback read None where the statement reads its target.
lower_host_full_sum now gives the answer a name of its own for such a
statement and assigns the target from it when the helper answered:

_helion_full_sum = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
if _helion_full_sum is None:
    out = torch.sum(out)
else:
    out = _helion_full_sum

Its divisor. The call took the divisor as an argument
(divisor=x.size(0)), so every call evaluated it before the helper
decided, and the fallback of a declined call evaluated it again. The proof
admits tensor metadata in a divisor (x.size(0), x.numel(),
x.shape[0]) and called that safe to evaluate twice. A function mode of
the caller sees those calls, and so does a tensor subclass with
__torch_function__: on a declined call each saw one more than the
statement makes, ahead of the sum, where the helper's rule is that a
declined call leaves the exact original call. This predates the stack
(d32e9ca, the divisor support). The site now hands the divisor over as a
function,

total = _cute_try_full_sum(out, mean=False, divisor_fn=lambda: x.size(0),
                           _launcher=_launcher)

and try_full_sum does not call it on a build whose sums it declines, nor
under a function or dispatch mode of the caller. There the statement
evaluates its divisor once, in its own order: that is every build but the
audited one, and every call under a mode. Replayed on CPU over an operand
that records the reads of its size, a declined call reads it twice at
origin/main (before the helper and in the fallback) and once here.

Otherwise, on the audited build, the helper calls the function where the
argument was evaluated, ahead of its proofs, so those calls behave as they
did: a call that the helper answers has evaluated the divisor before the
sum, and a call that its proofs decline has evaluated it once before the
statement does so again. KNOWN_GAPS.md records that
(cute-full-sum-evaluates-its-divisor-early). Calling the function after the
proofs instead would let the divisor's code invalidate them before the
launch (the operand's storage, device or length), so they would have to run
a second time on each answered call, and the sum would still be read after
the divisor. Both forms are reproduced on the audited build (Testing), which
no CI job runs.

The reciprocal. The helper's kernel multiplies the sum by a factor, and
_reciprocal_factor computed it as one over the divisor's FP32 value, in
FP32. That was ATen's formula until pytorch/pytorch#169507 (December 2025).
Since then div_true_kernel_cuda takes the reciprocal in FP64 and narrows
it,

inv_b = static_cast<opmath_t>(
    high_prec_t(1.0) / iter.scalar_value<high_prec_t>(2));

with high_prec_t = double, and multiplies in FP32 (MulFunctor<opmath_t>):
aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu at the audited revision
(PyTorch main 6d5f66bd5b) and at both earlier pins (a970aa8b98,
e2dee2a4b9). The pins' audit covered the reduction sources, not this
kernel; the pin's comment in helion/runtime/cute/paired_sum.py now names it
for the next one.
The two reciprocals differ for a divisor that is no FP32 number of at most
24 bits: for 1.1 ATen multiplies by 0.9090909361839294 and the helper by
0.9090908765792847. So on the one build where the helper answers, a scaled
sum could differ from the statement in its last bits; the divisors of the
existing tests (3, 7, 0.25, 1037, row counts) are FP32 numbers, for which
both agree. Measured on a B200 with torch 2.15.0+cu132, which has the same
kernel: of 40000 random float divisors 10536 tell the two apart, of 25000
random int divisors 5997, and on 300 of each ATen's quotient of an FP32
one was the narrowed FP64 reciprocal every time. On the audited build
itself the helper's scaled sum of 4096 random FP32 numbers differed from
the statement's for 1418 of 2400 sums at the parent commit (400 tensors by
the divisors 1.1, 0.03, 16.1, 2**24 + 1, 3 and 1037), and for none here.
_reciprocal_factor now takes the reciprocal that way. Two more things
about the value it reads:

  • Of an instance of a subclass of int or float it reads the value that
    the instance stores (int.__index__, float.__float__), which is the
    value ATen divides by (it takes the stored double of whatever passes
    PyFloat_Check, and an int's digits). It asked float() of the
    instance, which a subclass may answer with another value.
  • It takes an int from -263 up to 264, the integers that ATen wraps
    (measured: it raises for -(263) - 1 and for 264). The helper had a
    reciprocal for every int that float() converts, so it answered where
    the statement raises; such a divisor now declines.

try_full_sum keeps divisor, the value, next to divisor_fn: a
standalone file that helion/autotuner/aot_compile.py wrote before this
change passes it, and keeps the behavior it had.

The tests of this rewrite read generated host code, yet five of them were
skipped on every build but the audited one, and the module ran in the GPU
lane. test/test_cute_host_full_sum.py is now a cpu_only module that
renders on CPU: its codegen tests run on every build, without a GPU, and
its cuda items run on the device; those of them that launch the helper's
kernel still need the audited build. The device half of the helper's
decline test is a cuda item of its own, which now holds the rank case as
a tensor that passes every other proof. The short-tensor fallback test,
whose sum the helper declines on every build, no longer asks for the
audited one.

Compatibility: CuTe only. Generated host code changes for a full sum whose
statement reads its target (the answer's own name; a later site of that
kernel that needs a name of its own takes the next free one) and for a
scaled sum (divisor_fn=lambda: ... where it had divisor=...). Other
kernels render as before. On the audited build a scaled sum that the helper
answers is multiplied by the reciprocal that ATen multiplies by, which
changes its last bits for divisors that are no FP32 numbers of at most 24
bits; a divisor that is an instance of a subclass of int or float is
taken by the value it stores, and an int that ATen raises for is left to
the statement.

Tests (test/test_cute_host_full_sum.py):

  • The two rebinding forms render the answer under its own name; the
    rendered statements, run on CPU with a stand-in helper, leave the
    original statement's result when it declines and its answer when it does
    not (one render per kernel).
  • The rendered statements of a scaled sum, replayed from the render that
    the existing divisor test makes, over an operand that counts the reads
    of its size: one read whether the stand-in helper declines or answers.
  • The helper on CPU: with the build declined, or under a function, a
    dispatch or a device mode, it does not read a divisor function; with the
    build admitted and no mode it reads it once before a proof declines the
    call (the known gap's second form, which the test pins); the reciprocal
    of plain numbers, of 1.1 and 254 + 230 + 1 (which tell the formulas
    apart), of -263, 263 and 264 - 1, of a float subclass whose
    float() doubles its value and of an int subclass whose float() and
    index add one; none for a bool, a tensor, a string, a complex number,
    -(2
    63) - 1, 2**64 and 1 << 80.
  • The helper on the device with a stand-in launcher, so on every build:
    a divisor function is read once and gives the same launch as the value;
    the two subclasses launch with the reciprocal of what they store; a
    tensor or bool divisor and a mean with a divisor decline, as do the
    tensors the helper does not take (short, misaligned, strided, rank-2,
    fp16, grad-requiring).
  • On the audited build (skipped elsewhere): for 19 divisors (1.1, 0.03,
    16.1, 224 + 1, 254 + 230 + 1, 263 + 240 + 1, 1e300, 1e-300,
    both zeros and the two subclasses among them) ATen's quotient of one is
    the factor, and its quotient of 4096 random numbers is their FP32
    product with the factor; ATen raises for -(2
    63) - 1 and 264. The
    test of the helper's own kernel on divisors gets 1.1 and 2
    24 + 1.
  • On the device both rebinding kernels, with a sum the helper declines on
    every build, return what the original statements compute.

Testing: B200, CUDA 13.2. On the audited build (torch
2.16.0.dev20261026+cu130, in a scratch environment), the six test modules
of the host sum helpers on both lanes with GPU 6
(test_cute_host_full_sum.py, test_cute_paired_sum_runtime.py,
test_cute_single_sum_runtime.py, test_cute_host_paired_sum_abi.py,
test_cute_host_single_sum_abi.py, test_cute_sum_tree_admission.py): GPU
lane 38 passed, CPU lane 201 passed, none skipped, so the helper's kernel
ran its tests, the ATen comparison of the reciprocal among them. The known
gap's forms, run there: an answered call whose divisor function zeroes the
operand returns 0 where the statement gives 64; a call on a CPU, a strided
or an fp16 tensor reads its divisor once and declines; under a device mode
the divisor is not read. On torch 2.15.0+cu132, which the lanes of this
stack run on, scripts/run_tests.py --backend cute --gpus 4 test/test_cute_host_full_sum.py: GPU lane 4 passed, 34 skipped (the tests
that need the audited build); CPU lane 18 passed. test/test_autoreview.py,
which checks the form of the entries of KNOWN_GAPS.md: 157 passed. With
the lowering and the helper of the parent commit, the tests of the
rebinding forms, of the scaled sum's rendered call and reads and of the
reciprocal fail. ./lint.sh check passes. Lanes at the tip of the stack,
which holds this commit, on origin/main 9a31efc: scripts/run_tests.py --backend cute --gpus 0,4, CPU lane 27430 passed, 689 skipped, 1 failed
(test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition,
which fails at 9a31efc as well); GPU lane 16014 passed, 2384 skipped, 3
failed on a timeout while other suites loaded the machine
(test_cute_standalone.py::test_native_source_edit_without_helion,
test_examples.py::TestExamples::test_linear_monkeypatch_gated_delta_rule,
test_handoff_bundle.py::test_namedtuple_bundle_replays_in_fresh_process) and
passed when run again alone. scripts/run_tests.py --backend triton --gpus 1,4, GPU lane 3408 passed, 2411 skipped, 2 failed
(test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and
::test_task_accumulators_get_their_own_rings, which fail at 9a31efc as
well); CPU lane 5168 passed, 632 skipped.

Review notes:

  • Deferred: "an answered call evaluates the divisor before the sum" and "a
    call that evaluated the divisor can still decline". KNOWN_GAPS.md,
    cute-full-sum-evaluates-its-divisor-early. At origin/main (f615a9b) the
    rendered call is divisor=x.size(0): the replay above reads the divisor
    before the helper on every call and again in the fallback of every
    declined one, on every build. This commit leaves both forms on the
    audited build as they were, outside a mode of the caller, and removes
    the second on every other build and under such a mode.
  • Not taken: "run the proofs again after the divisor". The helper calls the
    function ahead of its proofs, where the argument was evaluated, so the
    divisor's code cannot invalidate a proof that already ran.

autoreview passed: claude, codex

For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and
rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as
layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe
backend.

Kernels: none gets faster; two fixes to what runs when the helper of a full
host sum declines, which it does on every Torch build but the audited one.
Under `cute_host_paired_sum` "mapped" or "narrow", a kernel whose host tail
assigns a full sum to the name of its operand (`out = torch.sum(out)`) or of
its divisor (`n = torch.sum(out) / n`) raised a TypeError, and a scaled sum
(`torch.sum(out) / x.size(0)`) evaluated its divisor twice. A third fix is
to the helper's own arithmetic: it multiplied by another reciprocal than
ATen does for divisors such as 1.1.

Regression check for attention, which was hillclimbed before this stack:
the 12 pull requests of this stack together (#4811 to #4822) against plain
main (74ac871), on a B200.
- Generated code, rendered on CPU for the B200 target: all 1,298 configs
  that main renders for 145 attention cases generate the same source with
  the stack, and no seed list changes. The cases are the kernels of
  examples/attention.py (forward and backward), flex_attention.py,
  blackwell_attention.py and fp8_attention.py, and of
  benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs
  are each case's default and every compiler seed.
- The same with the attention stack (#4797 to #4810) under both sides: 759
  forward and 626 backward and attention-gym configs (defaults, seeds,
  pinned configs), 7,493 more configs that the search reaches on 12
  forward cases (one knob changed at a time, random draws) and 3,861 with
  random draws on the backward and attention-gym kernels generate the same
  source with and without this stack, and the 11 kernels compiled on the
  GPU (the eight forward shapes below and three fp8 attention inputs) have
  the same MLIR bytecode.
- Time: the eight forward shapes of examples/attention.py (dense and
  causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned
  configs, with and without this stack, interleaved, a new process for
  every reading, 4 to 8 rounds a shape. The best readings with the stack
  are 0.994 to 1.007 times those without. On this power-capped GPU every
  implementation, cuDNN SDPA included, reads one of two levels 3 to 5%
  apart from process to process; both sides read the same two levels.

With "mapped" or "narrow" a full host sum goes to a runtime helper
(`try_full_sum`), and the original statement runs when the helper returns
None. Two things kept that statement from running as it was written.

Its operand. The rewrite assigned the helper's answer to the statement's
target:

    out = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if out is None:
        out = torch.sum(out)

so the fallback read None where the statement reads its target.
`lower_host_full_sum` now gives the answer a name of its own for such a
statement and assigns the target from it when the helper answered:

    _helion_full_sum = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if _helion_full_sum is None:
        out = torch.sum(out)
    else:
        out = _helion_full_sum

Its divisor. The call took the divisor as an argument
(`divisor=x.size(0)`), so every call evaluated it before the helper
decided, and the fallback of a declined call evaluated it again. The proof
admits tensor metadata in a divisor (`x.size(0)`, `x.numel()`,
`x.shape[0]`) and called that safe to evaluate twice. A function mode of
the caller sees those calls, and so does a tensor subclass with
`__torch_function__`: on a declined call each saw one more than the
statement makes, ahead of the sum, where the helper's rule is that a
declined call leaves the exact original call. This predates the stack
(d32e9ca, the divisor support). The site now hands the divisor over as a
function,

    total = _cute_try_full_sum(out, mean=False, divisor_fn=lambda: x.size(0),
                               _launcher=_launcher)

and `try_full_sum` does not call it on a build whose sums it declines, nor
under a function or dispatch mode of the caller. There the statement
evaluates its divisor once, in its own order: that is every build but the
audited one, and every call under a mode. Replayed on CPU over an operand
that records the reads of its size, a declined call reads it twice at
origin/main (before the helper and in the fallback) and once here.

Otherwise, on the audited build, the helper calls the function where the
argument was evaluated, ahead of its proofs, so those calls behave as they
did: a call that the helper answers has evaluated the divisor before the
sum, and a call that its proofs decline has evaluated it once before the
statement does so again. KNOWN_GAPS.md records that
(cute-full-sum-evaluates-its-divisor-early). Calling the function after the
proofs instead would let the divisor's code invalidate them before the
launch (the operand's storage, device or length), so they would have to run
a second time on each answered call, and the sum would still be read after
the divisor. Both forms are reproduced on the audited build (Testing), which
no CI job runs.

The reciprocal. The helper's kernel multiplies the sum by a factor, and
`_reciprocal_factor` computed it as one over the divisor's FP32 value, in
FP32. That was ATen's formula until pytorch/pytorch#169507 (December 2025).
Since then `div_true_kernel_cuda` takes the reciprocal in FP64 and narrows
it,

    inv_b = static_cast<opmath_t>(
        high_prec_t(1.0) / iter.scalar_value<high_prec_t>(2));

with `high_prec_t = double`, and multiplies in FP32 (`MulFunctor<opmath_t>`):
aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu at the audited revision
(PyTorch main 6d5f66bd5b) and at both earlier pins (a970aa8b98,
e2dee2a4b9). The pins' audit covered the reduction sources, not this
kernel; the pin's comment in helion/runtime/cute/paired_sum.py now names it
for the next one.
The two reciprocals differ for a divisor that is no FP32 number of at most
24 bits: for 1.1 ATen multiplies by 0.9090909361839294 and the helper by
0.9090908765792847. So on the one build where the helper answers, a scaled
sum could differ from the statement in its last bits; the divisors of the
existing tests (3, 7, 0.25, 1037, row counts) are FP32 numbers, for which
both agree. Measured on a B200 with torch 2.15.0+cu132, which has the same
kernel: of 40000 random `float` divisors 10536 tell the two apart, of 25000
random `int` divisors 5997, and on 300 of each ATen's quotient of an FP32
one was the narrowed FP64 reciprocal every time. On the audited build
itself the helper's scaled sum of 4096 random FP32 numbers differed from
the statement's for 1418 of 2400 sums at the parent commit (400 tensors by
the divisors 1.1, 0.03, 16.1, 2**24 + 1, 3 and 1037), and for none here.
`_reciprocal_factor` now takes the reciprocal that way. Two more things
about the value it reads:
- Of an instance of a subclass of `int` or `float` it reads the value that
  the instance stores (`int.__index__`, `float.__float__`), which is the
  value ATen divides by (it takes the stored double of whatever passes
  `PyFloat_Check`, and an `int`'s digits). It asked `float()` of the
  instance, which a subclass may answer with another value.
- It takes an `int` from -2**63 up to 2**64, the integers that ATen wraps
  (measured: it raises for -(2**63) - 1 and for 2**64). The helper had a
  reciprocal for every `int` that `float()` converts, so it answered where
  the statement raises; such a divisor now declines.

`try_full_sum` keeps `divisor`, the value, next to `divisor_fn`: a
standalone file that helion/autotuner/aot_compile.py wrote before this
change passes it, and keeps the behavior it had.

The tests of this rewrite read generated host code, yet five of them were
skipped on every build but the audited one, and the module ran in the GPU
lane. test/test_cute_host_full_sum.py is now a `cpu_only` module that
renders on CPU: its codegen tests run on every build, without a GPU, and
its `cuda` items run on the device; those of them that launch the helper's
kernel still need the audited build. The device half of the helper's
decline test is a `cuda` item of its own, which now holds the rank case as
a tensor that passes every other proof. The short-tensor fallback test,
whose sum the helper declines on every build, no longer asks for the
audited one.

Compatibility: CuTe only. Generated host code changes for a full sum whose
statement reads its target (the answer's own name; a later site of that
kernel that needs a name of its own takes the next free one) and for a
scaled sum (`divisor_fn=lambda: ...` where it had `divisor=...`). Other
kernels render as before. On the audited build a scaled sum that the helper
answers is multiplied by the reciprocal that ATen multiplies by, which
changes its last bits for divisors that are no FP32 numbers of at most 24
bits; a divisor that is an instance of a subclass of `int` or `float` is
taken by the value it stores, and an `int` that ATen raises for is left to
the statement.

Tests (test/test_cute_host_full_sum.py):
- The two rebinding forms render the answer under its own name; the
  rendered statements, run on CPU with a stand-in helper, leave the
  original statement's result when it declines and its answer when it does
  not (one render per kernel).
- The rendered statements of a scaled sum, replayed from the render that
  the existing divisor test makes, over an operand that counts the reads
  of its size: one read whether the stand-in helper declines or answers.
- The helper on CPU: with the build declined, or under a function, a
  dispatch or a device mode, it does not read a divisor function; with the
  build admitted and no mode it reads it once before a proof declines the
  call (the known gap's second form, which the test pins); the reciprocal
  of plain numbers, of 1.1 and 2**54 + 2**30 + 1 (which tell the formulas
  apart), of -2**63, 2**63 and 2**64 - 1, of a `float` subclass whose
  `float()` doubles its value and of an `int` subclass whose `float()` and
  index add one; none for a `bool`, a tensor, a string, a complex number,
  -(2**63) - 1, 2**64 and 1 << 80.
- The helper on the device with a stand-in launcher, so on every build:
  a divisor function is read once and gives the same launch as the value;
  the two subclasses launch with the reciprocal of what they store; a
  tensor or `bool` divisor and a mean with a divisor decline, as do the
  tensors the helper does not take (short, misaligned, strided, rank-2,
  fp16, grad-requiring).
- On the audited build (skipped elsewhere): for 19 divisors (1.1, 0.03,
  16.1, 2**24 + 1, 2**54 + 2**30 + 1, 2**63 + 2**40 + 1, 1e300, 1e-300,
  both zeros and the two subclasses among them) ATen's quotient of one is
  the factor, and its quotient of 4096 random numbers is their FP32
  product with the factor; ATen raises for -(2**63) - 1 and 2**64. The
  test of the helper's own kernel on divisors gets 1.1 and 2**24 + 1.
- On the device both rebinding kernels, with a sum the helper declines on
  every build, return what the original statements compute.

Testing: B200, CUDA 13.2. On the audited build (torch
2.16.0.dev20261026+cu130, in a scratch environment), the six test modules
of the host sum helpers on both lanes with GPU 6
(test_cute_host_full_sum.py, test_cute_paired_sum_runtime.py,
test_cute_single_sum_runtime.py, test_cute_host_paired_sum_abi.py,
test_cute_host_single_sum_abi.py, test_cute_sum_tree_admission.py): GPU
lane 38 passed, CPU lane 201 passed, none skipped, so the helper's kernel
ran its tests, the ATen comparison of the reciprocal among them. The known
gap's forms, run there: an answered call whose divisor function zeroes the
operand returns 0 where the statement gives 64; a call on a CPU, a strided
or an fp16 tensor reads its divisor once and declines; under a device mode
the divisor is not read. On torch 2.15.0+cu132, which the lanes of this
stack run on, `scripts/run_tests.py --backend cute --gpus 4
test/test_cute_host_full_sum.py`: GPU lane 4 passed, 34 skipped (the tests
that need the audited build); CPU lane 18 passed. test/test_autoreview.py,
which checks the form of the entries of KNOWN_GAPS.md: 157 passed. With
the lowering and the helper of the parent commit, the tests of the
rebinding forms, of the scaled sum's rendered call and reads and of the
reciprocal fail. `./lint.sh check` passes. Lanes at the tip of the stack,
which holds this commit, on origin/main 9a31efc: `scripts/run_tests.py
--backend cute --gpus 0,4`, CPU lane 27430 passed, 689 skipped, 1 failed
(test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition,
which fails at 9a31efc as well); GPU lane 16014 passed, 2384 skipped, 3
failed on a timeout while other suites loaded the machine
(test_cute_standalone.py::test_native_source_edit_without_helion,
test_examples.py::TestExamples::test_linear_monkeypatch_gated_delta_rule,
test_handoff_bundle.py::test_namedtuple_bundle_replays_in_fresh_process) and
passed when run again alone. `scripts/run_tests.py --backend triton --gpus
1,4`, GPU lane 3408 passed, 2411 skipped, 2 failed
(test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and
::test_task_accumulators_get_their_own_rings, which fail at 9a31efc as
well); CPU lane 5168 passed, 632 skipped.

Review notes:
- Deferred: "an answered call evaluates the divisor before the sum" and "a
  call that evaluated the divisor can still decline". KNOWN_GAPS.md,
  cute-full-sum-evaluates-its-divisor-early. At origin/main (f615a9b) the
  rendered call is `divisor=x.size(0)`: the replay above reads the divisor
  before the helper on every call and again in the fallback of every
  declined one, on every build. This commit leaves both forms on the
  audited build as they were, outside a mode of the caller, and removes
  the second on every other build and under such a mode.
- Not taken: "run the proofs again after the divisor". The helper calls the
  function ahead of its proofs, where the argument was evaluated, so the
  divisor's code cannot invalidate a proof that already ran.

autoreview passed: claude, codex

stack-info: PR: #4816, branch: choijon5/cute-norm-bwd/6
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 28, 2026
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from 238a8ad to 5bd0c84 Compare November 28, 2026 17:16
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/5 branch from c879ad2 to 1fac11a Compare November 28, 2026 17:16
@choijon5
choijon5 marked this pull request as draft November 28, 2026 20:36
@choijon5
choijon5 changed the base branch from choijon5/cute-norm-bwd/5 to main November 28, 2026 20:36
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from 5bd0c84 to 33ca612 Compare November 28, 2026 20:37
@choijon5
choijon5 changed the base branch from main to choijon5/cute-norm-bwd/5 November 28, 2026 20:37
@choijon5
choijon5 marked this pull request as ready for review November 28, 2026 20:38
@choijon5
choijon5 marked this pull request as draft November 29, 2026 18:14
@choijon5
choijon5 changed the base branch from choijon5/cute-norm-bwd/5 to main November 29, 2026 18:14
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from 33ca612 to ed39e89 Compare November 29, 2026 18:15
@choijon5
choijon5 changed the base branch from main to choijon5/cute-norm-bwd/5 November 29, 2026 18:15
@choijon5
choijon5 marked this pull request as ready for review November 29, 2026 18:15
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/5 branch from 1daa07c to c99655b Compare November 29, 2026 20:06
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from ed39e89 to f54af1c Compare November 29, 2026 20:06
choijon5 added a commit that referenced this pull request Nov 29, 2026
For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and
rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as
layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe
backend.

Kernels: none gets faster; two fixes to what runs when the helper of a full
host sum declines, which it does on every Torch build but the audited one.
Under `cute_host_paired_sum` "mapped" or "narrow", a kernel whose host tail
assigns a full sum to the name of its operand (`out = torch.sum(out)`) or of
its divisor (`n = torch.sum(out) / n`) raised a TypeError, and a scaled sum
(`torch.sum(out) / x.size(0)`) evaluated its divisor twice. A third fix is
to the helper's own arithmetic: it multiplied by another reciprocal than
ATen does for divisors such as 1.1.

Regression check for attention, which was hillclimbed before this stack:
the 12 pull requests of this stack together (#4811 to #4822) against plain
main (74ac871), on a B200.
- Generated code, rendered on CPU for the B200 target: all 1,298 configs
  that main renders for 145 attention cases generate the same source with
  the stack, and no seed list changes. The cases are the kernels of
  examples/attention.py (forward and backward), flex_attention.py,
  blackwell_attention.py and fp8_attention.py, and of
  benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs
  are each case's default and every compiler seed.
- The same with the attention stack (#4797 to #4810) under both sides: 759
  forward and 626 backward and attention-gym configs (defaults, seeds,
  pinned configs), 7,493 more configs that the search reaches on 12
  forward cases (one knob changed at a time, random draws) and 3,861 with
  random draws on the backward and attention-gym kernels generate the same
  source with and without this stack, and the 11 kernels compiled on the
  GPU (the eight forward shapes below and three fp8 attention inputs) have
  the same MLIR bytecode.
- Time: the eight forward shapes of examples/attention.py (dense and
  causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned
  configs, with and without this stack, interleaved, a new process for
  every reading, 4 to 8 rounds a shape. The best readings with the stack
  are 0.994 to 1.007 times those without. On this power-capped GPU every
  implementation, cuDNN SDPA included, reads one of two levels 3 to 5%
  apart from process to process; both sides read the same two levels.

With "mapped" or "narrow" a full host sum goes to a runtime helper
(`try_full_sum`), and the original statement runs when the helper returns
None. Two things kept that statement from running as it was written.

Its operand. The rewrite assigned the helper's answer to the statement's
target:

    out = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if out is None:
        out = torch.sum(out)

so the fallback read None where the statement reads its target.
`lower_host_full_sum` now gives the answer a name of its own for such a
statement and assigns the target from it when the helper answered:

    _helion_full_sum = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if _helion_full_sum is None:
        out = torch.sum(out)
    else:
        out = _helion_full_sum

Its divisor. The call took the divisor as an argument
(`divisor=x.size(0)`), so every call evaluated it before the helper
decided, and the fallback of a declined call evaluated it again. The proof
admits tensor metadata in a divisor (`x.size(0)`, `x.numel()`,
`x.shape[0]`) and called that safe to evaluate twice. A function mode of
the caller sees those calls, and so does a tensor subclass with
`__torch_function__`: on a declined call each saw one more than the
statement makes, ahead of the sum, where the helper's rule is that a
declined call leaves the exact original call. This predates the stack
(d32e9ca, the divisor support). The site now hands the divisor over as a
function,

    total = _cute_try_full_sum(out, mean=False, divisor_fn=lambda: x.size(0),
                               _launcher=_launcher)

and `try_full_sum` does not call it on a build whose sums it declines, nor
under a function or dispatch mode of the caller. There the statement
evaluates its divisor once, in its own order: that is every build but the
audited one, and every call under a mode. Replayed on CPU over an operand
that records the reads of its size, a declined call reads it twice at
origin/main (before the helper and in the fallback) and once here.

Otherwise, on the audited build, the helper calls the function where the
argument was evaluated, ahead of its proofs, so those calls behave as they
did: a call that the helper answers has evaluated the divisor before the
sum, and a call that its proofs decline has evaluated it once before the
statement does so again. KNOWN_GAPS.md records that
(cute-full-sum-evaluates-its-divisor-early). Calling the function after the
proofs instead would let the divisor's code invalidate them before the
launch (the operand's storage, device or length), so they would have to run
a second time on each answered call, and the sum would still be read after
the divisor. Both forms are reproduced on the audited build (Testing), which
no CI job runs.

The reciprocal. The helper's kernel multiplies the sum by a factor, and
`_reciprocal_factor` computed it as one over the divisor's FP32 value, in
FP32. That was ATen's formula until pytorch/pytorch#169507 (December 2025).
Since then `div_true_kernel_cuda` takes the reciprocal in FP64 and narrows
it,

    inv_b = static_cast<opmath_t>(
        high_prec_t(1.0) / iter.scalar_value<high_prec_t>(2));

with `high_prec_t = double`, and multiplies in FP32 (`MulFunctor<opmath_t>`):
aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu at the audited revision
(PyTorch main 6d5f66bd5b) and at both earlier pins (a970aa8b98,
e2dee2a4b9). The pins' audit covered the reduction sources, not this
kernel; the pin's comment in helion/runtime/cute/paired_sum.py now names it
for the next one.
The two reciprocals differ for a divisor that is no FP32 number of at most
24 bits: for 1.1 ATen multiplies by 0.9090909361839294 and the helper by
0.9090908765792847. So on the one build where the helper answers, a scaled
sum could differ from the statement in its last bits; the divisors of the
existing tests (3, 7, 0.25, 1037, row counts) are FP32 numbers, for which
both agree. Measured on a B200 with torch 2.15.0+cu132, which has the same
kernel: of 40000 random `float` divisors 10536 tell the two apart, of 25000
random `int` divisors 5997, and on 300 of each ATen's quotient of an FP32
one was the narrowed FP64 reciprocal every time. On the audited build
itself the helper's scaled sum of 4096 random FP32 numbers differed from
the statement's for 1418 of 2400 sums at the parent commit (400 tensors by
the divisors 1.1, 0.03, 16.1, 2**24 + 1, 3 and 1037), and for none here.
`_reciprocal_factor` now takes the reciprocal that way. Two more things
about the value it reads:
- Of an instance of a subclass of `int` or `float` it reads the value that
  the instance stores (`int.__index__`, `float.__float__`), which is the
  value ATen divides by (it takes the stored double of whatever passes
  `PyFloat_Check`, and an `int`'s digits). It asked `float()` of the
  instance, which a subclass may answer with another value.
- It takes an `int` from -2**63 up to 2**64, the integers that ATen wraps
  (measured: it raises for -(2**63) - 1 and for 2**64). The helper had a
  reciprocal for every `int` that `float()` converts, so it answered where
  the statement raises; such a divisor now declines.

`try_full_sum` keeps `divisor`, the value, next to `divisor_fn`: a
standalone file that helion/autotuner/aot_compile.py wrote before this
change passes it, and keeps the behavior it had.

The tests of this rewrite read generated host code, yet five of them were
skipped on every build but the audited one, and the module ran in the GPU
lane. test/test_cute_host_full_sum.py is now a `cpu_only` module that
renders on CPU: its codegen tests run on every build, without a GPU, and
its `cuda` items run on the device; those of them that launch the helper's
kernel still need the audited build. The device half of the helper's
decline test is a `cuda` item of its own, which now holds the rank case as
a tensor that passes every other proof. The short-tensor fallback test,
whose sum the helper declines on every build, no longer asks for the
audited one.

Compatibility: CuTe only. Generated host code changes for a full sum whose
statement reads its target (the answer's own name; a later site of that
kernel that needs a name of its own takes the next free one) and for a
scaled sum (`divisor_fn=lambda: ...` where it had `divisor=...`). Other
kernels render as before. On the audited build a scaled sum that the helper
answers is multiplied by the reciprocal that ATen multiplies by, which
changes its last bits for divisors that are no FP32 numbers of at most 24
bits; a divisor that is an instance of a subclass of `int` or `float` is
taken by the value it stores, and an `int` that ATen raises for is left to
the statement.

Tests (test/test_cute_host_full_sum.py):
- The two rebinding forms render the answer under its own name; the
  rendered statements, run on CPU with a stand-in helper, leave the
  original statement's result when it declines and its answer when it does
  not (one render per kernel).
- The rendered statements of a scaled sum, replayed from the render that
  the existing divisor test makes, over an operand that counts the reads
  of its size: one read whether the stand-in helper declines or answers.
- The helper on CPU: with the build declined, or under a function, a
  dispatch or a device mode, it does not read a divisor function; with the
  build admitted and no mode it reads it once before a proof declines the
  call (the known gap's second form, which the test pins); the reciprocal
  of plain numbers, of 1.1 and 2**54 + 2**30 + 1 (which tell the formulas
  apart), of -2**63, 2**63 and 2**64 - 1, of a `float` subclass whose
  `float()` doubles its value and of an `int` subclass whose `float()` and
  index add one; none for a `bool`, a tensor, a string, a complex number,
  -(2**63) - 1, 2**64 and 1 << 80.
- The helper on the device with a stand-in launcher, so on every build:
  a divisor function is read once and gives the same launch as the value;
  the two subclasses launch with the reciprocal of what they store; a
  tensor or `bool` divisor and a mean with a divisor decline, as do the
  tensors the helper does not take (short, misaligned, strided, rank-2,
  fp16, grad-requiring).
- On the audited build (skipped elsewhere): for 19 divisors (1.1, 0.03,
  16.1, 2**24 + 1, 2**54 + 2**30 + 1, 2**63 + 2**40 + 1, 1e300, 1e-300,
  both zeros and the two subclasses among them) ATen's quotient of one is
  the factor, and its quotient of 4096 random numbers is their FP32
  product with the factor; ATen raises for -(2**63) - 1 and 2**64. The
  test of the helper's own kernel on divisors gets 1.1 and 2**24 + 1.
- On the device both rebinding kernels, with a sum the helper declines on
  every build, return what the original statements compute.

Testing: B200, CUDA 13.2. On the audited build (torch
2.16.0.dev20261026+cu130, in a scratch environment), the six test modules
of the host sum helpers on both lanes with GPU 6
(test_cute_host_full_sum.py, test_cute_paired_sum_runtime.py,
test_cute_single_sum_runtime.py, test_cute_host_paired_sum_abi.py,
test_cute_host_single_sum_abi.py, test_cute_sum_tree_admission.py): GPU
lane 38 passed, CPU lane 201 passed, none skipped, so the helper's kernel
ran its tests, the ATen comparison of the reciprocal among them. The known
gap's forms, run there: an answered call whose divisor function zeroes the
operand returns 0 where the statement gives 64; a call on a CPU, a strided
or an fp16 tensor reads its divisor once and declines; under a device mode
the divisor is not read. On torch 2.15.0+cu132, which the lanes of this
stack run on, `scripts/run_tests.py --backend cute --gpus 4
test/test_cute_host_full_sum.py`: GPU lane 4 passed, 34 skipped (the tests
that need the audited build); CPU lane 18 passed. test/test_autoreview.py,
which checks the form of the entries of KNOWN_GAPS.md: 157 passed. With
the lowering and the helper of the parent commit, the tests of the
rebinding forms, of the scaled sum's rendered call and reads and of the
reciprocal fail. `./lint.sh check` passes. Lanes at the tip of the stack,
which holds this commit, on origin/main 9a31efc: `scripts/run_tests.py
--backend cute --gpus 0,4`, CPU lane 27430 passed, 689 skipped, 1 failed
(test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition,
which fails at 9a31efc as well); GPU lane 16014 passed, 2384 skipped, 3
failed on a timeout while other suites loaded the machine
(test_cute_standalone.py::test_native_source_edit_without_helion,
test_examples.py::TestExamples::test_linear_monkeypatch_gated_delta_rule,
test_handoff_bundle.py::test_namedtuple_bundle_replays_in_fresh_process) and
passed when run again alone. `scripts/run_tests.py --backend triton --gpus
1,4`, GPU lane 3408 passed, 2411 skipped, 2 failed
(test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and
::test_task_accumulators_get_their_own_rings, which fail at 9a31efc as
well); CPU lane 5168 passed, 632 skipped.

Review notes:
- Deferred: "an answered call evaluates the divisor before the sum" and "a
  call that evaluated the divisor can still decline". KNOWN_GAPS.md,
  cute-full-sum-evaluates-its-divisor-early. At origin/main (f615a9b) the
  rendered call is `divisor=x.size(0)`: the replay above reads the divisor
  before the helper on every call and again in the fallback of every
  declined one, on every build. This commit leaves both forms on the
  audited build as they were, outside a mode of the caller, and removes
  the second on every other build and under such a mode.
- Not taken: "run the proofs again after the divisor". The helper calls the
  function ahead of its proofs, where the argument was evaluated, so the
  divisor's code cannot invalidate a proof that already ran.

autoreview passed: claude, codex

stack-info: PR: #4816, branch: choijon5/cute-norm-bwd/6
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/5 branch from c99655b to 32686e6 Compare November 29, 2026 20:08
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from f54af1c to 17b66a7 Compare November 29, 2026 20:08
choijon5 added a commit that referenced this pull request Nov 29, 2026
For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and
rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as
layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe
backend.

Kernels: none gets faster; two fixes to what runs when the helper of a full
host sum declines, which it does on every Torch build but the audited one.
Under `cute_host_paired_sum` "mapped" or "narrow", a kernel whose host tail
assigns a full sum to the name of its operand (`out = torch.sum(out)`) or of
its divisor (`n = torch.sum(out) / n`) raised a TypeError, and a scaled sum
(`torch.sum(out) / x.size(0)`) evaluated its divisor twice. A third fix is
to the helper's own arithmetic: it multiplied by another reciprocal than
ATen does for divisors such as 1.1.

Regression check for attention, which was hillclimbed before this stack:
the 12 pull requests of this stack together (#4811 to #4822) against plain
main (74ac871), on a B200.
- Generated code, rendered on CPU for the B200 target: all 1,298 configs
  that main renders for 145 attention cases generate the same source with
  the stack, and no seed list changes. The cases are the kernels of
  examples/attention.py (forward and backward), flex_attention.py,
  blackwell_attention.py and fp8_attention.py, and of
  benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs
  are each case's default and every compiler seed.
- The same with the attention stack (#4797 to #4810) under both sides: 759
  forward and 626 backward and attention-gym configs (defaults, seeds,
  pinned configs), 7,493 more configs that the search reaches on 12
  forward cases (one knob changed at a time, random draws) and 3,861 with
  random draws on the backward and attention-gym kernels generate the same
  source with and without this stack, and the 11 kernels compiled on the
  GPU (the eight forward shapes below and three fp8 attention inputs) have
  the same MLIR bytecode.
- Time: the eight forward shapes of examples/attention.py (dense and
  causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned
  configs, with and without this stack, interleaved, a new process for
  every reading, 4 to 8 rounds a shape. The best readings with the stack
  are 0.994 to 1.007 times those without. On this power-capped GPU every
  implementation, cuDNN SDPA included, reads one of two levels 3 to 5%
  apart from process to process; both sides read the same two levels.

With "mapped" or "narrow" a full host sum goes to a runtime helper
(`try_full_sum`), and the original statement runs when the helper returns
None. Two things kept that statement from running as it was written.

Its operand. The rewrite assigned the helper's answer to the statement's
target:

    out = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if out is None:
        out = torch.sum(out)

so the fallback read None where the statement reads its target.
`lower_host_full_sum` now gives the answer a name of its own for such a
statement and assigns the target from it when the helper answered:

    _helion_full_sum = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if _helion_full_sum is None:
        out = torch.sum(out)
    else:
        out = _helion_full_sum

Its divisor. The call took the divisor as an argument
(`divisor=x.size(0)`), so every call evaluated it before the helper
decided, and the fallback of a declined call evaluated it again. The proof
admits tensor metadata in a divisor (`x.size(0)`, `x.numel()`,
`x.shape[0]`) and called that safe to evaluate twice. A function mode of
the caller sees those calls, and so does a tensor subclass with
`__torch_function__`: on a declined call each saw one more than the
statement makes, ahead of the sum, where the helper's rule is that a
declined call leaves the exact original call. This predates the stack
(d32e9ca, the divisor support). The site now hands the divisor over as a
function,

    total = _cute_try_full_sum(out, mean=False, divisor_fn=lambda: x.size(0),
                               _launcher=_launcher)

and `try_full_sum` does not call it on a build whose sums it declines, nor
under a function or dispatch mode of the caller. There the statement
evaluates its divisor once, in its own order: that is every build but the
audited one, and every call under a mode. Replayed on CPU over an operand
that records the reads of its size, a declined call reads it twice at
origin/main (before the helper and in the fallback) and once here.

Otherwise, on the audited build, the helper calls the function where the
argument was evaluated, ahead of its proofs, so those calls behave as they
did: a call that the helper answers has evaluated the divisor before the
sum, and a call that its proofs decline has evaluated it once before the
statement does so again. KNOWN_GAPS.md records that
(cute-full-sum-evaluates-its-divisor-early). Calling the function after the
proofs instead would let the divisor's code invalidate them before the
launch (the operand's storage, device or length), so they would have to run
a second time on each answered call, and the sum would still be read after
the divisor. Both forms are reproduced on the audited build (Testing), which
no CI job runs.

The reciprocal. The helper's kernel multiplies the sum by a factor, and
`_reciprocal_factor` computed it as one over the divisor's FP32 value, in
FP32. That was ATen's formula until pytorch/pytorch#169507 (December 2025).
Since then `div_true_kernel_cuda` takes the reciprocal in FP64 and narrows
it,

    inv_b = static_cast<opmath_t>(
        high_prec_t(1.0) / iter.scalar_value<high_prec_t>(2));

with `high_prec_t = double`, and multiplies in FP32 (`MulFunctor<opmath_t>`):
aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu at the audited revision
(PyTorch main 6d5f66bd5b) and at both earlier pins (a970aa8b98,
e2dee2a4b9). The pins' audit covered the reduction sources, not this
kernel; the pin's comment in helion/runtime/cute/paired_sum.py now names it
for the next one.
The two reciprocals differ for a divisor that is no FP32 number of at most
24 bits: for 1.1 ATen multiplies by 0.9090909361839294 and the helper by
0.9090908765792847. So on the one build where the helper answers, a scaled
sum could differ from the statement in its last bits; the divisors of the
existing tests (3, 7, 0.25, 1037, row counts) are FP32 numbers, for which
both agree. Measured on a B200 with torch 2.15.0+cu132, which has the same
kernel: of 40000 random `float` divisors 10536 tell the two apart, of 25000
random `int` divisors 5997, and on 300 of each ATen's quotient of an FP32
one was the narrowed FP64 reciprocal every time. On the audited build
itself the helper's scaled sum of 4096 random FP32 numbers differed from
the statement's for 1418 of 2400 sums at the parent commit (400 tensors by
the divisors 1.1, 0.03, 16.1, 2**24 + 1, 3 and 1037), and for none here.
`_reciprocal_factor` now takes the reciprocal that way. Two more things
about the value it reads:
- Of an instance of a subclass of `int` or `float` it reads the value that
  the instance stores (`int.__index__`, `float.__float__`), which is the
  value ATen divides by (it takes the stored double of whatever passes
  `PyFloat_Check`, and an `int`'s digits). It asked `float()` of the
  instance, which a subclass may answer with another value.
- It takes an `int` from -2**63 up to 2**64, the integers that ATen wraps
  (measured: it raises for -(2**63) - 1 and for 2**64). The helper had a
  reciprocal for every `int` that `float()` converts, so it answered where
  the statement raises; such a divisor now declines.

`try_full_sum` keeps `divisor`, the value, next to `divisor_fn`: a
standalone file that helion/autotuner/aot_compile.py wrote before this
change passes it, and keeps the behavior it had.

The tests of this rewrite read generated host code, yet five of them were
skipped on every build but the audited one, and the module ran in the GPU
lane. test/test_cute_host_full_sum.py is now a `cpu_only` module that
renders on CPU: its codegen tests run on every build, without a GPU, and
its `cuda` items run on the device; those of them that launch the helper's
kernel still need the audited build. The device half of the helper's
decline test is a `cuda` item of its own, which now holds the rank case as
a tensor that passes every other proof. The short-tensor fallback test,
whose sum the helper declines on every build, no longer asks for the
audited one.

Compatibility: CuTe only. Generated host code changes for a full sum whose
statement reads its target (the answer's own name; a later site of that
kernel that needs a name of its own takes the next free one) and for a
scaled sum (`divisor_fn=lambda: ...` where it had `divisor=...`). Other
kernels render as before. On the audited build a scaled sum that the helper
answers is multiplied by the reciprocal that ATen multiplies by, which
changes its last bits for divisors that are no FP32 numbers of at most 24
bits; a divisor that is an instance of a subclass of `int` or `float` is
taken by the value it stores, and an `int` that ATen raises for is left to
the statement.

Tests (test/test_cute_host_full_sum.py):
- The two rebinding forms render the answer under its own name; the
  rendered statements, run on CPU with a stand-in helper, leave the
  original statement's result when it declines and its answer when it does
  not (one render per kernel).
- The rendered statements of a scaled sum, replayed from the render that
  the existing divisor test makes, over an operand that counts the reads
  of its size: one read whether the stand-in helper declines or answers.
- The helper on CPU: with the build declined, or under a function, a
  dispatch or a device mode, it does not read a divisor function; with the
  build admitted and no mode it reads it once before a proof declines the
  call (the known gap's second form, which the test pins); the reciprocal
  of plain numbers, of 1.1 and 2**54 + 2**30 + 1 (which tell the formulas
  apart), of -2**63, 2**63 and 2**64 - 1, of a `float` subclass whose
  `float()` doubles its value and of an `int` subclass whose `float()` and
  index add one; none for a `bool`, a tensor, a string, a complex number,
  -(2**63) - 1, 2**64 and 1 << 80.
- The helper on the device with a stand-in launcher, so on every build:
  a divisor function is read once and gives the same launch as the value;
  the two subclasses launch with the reciprocal of what they store; a
  tensor or `bool` divisor and a mean with a divisor decline, as do the
  tensors the helper does not take (short, misaligned, strided, rank-2,
  fp16, grad-requiring).
- On the audited build (skipped elsewhere): for 19 divisors (1.1, 0.03,
  16.1, 2**24 + 1, 2**54 + 2**30 + 1, 2**63 + 2**40 + 1, 1e300, 1e-300,
  both zeros and the two subclasses among them) ATen's quotient of one is
  the factor, and its quotient of 4096 random numbers is their FP32
  product with the factor; ATen raises for -(2**63) - 1 and 2**64. The
  test of the helper's own kernel on divisors gets 1.1 and 2**24 + 1.
- On the device both rebinding kernels, with a sum the helper declines on
  every build, return what the original statements compute.

Testing: B200, CUDA 13.2. On the audited build (torch
2.16.0.dev20261026+cu130, in a scratch environment), the six test modules
of the host sum helpers on both lanes with GPU 6
(test_cute_host_full_sum.py, test_cute_paired_sum_runtime.py,
test_cute_single_sum_runtime.py, test_cute_host_paired_sum_abi.py,
test_cute_host_single_sum_abi.py, test_cute_sum_tree_admission.py): GPU
lane 38 passed, CPU lane 201 passed, none skipped, so the helper's kernel
ran its tests, the ATen comparison of the reciprocal among them. The known
gap's forms, run there: an answered call whose divisor function zeroes the
operand returns 0 where the statement gives 64; a call on a CPU, a strided
or an fp16 tensor reads its divisor once and declines; under a device mode
the divisor is not read. On torch 2.15.0+cu132, which the lanes of this
stack run on, `scripts/run_tests.py --backend cute --gpus 4
test/test_cute_host_full_sum.py`: GPU lane 4 passed, 34 skipped (the tests
that need the audited build); CPU lane 18 passed. test/test_autoreview.py,
which checks the form of the entries of KNOWN_GAPS.md: 157 passed. With
the lowering and the helper of the parent commit, the tests of the
rebinding forms, of the scaled sum's rendered call and reads and of the
reciprocal fail. `./lint.sh check` passes. Lanes at the tip of the stack,
which holds this commit, on origin/main 9a31efc: `scripts/run_tests.py
--backend cute --gpus 0,4`, CPU lane 27430 passed, 689 skipped, 1 failed
(test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition,
which fails at 9a31efc as well); GPU lane 16014 passed, 2384 skipped, 3
failed on a timeout while other suites loaded the machine
(test_cute_standalone.py::test_native_source_edit_without_helion,
test_examples.py::TestExamples::test_linear_monkeypatch_gated_delta_rule,
test_handoff_bundle.py::test_namedtuple_bundle_replays_in_fresh_process) and
passed when run again alone. `scripts/run_tests.py --backend triton --gpus
1,4`, GPU lane 3408 passed, 2411 skipped, 2 failed
(test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and
::test_task_accumulators_get_their_own_rings, which fail at 9a31efc as
well); CPU lane 5168 passed, 632 skipped.

Review notes:
- Deferred: "an answered call evaluates the divisor before the sum" and "a
  call that evaluated the divisor can still decline". KNOWN_GAPS.md,
  cute-full-sum-evaluates-its-divisor-early. At origin/main (f615a9b) the
  rendered call is `divisor=x.size(0)`: the replay above reads the divisor
  before the helper on every call and again in the fallback of every
  declined one, on every build. This commit leaves both forms on the
  audited build as they were, outside a mode of the caller, and removes
  the second on every other build and under such a mode.
- Not taken: "run the proofs again after the divisor". The helper calls the
  function ahead of its proofs, where the argument was evaluated, so the
  divisor's code cannot invalidate a proof that already ran.

autoreview passed: claude, codex

stack-info: PR: #4816, branch: choijon5/cute-norm-bwd/6
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/5 branch from 32686e6 to 0d16ced Compare November 29, 2026 20:09
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from 17b66a7 to 83095df Compare November 29, 2026 20:09
choijon5 added a commit that referenced this pull request Nov 29, 2026
For the norm backward kernels (layer_norm_bwd in examples/layer_norm.py and
rms_norm_bwd in examples/rms_norm.py, which TritonBench runs as
layer_norm-bwd and rms_norm-bwd): part of their hillclimb on the CuTe
backend.

Kernels: none gets faster; two fixes to what runs when the helper of a full
host sum declines, which it does on every Torch build but the audited one.
Under `cute_host_paired_sum` "mapped" or "narrow", a kernel whose host tail
assigns a full sum to the name of its operand (`out = torch.sum(out)`) or of
its divisor (`n = torch.sum(out) / n`) raised a TypeError, and a scaled sum
(`torch.sum(out) / x.size(0)`) evaluated its divisor twice. A third fix is
to the helper's own arithmetic: it multiplied by another reciprocal than
ATen does for divisors such as 1.1.

Regression check for attention, which was hillclimbed before this stack:
the 12 pull requests of this stack together (#4811 to #4822) against plain
main (74ac871), on a B200.
- Generated code, rendered on CPU for the B200 target: all 1,298 configs
  that main renders for 145 attention cases generate the same source with
  the stack, and no seed list changes. The cases are the kernels of
  examples/attention.py (forward and backward), flex_attention.py,
  blackwell_attention.py and fp8_attention.py, and of
  benchmarks/cute/attnbwd_kernels.py and attngym_kernels.py; the configs
  are each case's default and every compiler seed.
- The same with the attention stack (#4797 to #4810) under both sides: 759
  forward and 626 backward and attention-gym configs (defaults, seeds,
  pinned configs), 7,493 more configs that the search reaches on 12
  forward cases (one knob changed at a time, random draws) and 3,861 with
  random draws on the backward and attention-gym kernels generate the same
  source with and without this stack, and the 11 kernels compiled on the
  GPU (the eight forward shapes below and three fp8 attention inputs) have
  the same MLIR bytecode.
- Time: the eight forward shapes of examples/attention.py (dense and
  causal, B2 H32 S1024 D64 fp16 to B8 H32 S8192 D128 bf16) at pinned
  configs, with and without this stack, interleaved, a new process for
  every reading, 4 to 8 rounds a shape. The best readings with the stack
  are 0.994 to 1.007 times those without. On this power-capped GPU every
  implementation, cuDNN SDPA included, reads one of two levels 3 to 5%
  apart from process to process; both sides read the same two levels.

With "mapped" or "narrow" a full host sum goes to a runtime helper
(`try_full_sum`), and the original statement runs when the helper returns
None. Two things kept that statement from running as it was written.

Its operand. The rewrite assigned the helper's answer to the statement's
target:

    out = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if out is None:
        out = torch.sum(out)

so the fallback read None where the statement reads its target.
`lower_host_full_sum` now gives the answer a name of its own for such a
statement and assigns the target from it when the helper answered:

    _helion_full_sum = _cute_try_full_sum(out, mean=False, _launcher=_launcher)
    if _helion_full_sum is None:
        out = torch.sum(out)
    else:
        out = _helion_full_sum

Its divisor. The call took the divisor as an argument
(`divisor=x.size(0)`), so every call evaluated it before the helper
decided, and the fallback of a declined call evaluated it again. The proof
admits tensor metadata in a divisor (`x.size(0)`, `x.numel()`,
`x.shape[0]`) and called that safe to evaluate twice. A function mode of
the caller sees those calls, and so does a tensor subclass with
`__torch_function__`: on a declined call each saw one more than the
statement makes, ahead of the sum, where the helper's rule is that a
declined call leaves the exact original call. This predates the stack
(d32e9ca, the divisor support). The site now hands the divisor over as a
function,

    total = _cute_try_full_sum(out, mean=False, divisor_fn=lambda: x.size(0),
                               _launcher=_launcher)

and `try_full_sum` does not call it on a build whose sums it declines, nor
under a function or dispatch mode of the caller. There the statement
evaluates its divisor once, in its own order: that is every build but the
audited one, and every call under a mode. Replayed on CPU over an operand
that records the reads of its size, a declined call reads it twice at
origin/main (before the helper and in the fallback) and once here.

Otherwise, on the audited build, the helper calls the function where the
argument was evaluated, ahead of its proofs, so those calls behave as they
did: a call that the helper answers has evaluated the divisor before the
sum, and a call that its proofs decline has evaluated it once before the
statement does so again. KNOWN_GAPS.md records that
(cute-full-sum-evaluates-its-divisor-early). Calling the function after the
proofs instead would let the divisor's code invalidate them before the
launch (the operand's storage, device or length), so they would have to run
a second time on each answered call, and the sum would still be read after
the divisor. Both forms are reproduced on the audited build (Testing), which
no CI job runs.

The reciprocal. The helper's kernel multiplies the sum by a factor, and
`_reciprocal_factor` computed it as one over the divisor's FP32 value, in
FP32. That was ATen's formula until pytorch/pytorch#169507 (December 2025).
Since then `div_true_kernel_cuda` takes the reciprocal in FP64 and narrows
it,

    inv_b = static_cast<opmath_t>(
        high_prec_t(1.0) / iter.scalar_value<high_prec_t>(2));

with `high_prec_t = double`, and multiplies in FP32 (`MulFunctor<opmath_t>`):
aten/src/ATen/native/cuda/BinaryDivTrueKernel.cu at the audited revision
(PyTorch main 6d5f66bd5b) and at both earlier pins (a970aa8b98,
e2dee2a4b9). The pins' audit covered the reduction sources, not this
kernel; the pin's comment in helion/runtime/cute/paired_sum.py now names it
for the next one.
The two reciprocals differ for a divisor that is no FP32 number of at most
24 bits: for 1.1 ATen multiplies by 0.9090909361839294 and the helper by
0.9090908765792847. So on the one build where the helper answers, a scaled
sum could differ from the statement in its last bits; the divisors of the
existing tests (3, 7, 0.25, 1037, row counts) are FP32 numbers, for which
both agree. Measured on a B200 with torch 2.15.0+cu132, which has the same
kernel: of 40000 random `float` divisors 10536 tell the two apart, of 25000
random `int` divisors 5997, and on 300 of each ATen's quotient of an FP32
one was the narrowed FP64 reciprocal every time. On the audited build
itself the helper's scaled sum of 4096 random FP32 numbers differed from
the statement's for 1418 of 2400 sums at the parent commit (400 tensors by
the divisors 1.1, 0.03, 16.1, 2**24 + 1, 3 and 1037), and for none here.
`_reciprocal_factor` now takes the reciprocal that way. Two more things
about the value it reads:
- Of an instance of a subclass of `int` or `float` it reads the value that
  the instance stores (`int.__index__`, `float.__float__`), which is the
  value ATen divides by (it takes the stored double of whatever passes
  `PyFloat_Check`, and an `int`'s digits). It asked `float()` of the
  instance, which a subclass may answer with another value.
- It takes an `int` from -2**63 up to 2**64, the integers that ATen wraps
  (measured: it raises for -(2**63) - 1 and for 2**64). The helper had a
  reciprocal for every `int` that `float()` converts, so it answered where
  the statement raises; such a divisor now declines.

`try_full_sum` keeps `divisor`, the value, next to `divisor_fn`: a
standalone file that helion/autotuner/aot_compile.py wrote before this
change passes it, and keeps the behavior it had.

The tests of this rewrite read generated host code, yet five of them were
skipped on every build but the audited one, and the module ran in the GPU
lane. test/test_cute_host_full_sum.py is now a `cpu_only` module that
renders on CPU: its codegen tests run on every build, without a GPU, and
its `cuda` items run on the device; those of them that launch the helper's
kernel still need the audited build. The device half of the helper's
decline test is a `cuda` item of its own, which now holds the rank case as
a tensor that passes every other proof. The short-tensor fallback test,
whose sum the helper declines on every build, no longer asks for the
audited one.

Compatibility: CuTe only. Generated host code changes for a full sum whose
statement reads its target (the answer's own name; a later site of that
kernel that needs a name of its own takes the next free one) and for a
scaled sum (`divisor_fn=lambda: ...` where it had `divisor=...`). Other
kernels render as before. On the audited build a scaled sum that the helper
answers is multiplied by the reciprocal that ATen multiplies by, which
changes its last bits for divisors that are no FP32 numbers of at most 24
bits; a divisor that is an instance of a subclass of `int` or `float` is
taken by the value it stores, and an `int` that ATen raises for is left to
the statement.

Tests (test/test_cute_host_full_sum.py):
- The two rebinding forms render the answer under its own name; the
  rendered statements, run on CPU with a stand-in helper, leave the
  original statement's result when it declines and its answer when it does
  not (one render per kernel).
- The rendered statements of a scaled sum, replayed from the render that
  the existing divisor test makes, over an operand that counts the reads
  of its size: one read whether the stand-in helper declines or answers.
- The helper on CPU: with the build declined, or under a function, a
  dispatch or a device mode, it does not read a divisor function; with the
  build admitted and no mode it reads it once before a proof declines the
  call (the known gap's second form, which the test pins); the reciprocal
  of plain numbers, of 1.1 and 2**54 + 2**30 + 1 (which tell the formulas
  apart), of -2**63, 2**63 and 2**64 - 1, of a `float` subclass whose
  `float()` doubles its value and of an `int` subclass whose `float()` and
  index add one; none for a `bool`, a tensor, a string, a complex number,
  -(2**63) - 1, 2**64 and 1 << 80.
- The helper on the device with a stand-in launcher, so on every build:
  a divisor function is read once and gives the same launch as the value;
  the two subclasses launch with the reciprocal of what they store; a
  tensor or `bool` divisor and a mean with a divisor decline, as do the
  tensors the helper does not take (short, misaligned, strided, rank-2,
  fp16, grad-requiring).
- On the audited build (skipped elsewhere): for 19 divisors (1.1, 0.03,
  16.1, 2**24 + 1, 2**54 + 2**30 + 1, 2**63 + 2**40 + 1, 1e300, 1e-300,
  both zeros and the two subclasses among them) ATen's quotient of one is
  the factor, and its quotient of 4096 random numbers is their FP32
  product with the factor; ATen raises for -(2**63) - 1 and 2**64. The
  test of the helper's own kernel on divisors gets 1.1 and 2**24 + 1.
- On the device both rebinding kernels, with a sum the helper declines on
  every build, return what the original statements compute.

Testing: B200, CUDA 13.2. On the audited build (torch
2.16.0.dev20261026+cu130, in a scratch environment), the six test modules
of the host sum helpers on both lanes with GPU 6
(test_cute_host_full_sum.py, test_cute_paired_sum_runtime.py,
test_cute_single_sum_runtime.py, test_cute_host_paired_sum_abi.py,
test_cute_host_single_sum_abi.py, test_cute_sum_tree_admission.py): GPU
lane 38 passed, CPU lane 201 passed, none skipped, so the helper's kernel
ran its tests, the ATen comparison of the reciprocal among them. The known
gap's forms, run there: an answered call whose divisor function zeroes the
operand returns 0 where the statement gives 64; a call on a CPU, a strided
or an fp16 tensor reads its divisor once and declines; under a device mode
the divisor is not read. On torch 2.15.0+cu132, which the lanes of this
stack run on, `scripts/run_tests.py --backend cute --gpus 4
test/test_cute_host_full_sum.py`: GPU lane 4 passed, 34 skipped (the tests
that need the audited build); CPU lane 18 passed. test/test_autoreview.py,
which checks the form of the entries of KNOWN_GAPS.md: 157 passed. With
the lowering and the helper of the parent commit, the tests of the
rebinding forms, of the scaled sum's rendered call and reads and of the
reciprocal fail. `./lint.sh check` passes. Lanes at the tip of the stack,
which holds this commit, on origin/main 9a31efc: `scripts/run_tests.py
--backend cute --gpus 0,4`, CPU lane 27430 passed, 689 skipped, 1 failed
(test/test_cute_fragment_assertion.py::test_assertions_in_binary_cross_entropy_decomposition,
which fails at 9a31efc as well); GPU lane 16014 passed, 2384 skipped, 3
failed on a timeout while other suites loaded the machine
(test_cute_standalone.py::test_native_source_edit_without_helion,
test_examples.py::TestExamples::test_linear_monkeypatch_gated_delta_rule,
test_handoff_bundle.py::test_namedtuple_bundle_replays_in_fresh_process) and
passed when run again alone. `scripts/run_tests.py --backend triton --gpus
1,4`, GPU lane 3408 passed, 2411 skipped, 2 failed
(test/test_gluon_ring.py::TestGluonRing::test_two_dots_in_one_loop and
::test_task_accumulators_get_their_own_rings, which fail at 9a31efc as
well); CPU lane 5168 passed, 632 skipped.

Review notes:
- Deferred: "an answered call evaluates the divisor before the sum" and "a
  call that evaluated the divisor can still decline". KNOWN_GAPS.md,
  cute-full-sum-evaluates-its-divisor-early. At origin/main (f615a9b) the
  rendered call is `divisor=x.size(0)`: the replay above reads the divisor
  before the helper on every call and again in the fallback of every
  declined one, on every build. This commit leaves both forms on the
  audited build as they were, outside a mode of the caller, and removes
  the second on every other build and under such a mode.
- Not taken: "run the proofs again after the divisor". The helper calls the
  function ahead of its proofs, where the argument was evaluated, so the
  divisor's code cannot invalidate a proof that already ran.

autoreview passed: claude, codex

stack-info: PR: #4816, branch: choijon5/cute-norm-bwd/6
@choijon5
choijon5 force-pushed the choijon5/cute-norm-bwd/6 branch from 83095df to 69b136b Compare November 29, 2026 20:10
@choijon5
choijon5 changed the base branch from choijon5/cute-norm-bwd/5 to main November 29, 2026 20:11
@choijon5
choijon5 merged commit a69815d into main Nov 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants