Skip to content

Preserve submodule names in torch::nn::Sequential::clone() - #195107

Closed
egeboy35 wants to merge 2 commits into
pytorch:mainfrom
egeboy35:fix-sequential-clone-names
Closed

egeboy35 wants to merge 2 commits into
pytorch:mainfrom
egeboy35:fix-sequential-clone-names

Conversation

@egeboy35

@egeboy35 egeboy35 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #71069.

SequentialImpl::clone() rebuilt the container with the unnamed push_back overload, which
assigns each submodule the positional name std::to_string(modules_.size()). Every registered
name was replaced by its index, so cloning a named Sequential silently rewrote its
state_dict keys — encoder.weight became 0.weight — breaking a save/load round trip
against the original module with no error.

ModuleDictImpl::clone() is unaffected because its modules_ is an OrderedDict and it
clones through insert(key, value). Sequential's modules_ is a plain std::vector<AnyModule>
and carries no names, so they have to come from the registered children. clone() now reads
them from the public named_children() and uses the named push_back.

This deliberately does not use modules_[i].ptr()->name(): that returns the demangled RTTI
type name, so a container holding two modules of the same type would produce duplicate keys.

Test

SequentialTest.ClonePreservesSubmoduleNames, next to the existing IsCloneable. It asserts on
named_children().keys() and named_parameters().keys() rather than on Module::name() — the
latter is the type name and compares equal whether or not the bug is present, which is what
made the test in the earlier abandoned attempt (#90112) vacuous.

I cannot launch gtest binaries on my machine (Device Guard blocks unsigned executables), so the
same scenarios were run through a Python extension module against the real container. Before:

named   clone    : 0, 1
params  clone    : 0.weight, 0.bias
mixed   clone    : 0, 1, 2
unnamed clone    : 0, 1, 2, 3

After:

named   clone    : encoder, act
params  clone    : encoder.weight, encoder.bias
mixed   clone    : first, 1, last
unnamed clone    : 0, 1, 2, 3

An unnamed submodule keeps the positional name it was originally given rather than being
renumbered around the named ones, and a container with no names at all is unchanged.

On numeric submodule names

@malfet asked this on the earlier attempt (#90112) and it was never answered, so:

numeric original : 2, 0, 1
numeric clone    : 2, 0, 1
numeric clone^2  : 2, 0, 1
collision build  : THREW on the original -> Submodule '1' already defined

Names round trip verbatim, so numeric names that do not match their position are preserved
rather than renumbered, and cloning is idempotent. A container whose auto-name would collide
with an explicit numeric one cannot be built at all: register_module inserts into an
OrderedDict, which throws on a duplicate key, so Sequential({{"1", A}}) followed by an
unnamed push_back throws on the original long before clone() is reached. The proposed
behaviour is strictly closer to the original than today's renumbering.

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

cc @jbschlosser @malfet

SequentialImpl::clone() rebuilt the container with the unnamed push_back
overload, which assigns each submodule the positional name
std::to_string(modules_.size()). Every registered name was therefore
replaced by its index, so cloning a named Sequential silently rewrote its
state_dict keys:

  encoder.weight, encoder.bias   ->   0.weight, 0.bias

which breaks a save/load round trip against the original module without
any error. ModuleDictImpl::clone() does not have this problem because its
modules_ is an OrderedDict and it clones through insert(key, value);
Sequential's modules_ is a plain vector of AnyModule and carries no names,
so the names have to come from the registered children.

clone() now reads them from the public named_children() and uses the named
push_back overload. Note this cannot use modules_[i].ptr()->name(): that
returns the demangled RTTI type name, so a container holding two modules of
the same type would produce duplicate keys.

Fixes pytorch#71069

Test Plan:

Added SequentialTest.ClonePreservesSubmoduleNames next to the existing
IsCloneable, asserting on named_children().keys() and
named_parameters().keys() rather than on Module::name() - the latter is the
type name and compares equal whether or not the bug is present, which is
what made the test in the earlier abandoned attempt (pytorch#90112) vacuous.

The gtest binary cannot be launched on this machine (Device Guard blocks
unsigned executables), so the same scenarios were exercised at runtime
through a Python extension module. Before the fix:

```
named   clone    : 0, 1
params  clone    : 0.weight, 0.bias
mixed   clone    : 0, 1, 2
unnamed clone    : 0, 1, 2, 3
```

after:

```
named   clone    : encoder, act
params  clone    : encoder.weight, encoder.bias
mixed   clone    : first, 1, last
unnamed clone    : 0, 1, 2, 3
```

An unnamed submodule keeps the positional name it was originally given
rather than being renumbered around the named ones, and a container with no
names at all is unchanged.

```
cl.exe /Zs test\cpp\api\sequential.cpp   # with the build's include and define flags
```

Clean. clang-format 19.1.5 (the repository pins 19.1.4) reports no changes.

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

Co-Authored-By: Claude Opus 5 <[email protected]>
@pytorch-bot

pytorch-bot Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit c7abbea with merge base 3d0205b (image):
💚 Looks good so far! There are no failures yet. 💚

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 28, 2026
// rewrite the state_dict keys of any `Sequential` built with names.
const std::vector<std::string> names = named_children().keys();
for (const auto i : c10::irange(modules_.size())) {
clone->push_back(names[i], modules_[i].clone(device));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does but not take arguments by value? We could make std::vector non-const and call std::move on names[i]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — done in c7abbea. push_back(std::string name, AnyModule) does take the name by value (sequential.h:258), and the vector named_children().keys() returns is a temporary owned by clone(), so its elements are safe to move from. Dropped the const and moved.

Re-ran the harness after the change; names still round trip identically, including the mixed named/unnamed and all-numeric cases.

🤖 Addressed by Claude Code

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually yeah just use the named_children directly. No need to materialize and allocate that temporary std::vector

Review nit from @Skylion007. push_back(std::string name, AnyModule) takes
the name by value (sequential.h:258), so passing a const vector's element
copied each string. The keys vector returned by named_children() is a
temporary owned by clone(), so its elements can be moved from.

Test Plan: comment-free behaviour change; the existing
SequentialTest.ClonePreservesSubmoduleNames covers it.

```
cl.exe /Zs test\cpp\api\sequential.cpp   # with the build's include and define flags
```

Clean. clang-format 19.1.5 reports no changes.

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

Co-Authored-By: Claude Opus 5 <[email protected]>
// Submodule names live in the registered children, not in `modules_`.
// Pushing the clones back unnamed would renumber them 0..N-1 and silently
// rewrite the state_dict keys of any `Sequential` built with names.
std::vector<std::string> names = named_children().keys();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this temporary? Just use the iterator for named_children directly and use.key() and .value() to materialize a value from every reference. More memory efficient this way too.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually the best way to avoid a second copy

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually the best way to

// Submodule names live in the registered children, not in `modules_`.
// Pushing the clones back unnamed would renumber them 0..N-1 and silently
// rewrite the state_dict keys of any `Sequential` built with names.
std::vector<std::string> names = named_children().keys();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This actually the best way to avoid a second copy

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 29, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete the comment

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@Skylion007

Copy link
Copy Markdown
Collaborator

@egeboy35 Please revert to your original commit: c7abbea, I now agree with after seeing the templating issue annoyingly

@Skylion007 Skylion007 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revert my changes, your initial approach was correct given the template deduction constraint

@egeboy35
egeboy35 force-pushed the fix-sequential-clone-names branch from 7d1aa8a to c7abbea Compare August 30, 2026 11:00
@egeboy35

Copy link
Copy Markdown
Contributor Author

Done — force-pushed back to c7abbea828b, which restores the c10::irange include and the
comment along with the loop.

For the record, since it may be worth knowing if this comes up again: the blocker is that
named_children() hands back std::shared_ptr<Module>, so child.value()->clone(device)
returns a shared_ptr<Module> and selects push_back(std::string, std::shared_ptr<ModuleType>)
with ModuleType = Module. That erases the concrete type the AnyModule needs for forward(),
which is why every build job went red rather than just a test. modules_[i].clone(device)
returns an AnyModule and keeps it.

So the temporary vector is not really avoidable here without touching AnyModule — the names
and the type-erased modules live in two different containers, and only modules_ has the type.
The std::move you suggested earlier still applies and is in.

Thanks for the quick look on this one.

🤖 Addressed by Claude Code

@egeboy35

Copy link
Copy Markdown
Contributor Author

One heads-up so this does not sit silently: the force-push reset the fork-PR workflow approval,
so pull, Lint, BC Lint and docs-build are all back at action_required on
c7abbea828b. The approval survived, but there is no CI to merge against until someone
approves the runs.

Sorry for the round trip — that is just what a force-push does to a fork PR, and you had asked
for the revert.

🤖 Addressed by Claude Code

@egeboy35

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 2 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@egeboy35

Copy link
Copy Markdown
Contributor Author

Sorry for the noise above — I triggered that merge and it failed for a reason that is not visible in the checks list, so recording it here.

There are two sets of workflow runs on c7abbea828b. The set triggered at 11:00 by the force-push is still sitting at action_required and was never approved — runs 33307828409 (BC Lint) and 33307828669 (pull) are the two the merge bot named. A later set did run and is fully green, which is why gh pr checks shows 317 passing and no failures: action_required runs simply do not appear there.

So the code and the CI are fine; the merge is blocked by those two never-approved runs. Approving them should clear it. Nothing needed from my side that I can see, but happy to rebase onto viable/strict instead if that is a cleaner way to get a fresh, approvable set.

🤖 Addressed by Claude Code

@Skylion007

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…95107)

Fixes pytorch#71069.

`SequentialImpl::clone()` rebuilt the container with the *unnamed* `push_back` overload, which
assigns each submodule the positional name `std::to_string(modules_.size())`. Every registered
name was replaced by its index, so cloning a named `Sequential` silently rewrote its
`state_dict` keys — `encoder.weight` became `0.weight` — breaking a save/load round trip
against the original module with no error.

`ModuleDictImpl::clone()` is unaffected because its `modules_` is an `OrderedDict` and it
clones through `insert(key, value)`. `Sequential`'s `modules_` is a plain `std::vector<AnyModule>`
and carries no names, so they have to come from the registered children. `clone()` now reads
them from the public `named_children()` and uses the named `push_back`.

This deliberately does not use `modules_[i].ptr()->name()`: that returns the demangled RTTI
type name, so a container holding two modules of the same type would produce duplicate keys.

### Test

`SequentialTest.ClonePreservesSubmoduleNames`, next to the existing `IsCloneable`. It asserts on
`named_children().keys()` and `named_parameters().keys()` rather than on `Module::name()` — the
latter is the *type* name and compares equal whether or not the bug is present, which is what
made the test in the earlier abandoned attempt (pytorch#90112) vacuous.

I cannot launch gtest binaries on my machine (Device Guard blocks unsigned executables), so the
same scenarios were run through a Python extension module against the real container. Before:

```
named   clone    : 0, 1
params  clone    : 0.weight, 0.bias
mixed   clone    : 0, 1, 2
unnamed clone    : 0, 1, 2, 3
```

After:

```
named   clone    : encoder, act
params  clone    : encoder.weight, encoder.bias
mixed   clone    : first, 1, last
unnamed clone    : 0, 1, 2, 3
```

An unnamed submodule keeps the positional name it was originally given rather than being
renumbered around the named ones, and a container with no names at all is unchanged.

### On numeric submodule names

@malfet asked this on the earlier attempt (pytorch#90112) and it was never answered, so:

```
numeric original : 2, 0, 1
numeric clone    : 2, 0, 1
numeric clone^2  : 2, 0, 1
collision build  : THREW on the original -> Submodule '1' already defined
```

Names round trip verbatim, so numeric names that do not match their position are preserved
rather than renumbered, and cloning is idempotent. A container whose auto-name would collide
with an explicit numeric one cannot be built at all: `register_module` inserts into an
`OrderedDict`, which throws on a duplicate key, so `Sequential({{"1", A}})` followed by an
unnamed `push_back` throws on the *original* long before `clone()` is reached. The proposed
behaviour is strictly closer to the original than today's renumbering.

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

Pull Request resolved: pytorch#195107
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Opus 5 <[email protected]>
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…95107)

Fixes pytorch#71069.

`SequentialImpl::clone()` rebuilt the container with the *unnamed* `push_back` overload, which
assigns each submodule the positional name `std::to_string(modules_.size())`. Every registered
name was replaced by its index, so cloning a named `Sequential` silently rewrote its
`state_dict` keys — `encoder.weight` became `0.weight` — breaking a save/load round trip
against the original module with no error.

`ModuleDictImpl::clone()` is unaffected because its `modules_` is an `OrderedDict` and it
clones through `insert(key, value)`. `Sequential`'s `modules_` is a plain `std::vector<AnyModule>`
and carries no names, so they have to come from the registered children. `clone()` now reads
them from the public `named_children()` and uses the named `push_back`.

This deliberately does not use `modules_[i].ptr()->name()`: that returns the demangled RTTI
type name, so a container holding two modules of the same type would produce duplicate keys.

### Test

`SequentialTest.ClonePreservesSubmoduleNames`, next to the existing `IsCloneable`. It asserts on
`named_children().keys()` and `named_parameters().keys()` rather than on `Module::name()` — the
latter is the *type* name and compares equal whether or not the bug is present, which is what
made the test in the earlier abandoned attempt (pytorch#90112) vacuous.

I cannot launch gtest binaries on my machine (Device Guard blocks unsigned executables), so the
same scenarios were run through a Python extension module against the real container. Before:

```
named   clone    : 0, 1
params  clone    : 0.weight, 0.bias
mixed   clone    : 0, 1, 2
unnamed clone    : 0, 1, 2, 3
```

After:

```
named   clone    : encoder, act
params  clone    : encoder.weight, encoder.bias
mixed   clone    : first, 1, last
unnamed clone    : 0, 1, 2, 3
```

An unnamed submodule keeps the positional name it was originally given rather than being
renumbered around the named ones, and a container with no names at all is unchanged.

### On numeric submodule names

@malfet asked this on the earlier attempt (pytorch#90112) and it was never answered, so:

```
numeric original : 2, 0, 1
numeric clone    : 2, 0, 1
numeric clone^2  : 2, 0, 1
collision build  : THREW on the original -> Submodule '1' already defined
```

Names round trip verbatim, so numeric names that do not match their position are preserved
rather than renumbered, and cloning is idempotent. A container whose auto-name would collide
with an explicit numeric one cannot be built at all: `register_module` inserts into an
`OrderedDict`, which throws on a duplicate key, so `Sequential({{"1", A}})` followed by an
unnamed `push_back` throws on the *original* long before `clone()` is reached. The proposed
behaviour is strictly closer to the original than today's renumbering.

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

Pull Request resolved: pytorch#195107
Approved by: https://github.com/Skylion007

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: cpp release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

C++ torch::nn::Sequential clone() method overwrites child module names

4 participants