Skip to content

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

Closed

Description

@meganset

🐛 Describe the bug

The clone method of torch::nn::Sequential fails to pick up the names of child modules, e.g.

torch::nn::Sequential q({ {"A", torch::nn::Linear(1,2)},
                           {"B", torch::nn::ReLU()} });
 std::cerr << *q << "\n";

 auto c=q->clone();
 std::cerr << *c << "\n";

The above code results in:

torch::nn::Sequential(
  (A): torch::nn::Linear(in_features=1, out_features=2, bias=true)
  (B): torch::nn::ReLU()
)

torch::nn::Sequential(
  (0): torch::nn::Linear(in_features=1, out_features=2, bias=true)
  (1): torch::nn::ReLU()
)

the code in include/torch/nn/modules/container/sequential.h uses push_back without name:

  std::shared_ptr<Module> clone(
      const optional<Device>& device = nullopt) const override {
    auto clone = std::make_shared<SequentialImpl>();
    for (const auto& module : modules_) {
      clone->push_back(module.clone(device));
    }
    return clone;
  }

I think the clone loop needs to use the name of the child modules in the push_back() call,
something like:

    for (const auto& m : named_children())
      clone->push_back(m.key(), AnyModule(m.value().clone(device)));

Versions

I think this bug has been part of torch::nn::Sequential from the beginning

cc @jbschlosser @albanD @mruberry @walterddr @kshitij12345

Activity

  1. added
    module: cpp
    module: nn
    triaged
    on Jan 10, 2022
  2. jbschlosser commented on Jan 10, 2022

    @jbschlosser
    Contributor

    Hey @meganset, thanks for the report! We'd accept a PR fixing this to properly set the child module names when cloned.

  3. added a commit that references this issue on Aug 30, 2026
    823cdac
  4. added a commit that references this issue on Sep 2, 2026
    b555e59
  5. added a commit that references this issue on Sep 8, 2026
    e5b5999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    actionablemodule: cppmodule: nntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions