Repository navigation
Conversation
🔗 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.
|
|
Good catch, thanks — fixed in adb6fb3 by formatting the bool explicitly Verified locally that the rendered output is unchanged Worth noting the same pattern exists in the neighbouring |
adb6fb3 to
8a9f5a6
Compare
|
@Skylion007 thanks again for the two rounds here — both comments are addressed in One thing that may not be visible from the PR page: this PR's CI has never actually run. If you are happy with the code, approving the workflow runs would let CI exercise the new 🤖 Addressed by Claude Code |
|
@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 Two things that are not visible from the PR page and are the actual blockers:
This adds If a new module is not something you want to take on, say so and I will close it rather than leave 🤖 Addressed by Claude Code |
|
@claude review this PR |
|
Claude finished @Skylion007's task in 16m 38s —— View job The C++ Full reviewPR Review: #193936SummaryAdds Infrastructure
API Design
Testing
RecommendationRequest Changes Blocking: the missing cppdocs entry (the module is invisible in rendered C++ docs), the Separately, on the CI situation raised in the thread: the --- · branch |
|
Please update parity tracker.md |
|
@Skylion007 tracker row updated, and the rest of the review is addressed in The The three forward tests compared the module against the same Also fixed: the Deliberately not in this PR: the Locally: 🤖 Drafted with Claude Code under the repo's auto-fix flow. |
|
@Skylion007 the parity entries you asked for had a knock-on effect, and the fix Adding RMSNorm to I put the four in Developed with AI assistance (Claude); I reviewed the change and the reasoning above. |
…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]>
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]>
3a74f1f to
73c1694
Compare
|
|
|
Closing this, since the C++ frontend is frozen now (see drisspg's comment on #80494). Thanks for the reviews! |
Adds
torch::nn::RMSNorm(module, functional and options) to the libtorch C++frontend, closing a Python/C++ parity gap:
torch.nn.RMSNormhas existed on thePython side since 2.4, but C++ users have had to hand-roll the module or call
torch::rms_normdirectly. The ATen op (aten::rms_norm, CompositeImplicitAutograd) 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+srcmirror)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+srcmirror)test/cpp/api/{modules,functional}.cpp, twoRMSNormentriesin
torch/testing/_internal/common_nn.py(withcpp_constructor_args, so theC++/Python parity harness covers them), cppdocs entries, and a
torch::nn::RMSNorm|Yes|Norow intest/cpp_api_parity/parity-tracker.mdTwo details worth flagging for review:
epsisstd::optional<double>defaulting tostd::nullopt, notLayerNorm's
double = 1e-5. This mirrors Python, whereeps=Nonemeans "usethe machine epsilon of the computation (opmath) type", which
aten::rms_normresolvesinternally.
pretty_printrenders the unset case aseps=Noneto matchtorch.nn.RMSNorm.extra_repr.aten::rms_normusedto multiply by an engaged-but-undefined weight (the
elementwise_affine=falsecase) 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_normneeds no conversion.RMSNormNoAffinecoversthis path.
RMSNorm has a weight but no bias, so
RMSNormImplregisters onlyweight(initialized to ones when
elementwise_affineis true, undefined otherwise).Under dynamo, the four
TestNN.test_RMSNorm_1d_*tests generated from thecommon_nnentries fail inside compiled autograd (TypeError: add(): argument 'input' (position 1) must be Tensor, not NoneType), so they are listed intest/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, soF::rms_normpasses an undefined weight straight through:
That covers
ModulesTest.RMSNorm,RMSNormDefaultEps,RMSNormNoAffine,RMSNormInvalidWeightShape,PrettyPrintRMSNormandFunctionalTest.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.