Skip to content

Add torch::nn::RMSNorm to the C++ frontend - #193936

Closed
egeboy35 wants to merge 7 commits into
pytorch:mainfrom
egeboy35:add-cpp-rmsnorm
Closed

egeboy35 wants to merge 7 commits into
pytorch:mainfrom
egeboy35:add-cpp-rmsnorm

Conversation

@egeboy35

@egeboy35 egeboy35 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Adds torch::nn::RMSNorm (module, functional and options) to the libtorch C++
frontend, closing a Python/C++ parity gap: torch.nn.RMSNorm has existed on the
Python side since 2.4, but C++ users have had to hand-roll the module or call
torch::rms_norm directly. The ATen op (aten::rms_norm, CompositeImplicit
Autograd) already exists, so this is a thin frontend mirror of the LayerNorm
pattern.

Added:

  • RMSNormOptions / functional::RMSNormFuncOptions
    (torch/csrc/api/include/torch/nn/options/normalization.h + src mirror)
  • F::rms_norm (torch/csrc/api/include/torch/nn/functional/normalization.h)
  • RMSNormImpl + TORCH_MODULE(RMSNorm)
    (torch/csrc/api/include/torch/nn/modules/normalization.h + src mirror)
  • 6 tests in test/cpp/api/{modules,functional}.cpp, two RMSNorm entries
    in torch/testing/_internal/common_nn.py (with cpp_constructor_args, so the
    C++/Python parity harness covers them), cppdocs entries, and a
    torch::nn::RMSNorm|Yes|No row in test/cpp_api_parity/parity-tracker.md

Two details worth flagging for review:

  1. eps is std::optional<double> defaulting to std::nullopt, not
    LayerNorm's double = 1e-5. This mirrors Python, where eps=None means "use
    the machine epsilon of the computation (opmath) type", which aten::rms_norm resolves
    internally. pretty_print renders the unset case as eps=None to match
    torch.nn.RMSNorm.extra_repr.
  2. An undefined weight is passed straight through. aten::rms_norm used
    to multiply by an engaged-but-undefined weight (the elementwise_affine=false
    case) and raise "Expected a proper Tensor but got None"; Treat an engaged-but-undefined optional weight as no weight in rms_norm #195574 fixed that in
    ATen, so F::detail::rms_norm needs no conversion. RMSNormNoAffine covers
    this path.

RMSNorm has a weight but no bias, so RMSNormImpl registers only weight
(initialized to ones when elementwise_affine is true, undefined otherwise).

Under dynamo, the four TestNN.test_RMSNorm_1d_* tests generated from the
common_nn entries fail inside compiled autograd (TypeError: add(): argument 'input' (position 1) must be Tensor, not NoneType), so they are listed in test/compiled_autograd_skips/.
That turns off only compiled autograd for them; the rest of the dynamo path
still runs.

Test Plan: the six C++ tests follow the existing LayerNorm conventions. I ran
them locally on a Windows/MSVC source build of these commits on their previous
base (7744b78e00e, Aug 21 main) with #195574 cherry-picked, so F::rms_norm
passes an undefined weight straight through:

build/bin/test_api.exe --gtest_filter=*RMSNorm*:*LayerNorm*
[==========] 9 tests from 2 test suites ran. (18 ms total)
[  PASSED  ] 9 tests.

That covers ModulesTest.RMSNorm, RMSNormDefaultEps, RMSNormNoAffine,
RMSNormInvalidWeightShape, PrettyPrintRMSNorm and FunctionalTest.RMSNorm,
plus the existing LayerNorm tests next to them.

The code and this description were drafted with an AI assistant (Claude); I reviewed both and understand all changes.

@pytorch-bot

pytorch-bot Bot commented Aug 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⚠️ 4 Awaiting Approval

As of commit 73c1694 with merge base c3ed1b7 (image):

AWAITING APPROVAL - The following workflows need approval before CI can run:

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

@pytorch-bot pytorch-bot Bot added the release notes: cpp release notes category label Aug 18, 2026
@egeboy35

Copy link
Copy Markdown
Contributor Author

Good catch, thanks — fixed in adb6fb3 by formatting the bool explicitly
instead of setting std::boolalpha, which keeps the caller's stream flags
untouched without pulling in fmtlib or an RAII helper.

Verified locally that the rendered output is unchanged
(torch::nn::RMSNorm([2, 2], eps=None, elementwise_affine=true) /
..., eps=2e-05, elementwise_affine=false), so PrettyPrintRMSNorm still
passes, and that writing a bool to a stream after streaming an RMSNorm now
yields 1 instead of true.

Worth noting the same pattern exists in the neighbouring pretty_print
implementations (LayerNorm, the activation modules, etc.) — I left those
alone to keep this PR focused, but happy to send a separate cleanup PR if
that's wanted.

@drisspg drisspg added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Aug 19, 2026
@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007 thanks again for the two rounds here — both comments are addressed in
8a9f5a62fe5 (the fmt::print form you suggested).

One thing that may not be visible from the PR page: this PR's CI has never actually run.
It only has EasyCLA and the Meta internal check; the pull, Lint, BC Lint and
docs-build workflows are all sitting at action_required, waiting on a maintainer to
approve workflow runs for a fork PR. So there is no green signal to merge on, through no
change on my side.

If you are happy with the code, approving the workflow runs would let CI exercise the new
PrettyPrintRMSNorm and parity tests. Glad to rebase first if that helps.

🤖 Addressed by Claude Code

@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007 thanks for landing #195107 today.

Circling back on this one since it has been open a while and has drifted: both of your comments
are addressed in 8a9f5a62fe5 — the fmt::print(stream, ", elementwise_affine={})", ...) form you
suggested, with <fmt/ostream.h>, so pretty_print no longer touches the caller's stream flags.

Two things that are not visible from the PR page and are the actual blockers:

  • Its CI has still never run. Only EasyCLA and the Meta internal check are present; pull, Lint,
    BC Lint and docs-build are all at action_required, waiting on workflow approval for a fork
    PR. So there is no signal to review against.
  • There is no reviewer assigned, so it has no natural owner.

This adds torch::nn::RMSNorm to the C++ frontend mirroring the existing LayerNorm, with the
parity-tracker row and five tests. The one real subtlety I hit while writing it: aten::rms_norm
takes Tensor? weight, so an undefined weight has to be forwarded as std::nullopt rather than an
engaged-but-undefined optional, otherwise the elementwise_affine=false path raises "Expected a
proper Tensor but got None" — unlike layer_norm.

If a new module is not something you want to take on, say so and I will close it rather than leave
it sitting. Otherwise, approving the workflow runs would at least give it a green signal to judge.

🤖 Addressed by Claude Code

@Skylion007

Copy link
Copy Markdown
Collaborator

@claude review this PR

@claude

claude Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Claude finished @Skylion007's task in 16m 38s —— View job


The C++ RMSNorm mirror itself is correct and behaves as advertised, but it ships without a cppdocs entry, its parity-tracker.md Yes claim is inert (no test backs it), its three added forward tests are near-tautological because they compare the module against the same ATen op it calls with weight left at all-ones, and the code comment justifying the std::nullopt workaround is factually wrong about the ATen schema — so I'd request changes before landing.

Full review

PR Review: #193936

Summary

Adds torch::nn::RMSNorm (module + functional + options) to the libtorch C++ frontend as a mirror of LayerNorm. The implementation is behaviorally correct, but I found problems in four areas: a missing cppdocs registration, a parity-tracker claim that no test backs, tests that cannot distinguish a correct implementation from a broken one, and a code comment whose stated justification is factually incorrect (which matters because it points away from a real upstream bug).

Infrastructure

  • docs/cpp/source/api/nn/normalization.md was not updated. Every other module on that page has a doxygenclass pair — LayerNorm/LayerNormImpl at docs/cpp/source/api/nn/normalization.md:96-104, plus a bullet in the intro list at line 15 and an entry in the html_meta description/keywords at lines 4-5. RMSNorm has none of these, so the new module will be absent from the rendered cppdocs even though the PR's own header comments point users at the docs. Add a ## RMSNorm section with doxygenclass torch::nn::RMSNorm + torch::nn::RMSNormImpl after the LayerNorm section, and add it to the intro bullet list and html_meta. Fix this →

  • The torch::nn::RMSNorm|Yes|No row in test/cpp_api_parity/parity-tracker.md:88 is inert — nothing verifies the Yes. The harness at test/test_cpp_api_parity.py:40-64 iterates only over common_nn.module_tests, common_nn.get_new_module_tests(), and common_nn.criterion_tests. The tracker is consulted at test/cpp_api_parity/module_impl_check.py:315 only after a matching test dict has been found, so the assertion fires in the direction "test exists but tracker row missing" and never the reverse. LayerNorm's Yes is real because it has a dict at torch/testing/_internal/common_nn.py:2627-2631 carrying cpp_constructor_args. RMSNorm has zero occurrences in common_nn.py, so no generated C++/Python comparison runs. The existing ModuleInfo at common_modules.py:4849 does not help — nothing under test/cpp_api_parity/ consumes common_modules.py. Either add a common_nn.py entry with cpp_constructor_args so the Yes is actually exercised, or the row is an unverified assertion. Fix this →

  • The comment justifying the std::nullopt conversion is factually wrong, and it papers over an ATen bug rather than naming it. In torch/csrc/api/include/torch/nn/functional/normalization.h the comment says "aten::rms_norm takes an optional weight" and the PR description says this is "unlike aten::layer_norm". Both schemas are identical in that respect: native_functions.yaml:3276 declares layer_norm(..., Tensor? weight=None, ...) and :3301 declares rms_norm(..., Tensor? weight=None, ...). The actual cause is rms_norm_composite at aten/src/ATen/native/layer_norm.cpp:304, which gates on weight_opt.has_value() without also checking .defined() and then multiplies by the undefined tensor at line 305. That is internally inconsistent with rms_norm_symint two functions below (layer_norm.cpp:332-334 does borrow_from_optional_tensor + .defined()) and with math_native_layer_norm (layer_norm.cpp:211-212, 246-251), which is exactly why layer_norm tolerates the engaged-but-undefined optional and rms_norm does not. CPU does reach this path: _fused_rms_norm (native_functions.yaml:3305-3310) has no CPU dispatch and falls to CompositeImplicitAutograd: rms_norm_composite. Keeping the frontend conversion is fine, but the comment must state the real reason, and the one-line .defined() guard at layer_norm.cpp:304 should be fixed too — otherwise every other C++ caller of at::rms_norm hits the same trap. Fix this →

API Design

  • The eps documentation misstates the fallback, and diverges from the Python docs it is meant to mirror. torch/csrc/api/include/torch/nn/options/normalization.h:43-44 (RMSNormOptions) and :93-94 (RMSNormFuncOptions) both say "the machine epsilon of the input dtype is used", and the test comment in test/cpp/api/modules.cpp repeats it. ATen actually uses the opmath type's epsilon: rms_norm_composite upcasts via toOpMathType at aten/src/ATen/native/layer_norm.cpp:286 and then takes std::numeric_limits<float>::epsilon() at line 294 for fp16/bf16/fp32 inputs. So for a half input the value is ~1.19e-7, not fp16's ~9.77e-4 — off by four orders of magnitude from what the comment promises. The Python docstring gets this right and is explicit about it (torch/nn/modules/normalization.py:368-371); the C++ mirror should say the same thing. Fix this →

Testing

  • All three forward tests compare the module against the same ATen op the module itself calls, with weight left at its all-ones default — so they cannot fail if the weight is dropped or misapplied. ModulesTest.RMSNorm, RMSNormDefaultEps, and FunctionalTest.RMSNorm all assert allclose(model(x), torch::rms_norm(x, ..., model->weight, ...)). Because both sides receive the identical (all-ones, hence identity) weight, an implementation that ignored weight entirely, or applied it to the wrong axis, would still pass. LayerNorm's equivalent test has the same shape, but it is backed by the real common_nn.py parity test noted above; RMSNorm currently has no such backstop, so these are the only coverage there is. Fill model->weight with distinct non-unit values (or construct with a non-square normalized_shape) and assert against an independently computed expected value, so the weight application is actually pinned. Fix this →

  • No error-condition coverage. _check_rms_norm_inputs_symint (aten/src/ATen/native/layer_norm.h:15-45) raises for a weight whose shape disagrees with normalized_shape, for a zero-length normalized_shape, and for an input with fewer dims than normalized_shape. None of those paths are exercised. Since RMSNormFuncOptions::weight is user-settable, the shape-mismatch case in particular is reachable through the new public API and should be asserted with a message match.

  • PrettyPrintRMSNorm is inserted at test/cpp/api/modules.cpp:5016 — before PrettyPrintLayerNorm. Everywhere else in this PR (options/normalization.h, modules/normalization.h, src/nn/modules/normalization.cpp, and the tracker row) RMSNorm follows LayerNorm. Move it after PrettyPrintLayerNorm for consistency.

Recommendation

Request Changes

Blocking: the missing cppdocs entry (the module is invisible in rendered C++ docs), the parity-tracker.md Yes that no test backs, and forward tests that cannot distinguish a correct implementation from one that ignores weight. The wrong justification comment plus the unfixed layer_norm.cpp:304 guard should also be addressed since the comment actively misdirects the next reader.

Separately, on the CI situation raised in the thread: the action_required state is a fork-PR workflow-approval gate, not anything the author can clear. A maintainer approving the run is a prerequisite to getting any signal here.

--- · branch add-cpp-rmsnorm

@Skylion007

Copy link
Copy Markdown
Collaborator

Please update parity tracker.md

@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007 tracker row updated, and the rest of the review is addressed in 77db568.

The Yes was inert, as the review says: test_cpp_api_parity generates only from common_nn.py and RMSNorm had no entry there, so nothing checked it. Added affine and no-affine entries with cpp_constructor_args, which also gives the elementwise_affine=false path its first real coverage.

The three forward tests compared the module against the same at::rms_norm call the module itself makes, with the weight left at its all-ones default, so they could not fail if the weight were dropped. They now use a non-unit weight and a non-square normalized_shape and compare against a value expanded in the test. I checked that the comparison stops matching when the weight is removed, which was the point.

Also fixed: the eps docs (opmath epsilon, not the input dtype's), the std::nullopt comment (both schemas declare Tensor? weight=None — the real cause is rms_norm_composite gating on has_value() without .defined(), where rms_norm_symint checks it), the missing cppdocs entry, an error test for a weight whose shape disagrees with normalized_shape, and PrettyPrintRMSNorm ordering.

Deliberately not in this PR: the .defined() guard in rms_norm_composite itself. That is an ATen change with different reviewers, so I would rather send it separately than widen a C++ frontend PR — happy to do that if you would prefer it here.

Locally: pytest test/test_nn.py -k "RMSNorm and elementwise_affine" gives 4 passed, 4 skipped (CUDA), and the new C++ test bodies compile clean against the build's flags. test_api itself needs CI, which is still waiting on fork workflow approval.

🤖 Drafted with Claude Code under the repo's auto-fix flow.

@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007 the parity entries you asked for had a knock-on effect, and the fix
for it landed on Sep 1 in 06925e436 / 3a74f1f5d.

Adding RMSNorm to common_nn.py generates four test_nn.py tests, and all four
fail under PYTORCH_TEST_WITH_DYNAMO=1 with TypeError: add(): argument 'input' must be Tensor, not NoneType, thrown inside compiled autograd. RMSNorm's
backward is a decomposed MulBackward0 chain where LayerNorm's is one
NativeLayerNormBackward0, so compiled autograd carries gradcheck's
deliberately-undefined grad into an add.

I put the four in compiled_autograd_skips rather than
dynamo_expected_failures, which keeps the rest of the dynamo path running. Is
that the call you want here, or would you rather this wait on a compiled-autograd
fix?

Developed with AI assistance (Claude); I reviewed the change and the reasoning above.

pytorchmergebot pushed a commit that referenced this pull request Sep 24, 2026
…rm (#195574)

`aten::rms_norm` declares `Tensor? weight=None`, but `rms_norm_composite` gates the weight multiply on `weight_opt.has_value()` alone. A C++ caller forwarding a possibly-undefined Tensor where an optional is expected produces an engaged optional holding an undefined tensor, and that reaches `upcasted_result.mul(<undefined>)`:

```
Expected a proper Tensor but got None (or an undefined Tensor in C++) for argument #1 'other'
```

`at::layer_norm` accepts the same call, because `math_native_layer_norm` also checks `.defined()`. That asymmetry is the bug.

The MPS branch of `rms_norm_symint` had the same gate and would have handed an undefined weight to `_fused_rms_norm_mps`, so it is fixed here rather than left as a twin of the one being removed. I have no MPS hardware; that half is reasoned from the source and left to CI.

### Test

The failure is only reachable from C++ — Python cannot construct an engaged optional holding an undefined tensor — so the regression test is a gtest in `undefined_tensor_test.cpp`, which `aten/tools/run_tests.sh` already runs. It went there rather than `math_kernel_test.cpp`, which is built but appears in no runner list and so would not have gated this PR.

This machine's Device Guard policy refuses to launch freshly linked gtest binaries, so the assertions were exercised through a `cpp_extension` against a locally built `torch_cpu`. Same harness before and after:

```
before:  engaged-but-undefined  : THREW -> Expected a proper Tensor but got None ...
after:   engaged-but-undefined  : ok, numel=6
```

and the test's own assertion, plus a check that a real weight is still applied:

```
equal(undef, nullopt)  : true
max abs diff           : 0
weight still applied   : true
```

### Related

#193936 adds `torch::nn::RMSNorm` and currently works around this by converting an undefined weight to `std::nullopt` before calling `at::rms_norm`. If this lands first, that conversion and its comment can be dropped there.

Developed with AI assistance (Claude); I reproduced the failure, wrote the fix and ran the checks above.

Pull Request resolved: #195574
Approved by: https://github.com/drisspg

Co-authored-by: Claude Opus 5 <[email protected]>
egeboy35 and others added 7 commits September 26, 2026 01:22
torch.nn.RMSNorm has existed on the Python side since 2.4, but the libtorch
C++ frontend has no equivalent, so C++ users must hand-roll the module or call
torch::rms_norm directly. aten::rms_norm already exists as a
CompositeImplicitAutograd op, so this is a thin frontend mirror of the existing
LayerNorm pattern: options, functional and module (plus their src mirrors),
tests, and a parity-tracker row.

Two details differ from LayerNorm and are worth review attention:

eps is std::optional<double> defaulting to std::nullopt rather than
double = 1e-5, mirroring Python where eps=None means "use the machine epsilon
of the input dtype", which aten::rms_norm resolves internally; pretty_print
renders the unset case as eps=None to match extra_repr.

aten::rms_norm takes Tensor? weight (unlike aten::layer_norm), so an undefined
weight - the elementwise_affine=false case - must be forwarded as std::nullopt.
Passing the undefined tensor through as an engaged optional raises "Expected a
proper Tensor but got None"; F::detail::rms_norm converts explicitly and the
RMSNormNoAffine test covers it.

RMSNorm has a weight but no bias, so only weight is registered (ones when
elementwise_affine is true, undefined otherwise).

Test Plan:

Added 5 tests following the LayerNorm conventions: ModulesTest.RMSNorm,
ModulesTest.RMSNormDefaultEps, ModulesTest.RMSNormNoAffine,
ModulesTest.PrettyPrintRMSNorm, FunctionalTest.RMSNorm.

Locally (Windows/MSVC source build) the module was compiled into torch_cpu and
exercised through a small pybind harness: module output matches
torch::rms_norm for explicit and default eps, the functional matches the
weightless ATen call, elementwise_affine=false leaves weight undefined and
still computes correctly, weight initializes to ones, clone() works, and
pretty_print renders as asserted. The full test_api gtest binary could not be
run on this machine (Windows Smart App Control blocks freshly linked build
executables), so the gtest run is left to CI.

Developed with AI assistance (Claude); reviewed and approved by the author.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review follow-up: setting std::boolalpha modifies the caller's stream
state permanently, so every bool written to that stream afterwards is
formatted as true/false. Format the bool explicitly instead, which keeps
the rendered output identical without touching stream flags.

Verified locally: pretty_print still renders
"torch::nn::RMSNorm([2, 2], eps=None, elementwise_affine=true)" and
"torch::nn::RMSNorm([2, 2], eps=2e-05, elementwise_affine=false)"
(so the PrettyPrintRMSNorm assertions are unchanged), and writing a bool
to a stream after streaming an RMSNorm now yields "1" rather than "true".

Developed with AI assistance (Claude); reviewed and approved by the author.

Co-Authored-By: Claude Fable 5 <[email protected]>
Applying the reviewer's suggestion: fmt formats bools as true/false
without touching the stream's flags, so this drops the manual ternary
while keeping the caller's stream state clean and the rendered output
unchanged.

Developed with AI assistance (Claude); reviewed and approved by the author.

Co-Authored-By: Claude Fable 5 <[email protected]>
Worth reviewing in this order:

The parity-tracker row was inert. test_cpp_api_parity generates tests only
from common_nn.py, and RMSNorm had no entry there, so the
`torch::nn::RMSNorm|Yes|No` row asserted a parity that nothing checked. This
adds affine and no-affine entries with cpp_constructor_args, which also gives
the elementwise_affine=false path - the reason F::detail::rms_norm converts to
std::nullopt at all - its first real coverage.

The three forward tests could not fail. Each compared the module against the
same at::rms_norm call the module itself makes, with weight left at its
all-ones default, so an implementation that dropped the weight or applied it
along the wrong axis still passed. They now use a non-unit weight and a
non-square normalized_shape, and compare against a value expanded in the test.

Two comments were factually wrong. The eps docs promised the machine epsilon
of the input dtype, but rms_norm_composite upcasts via toOpMathType first, so
an fp16 input gets the float epsilon - four orders of magnitude away. And the
justification for the std::nullopt conversion claimed aten::rms_norm's schema
differs from aten::layer_norm's; both declare `Tensor? weight=None`. The real
cause is rms_norm_composite gating on has_value() without .defined(), unlike
rms_norm_symint. That ATen inconsistency is left for a separate PR.

Also adds the missing cppdocs entry, an error-path test for a weight whose
shape disagrees with normalized_shape, and moves PrettyPrintRMSNorm after
PrettyPrintLayerNorm to match the ordering used everywhere else here.

Test Plan:

The generated parity tests, which are what now back the tracker row:

```
python -m pytest test/test_nn.py -k "RMSNorm and elementwise_affine" -q
```

4 passed, 4 skipped (the skips are CUDA on a CPU-only box).

The expected value the C++ tests now assert against was checked against ATen,
including that it stops matching if the weight is dropped:

```
python -c "import torch; x=torch.randn(2,3); w=torch.tensor([0.5,1.5,-2.0]); e=2e-5; print(torch.allclose(x/torch.sqrt(x.pow(2).mean(-1,True)+e)*w, torch.rms_norm(x,[3],w,e)))"
```

The new C++ test bodies were compiled against the build's own flags; this
machine's Device Guard policy will not launch freshly linked gtest binaries,
so test_api itself is left to CI:

```
cl.exe @<build include flags> /Zs <probe holding the new test bodies>
```

0 errors. clang-format 19.1.5 reports no diff on the changed lines, and
`ruff check torch/testing/_internal/common_nn.py` passes.

Developed with AI assistance (Claude) under the repository's auto-fix flow.

Co-Authored-By: Claude Opus 5 <[email protected]>
The `common_nn.py` entries added in the previous commit generate four
`test_nn.py` tests, and all four fail under `PYTORCH_TEST_WITH_DYNAMO=1`:

```
TypeError: add(): argument 'input' (position 1) must be Tensor, not NoneType
  gradcheck.py:1382  _test_undefined_backward_mode
  gradcheck.py:1338  check_undefined_grad_support
  compiled_autograd.py:1266  runtime_wrapper
```

`gradcheck` feeds an undefined grad to backward on purpose. Under
`dynamo_wrapped` that backward is traced by compiled autograd, and RMSNorm's
backward is a chain of generic elementwise ops rather than one fused node -
`torch.nn.RMSNorm(...)(x).grad_fn` is `MulBackward0`, where the LayerNorm
equivalent is `NativeLayerNormBackward0`. Compiled autograd carries the
undefined grad into an `add` in that chain.

That is why LayerNorm's own parity test passes under the same config and
RMSNorm's does not; it is a gap in compiled autograd over a decomposed
backward, not something a C++ frontend PR should be fixing. Marking the four
tests is what `test/dynamo_expected_failures` exists for.

Test Plan:

The failure reproduces locally with the same message CI reports:

```
set PYTORCH_TEST_WITH_DYNAMO=1
python test/test_nn.py TestNN.test_RMSNorm_1d_elementwise_affine ...
```

`4 failed`, and the LayerNorm control passes:

```
python -m pytest test/test_nn.py -k LayerNorm_3d_no_affine_large_feature -q
```

`2 passed, 2 skipped`.

The marker files themselves cannot be exercised on this machine:
`find_test_dir()` in `torch/testing/_internal/dynamo_test_failures.py:33`
returns None on `win32`, so the whole mechanism is inert here. What I could
verify is that the four names resolve - loading the module with
`sys.platform` patched to `linux` finds `test_dir` and picks up 3326 entries,
including all four new ones. Applying the xfail is shared machinery used by
the other 3322 files and is left to CI.

Developed with AI assistance (Claude); I reproduced the failure and ran the
checks above.

Co-Authored-By: Claude Opus 5 <[email protected]>
The previous commit put the four tests in `dynamo_expected_failures`, which
marks the whole test as expected-to-fail under `PYTORCH_TEST_WITH_DYNAMO=1`.
That is heavier than the failure warrants: everything except compiled autograd
works, and xfailing the test throws that coverage away.

The traceback is entirely inside compiled autograd
(`compiled_autograd.py:1266 runtime_wrapper`), and `common_utils.py:2021` turns
compiled autograd on by default under dynamo, so `compiled_autograd_skips` is
the mechanism that fits: it applies `runWithoutCompiledAutograd` to just those
tests (`common_utils.py:3985-3988`) and lets the rest of the dynamo path keep
running.

Test Plan:

Dynamo on, compiled autograd off, which is exactly what the skip produces:

```
set PYTORCH_TEST_WITH_DYNAMO=1
set PYTORCH_TEST_WITHOUT_COMPILED_AUTOGRAD=1
python -m pytest test/test_nn.py -k "RMSNorm and elementwise_affine" -q
```

`4 passed, 4 skipped` - so disabling that one layer is sufficient, and the
tests still exercise dynamo. With compiled autograd left on the same four fail
with `TypeError: add(): argument 'input' (position 1) must be Tensor, not
NoneType`.

The marker files themselves still cannot be exercised here - `find_test_dir()`
returns None on win32 - but loading the module with `sys.platform` patched to
`linux` finds all four under `compiled_autograd_skips` (1208 entries) and none
left behind in `dynamo_expected_failures`.

Developed with AI assistance (Claude).

Co-Authored-By: Claude Opus 5 <[email protected]>
pytorch#195574 made at::rms_norm treat an engaged-but-undefined weight as no
weight, so the nullopt conversion and the comment describing the old ATen
behavior are no longer needed. RMSNormNoAffine covers that path.

Test Plan:

On the previous base (7744b78) with pytorch#195574 cherry-picked:

```
build/bin/test_api.exe --gtest_filter=*RMSNorm*:*LayerNorm*
```

9 tests passed, including ModulesTest.RMSNormNoAffine.

Developed with AI assistance (Claude).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007

Drafted by Claude (AI) for @egeboy35.

Now that #195574 has landed, the branch is rebased onto main and the undefined-weight conversion in F::rms_norm is gone. The RMSNorm gtests pass locally with that change on the old base plus #195574 (output in the description), and the rebased head's workflows are waiting for approval. The question from Sep 20 still stands: are compiled_autograd_skips fine for the four generated TestNN.test_RMSNorm_1d_* tests, or would you rather this wait for a compiled-autograd fix?

@egeboy35

Copy link
Copy Markdown
Contributor Author

@Skylion007

Drafted by Claude (AI) for @egeboy35.

Gentle ping on the Sep 30 question: are compiled_autograd_skips fine for the four generated TestNN.test_RMSNorm_1d_* tests, or should this wait for a compiled-autograd fix? The workflows on the current head have been waiting for approval since Sep 25 and expire around Oct 25, so approving them before then would save a re-push.

@egeboy35

egeboy35 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Closing this, since the C++ frontend is frozen now (see drisspg's comment on #80494). Thanks for the reviews!

@egeboy35 egeboy35 closed this Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

open source release notes: cpp release notes category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants