Skip to content

Don't overwrite torch::nn::Sequential module names when cloning - #90112

Closed
kvathupo wants to merge 5 commits into
pytorch:masterfrom
kvathupo:kvathupo/fix/sequential_clone
Closed

kvathupo wants to merge 5 commits into
pytorch:masterfrom
kvathupo:kvathupo/fix/sequential_clone

Conversation

@kvathupo

@kvathupo kvathupo commented Dec 3, 2022 •

Copy link
Copy Markdown
Contributor

What?
Fixes #71069

Further changes:

  1. Changed the parameters of the private torch::nn::Sequential::push_back() method used to unpack the parameters from the variadic constructor
  2. Added documentation to said constructor

Why?

  1. I initially changed the private push_back() method to solve what turned out to be a non-issue. Afterwards, I found these changes made it easier to understand. Also, now we don't need to rely on any public push_back() methods in unpacking: originally, the base case of 1 parameter in the variadic template was covered by the public push_back(M&& module).

Further Development?
Possible changes with C++17 (lmk if there's a wish list for that):

  • Replace c10::optional with std::optional
  • Add fine-grained type-checking with type traits in class Sequential; will save following the dependency chain

P.S.
I think you guys squash commits; if not, I can smash them.

@pytorch-bot pytorch-bot Bot added the release notes: cpp release notes category label Dec 3, 2022
@pytorch-bot

pytorch-bot Bot commented Dec 3, 2022 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 3 Failures

As of commit b3416fa:

NEW FAILURES - The following jobs have failed:

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

@kit1980
kit1980 requested a review from malfet December 7, 2022 01:37
@bdhirsh bdhirsh added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Dec 7, 2022
@kvathupo

Copy link
Copy Markdown
Contributor Author

@malfet ping

@malfet malfet 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.

Hmm, what would happen if one tries to clone container with numerical object names

@kvathupo

Copy link
Copy Markdown
Contributor Author

Hmm, what would happen if one tries to clone container with numerical object names

If I'm understanding correctly, that case is covered in the test: it mixes named and unnamed modules (modules of the sequence take the respective index value in the unnamed case)

@kvathupo
kvathupo requested a review from malfet December 15, 2022 00:24
@kvathupo

Copy link
Copy Markdown
Contributor Author

@malfet nudge- job failures seemingly unrelated, from jenkins

@kvathupo

Copy link
Copy Markdown
Contributor Author

@malfet - ping

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Feb 20, 2023
@github-actions github-actions Bot closed this Mar 22, 2023
pytorchmergebot pushed a commit that referenced this pull request Aug 30, 2026
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.

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

Co-authored-by: Claude Opus 5 <[email protected]>
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

open source release notes: cpp release notes category Stale 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.

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

4 participants