Create Sequential::extend (#9116)

Summary:
There is no way to concatenate two `Sequential`s in Python, but it's also easier to do in an immutable fashion by just writing `Sequential(first.modules() + second.modules())`. Concatenating vectors isn't as easy in C++, so I think it's fair to save users some for loops by giving them `Sequential::extend()`.

apaszke ebetica ezyang

CC jamespinkerton
Closes https://github.com/pytorch/pytorch/pull/9116

Reviewed By: ezyang

Differential Revision: D8719630

Pulled By: goldsborough

fbshipit-source-id: 840d7ac70755350e6202b493c531e30ecbb6546f
This commit is contained in:
Peter Goldsborough
2018-07-02 19:34:45 -07:00
committed by Facebook Github Bot
parent 16570ef0d5
commit 97b9712aed
2 changed files with 54 additions and 3 deletions
+30
View File
@@ -213,4 +213,34 @@ TEST_CASE("sequential") {
.sum()
.toCFloat() == 10);
}
SECTION("extend() pushes modules from other Sequential") {
struct A : torch::nn::Module { int forward(int x) { return x; } };
struct B : torch::nn::Module { int forward(int x) { return x; } };
struct C : torch::nn::Module { int forward(int x) { return x; } };
struct D : torch::nn::Module { int forward(int x) { return x; } };
Sequential a(A{}, B{});
Sequential b(C{}, D{});
a.extend(b);
REQUIRE(a.size() == 4);
REQUIRE(a[0]->is<A>());
REQUIRE(a[1]->is<B>());
REQUIRE(a[2]->is<C>());
REQUIRE(a[3]->is<D>());
REQUIRE(b.size() == 2);
REQUIRE(b[0]->is<C>());
REQUIRE(b[1]->is<D>());
std::vector<std::shared_ptr<A>> c = {std::make_shared<A>(),
std::make_shared<A>()};
b.extend(c);
REQUIRE(b.size() == 4);
REQUIRE(b[0]->is<C>());
REQUIRE(b[1]->is<D>());
REQUIRE(b[2]->is<A>());
REQUIRE(b[3]->is<A>());
}
}