Pretty printing of C++ modules (#15326)

Summary:
A long outstanding nicety: pretty printing of C++ modules. E.g.
```
  Sequential sequential(
      Linear(10, 3),
      Conv2d(1, 2, 3),
      Dropout(0.5),
      BatchNorm(5),
      Embedding(4, 10),
      LSTM(4, 5));
std::cout << sequential;
```
prints
```
torch::nn::Sequential(
  (0): torch::nn::Linear(in=10, out=3, with_bias=true)
  (1): torch::nn::Conv2d(input_channels=1, output_channels=2, kernel_size=[3, 3], stride=[1, 1])
  (2): torch::nn::Dropout(rate=0.5)
  (3): torch::nn::BatchNorm(features=5, eps=1e-05, momentum=0.1, affine=true, stateful=true)
  (4): torch::nn::Embedding(count=4, dimension=10)
  (5): torch::nn::LSTM(input_size=4, hidden_size=5, layers=1, dropout=0)
)
```

apaszke ebetica ezyang
Pull Request resolved: https://github.com/pytorch/pytorch/pull/15326

Differential Revision: D13518986

Pulled By: goldsborough

fbshipit-source-id: 63bf753672f0e348951de3645208f263581de5fb
This commit is contained in:
Peter Goldsborough
2018-12-19 21:38:00 -08:00
committed by Facebook Github Bot
parent 2ef0f1222a
commit eb5d28ecef
23 changed files with 306 additions and 13 deletions
+20
View File
@@ -832,3 +832,23 @@ TEST_F(ModuleTest, ThrowsWhenAttemptingtoGetTopLevelModuleAsSharedPtr) {
ASSERT_NO_THROW(module->modules());
}
}
struct EmptyModule : torch::nn::Module {};
TEST_F(ModuleTest, PrettyPrint) {
struct TestModule : torch::nn::Module {
TestModule(int x, float y) : x_(x), y_(y) {}
void pretty_print(std::ostream& stream) const {
stream << "TestModule(x=" << x_ << ", y=" << y_ << ")";
}
int x_;
float y_;
};
using namespace torch::nn;
ASSERT_EQ(c10::str(EmptyModule{}), "EmptyModule");
ASSERT_EQ(c10::str(TestModule(1, 3.14)), "TestModule(x=1, y=3.14)");
}